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

+436
View File
@@ -0,0 +1,436 @@
// Package keepstate turns a program's values into JSON and back, unexported
// fields and all, so that an app comes back as it was after a restart, without
// tags or methods on its types: a struct of its own, as main packages keep theirs,
// just works.
//
// It keeps data, not the world around it. What a function, a channel, an interface
// or a pointer to another package's type holds stays as the program made it, and so
// does a slice or a map of elements that hold any of those, which couldn't be made
// whole. A field whose type changed since the value was saved, as a change of the
// code may have done, stays as it is too. A pointer met a second time, as a list's
// link back, comes back nil where it was: data, not a graph.
package keepstate
import (
"bytes"
"encoding/json"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"time"
"unsafe"
)
// maxDepth bounds how deep it goes, and maxNodes how much it writes down: a value
// this large is no state to write every second.
const (
maxDepth = 4096
maxNodes = 1 << 20
)
var timeType = reflect.TypeFor[time.Time]()
// ownModule is this framework's: a type of it is the world around an app, what
// its pointers lead to, as a window or its elements, however close by.
var ownModule = "github.com/egoist/mygo"
// walk is one Encode or Decode.
type walk struct {
// pkg is the package of the value, and first the start of its path, which
// tells an app's other packages from the standard library's whatever its
// module is called.
pkg, first string
// seen are the pointers met.
seen map[unsafe.Pointer]bool
nodes int
// fits remembers keepable.
fits map[reflect.Type]bool
}
func newWalk(t reflect.Type) *walk {
pkg := pkgOf(t)
first, _, _ := strings.Cut(pkg, "/")
return &walk{pkg: pkg, first: first, seen: map[unsafe.Pointer]bool{}, fits: map[reflect.Type]bool{}}
}
// Encode returns v, a pointer, as JSON. Values it can't walk it leaves out. What
// goes wrong, as a value too large, is an error.
func Encode(v any) (data []byte, err error) {
defer func() {
if r := recover(); r != nil {
data, err = nil, fmt.Errorf("keepstate: %v", r)
}
}()
r := reflect.ValueOf(v)
if r.Kind() != reflect.Pointer || r.IsNil() {
return nil, nil
}
w := newWalk(r.Elem().Type())
tree, _ := w.encode(r.Elem(), 0)
if w.nodes > maxNodes {
return nil, fmt.Errorf("keepstate: more than %d values to keep", maxNodes)
}
return json.Marshal(tree)
}
// Decode sets what data holds in v, a pointer, as far as the two still agree.
func Decode(data []byte, v any) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("keepstate: %v", r)
}
}()
r := reflect.ValueOf(v)
if r.Kind() != reflect.Pointer || r.IsNil() {
return nil
}
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber() // integers whole
var tree any
if err := dec.Decode(&tree); err != nil {
return err
}
newWalk(r.Elem().Type()).decode(r.Elem(), tree, 0)
return nil
}
// pkgOf returns the package a value belongs to: of its element, for a slice or a
// map of its structs.
func pkgOf(t reflect.Type) string {
for {
switch t.Kind() {
case reflect.Pointer, reflect.Slice, reflect.Array, reflect.Map:
t = t.Elem()
default:
return t.PkgPath()
}
}
}
// walkable says whether to go into a struct: an app's, not the standard
// library's, whose locks and buffers restart as they are.
func (w *walk) walkable(t reflect.Type) bool {
path := t.PkgPath()
if path == "" || path == "main" || path == w.pkg {
return true
}
first, _, _ := strings.Cut(path, "/")
return first == w.first || strings.Contains(first, ".")
}
// followed says whether to go through a pointer to t: to data of the value's own
// package, not to the windows, cameras and bitmaps of others, nor through the
// framework's own types, which lead to all of a window's elements.
func (w *walk) followed(t reflect.Type) bool {
switch t.Kind() {
case reflect.Struct:
return t.PkgPath() == w.pkg && !isFramework(t.PkgPath())
case reflect.Func, reflect.Chan, reflect.UnsafePointer, reflect.Interface:
return false
}
return true
}
func isFramework(path string) bool {
if !strings.HasPrefix(path, ownModule) {
return false
}
return !strings.HasPrefix(path, ownModule+"/examples/")
}
// keepable says whether a value of t comes back whole, with nothing in it left to
// what the program made: what a new element of a collection must be.
func (w *walk) keepable(t reflect.Type) bool {
if ok, seen := w.fits[t]; seen {
return ok
}
w.fits[t] = true // a type that holds itself rests on the rest of it
ok := true
switch t.Kind() {
case reflect.Func, reflect.Chan, reflect.UnsafePointer, reflect.Interface:
ok = false
case reflect.Pointer:
ok = w.followed(t.Elem()) && w.keepable(t.Elem())
case reflect.Slice, reflect.Array:
ok = w.keepable(t.Elem())
case reflect.Map:
ok = validKey(t.Key()) && w.keepable(t.Elem())
case reflect.Struct:
if t == timeType {
break
}
ok = w.walkable(t)
for i := 0; ok && i < t.NumField(); i++ {
ok = w.keepable(t.Field(i).Type)
}
}
w.fits[t] = ok
return ok
}
func validKey(t reflect.Type) bool {
switch t.Kind() {
case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return true
}
return false
}
// encode returns what to write of v, and whether to write anything: a nil slice
// is written, as nil, and a function isn't.
func (w *walk) encode(v reflect.Value, depth int) (any, bool) {
if depth > maxDepth {
return nil, false
}
if w.nodes++; w.nodes > maxNodes {
return nil, false
}
v = reachable(v)
switch v.Kind() {
case reflect.Bool:
return v.Bool(), true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint(), true
case reflect.Float32, reflect.Float64:
f := v.Float()
if math.IsNaN(f) || math.IsInf(f, 0) {
return nil, false // JSON has none of those
}
return f, true
case reflect.String:
return v.String(), true
case reflect.Slice:
if !w.keepable(v.Type().Elem()) {
return nil, false
}
if v.IsNil() {
return nil, true
}
fallthrough
case reflect.Array:
out := make([]any, v.Len())
for i := range out {
out[i], _ = w.encode(v.Index(i), depth+1)
}
return out, true
case reflect.Map:
if !validKey(v.Type().Key()) || !w.keepable(v.Type().Elem()) {
return nil, false
}
if v.IsNil() {
return nil, true
}
out := make(map[string]any, v.Len())
for it := v.MapRange(); it.Next(); {
k, ok := keyString(it.Key())
if !ok {
continue
}
// A map's values can't be addressed, as reading unexported fields
// asks: a copy can.
e := reflect.New(v.Type().Elem()).Elem()
e.Set(it.Value())
out[k], _ = w.encode(e, depth+1)
}
return out, true
case reflect.Pointer:
if !w.followed(v.Type().Elem()) {
return nil, false
}
if v.IsNil() {
return nil, true
}
if w.seen[v.UnsafePointer()] {
return nil, false
}
w.seen[v.UnsafePointer()] = true
return w.encode(v.Elem(), depth+1)
case reflect.Struct:
if v.Type() == timeType {
if b, err := v.Interface().(time.Time).MarshalText(); err == nil {
return string(b), true
}
return nil, false
}
if !w.walkable(v.Type()) {
return nil, false
}
out := make(map[string]any, v.NumField())
t := v.Type()
for i := range t.NumField() {
if f, ok := w.encode(v.Field(i), depth+1); ok {
out[t.Field(i).Name] = f
}
}
return out, true
}
return nil, false
}
func keyString(k reflect.Value) (string, bool) {
switch k.Kind() {
case reflect.String:
return k.String(), true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(k.Int(), 10), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(k.Uint(), 10), true
}
return "", false
}
func keyValue(t reflect.Type, s string) (reflect.Value, bool) {
k := reflect.New(t).Elem()
switch t.Kind() {
case reflect.String:
k.SetString(s)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(s, 10, t.Bits())
if err != nil {
return k, false
}
k.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(s, 10, t.Bits())
if err != nil {
return k, false
}
k.SetUint(n)
default:
return k, false
}
return k, true
}
// reachable returns v without the read-only mark of an unexported field. Only an
// addressable value can lose it: every path here keeps values addressable.
func reachable(v reflect.Value) reflect.Value {
if v.CanSet() || !v.CanAddr() {
return v
}
return reflect.NewAt(v.Type(), unsafe.Pointer(v.UnsafeAddr())).Elem()
}
func (w *walk) decode(v reflect.Value, tree any, depth int) {
if depth > maxDepth {
return
}
v = reachable(v)
if !v.CanSet() {
return
}
switch v.Kind() {
case reflect.Bool:
if b, ok := tree.(bool); ok {
v.SetBool(b)
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if n, ok := tree.(json.Number); ok {
if i, err := n.Int64(); err == nil && !v.OverflowInt(i) {
v.SetInt(i)
}
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if n, ok := tree.(json.Number); ok {
if i, err := strconv.ParseUint(n.String(), 10, 64); err == nil && !v.OverflowUint(i) {
v.SetUint(i)
}
}
case reflect.Float32, reflect.Float64:
if n, ok := tree.(json.Number); ok {
if f, err := n.Float64(); err == nil && !v.OverflowFloat(f) {
v.SetFloat(f)
}
}
case reflect.String:
if s, ok := tree.(string); ok {
v.SetString(s)
}
case reflect.Slice:
if !w.keepable(v.Type().Elem()) {
return // the whole collection stays as made
}
if tree == nil {
v.SetZero()
return
}
if list, ok := tree.([]any); ok {
out := reflect.MakeSlice(v.Type(), len(list), len(list))
for i, x := range list {
w.decode(out.Index(i), x, depth+1)
}
v.Set(out)
}
case reflect.Array:
if list, ok := tree.([]any); ok {
for i, x := range list {
if i < v.Len() {
w.decode(v.Index(i), x, depth+1)
}
}
}
case reflect.Map:
if !validKey(v.Type().Key()) || !w.keepable(v.Type().Elem()) {
return
}
if tree == nil {
v.SetZero()
return
}
if m, ok := tree.(map[string]any); ok {
out := reflect.MakeMapWithSize(v.Type(), len(m))
for s, x := range m {
k, ok := keyValue(v.Type().Key(), s)
if !ok {
continue
}
e := reflect.New(v.Type().Elem()).Elem()
w.decode(e, x, depth+1)
out.SetMapIndex(k, e)
}
v.Set(out)
}
case reflect.Pointer:
if !w.followed(v.Type().Elem()) {
return
}
if tree == nil {
if w.keepable(v.Type().Elem()) {
v.SetZero()
}
return
}
if v.IsNil() {
if !w.keepable(v.Type().Elem()) {
return // what it holds that can't be kept stays as made: nothing
}
v.Set(reflect.New(v.Type().Elem()))
}
w.decode(v.Elem(), tree, depth+1)
case reflect.Struct:
if v.Type() == timeType {
if s, ok := tree.(string); ok {
var t time.Time
if t.UnmarshalText([]byte(s)) == nil {
v.Set(reflect.ValueOf(t))
}
}
return
}
m, ok := tree.(map[string]any)
if !ok || !w.walkable(v.Type()) {
return
}
t := v.Type()
for i := range t.NumField() {
if x, ok := m[t.Field(i).Name]; ok {
w.decode(v.Field(i), x, depth+1)
}
}
}
}
+321
View File
@@ -0,0 +1,321 @@
package keepstate
import (
"math"
"reflect"
"sync"
"testing"
"time"
"github.com/egoist/mygo/internal/scene"
)
func init() {
ownModule = "this test's types are an app's" // not the framework's world
}
type inner struct {
Name string
count int
}
type thing struct {
tab int
name string
on bool
ratio float64
big int64
rows []string
byName map[string]int
byID map[int]inner
in inner
when time.Time
took time.Duration
next *inner
empty []int
arr [2]int
mu sync.Mutex
fn func()
ch chan int
foreign *scene.Image
any any
nan float64
}
// A struct of an app's comes back whole, unexported fields and all.
func TestRoundTrip(t *testing.T) {
when := time.Date(2026, 11, 2, 12, 0, 0, 5, time.UTC)
a := &thing{
tab: 3, name: "中文 😀", on: true, ratio: 0.25, big: math.MaxInt64 - 1,
rows: []string{"a", "b"}, byName: map[string]int{"x": 1}, byID: map[int]inner{7: {"seven", 7}},
in: inner{"in", 2}, when: when, took: time.Minute, next: &inner{"next", 9}, arr: [2]int{4, 5},
nan: math.NaN(),
}
data, err := Encode(a)
if err != nil {
t.Fatal(err)
}
var b thing
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if b.tab != 3 || b.name != a.name || !b.on || b.ratio != 0.25 || b.big != a.big {
t.Errorf("scalars: %d %q %v", b.tab, b.name, b.ratio)
}
if !reflect.DeepEqual(b.rows, a.rows) || !reflect.DeepEqual(b.byName, a.byName) || !reflect.DeepEqual(b.byID, a.byID) {
t.Errorf("collections: %v %v %v", b.rows, b.byName, b.byID)
}
if b.in != a.in || !b.when.Equal(when) || b.took != time.Minute || b.next == nil || *b.next != *a.next || b.arr != a.arr {
t.Errorf("structs: %+v, %v", b.in, b.next)
}
}
// What it doesn't keep stays as the program made it.
func TestLeavesTheWorld(t *testing.T) {
made := func() {}
ch := make(chan int)
img := &scene.Image{W: 1}
a := &thing{tab: 1, foreign: &scene.Image{W: 9}, any: 5}
data, err := Encode(a)
if err != nil {
t.Fatal(err)
}
b := thing{fn: made, ch: ch, foreign: img, any: "made", ratio: 2}
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if b.fn == nil || b.ch != ch || b.foreign != img || img.W != 1 || b.any != "made" {
t.Errorf("the world changed: %v %v", b.foreign, b.any)
}
if b.tab != 1 {
t.Errorf("tab: %d", b.tab)
}
}
// A change of the code keeps what still fits.
func TestCodeChanged(t *testing.T) {
type before struct {
tab string
kept int
gone int
rows []int
byKey map[string]int
}
type after struct {
tab int // another type: stays as made
kept int
added string
rows []string // another type of element: its elements stay empty
byKey map[int]int
}
data, err := Encode(&before{tab: "x", kept: 5, gone: 9, rows: []int{1}, byKey: map[string]int{"a": 1}})
if err != nil {
t.Fatal(err)
}
b := after{tab: 7, added: "made"}
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if b.tab != 7 || b.kept != 5 || b.added != "made" {
t.Errorf("%+v", b)
}
}
// A pointer of the framework leads nowhere, whatever it holds: a widget's state
// may hold a handle that reaches all of a window's elements.
func TestFrameworkPointers(t *testing.T) {
defer func(m string) { ownModule = m }(ownModule)
ownModule = "github.com/egoist/mygo"
a := &inner{Name: "x"}
type holder struct {
in *inner
img *scene.Image
}
data, err := Encode(&holder{in: a, img: &scene.Image{W: 1}})
if err != nil {
t.Fatal(err)
}
if string(data) != "{}" {
t.Errorf("wrote %s", data)
}
}
// A cycle ends.
func TestCycle(t *testing.T) {
type node struct {
next *node
n int
}
a := &node{n: 1}
a.next = a
data, err := Encode(a)
if err != nil {
t.Fatal(err)
}
var b node
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if b.n != 1 {
t.Errorf("n: %d", b.n)
}
}
// Numbers that overflow what they go into stay out.
func TestOverflow(t *testing.T) {
type big struct{ n int64 }
type small struct{ n int8 }
data, err := Encode(&big{n: 1000})
if err != nil {
t.Fatal(err)
}
b := small{n: 1}
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if b.n != 1 {
t.Errorf("n: %d", b.n)
}
}
// Encoding a plain scalar, as a widget's local state is.
func TestScalar(t *testing.T) {
n := 42
data, err := Encode(&n)
if err != nil {
t.Fatal(err)
}
var m int
if err := Decode(data, &m); err != nil || m != 42 {
t.Errorf("%d, %v", m, err)
}
}
// What holds many ways to the same values stays quick and small.
func TestSharedPointers(t *testing.T) {
type node struct {
prev, next *node
n int
}
var first, last *node
for i := range 200 {
x := &node{n: i, prev: last}
if last != nil {
last.next = x
} else {
first = x
}
last = x
}
data, err := Encode(first)
if err != nil {
t.Fatal(err)
}
if len(data) > 200*64 {
t.Errorf("%d bytes for 200 nodes", len(data))
}
var back node
if err := Decode(data, &back); err != nil {
t.Fatal(err)
}
n := 0
for x := &back; x != nil; x = x.next {
if x.n != n {
t.Fatalf("node %d says %d", n, x.n)
}
n++
}
if n != 200 {
t.Errorf("%d of 200 nodes", n)
}
}
// A time inside a map's struct, whose values can't be addressed.
func TestTimeInMap(t *testing.T) {
type todo struct{ created time.Time }
type state struct {
exported map[string]todo
ptr map[string]*todo
}
when := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
a := state{exported: map[string]todo{"a": {when}}, ptr: map[string]*todo{"b": {when}}}
data, err := Encode(&a)
if err != nil {
t.Fatal(err)
}
var b state
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if !b.exported["a"].created.Equal(when) || b.ptr["b"] == nil || !b.ptr["b"].created.Equal(when) {
t.Errorf("%v %v", b.exported, b.ptr)
}
}
// A collection of what can't come back whole stays as the program made it, rather
// than coming back with holes.
func TestCollectionsStayWhole(t *testing.T) {
type row struct {
name string
fn func() int
}
type state struct {
rows []row
byName map[string]row
any []any
foreign []*scene.Image
kept []string
}
img := &scene.Image{W: 3}
fn := func() int { return 7 }
a := state{rows: []row{{"a", fn}, {"b", fn}}, kept: []string{"x"}}
data, err := Encode(&a)
if err != nil {
t.Fatal(err)
}
b := state{
rows: []row{{"made", fn}}, byName: map[string]row{"m": {"made", fn}},
any: []any{1}, foreign: []*scene.Image{img},
}
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if len(b.rows) != 1 || b.rows[0].name != "made" || b.rows[0].fn() != 7 || b.byName["m"].fn == nil {
t.Errorf("rows: %+v", b.rows)
}
if len(b.any) != 1 || b.foreign[0] != img {
t.Errorf("any %v, foreign %v", b.any, b.foreign)
}
if len(b.kept) != 1 || b.kept[0] != "x" {
t.Errorf("kept: %v", b.kept)
}
}
// Nil is a value: what the app emptied stays empty, whatever it starts with.
func TestNilComesBack(t *testing.T) {
type state struct {
items []string
names map[string]int
next *int
}
data, err := Encode(&state{})
if err != nil {
t.Fatal(err)
}
one := 1
b := state{items: []string{"seed"}, names: map[string]int{"seed": 1}, next: &one}
if err := Decode(data, &b); err != nil {
t.Fatal(err)
}
if b.items != nil || b.names != nil || b.next != nil {
t.Errorf("%+v", b)
}
}
// Too much to write every second is an error, not a stall.
func TestTooLarge(t *testing.T) {
big := make([]int, maxNodes+10)
if _, err := Encode(&big); err == nil {
t.Error("no error")
}
}