feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

@@ -0,0 +1,118 @@
package dev.mygo
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ConsumeParams
import com.android.billingclient.api.PendingPurchasesParams
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.QueryProductDetailsParams
import com.android.billingclient.api.QueryPurchasesParams
import org.json.JSONArray
import org.json.JSONObject
class PurchasesPlugin : MyGoPlugin {
private var buying: PluginReply? = null
private val details = HashMap<String, ProductDetails>()
private val updated = PurchasesUpdatedListener { r, list ->
val reply = buying
buying = null
when {
r.responseCode == BillingClient.BillingResponseCode.USER_CANCELED -> reply?.failure(PluginFailure("Canceled"))
r.responseCode != BillingClient.BillingResponseCode.OK -> reply?.failure(PluginFailure("Failed", r.debugMessage))
else -> list?.forEachIndexed { i, p ->
if (i == 0 && reply != null) reply.success(encode(p)) else PluginHost.emit("purchases", "purchase", encode(p))
}
}
}
private val client: BillingClient by lazy {
BillingClient.newBuilder(PluginHost.context).setListener(updated)
.enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()).build()
}
private fun encode(p: Purchase) = JSONObject().put("productId", p.products.firstOrNull() ?: "").put("token", p.purchaseToken)
.put("pending", p.purchaseState == Purchase.PurchaseState.PENDING).put("finished", p.isAcknowledged)
private fun ready(reply: PluginReply, then: () -> Unit) {
if (client.isReady) return then()
client.startConnection(object : BillingClientStateListener {
override fun onBillingServiceDisconnected() {}
override fun onBillingSetupFinished(r: BillingResult) {
if (r.responseCode == BillingClient.BillingResponseCode.OK) then() else reply.failure(PluginFailure("Failed", r.debugMessage))
}
})
}
private fun query(ids: List<String>, type: String, done: (List<ProductDetails>) -> Unit) {
val params = QueryProductDetailsParams.newBuilder().setProductList(ids.map {
QueryProductDetailsParams.Product.newBuilder().setProductId(it).setProductType(type).build()
}).build()
client.queryProductDetailsAsync(params) { _, list -> done(list) }
}
override fun call(method: String, args: JSONObject, reply: PluginReply) = ready(reply) {
when (method) {
"products" -> {
val a = args.optJSONArray("ids") ?: JSONArray()
val ids = List(a.length()) { a.getString(it) }
query(ids, BillingClient.ProductType.INAPP) { one ->
query(ids, BillingClient.ProductType.SUBS) { subs ->
val out = JSONArray()
for (d in one + subs) {
details[d.productId] = d
val once = d.oneTimePurchaseOfferDetails
val sub = d.subscriptionOfferDetails?.firstOrNull()?.pricingPhases?.pricingPhaseList?.lastOrNull()
out.put(JSONObject().put("id", d.productId).put("title", d.name).put("description", d.description)
.put("price", once?.formattedPrice ?: sub?.formattedPrice ?: "")
.put("priceMicros", once?.priceAmountMicros ?: sub?.priceAmountMicros ?: 0)
.put("currency", once?.priceCurrencyCode ?: sub?.priceCurrencyCode ?: "")
.put("subscription", sub != null))
}
reply.success(JSONObject().put("products", out))
}
}
}
"buy" -> {
val a = PluginHost.activity
val d = details[args.optString("id")]
if (a == null || d == null) {
reply.failure(PluginFailure("NoProduct", "ask for its product first"))
return@ready
}
val offer = BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(d)
d.subscriptionOfferDetails?.firstOrNull()?.let { offer.setOfferToken(it.offerToken) }
buying = reply
client.launchBillingFlow(a, BillingFlowParams.newBuilder().setProductDetailsParamsList(listOf(offer.build())).build())
}
"finish" -> {
val token = args.optString("token")
if (args.optBoolean("consumable")) {
client.consumeAsync(ConsumeParams.newBuilder().setPurchaseToken(token).build()) { r, _ ->
if (r.responseCode == BillingClient.BillingResponseCode.OK) reply.success(null) else reply.failure(PluginFailure("Failed", r.debugMessage))
}
} else {
client.acknowledgePurchase(AcknowledgePurchaseParams.newBuilder().setPurchaseToken(token).build()) { r ->
if (r.responseCode == BillingClient.BillingResponseCode.OK) reply.success(null) else reply.failure(PluginFailure("Failed", r.debugMessage))
}
}
}
"restore" -> {
val out = JSONArray()
val q = { type: String, next: () -> Unit ->
client.queryPurchasesAsync(QueryPurchasesParams.newBuilder().setProductType(type).build()) { _, list ->
list.forEach { out.put(encode(it)) }
next()
}
}
q(BillingClient.ProductType.INAPP) { q(BillingClient.ProductType.SUBS) { reply.success(JSONObject().put("purchases", out)) } }
}
else -> reply.failure(PluginFailure("NoMethod", method))
}
}
}
@@ -0,0 +1,70 @@
import Foundation
import StoreKit
final class PurchasesPlugin: MyGoPlugin {
private var open: [String: Transaction] = [:]
private var updates: Task<Void, Never>?
init() {
updates = Task { [weak self] in
for await result in Transaction.updates {
if case .verified(let t) = result, let self {
await MainActor.run { self.open[t.productID] = t }
PluginHost.emit("purchases", "purchase", ["productId": t.productID, "token": result.jwsRepresentation, "pending": false, "finished": false])
}
}
}
}
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
Task { @MainActor in
do {
switch method {
case "products":
let list = try await Product.products(for: args["ids"] as? [String] ?? [])
reply(.success(["products": list.map { p -> [String: Any] in
["id": p.id, "title": p.displayName, "description": p.description, "price": p.displayPrice,
"priceMicros": Int64((p.price as NSDecimalNumber).doubleValue * 1_000_000),
"currency": p.priceFormatStyle.currencyCode, "subscription": p.subscription != nil]
}]))
case "buy":
guard let p = try await Product.products(for: [args["id"] as? String ?? ""]).first else {
return reply(.failure(PluginFailure("NoProduct", "no such product")))
}
switch try await p.purchase() {
case .success(let result):
guard case .verified(let t) = result else {
return reply(.failure(PluginFailure("Unverified", "the store's signature does not verify")))
}
self.open[t.productID] = t
reply(.success(["productId": t.productID, "token": result.jwsRepresentation, "pending": false, "finished": false]))
case .pending:
reply(.success(["productId": p.id, "token": "", "pending": true, "finished": false]))
case .userCancelled:
reply(.failure(PluginFailure("Canceled")))
@unknown default:
reply(.failure(PluginFailure("Failed", "the store answered something unknown")))
}
case "finish":
let id = args["productId"] as? String ?? ""
await self.open[id]?.finish()
self.open[id] = nil
reply(.success(nil))
case "restore":
try? await AppStore.sync()
var out: [[String: Any]] = []
for await result in Transaction.currentEntitlements {
if case .verified(let t) = result {
out.append(["productId": t.productID, "token": result.jwsRepresentation, "pending": false, "finished": true])
}
}
reply(.success(["purchases": out]))
default:
reply(.failure(PluginFailure("NoMethod", method)))
}
} catch {
reply(.failure(PluginFailure("Failed", error.localizedDescription)))
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"mobile": {
"id": "purchases",
"ios": {"sources": ["ios/*.swift"], "class": "PurchasesPlugin", "frameworks": ["StoreKit"]},
"android": {
"sources": ["android/*.kt"],
"class": "PurchasesPlugin",
"permissions": ["com.android.vending.BILLING"],
"dependencies": ["com.android.billingclient:billing:7.1.1"]
}
}
}
+106
View File
@@ -0,0 +1,106 @@
// Package purchases sells what an app sells in itself: StoreKit 2 on iOS, and
// Google Play Billing on Android, which their stores require for digital goods.
// Products are set up in App Store Connect and the Play Console.
//
// products, err := purchases.Products(ctx, "pro.monthly", "coins.100")
// p, err := purchases.Buy(ctx, products[0].ID)
// if err == nil && p != nil {
// // Give what was bought, then:
// purchases.Finish(ctx, *p)
// }
//
// Elsewhere its functions report errors.ErrUnsupported.
package purchases
import (
"context"
"encoding/json"
"errors"
"github.com/egoist/mygo"
)
const pluginID = "purchases"
// Product is something for sale, as the store describes it to this user.
type Product struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
// Price is the price as the store shows it, in the user's currency.
Price string `json:"price"`
// PriceMicros is the price in millionths of Currency's unit.
PriceMicros int64 `json:"priceMicros"`
Currency string `json:"currency"`
// Subscription says it renews.
Subscription bool `json:"subscription"`
}
// Purchase is what the user bought.
type Purchase struct {
ProductID string `json:"productId"`
// Token is what the app's server verifies the purchase with: the
// transaction's signed JWS on iOS, the purchase token on Android.
Token string `json:"token"`
// Pending says the store waits for something first, as a parent's approval
// or a payment in cash: give nothing yet.
Pending bool `json:"pending"`
// Finished says the app already finished it.
Finished bool `json:"finished"`
// Consumable, set by the app before Finish, lets the user buy it again.
Consumable bool `json:"consumable"`
}
// ErrCanceled is what Buy fails with as the user goes back.
var ErrCanceled = errors.New("purchases: canceled")
// Products asks the store for what is for sale, by the products' IDs.
func Products(ctx context.Context, ids ...string) ([]Product, error) {
var r struct {
Products []Product `json:"products"`
}
err := mygo.Native(pluginID).Call(ctx, "products", map[string]any{"ids": ids}, &r)
return r.Products, err
}
// Buy shows the store's sheet of a product, and returns the purchase, which the
// app finishes once it gave what was bought (Finish). Call it off the main
// goroutine, as it waits for the user.
func Buy(ctx context.Context, id string) (*Purchase, error) {
var p Purchase
err := mygo.Native(pluginID).Call(ctx, "buy", map[string]any{"id": id}, &p)
var n *mygo.NativeError
if errors.As(err, &n) && n.Code == "Canceled" {
return nil, ErrCanceled
}
if err != nil {
return nil, err
}
return &p, nil
}
// Finish tells the store the app gave what was bought: without it, the store
// gives the purchase again, and Google Play refunds it in three days.
func Finish(ctx context.Context, p Purchase) error {
return mygo.Native(pluginID).Call(ctx, "finish", p, nil)
}
// Restore lists what the user bought and still has, as on a new device.
func Restore(ctx context.Context) ([]Purchase, error) {
var r struct {
Purchases []Purchase `json:"purchases"`
}
err := mygo.Native(pluginID).Call(ctx, "restore", nil, &r)
return r.Purchases, err
}
// OnUpdate calls fn on the main thread as a purchase comes outside Buy, as a
// subscription's renewal or one a parent approved. Finish it as well.
func OnUpdate(fn func(Purchase)) (off func()) {
return mygo.Native(pluginID).On("purchase", func(data []byte) {
var p Purchase
if json.Unmarshal(data, &p) == nil {
fn(p)
}
})
}