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,148 @@
package dev.mygo
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.json.JSONObject
/** WorkManager, each of the app's tasks a unique work of its name. */
class BackgroundPlugin : MyGoPlugin {
init {
instance = this
}
override fun call(method: String, args: JSONObject, reply: PluginReply) {
val wm = WorkManager.getInstance(PluginHost.context)
when (method) {
"ready" -> {
ready = true
for (e in waiting) PluginHost.emit("background", "run", e)
waiting.clear()
reply.success(null)
}
"schedule" -> {
val name = args.optString("name")
// The same again, as each launch asks: what's scheduled stands.
// Replacing it would put it off, or stop the task that started
// this very process.
val options = args.toString()
if (prefs().getString(name, null) == options) {
reply.success(null)
return
}
val every = args.optDouble("every", 0.0)
val delay = (args.optDouble("delay", 0.0) * 1000).toLong()
val c = Constraints.Builder()
.setRequiredNetworkType(if (args.optBoolean("network")) NetworkType.CONNECTED else NetworkType.NOT_REQUIRED)
.setRequiresCharging(args.optBoolean("charging"))
.build()
val data = Data.Builder().putString("name", name).build()
if (every > 0) {
val r = PeriodicWorkRequest.Builder(MyGoWorker::class.java, (every * 1000).toLong(), TimeUnit.MILLISECONDS)
.setConstraints(c).setInputData(data).setInitialDelay(delay, TimeUnit.MILLISECONDS)
.addTag(MyGoWorker.PERIODIC).build()
wm.enqueueUniquePeriodicWork(prefix + name, ExistingPeriodicWorkPolicy.UPDATE, r)
} else {
val r = OneTimeWorkRequest.Builder(MyGoWorker::class.java)
.setConstraints(c).setInputData(data).setInitialDelay(delay, TimeUnit.MILLISECONDS).build()
wm.enqueueUniqueWork(prefix + name, ExistingWorkPolicy.REPLACE, r)
}
prefs().edit().putString(name, options).apply()
reply.success(null)
}
"cancel" -> {
wm.cancelUniqueWork(prefix + args.optString("name"))
prefs().edit().remove(args.optString("name")).apply()
reply.success(null)
}
"done" -> {
val id = args.optLong("run")
val d = runs.remove(id)
d?.invoke(args.optBoolean("ok"))
reply.success(null)
}
else -> reply.failure(PluginFailure("UnknownMethod", method))
}
}
companion object {
private const val prefix = "mygo."
internal var instance: BackgroundPlugin? = null
private var ready = false
private val waiting = ArrayList<Map<String, Any>>()
private val runs = HashMap<Long, (Boolean) -> Unit>()
private var nextRun = 1L
/** Runs a task, on the UI thread: Go hears of it, once it listens. */
internal fun run(name: String, done: (Boolean) -> Unit): Long {
val id = nextRun++
runs[id] = done
val e = mapOf<String, Any>("run" to id, "name" to name)
if (ready) PluginHost.emit("background", "run", e) else waiting.add(e)
return id
}
/** The system's time ran out: what never began stays unbegun. */
internal fun stop(id: Long) {
runs.remove(id)
if (!waiting.removeAll { it["run"] == id }) PluginHost.emit("background", "stop", mapOf("run" to id))
}
internal fun prefs() = PluginHost.context.getSharedPreferences("mygo.background", Context.MODE_PRIVATE)
/** A task that runs once is done with: it may be scheduled again. */
internal fun finished(name: String) {
prefs().edit().remove(name).apply()
}
}
}
/** A task's turn, which may be what starts the process: Go starts with no Activity. */
class MyGoWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
@Volatile private var run = 0L
private val main = Handler(Looper.getMainLooper())
private val latch = CountDownLatch(1)
override fun doWork(): Result {
val name = inputData.getString("name") ?: return Result.failure()
var ok = false
main.post {
HostImpl.startHeadless(applicationContext)
run = BackgroundPlugin.run(name) {
ok = it
latch.countDown()
}
}
// WorkManager's limit is 10 minutes.
if (!latch.await(9, TimeUnit.MINUTES)) {
onStopped()
return Result.retry()
}
if (!ok) return Result.retry()
// What repeats stays on the list, of which this run is one.
if (!tags.contains(MyGoWorker.PERIODIC)) main.post { BackgroundPlugin.finished(name) }
return Result.success()
}
override fun onStopped() {
val id = run
if (id != 0L) main.post { BackgroundPlugin.stop(id) }
latch.countDown() // WorkManager no longer waits for this thread
}
companion object {
const val PERIODIC = "mygo.periodic"
}
}
+172
View File
@@ -0,0 +1,172 @@
// Package background runs an app's Go code while it isn't open, as the phone
// finds the time: syncing a feed overnight, uploading what waited for a network.
// BGTaskScheduler on iOS, WorkManager on Android; elsewhere Schedule reports
// errors.ErrUnsupported.
//
// The system starts the app's process to run a task, without showing it, and
// main runs as ever: call Handle before App.Run, so that the handler is there
// by then.
//
// background.Handle("sync", func(ctx context.Context) error {
// return syncFeed(ctx)
// })
// mygo.App.WhenReady(func() {
// go background.Schedule(context.Background(), "sync", background.Options{
// Every: 4 * time.Hour, Network: true,
// })
// })
//
// When a task runs is the system's choice: after Delay, around Every, with what
// it knows of the battery and of how much the user opens the app. iOS gives a
// task about 30 seconds, or minutes with Long; Android about 10 minutes. A
// handler stops when its context ends. A repeating task outlives the process and
// reboots until Cancel; one that runs once does until it succeeds.
package background
import (
"context"
"encoding/json"
"log"
"sync"
"time"
"github.com/egoist/mygo"
)
const pluginID = "background"
// Options say when a task may run.
type Options struct {
// Every repeats it, at least 15 minutes apart on either system. Without it
// the task runs once.
Every time.Duration
// Delay is the least it waits before it runs the first time.
Delay time.Duration
// Network waits for a network; on iOS, for Long tasks only, as the system
// decides when others run.
Network bool
// Charging waits for the phone to charge; on iOS, for Long tasks only.
Charging bool
// Long asks for minutes, which on iOS come rarely, overnight and charging,
// rather than half a minute.
Long bool
}
var tasks struct {
sync.Mutex
handlers map[string]func(context.Context) error
running map[int64]context.CancelFunc
}
// init listens, whether the app handles a task or no longer does, for the system
// to hear back about what it still has on its list.
func init() {
tasks.handlers = map[string]func(context.Context) error{}
tasks.running = map[int64]context.CancelFunc{}
p := mygo.Native(pluginID)
p.On("run", func(data []byte) {
var e runEvent
if json.Unmarshal(data, &e) == nil {
run(e, finish)
}
})
p.On("stop", func(data []byte) {
var e runEvent
if json.Unmarshal(data, &e) == nil {
stop(e.Run)
}
})
mygo.App.WhenReady(func() {
if !p.Available() {
return
}
// What the system started the process for waited for this.
go func() {
if err := p.Call(context.Background(), "ready", nil, nil); err != nil {
log.Printf("background: %v", err)
}
}()
})
}
// Handle says what a task does, before App.Run. It runs on a goroutine of its
// own, off the main thread. A task whose handler returns an error runs again
// later.
func Handle(name string, fn func(ctx context.Context) error) {
tasks.Lock()
defer tasks.Unlock()
tasks.handlers[name] = fn
}
// Schedule asks the system to run a task, in place of one of its name with other
// options: with the same ones, as an app does each time it starts, nothing
// changes, so that a task isn't put off again and again, nor stopped as it runs.
// Call it off the main goroutine, or with go.
func Schedule(ctx context.Context, name string, o Options) error {
return mygo.Native(pluginID).Call(ctx, "schedule", map[string]any{
"name": name, "every": o.Every.Seconds(), "delay": o.Delay.Seconds(),
"network": o.Network, "charging": o.Charging, "long": o.Long,
}, nil)
}
// Cancel takes a task off the system's list.
func Cancel(ctx context.Context, name string) error {
return mygo.Native(pluginID).Call(ctx, "cancel", map[string]any{"name": name}, nil)
}
type runEvent struct {
Run int64 `json:"run"`
Name string `json:"name"`
}
// run runs a task's handler, and tells what came of it. What has no handler
// finishes: the app no longer does it.
func run(e runEvent, done func(run int64, ok bool)) {
tasks.Lock()
fn := tasks.handlers[e.Name]
if fn == nil {
tasks.Unlock()
done(e.Run, true)
return
}
ctx, cancel := context.WithCancel(context.Background())
tasks.running[e.Run] = cancel
tasks.Unlock()
go func() {
err := func() (err error) {
defer func() {
if r := recover(); r != nil {
log.Printf("background: task %s: %v", e.Name, r)
err = context.Canceled
}
}()
return fn(ctx)
}()
if err != nil {
log.Printf("background: task %s: %v", e.Name, err)
}
tasks.Lock()
delete(tasks.running, e.Run)
tasks.Unlock()
cancel()
done(e.Run, err == nil)
}()
}
// stop ends a task's context, as the system's time for it ended.
func stop(id int64) {
tasks.Lock()
cancel := tasks.running[id]
tasks.Unlock()
if cancel != nil {
cancel()
}
}
func finish(id int64, ok bool) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := mygo.Native(pluginID).Call(ctx, "done", map[string]any{"run": id, "ok": ok}, nil); err != nil {
log.Printf("background: %v", err)
}
}
+61
View File
@@ -0,0 +1,61 @@
package background
import (
"context"
"errors"
"testing"
"github.com/egoist/mygo/internal/wait"
)
type result struct {
run int64
ok bool
}
func handlers(t *testing.T, m map[string]func(context.Context) error) {
t.Helper()
tasks.Lock()
defer tasks.Unlock()
tasks.handlers, tasks.running = m, map[int64]context.CancelFunc{}
}
// A task runs its handler and says what came of it; one the app no longer has
// finishes, so that the system stops asking; a panic stays in its task.
func TestRun(t *testing.T) {
handlers(t, map[string]func(context.Context) error{
"fine": func(context.Context) error { return nil },
"fails": func(context.Context) error { return errors.New("no network") },
"panics": func(context.Context) error { panic("oh") },
})
done := make(chan result, 1)
report := func(run int64, ok bool) { done <- result{run, ok} }
for i, c := range []struct {
name string
ok bool
}{{"fine", true}, {"fails", false}, {"panics", false}, {"gone", true}} {
run(runEvent{Run: int64(i), Name: c.name}, report)
if got := wait.For(t, c.name, done); got != (result{int64(i), c.ok}) {
t.Errorf("%s: %+v", c.name, got)
}
}
}
// The system's time running out ends the handler's context.
func TestStop(t *testing.T) {
started := make(chan struct{})
handlers(t, map[string]func(context.Context) error{
"long": func(ctx context.Context) error {
close(started)
<-ctx.Done()
return ctx.Err()
},
})
done := make(chan result, 1)
run(runEvent{Run: 7, Name: "long"}, func(run int64, ok bool) { done <- result{run, ok} })
wait.For(t, "it to start", started)
stop(7)
if got := wait.For(t, "it to end", done); got != (result{7, false}) {
t.Errorf("stopped: %+v", got)
}
}
@@ -0,0 +1,197 @@
import BackgroundTasks
import UIKit
/// BGTaskScheduler: one identifier for what takes seconds and one for what takes
/// minutes, which the plugin's named tasks share, each with when it's due.
final class BackgroundPlugin: MyGoPlugin {
private struct Task: Codable {
var every: Double
var delay: Double
var next: Date
var long: Bool
var network: Bool
var charging: Bool
func sameOptions(as o: Task) -> Bool {
every == o.every && delay == o.delay && long == o.long && network == o.network && charging == o.charging
}
}
/// What one of the system's tasks is running.
private final class Run {
let task: BGTask
let long: Bool
var left: Set<Int>
var ok = true
var done = false
init(task: BGTask, long: Bool, left: Set<Int>) {
self.task = task
self.long = long
self.left = left
}
}
private let refreshID: String
private let processingID: String
private let storeKey = "mygo.background.tasks"
private var nextRun = 1
private var runs: [Int: Run] = [:]
private var names: [Int: String] = [:]
private var ready = false
private var waiting: [[String: Any]] = []
init() {
let id = Bundle.main.bundleIdentifier ?? ""
refreshID = id + ".mygo.refresh"
processingID = id + ".mygo.processing"
// Before the app finishes launching, which is why plugins register then.
BGTaskScheduler.shared.register(forTaskWithIdentifier: refreshID, using: .main) { [weak self] t in
self?.fired(t, long: false)
}
BGTaskScheduler.shared.register(forTaskWithIdentifier: processingID, using: .main) { [weak self] t in
self?.fired(t, long: true)
}
}
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
switch method {
case "ready":
ready = true
for e in waiting { PluginHost.emit("background", "run", e) }
waiting = []
reply(.success(nil))
case "schedule":
var all = load()
let name = args["name"] as? String ?? ""
let every = (args["every"] as? Double) ?? 0
let delay = (args["delay"] as? Double) ?? 0
let t = Task(every: every, delay: delay, next: Date().addingTimeInterval(delay),
long: args["long"] as? Bool ?? false, network: args["network"] as? Bool ?? false,
charging: args["charging"] as? Bool ?? false)
// The same again, as each launch asks: when it's due stands, or it
// would be put off for ever by an app that's opened often.
if let old = all[name], old.sameOptions(as: t) {
reply(.success(nil))
return
}
all[name] = t
save(all)
do {
try submit(all)
reply(.success(nil))
} catch {
// The simulator has no scheduler.
reply(.failure(PluginFailure("Unavailable", "\(error)")))
}
case "cancel":
var all = load()
all[args["name"] as? String ?? ""] = nil
save(all)
try? submit(all)
reply(.success(nil))
case "done":
finished(run: args["run"] as? Int ?? 0, ok: args["ok"] as? Bool ?? false)
reply(.success(nil))
default:
reply(.failure(PluginFailure("UnknownMethod", method)))
}
}
private func load() -> [String: Task] {
guard let d = UserDefaults.standard.data(forKey: storeKey),
let all = try? JSONDecoder().decode([String: Task].self, from: d) else { return [:] }
return all
}
private func save(_ all: [String: Task]) {
if let d = try? JSONEncoder().encode(all) { UserDefaults.standard.set(d, forKey: storeKey) }
}
/// Asks for the earliest of what's due, of each kind.
private func submit(_ all: [String: Task]) throws {
let quick = all.values.filter { !$0.long }
let long = all.values.filter { $0.long }
BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: refreshID)
BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: processingID)
if let at = quick.map(\.next).min() {
let r = BGAppRefreshTaskRequest(identifier: refreshID)
r.earliestBeginDate = at
try BGTaskScheduler.shared.submit(r)
}
if let at = long.map(\.next).min() {
let r = BGProcessingTaskRequest(identifier: processingID)
r.earliestBeginDate = at
r.requiresNetworkConnectivity = long.contains { $0.network }
r.requiresExternalPower = long.contains { $0.charging }
try BGTaskScheduler.shared.submit(r)
}
}
private func fired(_ task: BGTask, long: Bool) {
var all = load()
let now = Date()
let due = all.filter { $0.value.long == long && $0.value.next <= now.addingTimeInterval(60) }
for (name, t) in due where t.every > 0 {
all[name]?.next = now.addingTimeInterval(t.every)
}
save(all)
try? submit(all)
if due.isEmpty {
task.setTaskCompleted(success: true)
return
}
var ids = Set<Int>()
for name in due.keys {
let id = nextRun
nextRun += 1
ids.insert(id)
names[id] = name
let e: [String: Any] = ["run": id, "name": name]
if ready {
PluginHost.emit("background", "run", e)
} else {
waiting.append(e)
}
}
let run = Run(task: task, long: long, left: ids)
for id in ids { runs[id] = run }
task.expirationHandler = { [weak self, weak run] in
guard let self, let run else { return }
// Handlers get a moment to let go of what they hold, as a database's
// lock, before the system suspends the app.
for id in run.left {
if let i = self.waiting.firstIndex(where: { $0["run"] as? Int == id }) {
self.waiting.remove(at: i)
self.finished(run: id, ok: false)
} else {
PluginHost.emit("background", "stop", ["run": id])
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self, weak run] in
guard let self, let run, !run.done else { return }
for id in run.left { self.finished(run: id, ok: false) }
}
}
}
private func finished(run id: Int, ok: Bool) {
guard let run = runs.removeValue(forKey: id) else { return }
run.left.remove(id)
run.ok = run.ok && ok
if ok, let name = names[id] {
// Once it succeeded, what runs once is off the list; failed, it
// stays, to run again.
var all = load()
if let t = all[name], t.every == 0 {
all[name] = nil
save(all)
try? submit(all)
}
}
names[id] = nil
if run.left.isEmpty && !run.done {
run.done = true
run.task.setTaskCompleted(success: run.ok)
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"mobile": {
"id": "background",
"ios": {
"sources": ["ios/*.swift"],
"class": "BackgroundPlugin",
"frameworks": ["BackgroundTasks"],
"infoPlist": {
"UIBackgroundModes": ["fetch", "processing"],
"BGTaskSchedulerPermittedIdentifiers": ["$(IDENTIFIER).mygo.refresh", "$(IDENTIFIER).mygo.processing"]
}
},
"android": {
"sources": ["android/*.kt"],
"class": "BackgroundPlugin",
"dependencies": ["androidx.work:work-runtime:2.10.1"]
}
}
}