feat: bootstrap OpenChamber native Android client
Add a Go client for OpenChamber built with Asuka's native widgets. - internal/ocapi: health, password-to-device-token auth, session and message paging, prompt/interrupt/model/agent, permissions, SSE events, HTTP/SOCKS5 proxies and certificate pinning - internal/storage: connection settings plus a device token in the platform keystore, with a per-install id for server-side dedupe - internal/appui: connect, session list and chat screens with streaming Markdown, reasoning/tool folding, permission cards and session actions - netcfg: native module that enables cleartext HTTP in release builds - cmd/ocprobe: terminal probe for the API - headless UI tests (uitest) and the research/plan document
This commit is contained in:
commit
254d08b1bd
35 files changed
+4922
No files matched your search
@@ -0,0 +1,5 @@
|
||||
dist/
|
||||
.DS_Store
|
||||
*.apk
|
||||
*.aab
|
||||
*.jks
|
||||
@@ -0,0 +1,477 @@
|
||||
# OpenChamber 手机客户端(asuka/Go)调研与开发计划
|
||||
|
||||
> 调研对象:asuka(Go + 原生控件)v0.1.1 / main,OpenChamber 2.7.0,opencode v2.2.7
|
||||
> 目标:Android 优先的手机客户端,MVP = 输入地址 + 密码连接(可选 http/socks5 代理),浏览并操作现有会话
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论
|
||||
|
||||
**可行,且 asuka 的覆盖度比预期好。** 但真正的风险不在 UI,而在三处:
|
||||
|
||||
1. **Android 构建链**:本机没有 JDK / Android SDK / NDK。asuka 要求每个平台自己的工具链,第一次搭环境要花半天,且 **asuka v0.1.1 在 Linux 上 `go install` 会编译失败**(`syscall.SO_REUSEPORT`),必须从 `main` 安装。
|
||||
2. **release 版默认禁止明文 HTTP**:asuka 只在 debug manifest 里开 `usesCleartextTraffic`。连 `http://192.168.x.x:3000` 这类自建服务需要额外处理(加一个只声明 manifest 的 native 包,或统一走 HTTPS)。
|
||||
3. **asuka 仍在 0.1.x**:API 还会变。需要 pin 版本,并且**先用 Web 目标(已验证可构建)和 Linux 桌面目标做 UI 迭代**,再落到 Android。
|
||||
|
||||
**建议不要直接写界面**:先花 0.5–1 天写一个不依赖 UI 的 Go 客户端包 + CLI 探针,连本机 OpenChamber 跑通
|
||||
「健康检查 → 密码登录换 token → 列会话 → 拉消息 → 订阅 SSE → 发一条 prompt」,
|
||||
把协议层的不确定性一次性消掉,再投入 UI 和 Android 环境。这样 Android 环境出问题也不会堵住进度。
|
||||
|
||||
---
|
||||
|
||||
## 0.1 进展(2026-11-15)
|
||||
|
||||
M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行的 OpenChamber 2.7.0(无密码):
|
||||
|
||||
| 项 | 结果 |
|
||||
| --- | --- |
|
||||
| Go 版本 | **mise 安装的 1.26.3**(`which go` → `~/.local/share/mise/installs/go/1.26.3/bin/go`),不是系统 Go |
|
||||
| asuka CLI | 从 `@main`(`v0.1.2-0.20261114215826-2602a98fec66`)安装成功;`@latest` 在 Linux 编译失败(`syscall.SO_REUSEPORT`) |
|
||||
| 协议层 | `internal/ocapi`:health、`/auth/session`(密码登录 + 设备 token)、会话列表/分页、消息分页、prompt/interrupt/model/agent、权限、SSE、代理、证书指纹 |
|
||||
| CLI 探针 | `cmd/ocprobe`:对真实服务器跑通 `health`、`sessions`、`messages`、`events`(收到 `server.connected`) |
|
||||
| 界面 | 连接页 + 会话列表 + 聊天页(`internal/appui`),`asuka build --platform web` 通过(14.5 MB wasm) |
|
||||
| 持久化 | `internal/storage`:连接信息进 store,token 进 `asuka/sdk/secure`(Android Keystore);安装 ID 用于设备去重 |
|
||||
| 自动恢复 | 冷启动读 token 自动重连;token 失效自动清除并提示重新输入密码;401 统一登出 |
|
||||
| 实时 | 连接后订阅 `/api/event`:列表增量、运行状态、权限计数;断线退避重连,恢复后重读列表与当前会话尾部 |
|
||||
| 聊天 | 消息分页(30/页,向上加载)、Markdown 流式渲染、思考/工具结果折叠、乐观发送(客户端 `msg_` id)、停止、错误提示 |
|
||||
| 测试 | `go test ./... -race` 全绿;`uitest` 无头测试覆盖:密码登录、错密码、免密服务器、token 自动重连、token 失效、打开会话、发送消息、SSE 流式增量、权限卡片与回复 |
|
||||
| Android 真机 | 模拟器(Android 36 / x86_64)安装 debug 包,连接本机 OpenChamber,会话列表与聊天页均正常(截图见下) |
|
||||
| release 构建 | `asuka build -p android` 产出 `dist/OpenChamber.aab`;合并后的 release manifest 含 `usesCleartextTraffic="true"`(由 `netcfg` 模块合入),明文 HTTP 在 release 可用 |
|
||||
| 会话操作 | 滑动归档/删除、长按菜单、重命名(Alert 输入框)、删除二次确认 |
|
||||
| 权限审批 | 聊天页内联卡片(允许一次/总是允许/拒绝),启动时补齐待批列表,SSE 实时增删 |
|
||||
| 下一步 | M4 余项:模型/Agent 切换、新建会话;M5:Android 真机 + release 明文 HTTP |
|
||||
|
||||
**明文 HTTP 的落地方式**(用户已确认 release 也要支持):native 包 `netcfg` 已加入(`main.go` 里空白导入),Gradle 会把它的 manifest 合并进 release。已实测 release 的合并 manifest 含 `usesCleartextTraffic="true"`,并用 release APK 连上了 `http://10.0.2.2:3000`:
|
||||
|
||||
```bash
|
||||
asuka native new ./netcfg # 生成 Go/Kotlin/Web/desktop 各平台骨架
|
||||
```
|
||||
|
||||
然后在 `netcfg/android/src/main/AndroidManifest.xml` 写:
|
||||
|
||||
```xml
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application android:usesCleartextTraffic="true" />
|
||||
</manifest>
|
||||
```
|
||||
|
||||
库 manifest 会合并进 app 的 manifest;`asuka` 只在 debug manifest 里自带这条,所以 release 需要它。若想更严格,可用 `android:networkSecurityConfig` 只放行 RFC1918 网段。
|
||||
|
||||
### 环境(已就绪)
|
||||
|
||||
- JDK 21:`~/SDK/jdk-21`(TUNA 镜像的 Temurin 21.0.13),给 Gradle 本身
|
||||
- JDK 17:`~/SDK/jdk-17`(Temurin 17.0.21),Android 工程要 Java 17 toolchain;在 `~/.gradle/gradle.properties` 里登记:
|
||||
`org.gradle.java.installations.paths=/home/blumia/SDK/jdk-21,/home/blumia/SDK/jdk-17`
|
||||
- Android SDK:`~/SDK/AndroidSDK`
|
||||
- `ANDROID_HOME=$HOME/SDK/AndroidSDK`
|
||||
- `JAVA_HOME=$HOME/SDK/jdk-21`
|
||||
- 组件:platform-tools、platforms;android-36、build-tools;36.0.0、NDK 30.0.16248370、emulator、system-images;android-36;google_apis;x86_64
|
||||
- 模拟器:AVD `oc36`(Android 36,x86_64),无窗口启动:
|
||||
`emulator -avd oc36 -no-window -no-audio -no-boot-anim -gpu swiftshader_indirect`
|
||||
- Gradle:wrapper 需要 `gradle-8.14.3-bin.zip`;`services.gradle.org` 在本机超时,已从腾讯镜像
|
||||
`https://mirrors.cloud.tencent.com/gradle/` 下载并放进
|
||||
`~/.gradle/wrapper/dists/gradle-8.14.3-bin/cv11ve7ro1n3o1j4so8xd9n66/`
|
||||
- release 签名:本机用测试 keystore `~/SDK/test-upload.jks`(`ASUKA_KEYSTORE`、`ASUKA_KEY_ALIAS=upload`、密码 `testpass`);正式发布请换成自己的上传密钥
|
||||
- 运行:`asuka dev --platform android`(首次会启动模拟器/安装 debug 包)
|
||||
|
||||
---
|
||||
|
||||
## 1. asuka 调研
|
||||
|
||||
### 1.1 它是什么 / 怎么工作
|
||||
|
||||
- Go 写业务和界面,每个平台用**自己的原生控件**渲染(Android 是 Android Views + Material 3),不是 WebView,也不是 canvas。
|
||||
- 组件函数**只执行一次**;之后靠 signals 做细粒度更新。**组件体里读 signal 只读到那一次**,必须用 `signal.Func` / `ui.Val` 这类 accessor(`asuka vet` 会自动检查这类错误)。
|
||||
- **所有 signal 写入必须在主线程**。网络、SSE、文件都要在 goroutine 里做,结果用 `ui.Post` 回主线程。
|
||||
- `asuka dev -p android` 默认热重载:Go 代码跑在电脑上,手机里的 player 负责显示;`--no-hot` / release 才把 Go 编进 APK。
|
||||
- Android 构建参数(asuka 自带 Gradle 工程):`minSdk 33`、`compileSdk / targetSdk 36`、AGP 8.12、Kotlin 2.1.20、JDK 17。release 产物是 `.aab`。
|
||||
|
||||
### 1.2 MVP 需要的组件(已确认存在)
|
||||
|
||||
| 需求 | asuka 能力 |
|
||||
| --- | --- |
|
||||
| 页面导航、标题栏、返回 | `ui.Stack` + `ui.UseNavigator` + `ui.ScreenOptions{Title, Actions, Search}` |
|
||||
| 底部 tab | `ui.Tabs`(Android 上是 Material 底部导航) |
|
||||
| 会话列表 | `ui.List`(回收列表)+ `Section`(按项目分组)+ `OnRefresh`(下拉刷新)+ `SwipeActions`(归档/删除)+ `OnEndReached`(分页) |
|
||||
| 聊天时间线 | `ui.List{Anchor: ui.AnchorBottom, OnStartReached: 加载更早}`:新消息贴底、行高变化保持贴底,用户上滑后不打扰 |
|
||||
| Markdown / 代码块 | `asuka/sdk/markdown`:`markdown.View{Text, Streaming}`,流式追加只重排正在写的那一块;GFM、表格、脚注、数学 |
|
||||
| 输入框 | `ui.TextField{Multiline, Lines, Selection, Placeholder}`,键盘避让靠 `ui.SafeArea` |
|
||||
| 弹窗 / 确认 | `ui.Sheet`、`ui.Alert`、`ui.ActionSheet` |
|
||||
| 安全存 token | `asuka/sdk/secure`(Android = Android Keystore AES-GCM + 私有 SharedPreferences) |
|
||||
| 轻量设置 | `asuka/sdk/store` 的 `store.Signal`(跨启动保留) |
|
||||
| 前后台 | `app.OnLifecycle(Foreground/Background/MemoryWarning)` |
|
||||
| 图片展示(后续) | `ui.Image`(http(s) 直读,Android 有磁盘缓存) |
|
||||
| 通知(后续) | `asuka/sdk/notify` / `asuka/sdk/push` |
|
||||
|
||||
### 1.3 已经踩到的坑
|
||||
|
||||
- **v0.1.1 在 Linux 编译失败**:
|
||||
`internal/devtunnel/listen_unix.go:19` 用了 `syscall.SO_REUSEPORT`(Linux 的 `syscall` 没有),main 已改成 `golang.org/x/sys/unix`。
|
||||
→ 必须 `go install github.com/egoist/asuka/cmd/asuka@main`,并在项目 `go.mod` 里 pin 住伪版本。
|
||||
- **本机可运行的验证**:`asuka new` + `asuka build --platform web` 成功(6.2 MB wasm / 1.7 MB gzip)。
|
||||
- **Linux 桌面目标可用**:GTK4 + libadwaita 1.7.6 运行时已装,可直接 `asuka dev`(GTK 窗口)做原生手感调试;缺 `libadwaita-1` 的 pkg-config 不影响(asuka 是动态加载)。
|
||||
- **不要用 WebView 渲染聊天**:`ui.WebView` 存在,但那样就退回现有 Capacitor 方案了;Markdown 用官方 `sdk/markdown`。
|
||||
|
||||
---
|
||||
|
||||
## 2. 服务端对接
|
||||
|
||||
### 2.1 结构
|
||||
|
||||
```
|
||||
[手机 app] --HTTPS/HTTP--> [OpenChamber :3000]
|
||||
├─ /auth/*, /api/client-auth/* 认证与设备 token
|
||||
├─ /api/session/*, /api/event, ... 透传 opencode v2 API
|
||||
└─ /health, /api/opencode/health 探活与版本
|
||||
```
|
||||
|
||||
`/api/*` 基本是 opencode v2 API 的通用反代(`packages/web/server/lib/opencode/proxy.js`),所以按 opencode v2 的契约写,OpenChamber 升级时兼容性最好。
|
||||
|
||||
### 2.2 认证(MVP 核心,已验证)
|
||||
|
||||
官方 Capacitor 客户端的字段可以直接照抄(`packages/ui/src/apps/mobileConnections.ts`):
|
||||
|
||||
1. **探活 + 版本 + 防串服**
|
||||
`GET /health`(免鉴权)
|
||||
→ `{status:"ok", openchamberVersion, runtime, compatibility, serverId?}`
|
||||
记下 `serverId`,之后重连时校验,避免路由器把同一个 LAN 地址分给了另一台机器。
|
||||
|
||||
2. **用已有 token 探测**
|
||||
`GET /auth/session` + `Authorization: Bearer <token>`
|
||||
→ `200 {authenticated:true, scope:"client"}` / `401 {authenticated:false, locked:true}`
|
||||
没有配置密码的服务器返回 `{authenticated:true, disabled:true}`,此时不需要 token。
|
||||
|
||||
3. **密码登录并一次拿到设备 token**
|
||||
```http
|
||||
POST /auth/session
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"password": "……",
|
||||
"trustDevice": true,
|
||||
"issueClientToken": true,
|
||||
"clientLabel": "OpenChamber Native",
|
||||
"clientKind": "mobile",
|
||||
"deviceName": "Pixel 9",
|
||||
"devicePlatform": "android",
|
||||
"deviceModel": "Pixel 9",
|
||||
"dedupeKey": "<本机安装 ID,稳定不变>"
|
||||
}
|
||||
```
|
||||
→ `{authenticated:true, clientToken:"oc_client_…", client:{…}}`
|
||||
|
||||
- token 默认 **7 天**(服务端 `OPENCHAMBER_UI_TRUSTED_SESSION_TTL_DAYS`),只存哈希;过期/撤销后 API 返回 401。
|
||||
- `dedupeKey` 让同一台手机反复登录只占**一条**设备记录(官方用 localStorage UUID;我们用 `store.Signal` 持久化一个 UUID)。
|
||||
- 密码错误有限流:返回 `429 {retryAfter}`,UI 必须显示冷却。
|
||||
- 之后所有请求带 `Authorization: Bearer oc_client_…`,**不要依赖 cookie**(原生客户端没有 cookie jar;relay 场景 cookie 也过不去)。
|
||||
- 不要发 `Origin` 头(Go 默认不发);服务端只对带 Origin 的请求做来源校验。
|
||||
|
||||
### 2.3 会话与消息接口(已验证)
|
||||
|
||||
目录作用域:会话类请求带 `x-opencode-directory: <percent-encoded 绝对路径>`;列表接口也可用 `?directory=`(OpenChamber 会规范化)。不传 directory 的 `/api/session` 是**全局列表**,每条会话自带 `location.directory`,所以「全部会话」视图一次请求就够。
|
||||
|
||||
| 功能 | 请求 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 会话列表 | `GET /api/session?limit=50&order=desc[&directory=][&search=][&archived=]` | `{data:[Session], cursor:{next,previous}}`,cursor 不透明 |
|
||||
| 运行中会话 | `GET /api/session/active` | `{data:{ses_x:{type:"running"}}}` |
|
||||
| 会话详情 | `GET /api/session/{id}` | `{data:Session}` |
|
||||
| 消息分页 | `GET /api/session/{id}/message?limit=50&order=desc&cursor=` | `{data:[Message], cursor:{next}}`,倒序取最新,往前翻历史 |
|
||||
| 发送消息 | `POST /api/session/{id}/prompt` | `{id?, text, files?, agents?, skills?}`,正文流式回来 |
|
||||
| 中断 | `POST /api/session/{id}/interrupt` | `{interrupted:true}` |
|
||||
| 切换模型 | `POST /api/session/{id}/model` | `{model:{providerID,id,variant?}}` |
|
||||
| 切换 Agent | `POST /api/session/{id}/agent` | `{agent:"build"}` |
|
||||
| 新建会话 | `POST /api/session` | `{title?, agent?, model?, location:{directory}}` |
|
||||
| 改名 / 归档 | `PATCH /api/session/{id}` | `{title?}` / `{archived:true|false}` |
|
||||
| 删除 | `DELETE /api/session/{id}` | 204 |
|
||||
| 模型列表 | `GET /api/model?location[directory]=<abs>` | 透传 opencode |
|
||||
| Agent 列表 | `GET /api/agent?location[directory]=<abs>` | 同上 |
|
||||
| 待批权限 | `GET /api/permission/request?location[directory]=<abs>` | 启动时补齐 |
|
||||
| 批复权限 | `POST /api/session/{id}/permission/{requestID}/reply` | `{decision:"once"|"always"|"reject", message?}` |
|
||||
| 事件流 | `GET /api/event`(SSE,可 `?types=…`) | 需要 Bearer |
|
||||
| OpenCode 就绪 | `GET /api/opencode/health?wait=15000` | 服务端没起 opencode 时用 |
|
||||
| 默认目录 | `GET /api/location` | `{directory, project}` |
|
||||
|
||||
**Session(节选)**
|
||||
|
||||
```jsonc
|
||||
{"id":"ses_…","projectID":"…","agent":"build",
|
||||
"model":{"id":"…","providerID":"…","variant":"default"},
|
||||
"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
|
||||
"title":"…",
|
||||
"time":{"created":1794734543641,"updated":…,"busy":…,"idle":…,"viewed":…,"archived":…},
|
||||
"location":{"directory":"/home/me/project"},
|
||||
"metadata":{"openchamber":{"work":{"state":"open"}}}}
|
||||
```
|
||||
|
||||
**Message(节选)**
|
||||
|
||||
```jsonc
|
||||
{"id":"msg_…","type":"user","text":"…","files":[…],"time":{"created":…}}
|
||||
{"id":"msg_…","type":"assistant","agent":"build","model":{…},
|
||||
"content":[
|
||||
{"type":"text","text":"…"},
|
||||
{"type":"reasoning","text":"…","time":{…}},
|
||||
{"type":"tool","id":"call_…","name":"shell","executed":false,
|
||||
"state":{"status":"completed","input":{…},"content":[{"type":"text","text":"…"}]},
|
||||
"time":{"created":…,"completed":…}}],
|
||||
"time":{"created":…,"streamed":…,"completed":…},
|
||||
"finish":"stop","cost":0,"tokens":{…}}
|
||||
// 其它类型:synthetic / shell / system / skill / compaction / agent-switched / model-switched / idle
|
||||
```
|
||||
|
||||
### 2.4 SSE 事件(MVP 子集)
|
||||
|
||||
信封:
|
||||
|
||||
```jsonc
|
||||
{"id":"evt_…","created":1794734734543,"type":"session.text.delta",
|
||||
"location":{"directory":"/home/me/project"},
|
||||
"durable":{"aggregateID":"ses_…","seq":42,"version":1},
|
||||
"data":{…}}
|
||||
```
|
||||
|
||||
| 事件 | 用途 |
|
||||
| --- | --- |
|
||||
| `server.connected` | 连接建立 |
|
||||
| `session.created/renamed/archived/unarchived/deleted` | 列表增量 |
|
||||
| `session.execution.started/succeeded/failed/interrupted` | 忙/闲状态(启动时再配合 `/api/session/active` 做全量对齐) |
|
||||
| `session.step.started/streamed/ended/failed` | assistant 消息出现与结束(tokens/cost/finish) |
|
||||
| `session.text.started/delta/ended` | 正文流式 |
|
||||
| `session.reasoning.*` | 思考流式(可折叠) |
|
||||
| `session.tool.input.*/called/progress/success/failed` | 工具状态机 |
|
||||
| `session.shell.started/ended` | 会话内 shell |
|
||||
| `session.usage.*`、`session.retry.scheduled` | 成本与重试提示 |
|
||||
| `permission.asked/replied` | 手机端弹审批 |
|
||||
|
||||
连接策略:
|
||||
|
||||
- `net/http` + `bufio.Scanner` 解析 `data:` 行;用 `?types=` 只订阅需要的类型(但 `server.connected` 总会发)。
|
||||
- 断线指数退避重连(1s → 30s + jitter);**恢复后对当前会话重取一页消息做全量对齐**——服务端明确事件流是 volatile(慢消费者会被断开,断线期间事件丢失)。
|
||||
- `durable.seq` 可用于检测缺口,MVP 用全量对齐更简单可靠。
|
||||
- 切后台 Android 可能掐断连接:回前台重连 + 重同步,不做后台常驻。
|
||||
|
||||
---
|
||||
|
||||
## 3. 客户端架构
|
||||
|
||||
### 3.1 目录结构
|
||||
|
||||
```
|
||||
openchamber-android-native/ # 本目录,新 Go module
|
||||
├── PLAN.md
|
||||
├── asuka.json # app 名称/ID/图标/Android 配置
|
||||
├── main.go # app.Run(App)
|
||||
├── cmd/ocprobe/ # M0 探针 CLI(连真实服务器,验收协议层)
|
||||
├── internal/ocapi/ # 纯 Go 客户端,零 UI 依赖,可单测
|
||||
│ ├── client.go # baseURL / token / transport(代理、TLS)/ 错误模型
|
||||
│ ├── auth.go # /health、/auth/session
|
||||
│ ├── sessions.go # 列表/详情/新建/改名/归档/删除/active
|
||||
│ ├── turn.go # prompt / interrupt / model / agent
|
||||
│ ├── messages.go # 分页
|
||||
│ ├── permissions.go # 列表与回复
|
||||
│ ├── catalog.go # /api/model、/api/agent、/api/location
|
||||
│ ├── events.go # SSE 解码 + 重连
|
||||
│ └── *_test.go # httptest + 真实服务集成
|
||||
├── internal/state/ # signals 与业务动作(把 ocapi 结果搬到 UI)
|
||||
├── internal/storage/ # secure token、store.Signal 设置、安装 ID
|
||||
└── app/ # 界面
|
||||
├── app.go # Tabs/Stack 根
|
||||
├── connect.go # 地址 / 密码 / 代理 / 自签证书
|
||||
├── sessions.go # 会话列表
|
||||
├── chat.go # 消息 + composer
|
||||
├── message.go # 消息渲染(user / assistant / tool / reasoning)
|
||||
├── permissions.go # 权限审批
|
||||
└── settings.go
|
||||
```
|
||||
|
||||
原则:
|
||||
|
||||
- `internal/ocapi` 不 import `ui`/`signal` → CI 里能 `go test ./...`,也能用 CLI 跑真服务。
|
||||
- UI 只读 state 的 signal,动作走 state 的方法;网络在 goroutine,回调 `ui.Post`。
|
||||
- 每个打开的会话一个「会话运行时」:SSE 订阅 + 消息缓存 + context 取消,页面 `signal.OnCleanup` 里关闭。
|
||||
|
||||
### 3.2 网络层
|
||||
|
||||
```go
|
||||
type Client struct {
|
||||
base *url.URL
|
||||
token string // oc_client_…
|
||||
http *http.Client
|
||||
serverID string // /health 的 serverId,重连时校验
|
||||
}
|
||||
|
||||
func NewClient(base string, opts Options) (*Client, error) // opts: Proxy, InsecureTLS, Timeout
|
||||
```
|
||||
|
||||
- **HTTP 代理**:`Transport.Proxy = http.ProxyURL(u)`(`http://host:port` / `https://`,走 CONNECT)。
|
||||
- **SOCKS5**:`golang.org/x/net/proxy.SOCKS5("tcp", host, nil, proxy.Direct)` 得到 `DialContext`,赋给 `Transport.DialContext`(不做认证,符合需求)。
|
||||
- **TLS**:默认系统校验;「信任自签证书」开关 → 记录 SHA-256 指纹 + `VerifyPeerCertificate` 固定,比 `InsecureSkipVerify` 更可感知。
|
||||
- **超时**:普通请求 20s;SSE 不设 `Client.Timeout`,用 `context` 取消 + 读超时看门狗。
|
||||
- **错误归一化**:`ErrUnauthorized`(401)、`ErrRateLimited`(429+retryAfter)、`ErrOffline`、`ErrNotOpenChamber`(`/health` 不带 `openchamberVersion`)。
|
||||
- **目录作用域**:`x-opencode-directory: url.PathEscape(dir)`,列表再带 `?directory=`。
|
||||
|
||||
### 3.3 UI 结构
|
||||
|
||||
```
|
||||
App
|
||||
├── 未连接: ConnectScreen
|
||||
│ ├── 服务器地址(自动补协议、去尾斜杠)
|
||||
│ ├── 密码(Secure)
|
||||
│ ├── 高级:代理类型 [无 / HTTP / SOCKS5] + 地址
|
||||
│ ├── 高级:信任自签证书
|
||||
│ └── 连接 → /health → /auth/session → 存 token
|
||||
└── 已连接: Tabs
|
||||
├── 会话
|
||||
│ ├── 列表(按项目分组;标题、模型、更新时间、运行中)
|
||||
│ ├── 下拉刷新 / 触底分页 / 搜索
|
||||
│ ├── 滑动:归档 / 删除
|
||||
│ └── → ChatScreen
|
||||
│ ├── 消息列表(AnchorBottom、日期分组、顶部加载更早)
|
||||
│ ├── assistant:markdown.View(Streaming) + reasoning 折叠 + tool 折叠摘要
|
||||
│ ├── user:气泡 + 附件占位
|
||||
│ ├── 忙碌:停止按钮 + 状态/错误行
|
||||
│ ├── composer:多行输入、模型/agent 菜单
|
||||
│ └── 标题栏:重命名 / 归档 / 删除 / 切换模型
|
||||
└── 设置(连接信息、重新登录、代理、关于)
|
||||
```
|
||||
|
||||
关键交互:
|
||||
|
||||
- **贴底**:`AnchorBottom` + 发送后 `ui.ScrollToEnd`。
|
||||
- **流式性能**:assistant 正文放在 `signal.NewFunc(string, nil)`;合并 30–60ms 内的事件再写 signal;`markdown.View{Streaming:true}` 只重排最后一块。
|
||||
- **工具调用**:一行摘要(`shell · 命令` / `read · 文件`),点击展开,展开状态放在外部 `map[callID]bool`(行会被回收,状态不能放在行里)。
|
||||
- **权限审批**:`permission.asked` 时 `ui.Alert` 显示 action/resource,三个按钮 once/always/reject;`permission.replied` 后关闭。
|
||||
- **401**:任何请求 401 → 清 token → 连接页,地址/代理保留。
|
||||
|
||||
---
|
||||
|
||||
## 4. MVP 范围与验收
|
||||
|
||||
| # | 功能 | 验收标准 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 地址 + 密码连接 | 支持 `host:port` 自动补协议;不可达 / 非 OpenChamber / 密码错误 / 限流都有明确提示 |
|
||||
| 2 | 可选代理(HTTP/SOCKS5,无认证) | 开/关都能连;地址错误时提示;无需认证字段 |
|
||||
| 3 | 自签证书开关 | 默认严格校验;打开后可连,并显示指纹 |
|
||||
| 4 | token 持久化 | 杀进程重开保持登录;过期/撤销 → 401 → 重登提示 |
|
||||
| 5 | 会话列表 | 全部项目的会话(标题/项目/更新时间/运行中);下拉刷新;分页;搜索 |
|
||||
| 6 | 会话操作 | 新建、重命名、归档、删除;操作后列表即时更新 |
|
||||
| 7 | 聊天查看 | 历史(markdown、代码块、工具调用、思考折叠);上滑加载更早;贴底 |
|
||||
| 8 | 流式回复 | 文字逐步出现;思考/工具状态实时;结束显示耗时/token |
|
||||
| 9 | 发送 / 停止 | 空消息不可发;发送后清空;运行中可停止 |
|
||||
| 10 | 模型 / Agent 切换 | 当前模型可见;切换后对后续消息生效 |
|
||||
| 11 | 权限审批 | 待批请求可见,可 once/always/reject;结果同步 |
|
||||
| 12 | 断线恢复 | 断网提示;恢复后重连 SSE 并补齐当前会话 |
|
||||
| 13 | Android 真机/模拟器 | 可安装运行;明文 HTTP / 自签证书场景按设计工作 |
|
||||
|
||||
**不在 MVP**:终端、文件/Git/PR、图片附件、语音、推送、Pairing v2 / Relay、多服务器切换。桌面/web 目标只用于调试,不算交付。
|
||||
|
||||
---
|
||||
|
||||
## 5. 里程碑
|
||||
|
||||
| 阶段 | 内容 | 产出 | 估算 |
|
||||
| --- | --- | --- | --- |
|
||||
| **M0** 环境与协议探针 | 安装 asuka(`@main`)+ 建 Go module;`cmd/ocprobe`:health → 登录 → 列会话 → 拉消息 → SSE 打印 → 发 prompt;`asuka build -p web` 验证工具链 | ✅ 已完成(见 §0.1),真实服务器验证通过 | 0.5–1d |
|
||||
| **M1** ocapi | 客户端包 + 类型 + 代理/TLS + 错误模型;`httptest` 单测 + 真实服务集成测试 | ✅ 完成(含 catalog/permissions/证书单测) | 1–2d |
|
||||
| **M2** 连接与会话列表 | ConnectScreen、secure token、state 层、SessionsScreen(先 web/Linux 目标) | ✅ 完成(自动重连、401 重登、实时列表) | 1–2d |
|
||||
| **M3** 聊天 | ChatScreen、消息渲染、markdown 流式、分页、composer、interrupt、自动贴底 | ✅ 完成(含 SSE 流式与工具/思考折叠) | 2–3d |
|
||||
| **M4** 操作与权限 | 新建/改名/归档/删除、模型/agent、权限审批、401/429/断网处理 | 验收表全绿(桌面) | 1–2d |
|
||||
| **M5** Android | 装 SDK/NDK/JDK + 模拟器/真机;明文 HTTP 与自签证书策略落地;真机跑通 | 手机上完整走通 | 1–2d |
|
||||
| **M6** 打磨与发布 | 图标/splash、i18n(zh-Hans/en)、空态/骨架屏、release AAB、CI | 可分发的构建 | 1–2d |
|
||||
|
||||
合计约 **8–12 人日**。M5 的环境安装可与 M1–M3 并行(下载耗时长)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 本机环境搭建(无 Android SDK)
|
||||
|
||||
现状:Go 1.26.3(mise)✅、`/dev/kvm` ✅、网络 ✅、asuka CLI 可从 `@main` 安装 ✅;缺 JDK、Android SDK/NDK、模拟器。
|
||||
|
||||
```bash
|
||||
# 1) JDK 17/21(Gradle 需要;asuka 会读 JAVA_HOME)
|
||||
sudo apt install openjdk-21-jdk-headless
|
||||
|
||||
# 2) Android command-line tools(不需要 Android Studio)
|
||||
mkdir -p ~/Android/Sdk/cmdline-tools
|
||||
cd /tmp && curl -LO https://dl.google.com/android/repository/commandlinetools-linux-13114758_latest.zip
|
||||
unzip -q commandlinetools-linux-*.zip -d ~/Android/Sdk/cmdline-tools
|
||||
mv ~/Android/Sdk/cmdline-tools/cmdline-tools ~/Android/Sdk/cmdline-tools/latest
|
||||
|
||||
export ANDROID_HOME=$HOME/Android/Sdk
|
||||
export PATH=$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH
|
||||
|
||||
# 3) 接受许可并安装(compileSdk 36 / build-tools 36 / 最新 NDK)
|
||||
yes | sdkmanager --licenses
|
||||
sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.0.0" \
|
||||
"ndk;28.0.13004108" "emulator" "system-images;android-36;google_apis;x86_64"
|
||||
|
||||
# 4) 模拟器
|
||||
avdmanager create avd -n oc36 -k "system-images;android-36;google_apis;x86_64" -d pixel_7
|
||||
emulator -avd oc36 &
|
||||
|
||||
# 5) 构建与运行
|
||||
go install github.com/egoist/asuka/cmd/asuka@main # 注意:不能用 @latest
|
||||
asuka dev --platform android --device emulator-5554
|
||||
```
|
||||
|
||||
- 模拟器访问宿主机用 `10.0.2.2`;或 `adb reverse tcp:3000 tcp:3000` 后用 `http://127.0.0.1:3000`。真机同一 Wi-Fi 用内网 IP。
|
||||
- `asuka build --platform android` 产出 Play 用的 `.aab`;要侧载 APK 就对生成的 Gradle 工程跑 `./gradlew assembleDebug`,或用 `bundletool build-apks --mode=universal`。
|
||||
- 首次 Gradle 构建会下载依赖,比较慢。
|
||||
|
||||
---
|
||||
|
||||
## 7. 风险与对策
|
||||
|
||||
| 风险 | 影响 | 对策 |
|
||||
| --- | --- | --- |
|
||||
| asuka 0.1.x API 变动 | 升级破坏 | `go.mod` pin 伪版本;CI 固定 asuka 版本;升级单独 PR + 冒烟 |
|
||||
| v0.1.1 在 Linux 编译失败 | 装不上 CLI | 从 `@main` 安装并记录 commit(`0.1.2-0.20261114215826-2602a98fec66`) |
|
||||
| Android release 禁明文 HTTP | 连不上 `http://LAN:3000` | native 包 manifest 合并 `usesCleartextTraffic`(方案见 §0.1,M5 实测);或强制 HTTPS(Caddy / Tailscale) |
|
||||
| 自签证书 | TLS 失败 | 「信任该证书」+ 指纹固定;默认严格校验 |
|
||||
| SSE 断线/后台被杀 | 消息不同步 | 回前台重连 + 当前会话全量对齐;退避重连;UI 显示连接状态 |
|
||||
| 组件只跑一次 + 行回收 | 展开态错乱 | 行内状态放全局 `map[id]` signal;行只读 accessor |
|
||||
| 长会话 / 大工具输出 | 卡顿、内存 | 50 条/页分页;工具输出折叠 + 截断;只保留最近 N 条 |
|
||||
| Markdown 复杂度 | 渲染差异 | 官方 `sdk/markdown`(CommonMark + GFM + 数学);代码块自定义渲染 |
|
||||
| 权限回复枚举变化 | 审批失败 | M0 探针实测(协议 2.2.6:`once` / `always` / `reject`);失败降级为只读提示 |
|
||||
| SOCKS5 DNS 行为 | 解析失败 | SOCKS5 远程解析;用域名和 IP 两种目标测试 |
|
||||
| token 7 天过期 | 突然 401 | 统一 401 拦截 → 重登;设置页显示到期时间 |
|
||||
| 模拟器/真机不可用 | 无法验收 M6 | 先装 emulator + x86_64 镜像;真机 USB + `adb reverse` |
|
||||
|
||||
---
|
||||
|
||||
## 8. 测试
|
||||
|
||||
1. **ocapi 单测**:`httptest.Server` 模拟 `/health`、`/auth/session`、`/api/session`、SSE(分块写 `text/event-stream`),覆盖 401 / 429 / 断流 / 取消。
|
||||
2. **真实服务集成**:本机跑 OpenChamber(带 `--ui-password`),用环境变量提供 URL/密码跑 `-tags=integration`;`cmd/ocprobe` 同时是手工冒烟工具。
|
||||
3. **UI 冒烟**:`asuka dev -p web`(快)→ Linux 桌面(原生手感)→ Android 模拟器/真机。仓库里已有 `uitest` 无头 UI 测试(`internal/appui/root_test.go`),CI 可直接跑。
|
||||
4. **手工场景**:冷启动连接、错密码+限流、杀进程重开、飞行模式恢复、长会话上滑、流式发送/停止、权限批准/拒绝、归档/删除、切模型、自签证书、代理开关。
|
||||
|
||||
---
|
||||
|
||||
## 9. 已定与待定
|
||||
|
||||
已定(2026-11-15):
|
||||
|
||||
- 代码放在当前目录 `~/Sources/openchamber-android-native`,独立 Go module。
|
||||
- 明文 HTTP:**release 也要支持**内网 `http://` ⇒ M5 需要一个 native 包放行 cleartext(做法见 §0.1)。
|
||||
- M0 已完成;M1–M3 完成;M4 完成权限审批与会话操作,剩模型/Agent 切换与新建会话。
|
||||
- Android:debug 与 release(AAB 及用其生成的 release APK)都已在模拟器上连通本机服务器;release 的明文 HTTP 已验证。
|
||||
|
||||
待定:
|
||||
|
||||
1. **会话范围**:MVP 直接展示「所有项目」的全局会话列表(当前实现),还是先选项目/目录再进会话?
|
||||
2. **发布方式**:自签名 sideload / 内部分发,还是准备上 Google Play(影响 AAB、签名、隐私声明)?
|
||||
3. **界面语言**:先英文再中文,还是首发中英双语?
|
||||
|
||||
---
|
||||
|
||||
## 附:关键源码位置(本机)
|
||||
|
||||
- OpenChamber 认证:`packages/web/server/lib/ui-auth/ui-auth.js`(`/auth/session`、限流、信任设备)
|
||||
- 设备 token:`packages/web/server/lib/client-auth/remote-clients.js`、`pairing.js`
|
||||
- `/api/*` 反代与 `/health`:`packages/web/server/lib/opencode/{proxy,core-routes,routes}.js`
|
||||
- 真实客户端调用:`packages/ui/src/lib/opencode/client.ts`(`x-opencode-directory`、prompt / interrupt / permission 参数)
|
||||
- 现有移动端连接流程:`packages/ui/src/apps/mobileConnections.ts`
|
||||
- opencode v2 协议:`~/.bun/install/global/node_modules/@opencode/{protocol,schema}/dist`
|
||||
- asuka 源码:`~/go/pkg/mod/github.com/egoist/asuka@v0.1.2-0.20261114215826-2602a98fec66`
|
||||
(`examples/chat/main.go` 是聊天列表 + composer 的现成范例;`sdk/markdown` 是流式 Markdown)
|
||||
@@ -0,0 +1,72 @@
|
||||
# OpenChamber Native
|
||||
|
||||
A lightweight OpenChamber client for phones, written in Go with
|
||||
[Asuka](https://asuka.egoist.dev/)'s native widgets. Android first.
|
||||
|
||||
Status: M0–M3 done, M4 in progress — connect (password / passwordless, HTTP or
|
||||
SOCKS5 proxy, self-signed certificates), live session list, chat with streaming
|
||||
Markdown, permissions, archive/delete/rename, and a UI-independent API client.
|
||||
|
||||
## What is here
|
||||
|
||||
| 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 |
|
||||
| `internal/storage/` | Connection settings in `asuka/sdk/store`, device token in `asuka/sdk/secure` (Android Keystore), per-install id for device dedupe |
|
||||
| `internal/appui/` | Screens: connect, sessions, chat (streaming Markdown, reasoning/tool folding, permissions) |
|
||||
| `cmd/ocprobe/` | Terminal probe used to validate the API without a device |
|
||||
| `PLAN.md` | Research, API contract, architecture, milestones, risks |
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
# terminal probe against a running server
|
||||
go run ./cmd/ocprobe -url http://127.0.0.1:3000 health
|
||||
go run ./cmd/ocprobe -url http://127.0.0.1:3000 -limit 5 sessions
|
||||
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
|
||||
|
||||
# the app on this computer (browser / GTK window)
|
||||
asuka dev --platform web
|
||||
asuka dev
|
||||
|
||||
# headless tests, including the UI
|
||||
go test ./... -race
|
||||
```
|
||||
|
||||
`asuka` must be installed from `main`; the v0.1.1 release does not build on
|
||||
Linux:
|
||||
|
||||
```bash
|
||||
go install github.com/egoist/asuka/cmd/asuka@main
|
||||
```
|
||||
|
||||
## Android
|
||||
|
||||
The SDK lives at `~/SDK/AndroidSDK`, the JDKs at `~/SDK/jdk-21` (Gradle) and
|
||||
`~/SDK/jdk-17` (the Android toolchain; registered in
|
||||
`~/.gradle/gradle.properties` via `org.gradle.java.installations.paths`).
|
||||
|
||||
```bash
|
||||
export ANDROID_HOME=$HOME/SDK/AndroidSDK
|
||||
export JAVA_HOME=$HOME/SDK/jdk-21
|
||||
export PATH=$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$JAVA_HOME/bin:$PATH
|
||||
|
||||
asuka dev --platform android --device emulator-5554 # hot reload
|
||||
asuka dev --platform android --once --no-vet # build in, launch once
|
||||
|
||||
# release: a keystore is required
|
||||
export ASUKA_KEYSTORE=$HOME/SDK/test-upload.jks ASUKA_KEY_ALIAS=upload
|
||||
export ASUKA_KEYSTORE_PASSWORD=… ASUKA_KEY_PASSWORD=…
|
||||
asuka build --platform android # dist/OpenChamber.aab
|
||||
```
|
||||
|
||||
`netcfg/` is a native module whose only job is the Android manifest: it merges
|
||||
`android:usesCleartextTraffic="true"` into **release** builds too, because
|
||||
self-hosted OpenChamber servers are often plain HTTP on a LAN. Asuka enables it
|
||||
for debug only. Delete the package (and its blank import in `main.go`) to
|
||||
require HTTPS everywhere.
|
||||
|
||||
Proxies are entered as `http://host:port` or `socks5://host:port`
|
||||
(no proxy authentication). Plain `http://` works in debug builds; the release
|
||||
cleartext policy is decided in M5 (see `PLAN.md`).
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "OpenChamber",
|
||||
"id": "com.openchamber.native",
|
||||
"version": "0.1.0",
|
||||
"build": 1,
|
||||
"orientations": ["portrait", "landscape"]
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
// 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 "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
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
module github.com/openchamber/openchamber-native
|
||||
|
||||
go 1.26.3
|
||||
|
||||
require (
|
||||
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66
|
||||
golang.org/x/net v0.62.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/ebitengine/purego v0.11.2 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=
|
||||
github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
|
||||
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66 h1:jhKkamv03qrVjkWGz0vmZtWVoX1sXBF/xOCuG0vNQOc=
|
||||
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66/go.mod h1:BDM4nmtZiJ7SqoPnagKW2z5vHAus2Y4Mllg0NtBaKVo=
|
||||
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
|
||||
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.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=
|
||||
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
|
||||
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
@@ -0,0 +1,779 @@
|
||||
package appui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/asuka/colors"
|
||||
"github.com/egoist/asuka/fonts"
|
||||
"github.com/egoist/asuka/sdk/markdown"
|
||||
"github.com/egoist/asuka/signal"
|
||||
"github.com/egoist/asuka/ui"
|
||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||
)
|
||||
|
||||
// chatItem is one row of the chat list: a whole message, or one part of an
|
||||
// assistant message. Splitting parts into rows keeps every row's structure
|
||||
// fixed, which the list's recycled cells require.
|
||||
type chatItem struct {
|
||||
Key string
|
||||
Kind string // user | thinking | text | reasoning | tool | shell | note
|
||||
MsgID string
|
||||
Part int
|
||||
}
|
||||
|
||||
// chat is one open session: its messages, its event projection and its
|
||||
// composer.
|
||||
type chat struct {
|
||||
c *controller
|
||||
id string
|
||||
dir string
|
||||
nav *ui.Navigator
|
||||
open bool
|
||||
|
||||
title *signal.Signal[string]
|
||||
msgs *signal.Signal[[]ocapi.Message]
|
||||
byID *signal.Signal[map[string]ocapi.Message]
|
||||
running *signal.Signal[bool]
|
||||
loading *signal.Signal[bool]
|
||||
draft *signal.Signal[string]
|
||||
expanded *signal.Signal[map[string]bool]
|
||||
errText *signal.Signal[string]
|
||||
|
||||
olderCursor string
|
||||
hasMore bool
|
||||
|
||||
textSlots map[string]map[int]int
|
||||
reasoningSlots map[string]map[int]int
|
||||
reloadScheduled bool
|
||||
listNode ui.Node
|
||||
}
|
||||
|
||||
func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
|
||||
dir := ""
|
||||
if s.Location != nil {
|
||||
dir = s.Location.Directory
|
||||
}
|
||||
ch := &chat{
|
||||
c: c,
|
||||
id: s.ID,
|
||||
dir: dir,
|
||||
nav: nav,
|
||||
open: true,
|
||||
title: signal.New(s.Title),
|
||||
msgs: signal.NewFunc([]ocapi.Message{}, nil),
|
||||
byID: signal.NewFunc(map[string]ocapi.Message{}, nil),
|
||||
running: signal.New(c.active.Peek()[s.ID]),
|
||||
loading: signal.New(false),
|
||||
draft: signal.New(""),
|
||||
expanded: signal.NewFunc(map[string]bool{}, nil),
|
||||
errText: signal.New(""),
|
||||
textSlots: map[string]map[int]int{},
|
||||
reasoningSlots: map[string]map[int]int{},
|
||||
}
|
||||
c.chat = ch
|
||||
ch.load()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (ch *chat) client() *ocapi.Client { return ch.c.client }
|
||||
|
||||
func (ch *chat) load() {
|
||||
client := ch.client()
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
ch.loading.Set(true)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
||||
Directory: ch.dir, Limit: 30, Order: "desc",
|
||||
})
|
||||
ui.Post(func() {
|
||||
ch.loading.Set(false)
|
||||
if err != nil {
|
||||
if ocapi.IsUnauthorized(err) {
|
||||
ch.c.logout("登录已失效,请输入密码重新连接")
|
||||
return
|
||||
}
|
||||
ch.errText.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
ch.olderCursor = page.Cursor.Next
|
||||
ch.hasMore = page.Cursor.Next != ""
|
||||
ch.setMessages(ascending(page.Data))
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func (ch *chat) loadOlder() {
|
||||
if !ch.hasMore || ch.loading.Peek() || ch.olderCursor == "" {
|
||||
return
|
||||
}
|
||||
client := ch.client()
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
ch.loading.Set(true)
|
||||
cursor := ch.olderCursor
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
||||
Directory: ch.dir, Limit: 30, Cursor: cursor,
|
||||
})
|
||||
ui.Post(func() {
|
||||
ch.loading.Set(false)
|
||||
if err != nil {
|
||||
ch.errText.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
older := ascending(page.Data)
|
||||
ch.olderCursor = page.Cursor.Next
|
||||
ch.hasMore = page.Cursor.Next != ""
|
||||
ch.setMessages(append(older, ch.msgs.Peek()...))
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// reloadTail refetches the newest messages and replaces the tail, which is
|
||||
// how tool state and turn boundaries become authoritative.
|
||||
func (ch *chat) reloadTail() {
|
||||
client := ch.client()
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
|
||||
Directory: ch.dir, Limit: 30, Order: "desc",
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tail := ascending(page.Data)
|
||||
ui.Post(func() {
|
||||
ch.reloadScheduled = false
|
||||
if len(tail) == 0 {
|
||||
return
|
||||
}
|
||||
cutoff := tail[0].Time.Created
|
||||
keep := make([]ocapi.Message, 0, len(ch.msgs.Peek())+len(tail))
|
||||
for _, m := range ch.msgs.Peek() {
|
||||
if m.Time.Created < cutoff {
|
||||
keep = append(keep, m)
|
||||
}
|
||||
}
|
||||
ch.setMessages(append(keep, tail...))
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// scheduleReload coalesces the many events a tool call produces.
|
||||
func (ch *chat) scheduleReload() {
|
||||
if ch.reloadScheduled {
|
||||
return
|
||||
}
|
||||
ch.reloadScheduled = true
|
||||
time.AfterFunc(300*time.Millisecond, func() {
|
||||
ui.Post(func() {
|
||||
if ch.open {
|
||||
ch.reloadTail()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func (ch *chat) send() {
|
||||
text := strings.TrimSpace(ch.draft.Peek())
|
||||
if text == "" || ch.client() == nil {
|
||||
return
|
||||
}
|
||||
id := newMessageID()
|
||||
ch.draft.Set("")
|
||||
ch.errText.Set("")
|
||||
ch.running.Set(true)
|
||||
ch.addMessage(ocapi.Message{
|
||||
ID: id,
|
||||
Type: "user",
|
||||
Text: text,
|
||||
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
|
||||
})
|
||||
client := ch.client()
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||
defer cancel()
|
||||
err := client.Prompt(ctx, ch.id, ocapi.PromptOptions{Directory: ch.dir, Text: text, MessageID: id})
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
ui.Post(func() {
|
||||
ch.running.Set(false)
|
||||
if ocapi.IsUnauthorized(err) {
|
||||
ch.c.logout("登录已失效,请输入密码重新连接")
|
||||
return
|
||||
}
|
||||
ch.errText.Set(friendlyError(err))
|
||||
})
|
||||
}()
|
||||
ui.ScrollToEnd(ch.listNode, true)
|
||||
}
|
||||
|
||||
func (ch *chat) stop() {
|
||||
client := ch.client()
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
_, err := client.Interrupt(ctx, ch.id, ch.dir)
|
||||
ui.Post(func() {
|
||||
if err != nil {
|
||||
ch.errText.Set(friendlyError(err))
|
||||
}
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// handleEvent runs on the main thread, routed by the controller's stream.
|
||||
func (ch *chat) handleEvent(ev ocapi.Event) {
|
||||
switch ev.Type {
|
||||
case "session.execution.started":
|
||||
ch.running.Set(true)
|
||||
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
|
||||
ch.running.Set(false)
|
||||
ch.scheduleReload()
|
||||
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.Set(true)
|
||||
case "session.step.ended", "session.step.failed":
|
||||
ch.scheduleReload()
|
||||
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.scheduleReload()
|
||||
}
|
||||
}
|
||||
|
||||
type deltaData struct {
|
||||
AssistantMessageID string `json:"assistantMessageID"`
|
||||
Ordinal int `json:"ordinal"`
|
||||
Delta string `json:"delta"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
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.Peek()[id]; ok {
|
||||
return
|
||||
}
|
||||
ch.addMessage(ocapi.Message{ID: id, Type: "assistant", Time: ocapi.MessageTime{Created: created}})
|
||||
}
|
||||
|
||||
func (ch *chat) addMessage(m ocapi.Message) {
|
||||
list := ch.msgs.Peek()
|
||||
next := make([]ocapi.Message, len(list), len(list)+1)
|
||||
copy(next, list)
|
||||
next = append(next, m)
|
||||
sort.SliceStable(next, func(i, j int) bool {
|
||||
if next[i].Time.Created == next[j].Time.Created {
|
||||
return next[i].ID < next[j].ID
|
||||
}
|
||||
return next[i].Time.Created < next[j].Time.Created
|
||||
})
|
||||
ch.setMessages(next)
|
||||
}
|
||||
|
||||
func (ch *chat) updateMessage(id string, fn func(*ocapi.Message)) {
|
||||
list := ch.msgs.Peek()
|
||||
next := make([]ocapi.Message, len(list))
|
||||
copy(next, list)
|
||||
for i := range next {
|
||||
if next[i].ID == id {
|
||||
fn(&next[i])
|
||||
break
|
||||
}
|
||||
}
|
||||
ch.setMessages(next)
|
||||
}
|
||||
|
||||
// setMessages publishes a new transcript: the rows read byID, the list reads
|
||||
// the ordered slice. Duplicates (a page overlapping the loaded tail) are
|
||||
// dropped by id, the later copy winning.
|
||||
func (ch *chat) setMessages(list []ocapi.Message) {
|
||||
sort.SliceStable(list, func(i, j int) bool {
|
||||
if list[i].Time.Created == list[j].Time.Created {
|
||||
return list[i].ID < list[j].ID
|
||||
}
|
||||
return list[i].Time.Created < list[j].Time.Created
|
||||
})
|
||||
index := make(map[string]ocapi.Message, len(list))
|
||||
out := list[:0]
|
||||
for _, m := range list {
|
||||
if _, ok := index[m.ID]; ok {
|
||||
continue
|
||||
}
|
||||
index[m.ID] = m
|
||||
out = append(out, m)
|
||||
}
|
||||
ch.msgs.Set(out)
|
||||
ch.byID.Set(index)
|
||||
}
|
||||
|
||||
func (ch *chat) toggle(key string) {
|
||||
cur := ch.expanded.Peek()
|
||||
next := make(map[string]bool, len(cur)+1)
|
||||
for k, v := range cur {
|
||||
next[k] = v
|
||||
}
|
||||
next[key] = !cur[key]
|
||||
ch.expanded.Set(next)
|
||||
}
|
||||
|
||||
func (ch *chat) close() {
|
||||
ch.open = false
|
||||
if ch.c.chat == ch {
|
||||
ch.c.chat = nil
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rendering
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (ch *chat) screen() ui.Node {
|
||||
signal.OnCleanup(ch.close)
|
||||
ch.listNode = ui.List(ui.ListProps{
|
||||
Appearance: ui.ListBare,
|
||||
Anchor: ui.AnchorBottom,
|
||||
OnStartReached: ch.loadOlder,
|
||||
}, ch.items(), func(it chatItem) string { return it.Key }, ch.itemRow)
|
||||
|
||||
return ui.SafeArea(ui.Style{Grow: 1},
|
||||
ui.Column(ui.Style{Grow: 1},
|
||||
ui.Show(signal.Func(func() bool { return ch.errText.Get() != "" }), func() ui.Node {
|
||||
return ui.Text(ch.errText, ui.Style{Color: colors.Red, Font: fonts.Footnote,
|
||||
Padding: ui.Symmetric(4, 16)})
|
||||
}),
|
||||
ui.Show(ch.loading, func() ui.Node {
|
||||
return ui.Progress(nil, ui.Style{Padding: ui.Symmetric(2, 16)})
|
||||
}),
|
||||
ch.listNode,
|
||||
ch.permissionSection(),
|
||||
ch.composer(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// perms are the pending permission requests for this session.
|
||||
func (ch *chat) perms() signal.Accessor[[]ocapi.PermissionRequest] {
|
||||
return signal.Func(func() []ocapi.PermissionRequest {
|
||||
var out []ocapi.PermissionRequest
|
||||
for _, p := range ch.c.perms.Get() {
|
||||
if p.SessionID == ch.id {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
})
|
||||
}
|
||||
|
||||
func (ch *chat) permissionSection() ui.Node {
|
||||
list := ch.perms()
|
||||
shown := signal.Func(func() bool { return len(list.Get()) > 0 })
|
||||
return ui.Show(shown, func() ui.Node {
|
||||
return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(6, 12)},
|
||||
ui.For(list, func(p ocapi.PermissionRequest) string { return p.ID },
|
||||
func(p signal.Accessor[ocapi.PermissionRequest], _ signal.Accessor[int]) ui.Node {
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Gap: 8, Padding: ui.Symmetric(10, 12),
|
||||
CornerRadius: 12, Background: colors.SecondaryBackground}},
|
||||
ui.Text(signal.Func(func() string { return "需要权限:" + p.Get().Action }),
|
||||
ui.Style{Font: fonts.Footnote.Weighted(fonts.Semibold)}),
|
||||
ui.Show(signal.Func(func() bool { return strings.Join(p.Get().Resources, ", ") != "" }),
|
||||
func() ui.Node {
|
||||
return ui.Text(signal.Func(func() string {
|
||||
return strings.Join(p.Get().Resources, ", ")
|
||||
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
|
||||
}),
|
||||
ui.Row(ui.Style{Gap: 8, Wrap: true},
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("允许一次"), Variant: ui.ButtonTinted,
|
||||
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionOnce) }}),
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("总是允许"), Variant: ui.ButtonTinted,
|
||||
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionAlways) }}),
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("拒绝"), Variant: ui.ButtonGray,
|
||||
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionReject) }}),
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDecision) {
|
||||
client := ch.client()
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
err := client.ReplyPermission(ctx, req.SessionID, req.ID, decision, "")
|
||||
ui.Post(func() {
|
||||
if err != nil {
|
||||
ch.errText.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
list := ch.c.perms.Peek()
|
||||
next := make([]ocapi.PermissionRequest, 0, len(list))
|
||||
for _, p := range list {
|
||||
if p.ID != req.ID {
|
||||
next = append(next, p)
|
||||
}
|
||||
}
|
||||
ch.c.perms.Set(next)
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func (ch *chat) composer() ui.Node {
|
||||
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignEnd, Padding: ui.Symmetric(8, 12)},
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: ch.draft,
|
||||
Placeholder: ui.Val("发消息…"),
|
||||
Multiline: true,
|
||||
Style: ui.Style{Grow: 1, Lines: 5},
|
||||
}),
|
||||
ui.Show(ch.running,
|
||||
func() ui.Node {
|
||||
return ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("停止"),
|
||||
Variant: ui.ButtonGray,
|
||||
OnPress: ch.stop,
|
||||
})
|
||||
},
|
||||
func() ui.Node {
|
||||
return ui.Button(ui.ButtonProps{
|
||||
Icon: ui.IconSend,
|
||||
Label: ui.Val("发送"),
|
||||
Variant: ui.ButtonFilled,
|
||||
Disabled: signal.Func(func() bool { return strings.TrimSpace(ch.draft.Get()) == "" }),
|
||||
OnPress: ch.send,
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// items derives the list's rows: one per message, or per assistant part.
|
||||
func (ch *chat) items() signal.Accessor[[]chatItem] {
|
||||
return signal.Func(func() []chatItem {
|
||||
msgs := ch.msgs.Get()
|
||||
out := make([]chatItem, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
switch m.Type {
|
||||
case "user":
|
||||
out = append(out, chatItem{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
|
||||
case "assistant":
|
||||
if len(m.Content) == 0 {
|
||||
if m.Time.Completed == 0 {
|
||||
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
|
||||
}
|
||||
continue
|
||||
}
|
||||
for i, p := range m.Content {
|
||||
kind := p.Type
|
||||
switch kind {
|
||||
case "text", "reasoning":
|
||||
case "tool":
|
||||
default:
|
||||
continue
|
||||
}
|
||||
out = append(out, chatItem{
|
||||
Key: fmt.Sprintf("a/%s/%s/%d", m.ID, kind, i),
|
||||
Kind: kind,
|
||||
MsgID: m.ID,
|
||||
Part: i,
|
||||
})
|
||||
}
|
||||
case "shell":
|
||||
out = append(out, chatItem{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
|
||||
case "system", "synthetic", "skill", "compaction":
|
||||
if strings.TrimSpace(m.Text) != "" {
|
||||
out = append(out, chatItem{Key: "n/" + m.ID, Kind: "note", MsgID: m.ID})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
})
|
||||
}
|
||||
|
||||
func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui.Node {
|
||||
// The row's structure follows the item's kind, which changes only when
|
||||
// a recycled cell is bound to another item.
|
||||
return ui.Dynamic(func() ui.Node {
|
||||
cur := it.Get()
|
||||
switch cur.Kind {
|
||||
case "user":
|
||||
return ui.Row(ui.Style{Justify: ui.JustifyEnd, Padding: ui.Symmetric(4, 12)},
|
||||
ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 12), CornerRadius: 16,
|
||||
MaxWidth: ui.Pct(80), Background: colors.Accent}},
|
||||
ui.Text(ch.textOf(cur.MsgID), ui.Style{Color: colors.OnAccent}),
|
||||
),
|
||||
)
|
||||
case "thinking":
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
|
||||
ui.StaticText("正在思考…", ui.Style{Color: colors.SecondaryLabel, Font: fonts.Footnote}),
|
||||
)
|
||||
case "text":
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
|
||||
markdown.View(markdown.Props{
|
||||
Text: ch.partText(cur.MsgID, cur.Part),
|
||||
Streaming: ch.streaming(cur.MsgID),
|
||||
}),
|
||||
)
|
||||
case "reasoning":
|
||||
return ch.reasoningRow(cur)
|
||||
case "tool":
|
||||
return ch.toolRow(cur)
|
||||
case "shell":
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
|
||||
ui.Text(ch.shellText(cur.MsgID), ui.Style{Font: codeFont(), Color: colors.SecondaryLabel}),
|
||||
)
|
||||
case "note":
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
|
||||
ui.Text(ch.textOf(cur.MsgID), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||
)
|
||||
}
|
||||
return ui.View(ui.ViewProps{})
|
||||
})
|
||||
}
|
||||
|
||||
func (ch *chat) reasoningRow(cur chatItem) ui.Node {
|
||||
key := fmt.Sprintf("reason/%s/%d", cur.MsgID, cur.Part)
|
||||
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
|
||||
label := signal.Func(func() string {
|
||||
n := len([]rune(ch.partTextValue(cur.MsgID, cur.Part)))
|
||||
head := fmt.Sprintf("思考过程(%d 字)", n)
|
||||
if open.Get() {
|
||||
return "▾ " + head
|
||||
}
|
||||
return "▸ " + head
|
||||
})
|
||||
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
|
||||
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
|
||||
ui.Text(label, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||
),
|
||||
ui.Show(open, func() ui.Node {
|
||||
return ui.Text(ch.partText(cur.MsgID, cur.Part),
|
||||
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
func (ch *chat) toolRow(cur chatItem) ui.Node {
|
||||
key := fmt.Sprintf("tool/%s/%d", cur.MsgID, cur.Part)
|
||||
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
|
||||
part := ch.partAccessor(cur.MsgID, cur.Part)
|
||||
status := signal.Func(func() string {
|
||||
p := part.Get()
|
||||
if p.State == nil {
|
||||
return ""
|
||||
}
|
||||
return p.State.Status
|
||||
})
|
||||
headline := signal.Func(func() string {
|
||||
p := part.Get()
|
||||
icon := "●"
|
||||
switch status.Get() {
|
||||
case "running", "streaming":
|
||||
icon = "◌"
|
||||
case "completed":
|
||||
icon = "✓"
|
||||
case "error":
|
||||
icon = "✕"
|
||||
}
|
||||
mark := "▸"
|
||||
if open.Get() {
|
||||
mark = "▾"
|
||||
}
|
||||
return fmt.Sprintf("%s %s %s", icon, strings.TrimSpace(p.Name+" "+toolSummary(p)), mark)
|
||||
})
|
||||
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
|
||||
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
|
||||
ui.Text(headline, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2}),
|
||||
),
|
||||
ui.Show(open, func() ui.Node {
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 10), CornerRadius: 8,
|
||||
Background: colors.SecondaryBackground, Gap: 8}},
|
||||
ui.Text(signal.Func(func() string {
|
||||
p := part.Get()
|
||||
if p.State == nil {
|
||||
return ""
|
||||
}
|
||||
buf, _ := json.MarshalIndent(p.State.Input, "", " ")
|
||||
return string(buf)
|
||||
}), ui.Style{Font: codeFont()}),
|
||||
ui.Text(signal.Func(func() string { return toolOutput(part.Get()) }), ui.Style{Font: codeFont()}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Value helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (ch *chat) msg(id string) ocapi.Message { return ch.byID.Get()[id] }
|
||||
|
||||
func (ch *chat) textOf(id string) signal.Accessor[string] {
|
||||
return signal.Func(func() string { return ch.byID.Get()[id].Text })
|
||||
}
|
||||
|
||||
func (ch *chat) partAccessor(id string, index int) signal.Accessor[ocapi.ContentPart] {
|
||||
return signal.Func(func() ocapi.ContentPart {
|
||||
m := ch.byID.Get()[id]
|
||||
if index < 0 || index >= len(m.Content) {
|
||||
return ocapi.ContentPart{}
|
||||
}
|
||||
return m.Content[index]
|
||||
})
|
||||
}
|
||||
|
||||
func (ch *chat) partText(id string, index int) signal.Accessor[string] {
|
||||
return signal.Func(func() string { return ch.partTextValue(id, index) })
|
||||
}
|
||||
|
||||
func (ch *chat) partTextValue(id string, index int) string {
|
||||
m := ch.byID.Get()[id]
|
||||
if index < 0 || index >= len(m.Content) {
|
||||
return ""
|
||||
}
|
||||
return m.Content[index].Text
|
||||
}
|
||||
|
||||
func (ch *chat) streaming(id string) signal.Accessor[bool] {
|
||||
return signal.Func(func() bool {
|
||||
m := ch.byID.Get()[id]
|
||||
return m.Time.Completed == 0
|
||||
})
|
||||
}
|
||||
|
||||
func (ch *chat) shellText(id string) signal.Accessor[string] {
|
||||
return signal.Func(func() string {
|
||||
m := ch.byID.Get()[id]
|
||||
out := "$ " + m.Command
|
||||
if strings.TrimSpace(m.Output) != "" {
|
||||
out += "\n" + m.Output
|
||||
}
|
||||
return out
|
||||
})
|
||||
}
|
||||
|
||||
func toolSummary(p ocapi.ContentPart) string {
|
||||
if p.State == nil {
|
||||
return ""
|
||||
}
|
||||
for _, k := range []string{"command", "filePath", "pattern", "path", "description", "query"} {
|
||||
if v, ok := p.State.Input[k].(string); ok && strings.TrimSpace(v) != "" {
|
||||
return firstLine(v)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func toolOutput(p ocapi.ContentPart) string {
|
||||
if p.State == nil {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, c := range p.State.Content {
|
||||
if c.Type == "text" && c.Text != "" {
|
||||
if b.Len() > 0 {
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
b.WriteString(c.Text)
|
||||
}
|
||||
}
|
||||
out := b.String()
|
||||
if len(out) > 4000 {
|
||||
out = out[:4000] + "\n…"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func firstLine(s string) string {
|
||||
if i := strings.IndexByte(s, '\n'); i >= 0 {
|
||||
return s[:i]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func codeFont() fonts.Font { return fonts.Custom("monospace", fonts.Footnote) }
|
||||
|
||||
func ascending(list []ocapi.Message) []ocapi.Message {
|
||||
out := make([]ocapi.Message, len(list))
|
||||
for i, m := range list {
|
||||
out[len(list)-1-i] = m
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func newMessageID() string {
|
||||
var b [8]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return "msg_" + fmt.Sprint(time.Now().UnixMilli()) + hex.EncodeToString(b[:])
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package appui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/asuka/ui"
|
||||
"github.com/egoist/asuka/uitest"
|
||||
)
|
||||
|
||||
// chatServer serves one session with a short transcript, and records the
|
||||
// prompt a test sends.
|
||||
type chatServer struct {
|
||||
*httptest.Server
|
||||
prompts chan map[string]any
|
||||
replies chan map[string]any
|
||||
events chan string
|
||||
ready chan struct{}
|
||||
readyOne sync.Once
|
||||
}
|
||||
|
||||
func (cs *chatServer) push(ev string) {
|
||||
select {
|
||||
case cs.events <- ev:
|
||||
case <-time.After(2 * time.Second):
|
||||
panic("event stream is not consuming")
|
||||
}
|
||||
}
|
||||
|
||||
func newChatServer(t *testing.T) *chatServer {
|
||||
t.Helper()
|
||||
cs := &chatServer{
|
||||
prompts: make(chan map[string]any, 1),
|
||||
replies: make(chan map[string]any, 1),
|
||||
events: make(chan string, 8),
|
||||
ready: make(chan struct{}),
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true}`)
|
||||
})
|
||||
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
|
||||
})
|
||||
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"First session","time":{"created":1,"updated":2},
|
||||
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"data":{}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"data":[]}`)
|
||||
})
|
||||
mux.HandleFunc("/api/session/ses_1/message", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"data":[
|
||||
{"id":"msg_1","type":"user","text":"What is this?","time":{"created":10}},
|
||||
{"id":"msg_2","type":"assistant","time":{"created":11,"completed":12},
|
||||
"content":[{"type":"text","text":"**Hello** from the agent"}]}
|
||||
],"cursor":{}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/session/ses_1/prompt", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
select {
|
||||
case cs.prompts <- body:
|
||||
default:
|
||||
}
|
||||
cs.events <- `{"id":"evt_2","created":100,"type":"session.step.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream"}}`
|
||||
cs.events <- `{"id":"evt_3","created":101,"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream","ordinal":0,"delta":"streamed"}}`
|
||||
fmt.Fprint(w, `{"data":{}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/session/ses_1/permission/per_1/reply", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
select {
|
||||
case cs.replies <- body:
|
||||
default:
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
cs.readyOne.Do(func() { close(cs.ready) })
|
||||
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case ev := <-cs.events:
|
||||
fmt.Fprintf(w, "data: %s\n\n", ev)
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
cs.Server = httptest.NewServer(mux)
|
||||
t.Cleanup(cs.Close)
|
||||
return cs
|
||||
}
|
||||
|
||||
func TestOpenSessionAndSend(t *testing.T) {
|
||||
srv := newChatServer(t)
|
||||
st := &memStore{}
|
||||
a := uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
||||
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Tap("连接")
|
||||
a.WaitFor("First session")
|
||||
select {
|
||||
case <-srv.ready:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the event stream was never opened")
|
||||
}
|
||||
|
||||
a.Tap("First session")
|
||||
a.WaitFor("Hello from the agent")
|
||||
a.Expect("What is this?")
|
||||
|
||||
a.Type("发消息…", "ping")
|
||||
a.Tap("发送")
|
||||
a.WaitFor("ping")
|
||||
a.WaitFor("streamed")
|
||||
|
||||
select {
|
||||
case body := <-srv.prompts:
|
||||
if body["text"] != "ping" {
|
||||
t.Errorf("prompt text = %v", body["text"])
|
||||
}
|
||||
if id, _ := body["id"].(string); len(id) < 5 || id[:4] != "msg_" {
|
||||
t.Errorf("prompt id = %v", body["id"])
|
||||
}
|
||||
default:
|
||||
t.Fatal("no prompt reached the server")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissionCardAndReply(t *testing.T) {
|
||||
srv := newChatServer(t)
|
||||
// The session list's pending-permission read.
|
||||
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Tap("连接")
|
||||
a.WaitFor("First session")
|
||||
select {
|
||||
case <-srv.ready:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no event stream")
|
||||
}
|
||||
|
||||
a.Tap("First session")
|
||||
a.WaitFor("Hello from the agent")
|
||||
|
||||
srv.push(`{"id":"evt_10","created":200,"type":"permission.asked","data":{"sessionID":"ses_1","id":"per_1","action":"bash","resources":["npm test"]}}`)
|
||||
a.WaitFor("需要权限:bash")
|
||||
a.Expect("npm test")
|
||||
|
||||
a.Tap("允许一次")
|
||||
select {
|
||||
case body := <-srv.replies:
|
||||
if body["decision"] != "once" {
|
||||
t.Errorf("decision = %v", body["decision"])
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("no permission reply reached the server")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package appui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/egoist/asuka/ui"
|
||||
"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"`
|
||||
}
|
||||
|
||||
// startEvents subscribes to the server's event stream for the given client.
|
||||
// It must run on the main thread (it writes the cancel function).
|
||||
func (c *controller) startEvents(client *ocapi.Client, p connectParams) {
|
||||
if c.cancelSSE != nil {
|
||||
c.cancelSSE()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
c.cancelSSE = cancel
|
||||
sub := ocapi.Subscription{
|
||||
Types: eventTypes,
|
||||
OnEvent: func(ev ocapi.Event) {
|
||||
ui.Post(func() {
|
||||
if c.client != client {
|
||||
return
|
||||
}
|
||||
c.applyEvent(ev)
|
||||
})
|
||||
},
|
||||
OnState: func(st ocapi.SubscriptionState, err error) {
|
||||
switch st {
|
||||
case ocapi.Disconnected:
|
||||
ui.Post(func() {
|
||||
if c.client != client {
|
||||
return
|
||||
}
|
||||
c.status.Set("连接中断,正在重连…")
|
||||
})
|
||||
case ocapi.Subscribed:
|
||||
// Events missed while the stream was down are gone;
|
||||
// re-read the list and the open chat's tail.
|
||||
ui.Post(func() {
|
||||
if c.client != client {
|
||||
return
|
||||
}
|
||||
c.refresh()
|
||||
if c.chat != nil {
|
||||
c.chat.reloadTail()
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
}
|
||||
go client.Subscribe(ctx, sub)
|
||||
}
|
||||
|
||||
// applyEvent folds one server event into the list state. Main thread.
|
||||
func (c *controller) applyEvent(ev ocapi.Event) {
|
||||
if c.chat != nil {
|
||||
var ref struct {
|
||||
SessionID string `json:"sessionID"`
|
||||
}
|
||||
if ev.UnmarshalData(&ref) == nil && ref.SessionID == c.chat.id {
|
||||
c.chat.handleEvent(ev)
|
||||
}
|
||||
}
|
||||
switch ev.Type {
|
||||
case "session.created":
|
||||
var d sessionCreatedData
|
||||
if ev.UnmarshalData(&d) != nil || d.SessionID == "" {
|
||||
return
|
||||
}
|
||||
list := c.sessions.Peek()
|
||||
for _, s := range list {
|
||||
if s.ID == d.SessionID {
|
||||
return
|
||||
}
|
||||
}
|
||||
next := make([]ocapi.Session, 0, len(list)+1)
|
||||
next = append(next, 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},
|
||||
})
|
||||
c.sessions.Set(append(next, list...))
|
||||
|
||||
case "session.renamed":
|
||||
var d sessionRenamedData
|
||||
if ev.UnmarshalData(&d) != nil {
|
||||
return
|
||||
}
|
||||
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Title = d.Title })
|
||||
|
||||
case "session.model.selected":
|
||||
var d sessionModelData
|
||||
if ev.UnmarshalData(&d) != nil {
|
||||
return
|
||||
}
|
||||
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Model = d.Model })
|
||||
|
||||
case "session.agent.selected":
|
||||
var d sessionAgentData
|
||||
if ev.UnmarshalData(&d) != nil {
|
||||
return
|
||||
}
|
||||
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Agent = d.Agent })
|
||||
|
||||
case "session.archived":
|
||||
var d sessionRefData
|
||||
if ev.UnmarshalData(&d) != nil {
|
||||
return
|
||||
}
|
||||
c.removeSession(d.SessionID)
|
||||
|
||||
case "session.deleted":
|
||||
var d sessionRefData
|
||||
if ev.UnmarshalData(&d) != nil {
|
||||
return
|
||||
}
|
||||
c.removeSession(d.SessionID)
|
||||
|
||||
case "session.unarchived", "session.moved":
|
||||
// The event carries no full record; a list read is the truth.
|
||||
c.refresh()
|
||||
|
||||
case "session.execution.started":
|
||||
var d sessionRefData
|
||||
if ev.UnmarshalData(&d) != nil {
|
||||
return
|
||||
}
|
||||
c.setActive(d.SessionID, true)
|
||||
|
||||
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
|
||||
var d sessionRefData
|
||||
if ev.UnmarshalData(&d) != nil {
|
||||
return
|
||||
}
|
||||
c.setActive(d.SessionID, false)
|
||||
|
||||
case "permission.asked":
|
||||
var d permissionData
|
||||
if ev.UnmarshalData(&d) != nil || d.ID == "" {
|
||||
return
|
||||
}
|
||||
list := c.perms.Peek()
|
||||
for _, p := range list {
|
||||
if p.ID == d.ID {
|
||||
return
|
||||
}
|
||||
}
|
||||
next := make([]ocapi.PermissionRequest, len(list), len(list)+1)
|
||||
copy(next, list)
|
||||
next = append(next, ocapi.PermissionRequest{
|
||||
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
|
||||
})
|
||||
c.perms.Set(next)
|
||||
|
||||
case "permission.replied":
|
||||
var d struct {
|
||||
RequestID string `json:"requestID"`
|
||||
}
|
||||
if ev.UnmarshalData(&d) != nil || d.RequestID == "" {
|
||||
return
|
||||
}
|
||||
list := c.perms.Peek()
|
||||
next := make([]ocapi.PermissionRequest, 0, len(list))
|
||||
for _, p := range list {
|
||||
if p.ID != d.RequestID {
|
||||
next = append(next, p)
|
||||
}
|
||||
}
|
||||
if len(next) != len(list) {
|
||||
c.perms.Set(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *controller) patchSession(id string, patch func(*ocapi.Session)) {
|
||||
list := c.sessions.Peek()
|
||||
next := make([]ocapi.Session, len(list))
|
||||
copy(next, list)
|
||||
for i := range next {
|
||||
if next[i].ID == id {
|
||||
patch(&next[i])
|
||||
c.sessions.Set(next)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *controller) removeSession(id string) {
|
||||
list := c.sessions.Peek()
|
||||
next := make([]ocapi.Session, 0, len(list))
|
||||
for _, s := range list {
|
||||
if s.ID != id {
|
||||
next = append(next, s)
|
||||
}
|
||||
}
|
||||
if len(next) != len(list) {
|
||||
c.sessions.Set(next)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *controller) setActive(id string, on bool) {
|
||||
cur := c.active.Peek()
|
||||
if cur[id] == on {
|
||||
return
|
||||
}
|
||||
next := make(map[string]bool, len(cur)+1)
|
||||
for k, v := range cur {
|
||||
next[k] = v
|
||||
}
|
||||
if on {
|
||||
next[id] = true
|
||||
} else {
|
||||
delete(next, id)
|
||||
}
|
||||
c.active.Set(next)
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
// Package appui holds the OpenChamber screens and their state.
|
||||
package appui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/asuka/signal"
|
||||
"github.com/egoist/asuka/ui"
|
||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||
"github.com/openchamber/openchamber-native/internal/storage"
|
||||
)
|
||||
|
||||
// Root is the app's root component.
|
||||
func Root() ui.Node {
|
||||
return rootWithStore(storage.New())
|
||||
}
|
||||
|
||||
func rootWithStore(st storage.Store) ui.Node {
|
||||
_, node := newApp(st)
|
||||
return node
|
||||
}
|
||||
|
||||
func newApp(st storage.Store) (*controller, ui.Node) {
|
||||
c := newController(st)
|
||||
signal.OnCleanup(c.shutdown)
|
||||
node := ui.Stack(c.screen, ui.ScreenOptions{
|
||||
Title: ui.Val("OpenChamber"),
|
||||
Actions: []ui.Action{{
|
||||
Title: ui.Val("刷新"),
|
||||
Icon: ui.IconRefresh,
|
||||
Disabled: signal.Func(func() bool { return !c.connected.Get() || c.busy.Get() }),
|
||||
OnPress: c.refresh,
|
||||
}},
|
||||
})
|
||||
return c, node
|
||||
}
|
||||
|
||||
type controller struct {
|
||||
st storage.Store
|
||||
|
||||
url *signal.Signal[string]
|
||||
password *signal.Signal[string]
|
||||
useProxy *signal.Signal[bool]
|
||||
proxy *signal.Signal[string]
|
||||
insecure *signal.Signal[bool]
|
||||
status *signal.Signal[string]
|
||||
|
||||
server *signal.Signal[string]
|
||||
connected *signal.Signal[bool]
|
||||
busy *signal.Signal[bool]
|
||||
sessions *signal.Signal[[]ocapi.Session]
|
||||
active *signal.Signal[map[string]bool]
|
||||
perms *signal.Signal[[]ocapi.PermissionRequest]
|
||||
|
||||
client *ocapi.Client
|
||||
cancelSSE context.CancelFunc
|
||||
chat *chat
|
||||
}
|
||||
|
||||
func newController(st storage.Store) *controller {
|
||||
c := &controller{
|
||||
st: st,
|
||||
url: signal.New(""),
|
||||
password: signal.New(""),
|
||||
useProxy: signal.New(false),
|
||||
proxy: signal.New(""),
|
||||
insecure: signal.New(false),
|
||||
status: signal.New("输入服务器地址与密码后连接"),
|
||||
server: signal.New(""),
|
||||
connected: signal.New(false),
|
||||
busy: signal.New(false),
|
||||
sessions: signal.NewFunc([]ocapi.Session{}, nil),
|
||||
active: signal.NewFunc(map[string]bool{}, nil),
|
||||
perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
||||
}
|
||||
if conn, ok := st.Connection(); ok {
|
||||
c.url.Set(conn.URL)
|
||||
c.proxy.Set(conn.Proxy)
|
||||
c.useProxy.Set(conn.Proxy != "")
|
||||
c.insecure.Set(conn.Insecure)
|
||||
c.status.Set("正在恢复连接…")
|
||||
c.reconnect(conn)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *controller) screen() ui.Node {
|
||||
return ui.SafeArea(ui.Style{Grow: 1},
|
||||
ui.Show(c.connected, c.sessionsScreen, c.connectScreen),
|
||||
)
|
||||
}
|
||||
|
||||
// shutdown stops what the controller started; the root owner calls it when
|
||||
// the app (or a test) unmounts.
|
||||
func (c *controller) shutdown() {
|
||||
if c.cancelSSE != nil {
|
||||
c.cancelSSE()
|
||||
c.cancelSSE = nil
|
||||
}
|
||||
c.client = nil
|
||||
}
|
||||
|
||||
func (c *controller) connect() {
|
||||
if c.busy.Peek() {
|
||||
return
|
||||
}
|
||||
params := connectParams{
|
||||
url: strings.TrimSpace(c.url.Peek()),
|
||||
password: c.password.Peek(),
|
||||
insecure: c.insecure.Peek(),
|
||||
explicit: true,
|
||||
}
|
||||
if c.useProxy.Peek() {
|
||||
params.proxy = strings.TrimSpace(c.proxy.Peek())
|
||||
}
|
||||
c.busy.Set(true)
|
||||
c.status.Set("连接中…")
|
||||
go func() {
|
||||
c.establish(params, "")
|
||||
}()
|
||||
}
|
||||
|
||||
// reconnect retries a stored connection, whose token lives in secure
|
||||
// storage (readable only off the main thread).
|
||||
func (c *controller) reconnect(conn storage.Connection) {
|
||||
go func() {
|
||||
token, ok, err := c.st.LoadToken(conn.URL)
|
||||
if err != nil || !ok {
|
||||
ui.Post(func() { c.status.Set("请重新输入密码") })
|
||||
return
|
||||
}
|
||||
params := connectParams{
|
||||
url: conn.URL,
|
||||
proxy: conn.Proxy,
|
||||
insecure: conn.Insecure,
|
||||
}
|
||||
c.establish(params, token)
|
||||
}()
|
||||
}
|
||||
|
||||
type connectParams struct {
|
||||
url string
|
||||
password string
|
||||
proxy string
|
||||
insecure bool
|
||||
// explicit means the user pressed Connect: a password prompt is
|
||||
// theirs to answer. A background reconnect never asks.
|
||||
explicit bool
|
||||
}
|
||||
|
||||
// establish runs the whole connect sequence off the main thread: health,
|
||||
// token probe, optional password login, first page of sessions. It reports
|
||||
// through the signals with ui.Post.
|
||||
func (c *controller) establish(p connectParams, token string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||
defer cancel()
|
||||
|
||||
fail := func(err error) {
|
||||
ui.Post(func() {
|
||||
c.busy.Set(false)
|
||||
c.status.Set(friendlyError(err))
|
||||
})
|
||||
}
|
||||
|
||||
opts := ocapi.Options{Proxy: p.proxy, InsecureSkipVerify: p.insecure}
|
||||
client, err := ocapi.New(p.url, opts)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
health, err := client.Health(ctx)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
if health.OpenChamberVersion == "" {
|
||||
fail(errors.New("这个地址不是 OpenChamber 服务器"))
|
||||
return
|
||||
}
|
||||
|
||||
passwordless := false
|
||||
if token != "" {
|
||||
client.SetToken(token)
|
||||
}
|
||||
auth, authErr := client.SessionStatus(ctx)
|
||||
switch {
|
||||
case authErr == nil:
|
||||
passwordless = auth.Disabled
|
||||
case ocapi.IsUnauthorized(authErr):
|
||||
if strings.TrimSpace(p.password) == "" {
|
||||
if token != "" {
|
||||
// The stored token is no good: drop it so the next
|
||||
// attempt does not retry with it.
|
||||
server := client.BaseURL()
|
||||
go func() { _ = c.st.ClearToken(server) }()
|
||||
}
|
||||
if p.explicit {
|
||||
fail(errUnauthorized)
|
||||
} else {
|
||||
ui.Post(func() { c.status.Set("登录已失效,请输入密码重新连接") })
|
||||
}
|
||||
return
|
||||
}
|
||||
res, err := client.Login(ctx, ocapi.LoginRequest{
|
||||
Password: p.password,
|
||||
DedupeKey: c.st.InstallID(),
|
||||
ClientLabel: "OpenChamber Native",
|
||||
ClientKind: "mobile",
|
||||
DevicePlatform: "android",
|
||||
})
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
if res.ClientToken == "" {
|
||||
fail(errors.New("登录没有返回设备 token"))
|
||||
return
|
||||
}
|
||||
if err := c.st.SaveToken(client.BaseURL(), res.ClientToken); err != nil {
|
||||
// A token that cannot be persisted still works for this run.
|
||||
_ = err
|
||||
}
|
||||
default:
|
||||
fail(authErr)
|
||||
return
|
||||
}
|
||||
|
||||
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"})
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
active, _ := client.ActiveSessions(ctx)
|
||||
running := make(map[string]bool, len(active))
|
||||
for id := range active {
|
||||
running[id] = true
|
||||
}
|
||||
perms, _ := client.PendingPermissions(ctx, "")
|
||||
|
||||
info := fmt.Sprintf("%s · OpenChamber %s", client.BaseURL(), health.OpenChamberVersion)
|
||||
if !health.IsOpenCodeReady {
|
||||
info += " · OpenCode 未就绪"
|
||||
}
|
||||
c.st.SaveConnection(storage.Connection{
|
||||
URL: client.BaseURL(),
|
||||
Proxy: p.proxy,
|
||||
Insecure: p.insecure,
|
||||
ServerID: health.ServerID,
|
||||
Passwordless: passwordless,
|
||||
})
|
||||
|
||||
ui.Post(func() {
|
||||
c.client = client
|
||||
c.sessions.Set(page.Data)
|
||||
c.active.Set(running)
|
||||
c.perms.Set(perms)
|
||||
c.server.Set(info)
|
||||
c.connected.Set(true)
|
||||
c.busy.Set(false)
|
||||
c.password.Set("")
|
||||
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
|
||||
c.startEvents(client, p)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) refresh() {
|
||||
if c.client == nil || c.busy.Peek() {
|
||||
return
|
||||
}
|
||||
c.busy.Set(true)
|
||||
client := c.client
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"})
|
||||
active, aerr := client.ActiveSessions(ctx)
|
||||
running := make(map[string]bool, len(active))
|
||||
for id := range active {
|
||||
running[id] = true
|
||||
}
|
||||
perms, perr := client.PendingPermissions(ctx, "")
|
||||
ui.Post(func() {
|
||||
c.busy.Set(false)
|
||||
if err != nil {
|
||||
if ocapi.IsUnauthorized(err) {
|
||||
c.logout("登录已失效,请输入密码重新连接")
|
||||
return
|
||||
}
|
||||
c.status.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
c.sessions.Set(page.Data)
|
||||
if aerr == nil {
|
||||
c.active.Set(running)
|
||||
}
|
||||
if perr == nil {
|
||||
c.perms.Set(perms)
|
||||
}
|
||||
c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data)))
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// logout drops the session but keeps the address so the user only types
|
||||
// the password again.
|
||||
func (c *controller) logout(reason string) {
|
||||
if c.cancelSSE != nil {
|
||||
c.cancelSSE()
|
||||
c.cancelSSE = nil
|
||||
}
|
||||
if c.client != nil {
|
||||
server := c.client.BaseURL()
|
||||
go func() { _ = c.st.ClearToken(server) }()
|
||||
}
|
||||
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
|
||||
c.chat.nav.Pop()
|
||||
}
|
||||
c.client = nil
|
||||
c.connected.Set(false)
|
||||
c.sessions.Set(nil)
|
||||
c.active.Set(map[string]bool{})
|
||||
c.perms.Set(nil)
|
||||
c.server.Set("")
|
||||
c.status.Set(reason)
|
||||
}
|
||||
|
||||
func (c *controller) disconnect() {
|
||||
c.logout("已断开")
|
||||
}
|
||||
|
||||
var errUnauthorized = errors.New("这个服务器需要密码")
|
||||
|
||||
func friendlyError(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
if wait, ok := ocapi.IsRateLimited(err); ok {
|
||||
secs := int(wait.Seconds() + 0.5)
|
||||
if secs <= 0 {
|
||||
secs = 30
|
||||
}
|
||||
return fmt.Sprintf("尝试过于频繁,请 %d 秒后重试", secs)
|
||||
}
|
||||
if ocapi.IsUnauthorized(err) {
|
||||
return "密码错误"
|
||||
}
|
||||
if errors.Is(err, errUnauthorized) {
|
||||
return "该服务器需要密码"
|
||||
}
|
||||
msg := err.Error()
|
||||
switch {
|
||||
case strings.Contains(msg, "certificate"):
|
||||
return "TLS 证书校验失败:" + msg
|
||||
case strings.Contains(msg, "no such host"):
|
||||
return "找不到这个地址:" + msg
|
||||
case strings.Contains(msg, "connection refused"):
|
||||
return "连接被拒绝,请确认服务器地址与端口"
|
||||
case strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline exceeded"):
|
||||
return "连接超时,请检查网络或代理"
|
||||
case strings.Contains(msg, "proxy"):
|
||||
return "代理连接失败:" + msg
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func shortPath(p string) string {
|
||||
p = strings.TrimRight(p, "/")
|
||||
if p == "" {
|
||||
return ""
|
||||
}
|
||||
if i := strings.LastIndex(p, "/"); i >= 0 && i+1 < len(p) {
|
||||
return p[i+1:]
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func relativeTime(ms int64) string {
|
||||
if ms <= 0 {
|
||||
return ""
|
||||
}
|
||||
d := time.Since(time.UnixMilli(ms))
|
||||
switch {
|
||||
case d < time.Minute:
|
||||
return "刚刚"
|
||||
case d < time.Hour:
|
||||
return fmt.Sprintf("%d 分钟前", int(d.Minutes()))
|
||||
case d < 24*time.Hour:
|
||||
return fmt.Sprintf("%d 小时前", int(d.Hours()))
|
||||
default:
|
||||
return fmt.Sprintf("%d 天前", int(d.Hours()/24))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package appui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/asuka/ui"
|
||||
"github.com/egoist/asuka/uitest"
|
||||
"github.com/openchamber/openchamber-native/internal/storage"
|
||||
)
|
||||
|
||||
// memStore is a storage.Store that keeps everything in memory.
|
||||
type memStore struct {
|
||||
mu sync.Mutex
|
||||
conn storage.Connection
|
||||
has bool
|
||||
tokens map[string]string
|
||||
id string
|
||||
}
|
||||
|
||||
func (m *memStore) Connection() (storage.Connection, bool) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.conn, m.has
|
||||
}
|
||||
func (m *memStore) SaveConnection(c storage.Connection) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.conn, m.has = c, c.URL != ""
|
||||
}
|
||||
func (m *memStore) ClearConnection() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.conn, m.has = storage.Connection{}, false
|
||||
}
|
||||
func (m *memStore) InstallID() string {
|
||||
if m.id == "" {
|
||||
m.id = "test-install"
|
||||
}
|
||||
return m.id
|
||||
}
|
||||
func (m *memStore) LoadToken(server string) (string, bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
t, ok := m.tokens[server]
|
||||
return t, ok, nil
|
||||
}
|
||||
func (m *memStore) SaveToken(server, token string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.tokens == nil {
|
||||
m.tokens = map[string]string{}
|
||||
}
|
||||
m.tokens[server] = token
|
||||
return nil
|
||||
}
|
||||
func (m *memStore) ClearToken(server string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.tokens, server)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) token(server string) string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.tokens[server]
|
||||
}
|
||||
|
||||
func (m *memStore) connection() storage.Connection {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.conn
|
||||
}
|
||||
|
||||
// fakeServer stands in for OpenChamber: /health, /auth/session and the
|
||||
// session list. password "" with validToken "" makes it passwordless.
|
||||
func fakeServer(t *testing.T, password, validToken string) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
authorized := func(r *http.Request) bool {
|
||||
if validToken == "" {
|
||||
return true
|
||||
}
|
||||
return r.Header.Get("Authorization") == "Bearer "+validToken
|
||||
}
|
||||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true,"serverId":"srv_1"}`)
|
||||
})
|
||||
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
|
||||
if password == "" {
|
||||
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if authorized(r) {
|
||||
fmt.Fprint(w, `{"authenticated":true,"scope":"client"}`)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
|
||||
case http.MethodPost:
|
||||
var body struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.Password != password {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
fmt.Fprint(w, `{"error":"Invalid credentials"}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, `{"authenticated":true,"clientToken":%q}`, validToken)
|
||||
}
|
||||
})
|
||||
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !authorized(r) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"data":[
|
||||
{"id":"ses_1","title":"First session","time":{"created":1,"updated":2},
|
||||
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],
|
||||
"cursor":{}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"data":[]}`)
|
||||
})
|
||||
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
<-r.Context().Done()
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func mount(t *testing.T, st *memStore) *uitest.App {
|
||||
t.Helper()
|
||||
return uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
||||
}
|
||||
|
||||
func TestConnectWithPassword(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
|
||||
st := &memStore{}
|
||||
a := mount(t, st)
|
||||
a.Expect("连接到 OpenChamber")
|
||||
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Type("密码(可选)", "secret")
|
||||
a.Tap("连接")
|
||||
a.WaitFor("First session")
|
||||
a.ExpectNo("密码(可选)")
|
||||
|
||||
if got := st.connection().URL; got != srv.URL {
|
||||
t.Errorf("connection not saved: %q", got)
|
||||
}
|
||||
if got := st.token(srv.URL); got != "oc_client_test" {
|
||||
t.Errorf("token not saved: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrongPassword(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
|
||||
a := mount(t, &memStore{})
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Type("密码(可选)", "nope")
|
||||
a.Tap("连接")
|
||||
a.WaitFor("密码错误")
|
||||
}
|
||||
|
||||
func TestAutoReconnectWithStoredToken(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
|
||||
st := &memStore{
|
||||
conn: storage.Connection{URL: srv.URL},
|
||||
has: true,
|
||||
tokens: map[string]string{srv.URL: "oc_client_test"},
|
||||
}
|
||||
a := mount(t, st)
|
||||
a.WaitFor("First session")
|
||||
a.ExpectNo("连接到 OpenChamber")
|
||||
}
|
||||
|
||||
func TestExpiredTokenAsksForPassword(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
|
||||
st := &memStore{
|
||||
conn: storage.Connection{URL: srv.URL},
|
||||
has: true,
|
||||
tokens: map[string]string{srv.URL: "revoked"},
|
||||
}
|
||||
a := mount(t, st)
|
||||
a.WaitFor("登录已失效,请输入密码重新连接")
|
||||
a.Expect("连接到 OpenChamber")
|
||||
a.Until("the revoked token to be dropped", func() bool { return st.token(srv.URL) == "" })
|
||||
}
|
||||
|
||||
func TestPasswordlessServer(t *testing.T) {
|
||||
srv := fakeServer(t, "", "")
|
||||
|
||||
st := &memStore{}
|
||||
a := mount(t, st)
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Tap("连接")
|
||||
a.WaitFor("First session")
|
||||
if got := st.connection(); !got.Passwordless {
|
||||
t.Errorf("passwordless not remembered: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package appui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/asuka/colors"
|
||||
"github.com/egoist/asuka/fonts"
|
||||
"github.com/egoist/asuka/signal"
|
||||
"github.com/egoist/asuka/ui"
|
||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||
)
|
||||
|
||||
func (c *controller) connectScreen() ui.Node {
|
||||
return ui.Scroll(
|
||||
ui.ScrollProps{
|
||||
Style: ui.Style{Grow: 1},
|
||||
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
|
||||
},
|
||||
ui.StaticText("连接到 OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
|
||||
ui.StaticText("输入正在运行的 OpenChamber 服务器地址。没有设置密码的服务器可以留空密码。",
|
||||
ui.Style{Color: colors.SecondaryLabel}),
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: c.url,
|
||||
Placeholder: ui.Val("http://192.168.1.5:3000"),
|
||||
Keyboard: ui.KeyboardURL,
|
||||
ContentType: "url",
|
||||
Autocapitalize: ui.CapitalizeNone,
|
||||
Autocorrect: ui.AutocorrectNo,
|
||||
ReturnKey: ui.ReturnNext,
|
||||
}),
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: c.password,
|
||||
Placeholder: ui.Val("密码(可选)"),
|
||||
Secure: true,
|
||||
ContentType: ui.ContentPassword,
|
||||
ReturnKey: ui.ReturnGo,
|
||||
OnSubmit: c.connect,
|
||||
}),
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||
ui.StaticText("使用代理", ui.Style{Grow: 1}),
|
||||
ui.Toggle(ui.ToggleProps{Value: c.useProxy}),
|
||||
),
|
||||
ui.Show(c.useProxy, func() ui.Node {
|
||||
return ui.TextField(ui.TextFieldProps{
|
||||
Value: c.proxy,
|
||||
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
|
||||
Keyboard: ui.KeyboardURL,
|
||||
Autocapitalize: ui.CapitalizeNone,
|
||||
Autocorrect: ui.AutocorrectNo,
|
||||
})
|
||||
}),
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
|
||||
ui.Toggle(ui.ToggleProps{Value: c.insecure}),
|
||||
),
|
||||
ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("连接"),
|
||||
Variant: ui.ButtonFilled,
|
||||
Disabled: c.busy,
|
||||
OnPress: c.connect,
|
||||
}),
|
||||
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *controller) sessionsScreen() ui.Node {
|
||||
nav := ui.UseNavigator()
|
||||
return ui.Column(ui.Style{Grow: 1},
|
||||
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 8, Align: ui.AlignCenter},
|
||||
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1, Grow: 1}),
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("断开"), Variant: ui.ButtonPlain, OnPress: c.disconnect}),
|
||||
),
|
||||
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
|
||||
func() ui.Node {
|
||||
return ui.Column(ui.Style{Padding: ui.All(20), Gap: 8},
|
||||
ui.StaticText("还没有会话", ui.Style{Font: fonts.Headline}),
|
||||
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
|
||||
)
|
||||
}),
|
||||
ui.List(ui.ListProps{
|
||||
Appearance: ui.ListPlain,
|
||||
OnRefresh: c.refresh,
|
||||
Refreshing: c.busy,
|
||||
SwipeActions: func(i int) []ui.Action {
|
||||
sess := c.sessions.Peek()[i]
|
||||
return []ui.Action{{Title: ui.Val("归档"), Icon: "archivebox",
|
||||
OnPress: func() { c.archiveSession(sess) }}}
|
||||
},
|
||||
LeadingSwipeActions: func(i int) []ui.Action {
|
||||
sess := c.sessions.Peek()[i]
|
||||
return []ui.Action{{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
|
||||
OnPress: func() { c.confirmDelete(sess) }}}
|
||||
},
|
||||
}, c.sessions, func(s ocapi.Session) string { return s.ID },
|
||||
func(s signal.Accessor[ocapi.Session], idx signal.Accessor[int]) ui.Node {
|
||||
return ui.View(ui.ViewProps{
|
||||
OnPress: func() {
|
||||
sess := s.Get()
|
||||
ch := c.openChat(&sess, nav)
|
||||
nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title})
|
||||
},
|
||||
OnLongPress: func() { c.sessionMenu(s.Get()) },
|
||||
}, c.sessionRow(s, idx))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *controller) sessionRow(s signal.Accessor[ocapi.Session], _ signal.Accessor[int]) ui.Node {
|
||||
return ui.Row(ui.Style{Gap: 10, Padding: ui.Symmetric(10, 16), Align: ui.AlignCenter},
|
||||
ui.Show(signal.Func(func() bool { return c.active.Get()[s.Get().ID] }),
|
||||
func() ui.Node {
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
|
||||
CornerRadius: 4, Background: colors.Accent}})
|
||||
}),
|
||||
ui.Column(ui.Style{Gap: 3, Grow: 1},
|
||||
ui.Text(signal.Func(func() string {
|
||||
if t := strings.TrimSpace(s.Get().Title); t != "" {
|
||||
return t
|
||||
}
|
||||
return "(未命名会话)"
|
||||
}), ui.Style{Font: fonts.Headline, Lines: 2}),
|
||||
ui.Text(signal.Func(func() string {
|
||||
sess := s.Get()
|
||||
dir := ""
|
||||
if sess.Location != nil {
|
||||
dir = sess.Location.Directory
|
||||
}
|
||||
updated := sess.Time.Updated
|
||||
if sess.Time.Busy > updated {
|
||||
updated = sess.Time.Busy
|
||||
}
|
||||
model := ""
|
||||
if sess.Model != nil {
|
||||
model = sess.Model.ID
|
||||
}
|
||||
parts := []string{shortPath(dir), relativeTime(updated), model}
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return strings.Join(out, " · ")
|
||||
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package appui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/asuka/signal"
|
||||
"github.com/egoist/asuka/ui"
|
||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||
)
|
||||
|
||||
func (c *controller) sessionMenu(s ocapi.Session) {
|
||||
ui.Alert(ui.AlertProps{
|
||||
Title: "会话",
|
||||
ActionSheet: true,
|
||||
Actions: []ui.Action{
|
||||
{Title: ui.Val("重命名"), Icon: "pencil", OnPress: func() { c.renameSession(s) }},
|
||||
{Title: ui.Val("归档"), Icon: "archivebox", OnPress: func() { c.archiveSession(s) }},
|
||||
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
|
||||
OnPress: func() { c.confirmDelete(s) }},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) renameSession(s ocapi.Session) {
|
||||
name := signal.New(s.Title)
|
||||
ui.Alert(ui.AlertProps{
|
||||
Title: "重命名会话",
|
||||
Message: "标题留空时,服务端不会自动生成新标题。",
|
||||
Fields: []ui.AlertField{{Text: name, Placeholder: "标题"}},
|
||||
Actions: []ui.Action{
|
||||
{Title: ui.Val("取消"), Role: ui.ActionCancel},
|
||||
{Title: ui.Val("保存"), Role: ui.ActionDefault,
|
||||
Disabled: signal.Func(func() bool { return strings.TrimSpace(name.Get()) == "" }),
|
||||
OnPress: func() { c.patchSessionOnServer(s, name.Get()) }},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) patchSessionOnServer(s ocapi.Session, title string) {
|
||||
client := c.client
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
dir := sessionDir(s)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
t := strings.TrimSpace(title)
|
||||
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Title: &t})
|
||||
ui.Post(func() {
|
||||
if err != nil {
|
||||
c.status.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
c.sessions.Update(func(list []ocapi.Session) []ocapi.Session {
|
||||
next := make([]ocapi.Session, len(list))
|
||||
copy(next, list)
|
||||
for i := range next {
|
||||
if next[i].ID == s.ID {
|
||||
next[i].Title = t
|
||||
}
|
||||
}
|
||||
return next
|
||||
})
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *controller) archiveSession(s ocapi.Session) {
|
||||
client := c.client
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
dir := sessionDir(s)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
archived := true
|
||||
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Archived: &archived})
|
||||
ui.Post(func() {
|
||||
if err != nil {
|
||||
c.status.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
c.removeSession(s.ID)
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *controller) confirmDelete(s ocapi.Session) {
|
||||
ui.Alert(ui.AlertProps{
|
||||
Title: "删除会话?",
|
||||
Message: "会话及其子会话会被永久删除,无法撤销。",
|
||||
Actions: []ui.Action{
|
||||
{Title: ui.Val("取消"), Role: ui.ActionCancel},
|
||||
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
|
||||
OnPress: func() { c.deleteSession(s) }},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) deleteSession(s ocapi.Session) {
|
||||
client := c.client
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
dir := sessionDir(s)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
err := client.DeleteSession(ctx, s.ID, dir)
|
||||
ui.Post(func() {
|
||||
if err != nil {
|
||||
c.status.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
c.removeSession(s.ID)
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func sessionDir(s ocapi.Session) string {
|
||||
if s.Location != nil {
|
||||
return s.Location.Directory
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
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))
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
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.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"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
|
||||
t.Errorf("prompt body: %v", promptBody)
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
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"
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
var page MessagePage
|
||||
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
|
||||
requestOptions{directory: o.Directory, query: q}, nil, &page)
|
||||
return page, err
|
||||
}
|
||||
|
||||
// ModelSelection lists the models the server offers for a directory.
|
||||
func (c *Client) Models(ctx context.Context, directory string) ([]ModelRef, error) {
|
||||
q := url.Values{}
|
||||
if directory != "" {
|
||||
q.Set("location[directory]", directory)
|
||||
}
|
||||
var payload struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
ProviderID string `json:"providerID"`
|
||||
Name string `json:"name"`
|
||||
Variant string `json:"variant"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := c.do(ctx, http.MethodGet, "/api/model", requestOptions{query: q}, nil, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ModelRef, 0, len(payload.Data))
|
||||
for _, m := range payload.Data {
|
||||
out = append(out, ModelRef{ID: m.ID, ProviderID: m.ProviderID, Variant: m.Variant})
|
||||
}
|
||||
return out, 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)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
|
||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// 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 {
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
Error json.RawMessage `json:"error,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"`
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Package storage keeps the connection settings in the app's store and the
|
||||
// device token in the platform's secure storage.
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/egoist/asuka/sdk/secure"
|
||||
"github.com/egoist/asuka/sdk/store"
|
||||
"github.com/egoist/asuka/signal"
|
||||
)
|
||||
|
||||
// Connection is the last server the app connected to.
|
||||
type Connection struct {
|
||||
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 servers need no token; remembering that avoids a
|
||||
// pointless password prompt on the next launch.
|
||||
Passwordless bool `json:"passwordless,omitempty"`
|
||||
}
|
||||
|
||||
// Store is the persistence the UI needs. Tests use a memory store.
|
||||
type Store interface {
|
||||
Connection() (Connection, bool)
|
||||
SaveConnection(Connection)
|
||||
ClearConnection()
|
||||
InstallID() string
|
||||
LoadToken(server string) (string, bool, error)
|
||||
SaveToken(server, token string) error
|
||||
ClearToken(server string) error
|
||||
}
|
||||
|
||||
// Persistent is the app's store: settings in store.json, tokens in the
|
||||
// Android Keystore / Keychain.
|
||||
type Persistent struct {
|
||||
conn *signal.Signal[Connection]
|
||||
hasConn *signal.Signal[bool]
|
||||
installID *signal.Signal[string]
|
||||
}
|
||||
|
||||
// New makes the persistent store. Call it on the main thread, while a
|
||||
// component builds, as any signal.
|
||||
func New() *Persistent {
|
||||
raw := store.Signal("openchamber.connection", "")
|
||||
var c Connection
|
||||
ok := raw.Get() != "" && json.Unmarshal([]byte(raw.Get()), &c) == nil && c.URL != ""
|
||||
p := &Persistent{
|
||||
conn: signal.NewFunc(c, nil),
|
||||
hasConn: signal.New(ok),
|
||||
installID: store.Signal("openchamber.installId", ""),
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *Persistent) Connection() (Connection, bool) {
|
||||
return p.conn.Get(), p.hasConn.Get()
|
||||
}
|
||||
|
||||
func (p *Persistent) SaveConnection(c Connection) {
|
||||
p.conn.Set(c)
|
||||
p.hasConn.Set(c.URL != "")
|
||||
buf, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Keep it in the store as JSON; the signal above stays the source of
|
||||
// truth for the UI.
|
||||
store.Set("openchamber.connection", string(buf))
|
||||
}
|
||||
|
||||
func (p *Persistent) ClearConnection() {
|
||||
p.conn.Set(Connection{})
|
||||
p.hasConn.Set(false)
|
||||
store.Set("openchamber.connection", "")
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if id := p.installID.Get(); id != "" {
|
||||
return id
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "openchamber-" + hex.EncodeToString(b[:8])
|
||||
}
|
||||
id := hex.EncodeToString(b[:])
|
||||
p.installID.Set(id)
|
||||
return id
|
||||
}
|
||||
|
||||
func (p *Persistent) tokenKey(server string) string {
|
||||
sum := sha256.Sum256([]byte(server))
|
||||
return "openchamber.token." + hex.EncodeToString(sum[:12])
|
||||
}
|
||||
|
||||
func (p *Persistent) LoadToken(server string) (string, bool, error) {
|
||||
return secure.Get(p.tokenKey(server))
|
||||
}
|
||||
|
||||
func (p *Persistent) SaveToken(server, token string) error {
|
||||
return secure.Set(p.tokenKey(server), token)
|
||||
}
|
||||
|
||||
func (p *Persistent) ClearToken(server string) error {
|
||||
return secure.Delete(p.tokenKey(server))
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// OpenChamber Native is a lightweight OpenChamber client for phones,
|
||||
// written in Go with Asuka's native widgets.
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/egoist/asuka/app"
|
||||
"github.com/openchamber/openchamber-native/internal/appui"
|
||||
|
||||
// The native module that lets a release build reach self-hosted
|
||||
// servers over plain HTTP (its Android manifest merges the flag). It
|
||||
// has no Go API this app calls; importing it is what puts its Gradle
|
||||
// module in the build.
|
||||
_ "github.com/openchamber/openchamber-native/netcfg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app.Run(appui.Root)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// swift-tools-version:5.9
|
||||
// The netcfg package's Swift, for iOS and macOS: the Asuka CLI builds it
|
||||
// with the apps that import the package. Its dependencies (Swift
|
||||
// packages) go here, as any package's.
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "NetcfgNative",
|
||||
platforms: [.iOS("16.0"), .macOS("11.0")],
|
||||
products: [.library(name: "NetcfgNative", targets: ["NetcfgNative"])],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/egoist/asuka", from: "0.1.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(name: "NetcfgNative", dependencies: [.product(name: "Asuka", package: "asuka")], path: "swift"),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
// The netcfg package's Kotlin for Android: a library module the Asuka CLI
|
||||
// builds into the apps that import the package. Its Kotlin is in its
|
||||
// namespace; its dependencies (Maven's) go here, its permissions and
|
||||
// services in src/main/AndroidManifest.xml.
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.github.openchamber.openchamber_native.netcfg"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- OpenChamber servers are often self-hosted on a LAN over plain HTTP.
|
||||
Asuka's own debug manifest enables cleartext, but a release build
|
||||
would block it, so this library module merges the flag into every
|
||||
variant. Remove this module to require HTTPS everywhere. -->
|
||||
<application android:usesCleartextTraffic="true" />
|
||||
</manifest>
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
// Code generated by asuka native. DO NOT EDIT.
|
||||
// asuka:native f84252246ecd432c
|
||||
|
||||
// What the package's Go declares (package netcfg), as its Kotlin implements
|
||||
// it. The Kotlin (in this package) writes the functions that make each:
|
||||
//
|
||||
// fun makeNetcfg(): Netcfg
|
||||
@file:Suppress("unused", "RedundantVisibilityModifier")
|
||||
|
||||
package com.github.openchamber.openchamber_native.netcfg
|
||||
|
||||
import dev.asuka.AsukaModuleProvider
|
||||
import dev.asuka.AsukaModules
|
||||
import dev.asuka.AsukaNativeContext
|
||||
import dev.asuka.AsukaNativeReader
|
||||
import dev.asuka.AsukaNativeView
|
||||
import dev.asuka.AsukaNativeWriter
|
||||
import dev.asuka.AsukaDeclaredError
|
||||
import dev.asuka.AsukaUnsupportedException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Netcfg greets in each platform's own code.
|
||||
*/
|
||||
public interface Netcfg {
|
||||
/**
|
||||
* Hello greets name.
|
||||
*/
|
||||
fun hello(name: String): String
|
||||
}
|
||||
|
||||
/** The package's native code as the host finds it (by its class's name): what makes, calls and shows what the package declares. */
|
||||
public object AsukaModule : AsukaModuleProvider {
|
||||
override fun make(iface: Int): Any = when (iface) {
|
||||
0 -> makeNetcfg()
|
||||
else -> throw AsukaUnsupportedException("no interface $iface")
|
||||
}
|
||||
|
||||
override fun call(obj: Any, iface: Int, method: Int, r: AsukaNativeReader, w: AsukaNativeWriter) {
|
||||
when (iface) {
|
||||
0 -> {
|
||||
val o = obj as Netcfg
|
||||
when (method) {
|
||||
1 -> { // Hello
|
||||
val name = r.string()
|
||||
r.check()
|
||||
val v = o.hello(name)
|
||||
w.string(v)
|
||||
}
|
||||
else -> throw AsukaUnsupportedException("no method $iface.$method")
|
||||
}
|
||||
}
|
||||
else -> throw AsukaUnsupportedException("no interface $iface")
|
||||
}
|
||||
}
|
||||
|
||||
override fun start(obj: Any, iface: Int, method: Int, r: AsukaNativeReader, done: (Result<AsukaNativeWriter>) -> kotlin.Unit): Job? {
|
||||
when (iface) {
|
||||
}
|
||||
throw AsukaUnsupportedException("no method $iface.$method")
|
||||
}
|
||||
|
||||
override fun makeView(name: String, ctx: AsukaNativeContext): AsukaNativeView? = when (name) {
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** The package's values on the wire (package native's format). */
|
||||
private object Wire {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// The netcfg package's Kotlin: what its Go declares, implemented on
|
||||
// Android (Netcfg.asuka.kt, beside it, is what asuka native generates).
|
||||
package com.github.openchamber.openchamber_native.netcfg
|
||||
|
||||
private class KotlinNetcfg : Netcfg {
|
||||
override fun hello(name: String) = "Hello, $name, from Kotlin"
|
||||
}
|
||||
|
||||
fun makeNetcfg(): Netcfg = KotlinNetcfg()
|
||||
@@ -0,0 +1,11 @@
|
||||
// Package netcfg is a native module: Netcfg, which each platform's native
|
||||
// code implements (asuka native).
|
||||
package netcfg
|
||||
|
||||
// Netcfg greets in each platform's own code.
|
||||
//
|
||||
//asuka:native
|
||||
type Netcfg interface {
|
||||
// Hello greets name.
|
||||
Hello(name string) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//go:build windows || (linux && !android)
|
||||
|
||||
package netcfg
|
||||
|
||||
// On Windows and Linux the package's native code is Go: NewNetcfg returns
|
||||
// this.
|
||||
func init() {
|
||||
implementNetcfg(func() (Netcfg, error) { return goHello{}, nil })
|
||||
}
|
||||
|
||||
type goHello struct{}
|
||||
|
||||
func (goHello) Hello(name string) (string, error) { return "Hello, " + name + ", from Go", nil }
|
||||
@@ -0,0 +1,50 @@
|
||||
// Code generated by asuka native. DO NOT EDIT.
|
||||
// asuka:native f84252246ecd432c
|
||||
|
||||
package netcfg
|
||||
|
||||
import (
|
||||
"github.com/egoist/asuka/native"
|
||||
)
|
||||
|
||||
// nativeModule is the package's native code, as the hosts find it.
|
||||
var nativeModule = &native.Module{ID: "github.com/openchamber/openchamber-native/netcfg", Swift: "AsukaModule_github_com_openchamber_openchamber_native_netcfg", Kotlin: "com.github.openchamber.openchamber_native.netcfg.AsukaModule", Errors: []error{}}
|
||||
|
||||
// NewNetcfg makes the platform's Netcfg: Go's, where the package implements it
|
||||
// in Go (implementNetcfg), else its native code's (Swift on iOS and macOS,
|
||||
// Kotlin on Android, JavaScript on the web). Without one, it returns an
|
||||
// error that is errors.ErrUnsupported.
|
||||
func NewNetcfg() (Netcfg, error) {
|
||||
if nativeImplNetcfg != nil {
|
||||
return nativeImplNetcfg()
|
||||
}
|
||||
o, err := nativeModule.New(0, "Netcfg")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &nativeNetcfg{o}, nil
|
||||
}
|
||||
|
||||
var nativeImplNetcfg func() (Netcfg, error)
|
||||
|
||||
// implementNetcfg makes NewNetcfg return Go's implementation: call it from an
|
||||
// init function of a file built for the platforms where the package's
|
||||
// native code is Go (Windows, Linux).
|
||||
func implementNetcfg(make func() (Netcfg, error)) { nativeImplNetcfg = make }
|
||||
|
||||
// nativeNetcfg is a Netcfg on the platform's side.
|
||||
type nativeNetcfg struct{ o *native.Object }
|
||||
|
||||
func (x *nativeNetcfg) Hello(name string) (string, error) {
|
||||
w := native.NewWriter()
|
||||
w.String(name)
|
||||
r, err := x.o.Call(1, w)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
v := r.String()
|
||||
if err := r.Done(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Code generated by asuka native. DO NOT EDIT.
|
||||
// asuka:native f84252246ecd432c
|
||||
|
||||
// What the package's Go declares (package netcfg), as its Swift implements
|
||||
// it. The Swift writes the functions that make each:
|
||||
//
|
||||
// func makeNetcfg() throws -> any Netcfg
|
||||
|
||||
import Foundation
|
||||
import Asuka
|
||||
|
||||
/// Netcfg greets in each platform's own code.
|
||||
public protocol Netcfg: AnyObject {
|
||||
/// Hello greets name.
|
||||
func hello(name: String) throws -> String
|
||||
}
|
||||
|
||||
/// The package's native code as the host finds it (by its Objective-C
|
||||
/// name): what makes, calls and shows what the package declares.
|
||||
@objc(AsukaModule_github_com_openchamber_openchamber_native_netcfg) public final class AsukaModule_github_com_openchamber_openchamber_native_netcfg: NSObject, AsukaModuleProvider {
|
||||
public static func make(_ iface: UInt32) throws -> AnyObject {
|
||||
switch iface {
|
||||
case 0: return try makeNetcfg()
|
||||
default: throw AsukaNativeError.unsupported("no interface \(iface)")
|
||||
}
|
||||
}
|
||||
|
||||
public static func call(_ object: AnyObject, _ iface: UInt32, _ method: UInt32, _ r: inout AsukaNativeReader, _ w: inout AsukaNativeWriter) throws {
|
||||
switch (iface, method) {
|
||||
case (0, 1): // Netcfg.Hello
|
||||
let o = object as! any Netcfg
|
||||
let name = r.string()
|
||||
try r.check()
|
||||
let v = try o.hello(name: name)
|
||||
w.string(v)
|
||||
default: throw AsukaNativeError.unsupported("no method \(iface).\(method)")
|
||||
}
|
||||
}
|
||||
|
||||
public static func start(_ object: AnyObject, _ iface: UInt32, _ method: UInt32, _ input: AsukaNativeReader, _ done: @escaping (Result<AsukaNativeWriter, Error>) -> Void) -> Task<Void, Never>? {
|
||||
var r = input
|
||||
switch (iface, method) {
|
||||
default:
|
||||
done(.failure(AsukaNativeError.unsupported("no method \(iface).\(method)")))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor public static func makeView(_ name: String, _ ctx: AsukaNativeContext) -> AsukaNativeView? {
|
||||
switch name {
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The package's values on the wire (package native's format).
|
||||
fileprivate enum Wire {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// The netcfg package's Swift: what its Go declares, implemented on iOS
|
||||
// and macOS (Netcfg.asuka.swift, beside it, is what asuka native generates).
|
||||
import Asuka
|
||||
import Foundation
|
||||
|
||||
final class SwiftNetcfg: Netcfg {
|
||||
func hello(name: String) throws -> String { "Hello, \(name), from Swift" }
|
||||
}
|
||||
|
||||
func makeNetcfg() throws -> any Netcfg { SwiftNetcfg() }
|
||||
@@ -0,0 +1,55 @@
|
||||
// Code generated by asuka native. DO NOT EDIT.
|
||||
// asuka:native f84252246ecd432c
|
||||
|
||||
// What the package's Go declares (package netcfg), as its JavaScript
|
||||
// implements it. netcfg.js exports the functions that make each:
|
||||
//
|
||||
// export function makeNetcfg() // returns its methods (lowerCamelCase)
|
||||
//
|
||||
// A method that takes a context in Go is async, and gets an AbortSignal
|
||||
// first. int64 and uint64 are BigInts; a time is a Date; a duration is
|
||||
// milliseconds; a []byte is a Uint8Array.
|
||||
|
||||
import * as impl from "./netcfg.js";
|
||||
|
||||
const { NativeWriter, NativeReader, DeclaredError, UnsupportedError, registerModule, retain, object } = globalThis.asuka.native;
|
||||
|
||||
const provider = {
|
||||
make(iface) {
|
||||
switch (iface) {
|
||||
case 0: return impl.makeNetcfg();
|
||||
}
|
||||
throw new UnsupportedError(`no interface ${iface}`);
|
||||
},
|
||||
|
||||
call(o, iface, method, r, w) {
|
||||
switch (iface * 65536 + method) {
|
||||
case 1: { // Netcfg.Hello
|
||||
const name = r.string();
|
||||
r.check();
|
||||
const v = o.hello(name);
|
||||
w.string(v);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new UnsupportedError(`no method ${iface}.${method}`);
|
||||
},
|
||||
|
||||
start(o, iface, method, r, signal) {
|
||||
switch (iface * 65536 + method) {
|
||||
}
|
||||
throw new UnsupportedError(`no method ${iface}.${method}`);
|
||||
},
|
||||
|
||||
makeView(name, ctx) {
|
||||
switch (name) {
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
registerModule("github.com/openchamber/openchamber-native/netcfg", provider);
|
||||
|
||||
// The package's values on the wire (package native's format).
|
||||
const Wire = {
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
// The netcfg package's JavaScript: what its Go declares, implemented on
|
||||
// the web (netcfg.asuka.js, beside it, is what asuka native generates).
|
||||
|
||||
export function makeNetcfg() {
|
||||
return {
|
||||
hello: (name) => `Hello, ${name}, from the web`,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user