Files
magpie/internal/gui/update_beside_unix_test.go
T
yetone 185ee6d5c1 gui: an auto restart brings a minimised main window back minimised on Windows (#3495, realLemonawa on X)
Settings' Auto restart after an update brought the main window back if
it was up, and on Windows a window minimised to the taskbar counts as
up, so the new version showed it on screen (quietly, without focus).
Now the old version notes whether it was minimised: the restart-quiet
mark reads "<seconds> minimised" (mainUp reads up and minimised
together on the main thread). The new version, on Windows, puts the
window straight onto the taskbar with SetWindowPlacement and
SW_SHOWMINNOACTIVE, never shown on screen and never activated, at its
kept place and size, with WPF_RESTORETOMAXIMIZED when it was maximised
(placeMain split into placeAt and the maximise). A mark of the seconds
alone, from an older version, still reads as a window up. A restart the
user clicked is unchanged.

The first auto update into this version is still made by the old one,
which doesn't write the word, so the window comes back minimised from
the update after it. macOS and Linux keep showing it quietly: #5926.

Run:
- Windows (xiaomi-gpu, in the signed-in console session through a
  one-shot schtasks /it, since the windows are real):
  TestRestartMinimisedComesBackMinimised, which starts the test binary
  as a Wails app three times: minimised, minimised and maximised, and
  shown. It checks the window comes back minimised, is never shown
  whole (WindowShow while not iconic), doesn't take the foreground,
  mainUp says up and minimised, and that SC_RESTORE brings it back
  (maximised when it was) with its page visible (the page reports
  document.visibilityState). PASS.
- Windows over ssh: go test -count=1 ./internal/gui/ fails only
  TestGatewayHeldByAContainer, TestPluginAgentMissingSaysSo (#5324),
  TestLodyImportHandoff, TestImportStatusUnreadableIsUnknown,
  TestUpdateThatWontStart (#4115, #1827) and TestProviderSaveClientCert
  (filed #5928); all six fail the same at origin/main 987eac0aa.
- mote (darwin): go test -count=1 ./internal/gui/ ok (166s); at the
  head rebased on 6b92824ff, the three vets and -run
  'Quiet|Restart|Lightweight|Main' ./internal/gui/ ok.
- gofmt clean; go vet darwin, GOOS=windows and GOOS=linux -tags nogui
  ./internal/gui/ ok (GOOS=linux with the GUI needs cgo and doesn't
  cross-compile from mote, on main too).

Broken by hand: showsMinimised false on Windows (the old show): the
two minimised cases red ("came back not minimised"). Without
WPF_RESTORETOMAXIMIZED: the maximised case red ("maximised=false, want
true"). Taking the minimised flag out of the mark is red in
TestRestartBySelfComesBackQuietly.

Not tried: a real update of the installed app on Windows (the
schtasks run drives the same openMain path the app's start takes); the
Windows test stays green with no show of our own after SC_RESTORE
(the restored page reports visible), so none was added.
2026-11-10 18:07:05 +08:00

154 lines
4.9 KiB
Go

//go:build darwin || linux
package gui
import (
"bufio"
"encoding/json"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// gaubeebangeel on X: an agent magpie serves runs `magpie update` at 4am.
// It put the new version in, and the app ran on as the old one until it
// was quit and reopened, which cut the agent off; to keep it going the
// agent needed a provider of its own. Now the command asks the app
// (gateway.RestartPath) to restart into what it put in, and the app does
// so as its own update would, handing the gateway over: the reply the
// agent has streaming finishes whole, the new version serves the next
// requests, and the old one quits once its stream has ended. On the old
// code the route isn't there (404) and nothing restarts.
func TestUpdateInATerminalRestartsTheAppWithoutCuttingIt(t *testing.T) {
release := make(chan struct{})
up := slowUpstream(t, release)
defer close(release)
gw := handoverSandbox(t, up.URL)
addr := gw.Addr()
// the binary as this magpie started from it, which the terminal's
// magpie update then replaces
exe := filepath.Join(t.TempDir(), "magpie")
if err := os.WriteFile(exe, []byte("v0.1.1"), 0o755); err != nil {
t.Fatal(err)
}
old := updates
t.Cleanup(func() { updates = old; gateway.SetRestarter(nil) })
updates = &updater{state: "latest", exe: exe}
updates.self, _ = os.Stat(exe)
quit := make(chan struct{})
updates.autoRestart = func() bool {
if restartInto(false, false, "", true, false) {
leave(func() { close(quit) })
return true
}
return false
}
gateway.SetRestarter(updates.restartBeside)
// the restart starts the child on a goroutine of its own, while this
// test waits for it to serve
var child atomic.Pointer[exec.Cmd]
startBeside = func(exe string, window bool, view string) error {
c := exec.Command(startExe, "-test.run=^TestHandoverSuccessor$", "-test.v")
c.Env = append(os.Environ(), successorEnv+"=1")
c.Stdout, c.Stderr = os.Stderr, os.Stderr
if err := c.Start(); err != nil {
return err
}
child.Store(c)
return nil
}
t.Cleanup(func() {
if c := child.Load(); c != nil {
c.Process.Kill()
c.Wait()
}
})
relaunchBinary = func(string, string, bool, string) error {
t.Error("restarted as before, rather than handing over")
return nil
}
resp, err := http.Post("http://"+addr+"/v1/chat/completions", "application/json",
strings.NewReader(`{"model":"plan/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
stream := bufio.NewReader(resp.Body)
if line, err := stream.ReadString('\n'); err != nil || !strings.Contains(line, "first") {
t.Fatalf("the stream's first chunk: %q %v", line, err)
}
// magpie update in a terminal: the binary replaced, then the ask
if err := os.WriteFile(exe, []byte("v0.1.2 is longer"), 0o755); err != nil {
t.Fatal(err)
}
r, err := http.Post("http://"+addr+gateway.RestartPath, "application/json", strings.NewReader(`{"version":"v0.1.2"}`))
if err != nil {
t.Fatal(err)
}
var reply gateway.RestartReply
json.NewDecoder(r.Body).Decode(&reply)
r.Body.Close()
if r.StatusCode != http.StatusOK || reply.State != "restarting" || !reply.Handover {
t.Fatalf("magpie update's ask: %d %+v", r.StatusCode, reply)
}
eventually2(t, 30*time.Second, "the new magpie never served the gateway", func() bool {
c := child.Load()
return c != nil && servedByPid(addr) == c.Process.Pid
})
q, err := http.Post("http://"+addr+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"plan/m1","messages":[{"role":"user","content":"hi"}]}`))
if err != nil {
t.Fatalf("a request after the restart: %v", err)
}
b, _ := io.ReadAll(q.Body)
q.Body.Close()
if q.StatusCode != 200 || !strings.Contains(string(b), "quick") {
t.Fatalf("a request after the restart: %d %s", q.StatusCode, b)
}
select {
case <-quit:
t.Fatal("quit with a reply streaming")
case <-time.After(time.Second):
}
release <- struct{}{}
rest, err := io.ReadAll(stream)
if err != nil || !strings.Contains(string(rest), "last") || !strings.Contains(string(rest), "[DONE]") {
t.Fatalf("the stream was cut: %q %v", rest, err)
}
select {
case <-quit:
case <-time.After(10 * time.Second):
t.Fatal("the old one didn't quit once its stream ended")
}
}
// A magpie that isn't the copy magpie update replaced stays as it is, and
// says so.
func TestUpdateOfAnotherCopyLeavesTheAppBe(t *testing.T) {
exe := filepath.Join(t.TempDir(), "magpie")
if err := os.WriteFile(exe, []byte("v0.1.1"), 0o755); err != nil {
t.Fatal(err)
}
u := &updater{state: "latest", exe: exe}
u.self, _ = os.Stat(exe)
u.autoRestart = func() bool { t.Error("restarted"); return true }
if r := u.restartBeside("v0.1.2"); r.State != "current" {
t.Fatalf("answered %+v", r)
}
if u.state != "latest" {
t.Fatalf("state %q", u.state)
}
}