* feat: add experimental Apple Silicon support with Nivfold Integrate the standalone Nivfold protocol 1 runner; tested against Nivfold f436fb6. The Windows Reims vGPU runtime remains independent. * fix: open QQ invites and VM SSH on macOS * fix: move VM, View and Help to the macOS menu bar * feat(macos): add resumable Apple restore image downloads Expose the compatible restore image in the VM wizard and Images page, validate downloads before caching, and fix macOS memory reporting and plugin SVG rendering. * fix(macos): localize the native application menu * fix(macos): address native desktop review findings
441 lines
12 KiB
Go
441 lines
12 KiB
Go
package app
|
|
|
|
// Long-running work (installer downloads, VM creation) is tracked as tasks and
|
|
// pushed to the frontend as "reims:task" events (docs/design-guidelines.md §7.3), so
|
|
// progress is a progress bar rather than one log line per percent.
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/vmstart"
|
|
)
|
|
|
|
const (
|
|
TaskRunning = "running"
|
|
TaskDone = "done"
|
|
TaskFailed = "failed"
|
|
TaskCanceled = "canceled"
|
|
|
|
TaskPhaseQueued = "queued"
|
|
TaskPhaseDownloading = "downloading"
|
|
)
|
|
|
|
// Task is one tracked job as the frontend sees it.
|
|
type Task struct {
|
|
ID string `json:"id"`
|
|
Kind string `json:"kind"` // installer/recovery/VM/runtime/app tasks or "plugin:<pluginID>"
|
|
Subject string `json:"subject"` // release ("26.7.3") or VM name
|
|
VM string `json:"vm,omitempty"`
|
|
InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" | "ipsw" while an installer download is attached
|
|
InstallerVersion string `json:"installer_version,omitempty"` // release ("26.7.3") or online target ("tahoe" / "latest")
|
|
InstallerPhase string `json:"installer_phase,omitempty"` // "queued" | "downloading" while active
|
|
Step string `json:"step"` // upstream wording, e.g. "downloading OpenCore 1.0.8"
|
|
Done int64 `json:"done"`
|
|
Total int64 `json:"total"` // 0 when unknown
|
|
Percent float64 `json:"percent"` // -1 when unknown
|
|
Rate float64 `json:"rate"` // bytes per second, 0 when unknown
|
|
Status string `json:"status"`
|
|
Error string `json:"error,omitempty"`
|
|
Result string `json:"result,omitempty"`
|
|
Cancelable bool `json:"cancelable"`
|
|
StartedAt int64 `json:"started_at"` // unix ms
|
|
UpdatedAt int64 `json:"updated_at"`
|
|
}
|
|
|
|
type taskEntry struct {
|
|
task Task
|
|
cancel context.CancelFunc
|
|
lastEmit time.Time
|
|
rate rateMeter
|
|
}
|
|
|
|
type taskManager struct {
|
|
mu sync.Mutex
|
|
seq int
|
|
tasks map[string]*taskEntry
|
|
emit func(Task)
|
|
}
|
|
|
|
// tasks is the process-wide manager; App methods below use it. Kept out of the
|
|
// App struct so this file stays self-contained.
|
|
var tasks = &taskManager{tasks: map[string]*taskEntry{}}
|
|
|
|
// emitInterval caps progress events per task; step and status changes always go out.
|
|
const emitInterval = 200 * time.Millisecond
|
|
|
|
// finishedTTL is how long finished tasks stay in GetTasks.
|
|
const finishedTTL = 10 * time.Minute
|
|
|
|
func (m *taskManager) start(kind, subject, vm string, cancel context.CancelFunc) string {
|
|
return m.startWithInstaller(kind, subject, vm, "", "", "", cancel)
|
|
}
|
|
|
|
func (m *taskManager) startWithInstaller(kind, subject, vm, installerKind, installerVersion, installerPhase string, cancel context.CancelFunc) string {
|
|
return m.startWithCancelFactory(kind, subject, vm, installerKind, installerVersion, installerPhase, func(string) context.CancelFunc { return cancel })
|
|
}
|
|
|
|
func (m *taskManager) startWithCancelFactory(kind, subject, vm, installerKind, installerVersion, installerPhase string, makeCancel func(string) context.CancelFunc) string {
|
|
m.mu.Lock()
|
|
m.seq++
|
|
id := fmt.Sprintf("%s-%d", kind, m.seq)
|
|
cancel := makeCancel(id)
|
|
now := time.Now().UnixMilli()
|
|
step := ""
|
|
if installerPhase == TaskPhaseQueued {
|
|
step = host.WaitingNote
|
|
}
|
|
e := &taskEntry{
|
|
task: Task{
|
|
ID: id, Kind: kind, Subject: subject, VM: vm,
|
|
InstallerKind: installerKind, InstallerVersion: installerVersion, InstallerPhase: installerPhase,
|
|
Step: step, Percent: -1, Status: TaskRunning, Cancelable: cancel != nil,
|
|
StartedAt: now, UpdatedAt: now,
|
|
},
|
|
cancel: cancel,
|
|
}
|
|
m.tasks[id] = e
|
|
m.pruneLocked()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
return id
|
|
}
|
|
|
|
// setInstaller attaches installer download metadata and phase to a running task.
|
|
func (m *taskManager) setInstaller(id, kind, version, phase string) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok || e.task.Status != TaskRunning {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.InstallerKind = kind
|
|
e.task.InstallerVersion = version
|
|
e.task.InstallerPhase = phase
|
|
if phase == TaskPhaseQueued {
|
|
e.task.Step = host.WaitingNote
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
}
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
// clearInstallerPhase marks a task's installer download stage complete while
|
|
// keeping the task running for any remaining work (e.g. OpenCore / disk creation).
|
|
func (m *taskManager) clearInstallerPhase(id string) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok || e.task.Status != TaskRunning {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
if e.task.InstallerPhase == "" {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.InstallerPhase = ""
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
// update applies an upstream progress report to the task.
|
|
func (m *taskManager) update(id string, u host.Update) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok || e.task.Status != TaskRunning {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
force := false
|
|
switch u.Kind {
|
|
case host.KindNote:
|
|
if u.Message != host.WaitingNote || e.task.InstallerKind == "" {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
if e.task.InstallerPhase == TaskPhaseQueued && e.task.Step == u.Message {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.InstallerPhase = TaskPhaseQueued
|
|
e.task.Step = u.Message
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
force = true
|
|
case host.KindStep:
|
|
if e.task.InstallerPhase == TaskPhaseQueued {
|
|
e.task.InstallerPhase = TaskPhaseDownloading
|
|
force = true
|
|
}
|
|
force = force || e.task.Step != u.Message
|
|
e.task.Step = u.Message
|
|
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
|
e.rate = rateMeter{}
|
|
case host.KindProgress:
|
|
if e.task.InstallerPhase == TaskPhaseQueued {
|
|
e.task.InstallerPhase = TaskPhaseDownloading
|
|
force = true
|
|
}
|
|
if u.Step != "" && u.Step != e.task.Step {
|
|
e.task.Step = u.Step
|
|
e.rate = rateMeter{}
|
|
force = true
|
|
}
|
|
e.task.Done, e.task.Total, e.task.Percent = u.Done, u.Total, u.Percent
|
|
e.task.Rate = e.rate.add(u.Done)
|
|
force = force || u.Percent >= 100
|
|
default:
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
if !force && time.Since(e.lastEmit) < emitInterval {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
e.lastEmit = time.Now()
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
func (m *taskManager) finish(id string, result string, err error) {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
switch {
|
|
case err == nil:
|
|
e.task.Status = TaskDone
|
|
e.task.Result = result
|
|
if e.task.Total > 0 {
|
|
e.task.Done, e.task.Percent = e.task.Total, 100
|
|
}
|
|
case errors.Is(err, context.Canceled) || strings.Contains(err.Error(), context.Canceled.Error()):
|
|
e.task.Status = TaskCanceled
|
|
default:
|
|
e.task.Status = TaskFailed
|
|
e.task.Error = err.Error()
|
|
}
|
|
e.task.InstallerPhase = ""
|
|
e.task.Cancelable = false
|
|
e.task.Rate = 0
|
|
e.task.UpdatedAt = time.Now().UnixMilli()
|
|
e.cancel = nil
|
|
t := e.task
|
|
m.mu.Unlock()
|
|
m.send(t)
|
|
}
|
|
|
|
func (m *taskManager) cancel(id string) error {
|
|
m.mu.Lock()
|
|
e, ok := m.tasks[id]
|
|
if !ok {
|
|
m.mu.Unlock()
|
|
return fmt.Errorf("no task %s", id)
|
|
}
|
|
cancel := e.cancel
|
|
m.mu.Unlock()
|
|
if cancel == nil {
|
|
return fmt.Errorf("task %s can't be stopped", id)
|
|
}
|
|
cancel()
|
|
return nil
|
|
}
|
|
|
|
// hasRunningDownload reports whether a download is in progress: closing the
|
|
// window would abort it, so the user is asked first.
|
|
func (m *taskManager) hasRunningDownload() bool {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
for _, e := range m.tasks {
|
|
if e.task.Status != TaskRunning {
|
|
continue
|
|
}
|
|
if e.task.InstallerPhase == TaskPhaseDownloading {
|
|
return true // such as a VM creation fetching its installer
|
|
}
|
|
switch e.task.Kind {
|
|
case "installer-download", "recovery-download", "runtime-install", "app-update", taskKindPluginDownload:
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (m *taskManager) hasRunningRestore() bool {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
for _, e := range m.tasks {
|
|
if e.task.Kind == "vm-restore" && e.task.Status == TaskRunning {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (m *taskManager) cancelAll() {
|
|
m.mu.Lock()
|
|
cancels := make([]context.CancelFunc, 0, len(m.tasks))
|
|
for _, e := range m.tasks {
|
|
if e.cancel != nil {
|
|
cancels = append(cancels, e.cancel)
|
|
}
|
|
}
|
|
m.mu.Unlock()
|
|
for _, fn := range cancels {
|
|
fn()
|
|
}
|
|
}
|
|
|
|
func (m *taskManager) get(id string) (Task, bool) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
e, ok := m.tasks[id]
|
|
if !ok {
|
|
return Task{}, false
|
|
}
|
|
return e.task, true
|
|
}
|
|
|
|
func (m *taskManager) list() []Task {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.pruneLocked()
|
|
out := make([]Task, 0, len(m.tasks))
|
|
for _, e := range m.tasks {
|
|
out = append(out, e.task)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].StartedAt < out[j].StartedAt })
|
|
return out
|
|
}
|
|
|
|
func (m *taskManager) pruneLocked() {
|
|
cutoff := time.Now().Add(-finishedTTL).UnixMilli()
|
|
for id, e := range m.tasks {
|
|
if e.task.Status != TaskRunning && e.task.UpdatedAt < cutoff {
|
|
delete(m.tasks, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (m *taskManager) send(t Task) {
|
|
m.mu.Lock()
|
|
emit := m.emit
|
|
m.mu.Unlock()
|
|
if emit != nil {
|
|
emit(t)
|
|
}
|
|
}
|
|
|
|
// rateMeter is bytes per second over a sliding window of about five seconds.
|
|
type rateMeter struct {
|
|
at []time.Time
|
|
done []int64
|
|
}
|
|
|
|
func (r *rateMeter) add(done int64) float64 {
|
|
now := time.Now()
|
|
r.at = append(r.at, now)
|
|
r.done = append(r.done, done)
|
|
for len(r.at) > 2 && now.Sub(r.at[0]) > 5*time.Second {
|
|
r.at, r.done = r.at[1:], r.done[1:]
|
|
}
|
|
dt := now.Sub(r.at[0]).Seconds()
|
|
if dt < 1 || done < r.done[0] {
|
|
return 0
|
|
}
|
|
return float64(done-r.done[0]) / dt
|
|
}
|
|
|
|
// ── App bindings ─────────────────────────────────────────────
|
|
|
|
func (a *App) taskEmitter() func(Task) {
|
|
return func(t Task) {
|
|
a.emit("reims:task", t)
|
|
}
|
|
}
|
|
|
|
// GetTasks lists running tasks and ones finished in the last few minutes.
|
|
func (a *App) GetTasks() []Task {
|
|
a.ensureTaskEmitter()
|
|
return tasks.list()
|
|
}
|
|
|
|
// CancelTask stops a cancelable task (a download pauses; rerunning resumes it).
|
|
func (a *App) CancelTask(id string) error { return tasks.cancel(id) }
|
|
|
|
func (a *App) ensureTaskEmitter() {
|
|
tasks.mu.Lock()
|
|
if tasks.emit == nil {
|
|
tasks.emit = a.taskEmitter()
|
|
}
|
|
tasks.mu.Unlock()
|
|
}
|
|
|
|
// ctlTaskWriter returns a writer for reims-ctl output that routes progress
|
|
// lines into a task and everything else to the log. reims-ctl prints its
|
|
// progress as "<step>: N% of <size>" (host.ParseCtlLine), sometimes behind
|
|
// a "<vm>: " prefix, which is dropped from the step. Each new step is logged
|
|
// once, so the log keeps the milestones without one line per percent.
|
|
// finish closes the task with the command's error.
|
|
func (a *App) ctlTaskWriter(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) {
|
|
a.ensureTaskEmitter()
|
|
id = tasks.start(kind, vm, vm, cancel)
|
|
lastStep := ""
|
|
lastLogAt := time.Now()
|
|
// vm is a VM name or a VM key.
|
|
name := vmNameFromKey(vm)
|
|
source := vm
|
|
if name == vm {
|
|
source = vmKey(vm)
|
|
}
|
|
trim := func(s string) string { return strings.TrimPrefix(s, name+": ") }
|
|
w = vmstart.LineWriter(func(line string) {
|
|
u, ok := host.ParseCtlLine(line)
|
|
if !ok {
|
|
return
|
|
}
|
|
if u.Kind == host.KindProgress {
|
|
u.Step = trim(u.Step)
|
|
if u.Step != lastStep {
|
|
lastStep = u.Step
|
|
lastLogAt = time.Now()
|
|
a.emitLog(source, u.Step)
|
|
} else if time.Since(lastLogAt) >= 30*time.Second {
|
|
lastLogAt = time.Now()
|
|
if u.Total > 0 {
|
|
a.emitLog(source, fmt.Sprintf("%s: %.0f%% (%.1f / %.1f MB)", u.Step, u.Percent, float64(u.Done)/1e6, float64(u.Total)/1e6))
|
|
} else if u.Done > 0 {
|
|
a.emitLog(source, fmt.Sprintf("%s: %.1f MB", u.Step, float64(u.Done)/1e6))
|
|
}
|
|
}
|
|
tasks.update(id, u)
|
|
return
|
|
}
|
|
a.emitLog(source, line)
|
|
step := trim(u.Message)
|
|
lastStep = step
|
|
lastLogAt = time.Now()
|
|
tasks.update(id, host.Update{Kind: host.KindStep, Message: step, Percent: -1})
|
|
})
|
|
return id, w, func(err error) { tasks.finish(id, "", err) }
|
|
}
|