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

+121
View File
@@ -0,0 +1,121 @@
// Command idlemem launches apps and reports how much memory each takes
// once idle, alone and with the processes it runs, its webview's:
// scripts/bench.ts measures release builds of examples/hello and
// examples/counter-native with it on every push to main. It needs a
// desktop session.
//
// go run ./internal/idlemem [-count 3] [-idle 6s] app...
//
// Each app runs count times, for idle each time, and the medians print as
// JSON, by the name of the app's file: {"hello": {"app": bytes, "total":
// bytes}}. Memory is what each platform shows for a process:
//
// - macOS: the physical footprint, as Activity Monitor shows it, of the
// app and of the WebKit processes that started with it and share its
// responsible process (a terminal, say, for an app not in a bundle);
// - Linux: the proportional set size of the app and of its descendants,
// WebKitGTK's processes, so that pages they share count once;
// - Windows: the private working set, as Task Manager shows it, of the
// app and of its descendants, WebView2's processes.
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
)
func main() {
count := flag.Int("count", 3, "how many times each app runs")
idle := flag.Duration("idle", 6*time.Second, "how long an app runs before it is measured")
flag.Parse()
out := map[string]map[string]uint64{}
for _, bin := range flag.Args() {
name := strings.TrimSuffix(filepath.Base(bin), ".exe")
var apps, totals []uint64
for range *count {
app, total, err := measure(bin, *idle)
if err != nil {
fmt.Fprintf(os.Stderr, "idlemem: %s: %v\n", name, err)
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "%s: %.1f MB, %.1f MB with its processes\n", name, float64(app)/1e6, float64(total)/1e6)
apps, totals = append(apps, app), append(totals, total)
}
out[name] = map[string]uint64{"app": median(apps), "total": median(totals)}
}
if err := json.NewEncoder(os.Stdout).Encode(out); err != nil {
fmt.Fprintln(os.Stderr, "idlemem:", err)
os.Exit(1)
}
}
// measure runs bin for idle, and returns the memory of its process, and of
// it with the processes it runs.
func measure(bin string, idle time.Duration) (app, total uint64, err error) {
s := before()
// The app's standard error tells why it exited, should it exit by
// itself: a Go program that panics, or crashes in native code, prints
// what it was doing there and exits with status 2. A file, not a pipe:
// the webview's processes inherit it, and Wait would wait for them to
// close a pipe.
stderr, err := os.CreateTemp("", "idlemem-*.log")
if err != nil {
return 0, 0, err
}
defer os.Remove(stderr.Name())
defer stderr.Close()
cmd := exec.Command(bin)
cmd.Env = append(os.Environ(), "MYGO_ENV=production")
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return 0, 0, err
}
exited := make(chan error, 1)
go func() { exited <- cmd.Wait() }()
select {
case err := <-exited:
return 0, 0, fmt.Errorf("exited after starting: %v%s", err, output(stderr.Name()))
case <-time.After(idle):
}
app, total, procs, err := usage(cmd.Process.Pid, s)
if len(procs) == 0 {
procs = []int{cmd.Process.Pid}
}
stopErr := stop(cmd.Process, procs)
select {
case <-exited:
case <-time.After(10 * time.Second):
cmd.Process.Kill()
<-exited
}
if err == nil {
err = stopErr
}
return app, total, err
}
// output returns what the app wrote to its standard error, in the file at
// path, to follow an error, or "" for nothing.
func output(path string) string {
b, _ := os.ReadFile(path)
if s := strings.TrimSpace(string(b)); s != "" {
return "; its standard error:\n" + s
}
return ""
}
func median(v []uint64) uint64 {
s := slices.Clone(v)
slices.Sort(s)
if len(s)%2 == 1 {
return s[len(s)/2]
}
return (s[len(s)/2-1] + s[len(s)/2]) / 2
}
+28
View File
@@ -0,0 +1,28 @@
package main
import (
"os"
"strings"
"testing"
"time"
)
// TestMain runs the test binary as an app that panics as it starts, for
// TestExitedAfterStarting.
func TestMain(m *testing.M) {
if os.Getenv("IDLEMEM_TEST_PANIC") == "1" {
panic("the app cannot start")
}
os.Exit(m.Run())
}
// TestExitedAfterStarting checks that an app that exits by itself before
// it is measured is told with what it wrote to its standard error, as the
// panic that ended it.
func TestExitedAfterStarting(t *testing.T) {
t.Setenv("IDLEMEM_TEST_PANIC", "1")
_, _, err := measure(os.Args[0], time.Hour)
if err == nil || !strings.Contains(err.Error(), "exited after starting: exit status 2") || !strings.Contains(err.Error(), "panic: the app cannot start") {
t.Fatalf("measure: %v, want the app's exit status and its panic", err)
}
}
+96
View File
@@ -0,0 +1,96 @@
//go:build !ios
package main
import (
"encoding/binary"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
"github.com/ebitengine/purego"
)
var (
procPidRusage func(pid, flavor int32, buf unsafe.Pointer) int32
procListAllPids func(buf unsafe.Pointer, size int32) int32
procPidPath func(pid int32, buf unsafe.Pointer, size uint32) int32
// responsibleFor is private API: nil where libSystem lacks it.
responsibleFor func(pid int32) int32
)
func init() {
lib, err := purego.Dlopen("/usr/lib/libSystem.B.dylib", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
panic(err)
}
purego.RegisterLibFunc(&procPidRusage, lib, "proc_pid_rusage")
purego.RegisterLibFunc(&procListAllPids, lib, "proc_listallpids")
purego.RegisterLibFunc(&procPidPath, lib, "proc_pidpath")
if _, err := purego.Dlsym(lib, "responsibility_get_pid_responsible_for_pid"); err == nil {
purego.RegisterLibFunc(&responsibleFor, lib, "responsibility_get_pid_responsible_for_pid")
}
}
// state is the WebKit processes that ran before the app started.
type state map[int32]bool
func before() state {
s := state{}
for _, pid := range webKit() {
s[pid] = true
}
return s
}
// usage counts the WebKit processes that started with the app and share
// its responsible process: WKWebView's, for its page, GPU and network.
func usage(pid int, s state) (app, total uint64, procs []int, err error) {
app, err = footprint(int32(pid))
if err != nil {
return 0, 0, nil, err
}
total, procs = app, []int{pid}
for _, p := range webKit() {
if s[p] || responsibleFor != nil && responsibleFor(p) != responsibleFor(int32(pid)) {
continue
}
if f, err := footprint(p); err == nil {
total += f
procs = append(procs, int(p))
}
}
return app, total, procs, nil
}
// footprint returns the physical footprint of pid: ri_phys_footprint of
// its rusage_info_v2, after a 16-byte UUID and seven counters.
func footprint(pid int32) (uint64, error) {
var info [512]byte
if procPidRusage(pid, 2, unsafe.Pointer(&info[0])) != 0 {
return 0, fmt.Errorf("proc_pid_rusage(%d) failed", pid)
}
return binary.LittleEndian.Uint64(info[72:]), nil
}
// webKit returns the processes of WebKit's XPC services.
func webKit() []int32 {
pids := make([]int32, max(procListAllPids(nil, 0), 4096)+256)
n := procListAllPids(unsafe.Pointer(&pids[0]), int32(4*len(pids)))
var out []int32
var path [4096]byte
for _, pid := range pids[:max(n, 0)] {
if l := procPidPath(pid, unsafe.Pointer(&path[0]), uint32(len(path))); l > 0 && strings.Contains(string(path[:l]), "/com.apple.WebKit.") {
out = append(out, pid)
}
}
return out
}
// stop asks the app to quit, which its WebKit processes follow.
func stop(p *os.Process, _ []int) error {
p.Signal(syscall.SIGTERM)
return nil
}
+87
View File
@@ -0,0 +1,87 @@
//go:build !android
package main
import (
"fmt"
"os"
"strconv"
"strings"
"syscall"
)
type state struct{}
func before() state { return state{} }
// usage counts the app's descendants: WebKitGTK's web and network
// processes, and what they run.
func usage(pid int, _ state) (app, total uint64, procs []int, err error) {
procs = append([]int{pid}, descendants(pid)...)
for i, p := range procs {
pss, err := pssOf(p)
if err != nil {
if i == 0 {
return 0, 0, nil, err
}
continue
}
if i == 0 {
app = pss
}
total += pss
}
return app, total, procs, nil
}
// pssOf returns the proportional set size of pid: its own pages, and its
// share of those it shares.
func pssOf(pid int) (uint64, error) {
b, err := os.ReadFile(fmt.Sprintf("/proc/%d/smaps_rollup", pid))
if err != nil {
return 0, err
}
for line := range strings.SplitSeq(string(b), "\n") {
if v, ok := strings.CutPrefix(line, "Pss:"); ok {
kb, err := strconv.ParseUint(strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(v), "kB")), 10, 64)
return kb << 10, err
}
}
return 0, fmt.Errorf("no Pss in /proc/%d/smaps_rollup", pid)
}
// descendants returns the processes pid started, and theirs.
func descendants(pid int) []int {
entries, _ := os.ReadDir("/proc")
children := map[int][]int{}
for _, e := range entries {
p, err := strconv.Atoi(e.Name())
if err != nil {
continue
}
b, err := os.ReadFile("/proc/" + e.Name() + "/stat")
if err != nil {
continue
}
// pid (comm) state ppid …, where comm may hold anything.
f := strings.Fields(string(b[strings.LastIndexByte(string(b), ')')+1:]))
if len(f) < 2 {
continue
}
if ppid, err := strconv.Atoi(f[1]); err == nil {
children[ppid] = append(children[ppid], p)
}
}
var out []int
for queue := children[pid]; len(queue) > 0; queue = queue[1:] {
out = append(out, queue[0])
queue = append(queue, children[queue[0]]...)
}
return out
}
// stop asks the app to quit, which its WebKit processes follow.
func stop(p *os.Process, _ []int) error {
p.Signal(syscall.SIGTERM)
return nil
}
+18
View File
@@ -0,0 +1,18 @@
//go:build !(darwin && !ios) && !(linux && !android) && !windows
package main
import (
"errors"
"os"
)
type state struct{}
func before() state { return state{} }
func usage(int, state) (app, total uint64, procs []int, err error) {
return 0, 0, nil, errors.New("not measured on this platform")
}
func stop(p *os.Process, _ []int) error { return p.Kill() }
+147
View File
@@ -0,0 +1,147 @@
package main
import (
"errors"
"os"
"syscall"
"unsafe"
)
type state struct{}
func before() state { return state{} }
var getProcessMemoryInfo = syscall.NewLazyDLL("kernel32.dll").NewProc("K32GetProcessMemoryInfo")
// processMemoryCountersEx2 is PROCESS_MEMORY_COUNTERS_EX2, of Windows 10
// 1809 and later.
type processMemoryCountersEx2 struct {
cb uint32
PageFaultCount uint32
PeakWorkingSetSize uintptr
WorkingSetSize uintptr
QuotaPeakPagedPoolUsage uintptr
QuotaPagedPoolUsage uintptr
QuotaPeakNonPagedPoolUsage uintptr
QuotaNonPagedPoolUsage uintptr
PagefileUsage uintptr
PeakPagefileUsage uintptr
PrivateUsage uintptr
PrivateWorkingSetSize uintptr
SharedCommitUsage uint64
}
const (
processTerminate = 0x0001
processQueryLimitedInformation = 0x1000
)
// usage counts the app's descendants: WebView2's browser process, and the
// renderer, GPU and utility processes it runs.
func usage(pid int, _ state) (app, total uint64, procs []int, err error) {
procs = append([]int{pid}, descendants(pid)...)
for i, p := range procs {
ws, err := privateWorkingSet(p)
if err != nil {
if i == 0 {
return 0, 0, nil, err
}
continue
}
if i == 0 {
app = ws
}
total += ws
}
return app, total, procs, nil
}
// privateWorkingSet returns the pages of pid in memory that no other
// process shares.
func privateWorkingSet(pid int) (uint64, error) {
h, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid))
if err != nil {
return 0, err
}
defer syscall.CloseHandle(h)
var c processMemoryCountersEx2
c.cb = uint32(unsafe.Sizeof(c))
if ok, _, err := getProcessMemoryInfo.Call(uintptr(h), uintptr(unsafe.Pointer(&c)), uintptr(c.cb)); ok == 0 {
return 0, err
}
return uint64(c.PrivateWorkingSetSize), nil
}
// descendants returns the processes pid started, and theirs.
func descendants(pid int) []int {
snap, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil
}
defer syscall.CloseHandle(snap)
children := map[int][]int{}
var e syscall.ProcessEntry32
e.Size = uint32(unsafe.Sizeof(e))
for err := syscall.Process32First(snap, &e); err == nil; err = syscall.Process32Next(snap, &e) {
children[int(e.ParentProcessID)] = append(children[int(e.ParentProcessID)], int(e.ProcessID))
}
// A parent's ID may have been reused by a process it did not start.
seen := map[int]bool{pid: true}
var out []int
for queue := children[pid]; len(queue) > 0; queue = queue[1:] {
if seen[queue[0]] {
continue
}
seen[queue[0]] = true
out = append(out, queue[0])
queue = append(queue, children[queue[0]]...)
}
return out
}
// stop ends the app and the processes it ran, as Windows has no signal
// to ask it to quit, and returns once all have exited, with those they
// started since usage looked. TerminateProcess only starts ending a
// process, and the next run's WebView2 could otherwise meet this run's
// browser still exiting, which holds the user data folder they share.
func stop(_ *os.Process, procs []int) error {
// A handle on a process keeps its ID from going to another process,
// which descendants would take for one of the app's.
held := map[int]syscall.Handle{}
defer func() {
for _, h := range held {
syscall.CloseHandle(h)
}
}()
app := procs[0]
for range 10 {
var ending []syscall.Handle
for _, pid := range procs {
if _, ok := held[pid]; ok {
continue
}
h, err := syscall.OpenProcess(processTerminate|syscall.SYNCHRONIZE, false, uint32(pid))
if err != nil {
continue // gone already
}
held[pid] = h
ending = append(ending, h)
}
if len(ending) == 0 {
return nil
}
for _, h := range ending {
syscall.TerminateProcess(h, 1)
}
for _, h := range ending {
if ev, _ := syscall.WaitForSingleObject(h, 10_000); ev != syscall.WAIT_OBJECT_0 {
return errors.New("a process of the app still runs 10s after it was ended")
}
}
if _, ok := held[app]; !ok {
return nil // its ID may be another process's now
}
procs = descendants(app)
}
return errors.New("the app's processes kept starting others as they were ended")
}