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

+63
View File
@@ -0,0 +1,63 @@
// Package pty runs processes in pseudo-terminals, in pure Go: /dev/ptmx on
// macOS and Linux, ConPTY on Windows.
package pty
import (
"errors"
"sync"
)
// Options describe a process to start in a pseudo-terminal.
type Options struct {
// Path is the program; Args its arguments, with Args[0] what the
// program sees as its name ("-zsh" starts a login shell).
Path string
Args []string
// Dir is the working directory, Env the environment ("KEY=value").
Dir string
Env []string
// Cols and Rows are the size of the terminal in cells, Width and
// Height in pixels.
Cols, Rows, Width, Height int
}
// ErrClosed is returned by Write after Close.
var ErrClosed = errors.New("pty: closed")
// PTY is a process running in a pseudo-terminal: Read returns its output,
// Write types into it.
type PTY struct {
sys
waitOnce sync.Once
code int
waitErr error
exited chan struct{}
}
// Start starts a process in a pseudo-terminal.
func Start(o Options) (*PTY, error) {
if o.Cols <= 0 || o.Rows <= 0 {
o.Cols, o.Rows = 80, 24
}
if len(o.Args) == 0 {
o.Args = []string{o.Path}
}
p := &PTY{exited: make(chan struct{})}
if err := p.start(o); err != nil {
return nil, err
}
go func() {
p.code, p.waitErr = p.wait()
close(p.exited)
}()
return p, nil
}
// Wait waits for the process to exit and returns its exit code.
func (p *PTY) Wait() (int, error) {
<-p.exited
return p.code, p.waitErr
}
// Exited is closed when the process exited.
func (p *PTY) Exited() <-chan struct{} { return p.exited }
@@ -0,0 +1,54 @@
//go:build !ios
package pty
import (
"bytes"
"fmt"
"os"
"syscall"
"unsafe"
)
// The ioctls of grantpt, unlockpt and ptsname on macOS (sys/ttycom.h).
const (
tiocptygrant = 0x20007454 // _IO('t', 84)
tiocptyunlk = 0x20007452 // _IO('t', 82)
tiocptygname = 0x40807453 // _IOC(IOC_OUT, 't', 83, 128)
)
func openMaster() (*os.File, string, error) {
master, err := os.OpenFile("/dev/ptmx", os.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0)
if err != nil {
return nil, "", fmt.Errorf("pty: %w", err)
}
var name [128]byte
for _, step := range []struct {
req uintptr
arg unsafe.Pointer
}{{tiocptygrant, nil}, {tiocptyunlk, nil}, {tiocptygname, unsafe.Pointer(&name[0])}} {
if err := ioctl(master, step.req, step.arg); err != nil {
master.Close()
return nil, "", fmt.Errorf("pty: %w", err)
}
}
n := bytes.IndexByte(name[:], 0)
if n < 0 {
n = len(name)
}
return master, string(name[:n]), nil
}
// waitReadable waits until the master has output, for a read that came back
// with EAGAIN because the os package could not make the descriptor one its
// poller waits on.
func (p *PTY) waitReadable() error {
fd := int(p.master.Fd())
var r syscall.FdSet
r.Bits[fd/32] |= 1 << (uint(fd) % 32)
for {
if err := syscall.Select(fd+1, &r, nil, nil, nil); err != syscall.EINTR {
return err
}
}
}
@@ -0,0 +1,43 @@
//go:build !android
package pty
import (
"fmt"
"os"
"strconv"
"syscall"
"unsafe"
)
func openMaster() (*os.File, string, error) {
master, err := os.OpenFile("/dev/ptmx", os.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0)
if err != nil {
return nil, "", fmt.Errorf("pty: %w", err)
}
var unlock int32
if err := ioctl(master, syscall.TIOCSPTLCK, unsafe.Pointer(&unlock)); err != nil {
master.Close()
return nil, "", fmt.Errorf("pty: unlocking: %w", err)
}
var n uint32
if err := ioctl(master, syscall.TIOCGPTN, unsafe.Pointer(&n)); err != nil {
master.Close()
return nil, "", fmt.Errorf("pty: %w", err)
}
return master, "/dev/pts/" + strconv.Itoa(int(n)), nil
}
// waitReadable waits until the master has output, for a read that came back
// with EAGAIN because the os package could not make the descriptor one its
// poller waits on.
func (p *PTY) waitReadable() error {
fd := int(p.master.Fd())
var r syscall.FdSet
r.Bits[fd/64] |= 1 << (uint(fd) % 64)
for {
if _, err := syscall.Select(fd+1, &r, nil, nil, nil); err != syscall.EINTR {
return err
}
}
}
@@ -0,0 +1,18 @@
//go:build !(darwin && !ios) && !(linux && !android) && !windows
package pty
import "errors"
type sys struct{}
func (p *PTY) start(Options) error { return errors.ErrUnsupported }
func (p *PTY) wait() (int, error) { return 0, errors.ErrUnsupported }
func (p *PTY) Read([]byte) (int, error) { return 0, errors.ErrUnsupported }
func (p *PTY) Write([]byte) (int, error) { return 0, errors.ErrUnsupported }
func (p *PTY) Resize(cols, rows, w, h int) error { return errors.ErrUnsupported }
func (p *PTY) ClearScreen() error { return nil }
func (p *PTY) Pid() int { return 0 }
func (p *PTY) Foreground() int { return 0 }
func (p *PTY) Close() error { return nil }
func (p *PTY) Kill() error { return errors.ErrUnsupported }
@@ -0,0 +1,110 @@
package pty
import (
"bytes"
"io"
"os"
"runtime"
"strings"
"testing"
"time"
"github.com/egoist/mygo/internal/wait"
)
// readAll reads the output of p until the process exits and the output
// ends.
func readAll(t *testing.T, p *PTY) string {
t.Helper()
var out bytes.Buffer
done := make(chan struct{})
go func() {
io.Copy(&out, p)
close(done)
}()
select {
case <-p.Exited():
case <-time.After(wait.Guard):
t.Fatal("the process did not exit")
}
// What the process wrote before it exited is still to read.
time.AfterFunc(200*time.Millisecond, func() { p.Close() })
<-done
return out.String()
}
func TestStart(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses sh")
}
p, err := Start(Options{Path: "/bin/sh", Args: []string{"sh", "-c", "echo hello; stty size; [ -t 0 ] && echo tty; exit 3"}, Cols: 100, Rows: 30, Env: []string{"TERM=dumb"}})
if err != nil {
t.Fatal(err)
}
out := readAll(t, p)
for _, want := range []string{"hello\r\n", "30 100\r\n", "tty\r\n"} {
if !strings.Contains(out, want) {
t.Errorf("output %q lacks %q", out, want)
}
}
if code, err := p.Wait(); code != 3 || err != nil {
t.Errorf("exit = %d, %v", code, err)
}
}
func TestResizeAndInput(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses sh")
}
p, err := Start(Options{Path: "/bin/sh", Args: []string{"sh", "-c", "read line; echo got $line; stty size"}, Env: []string{"TERM=dumb"}})
if err != nil {
t.Fatal(err)
}
if err := p.Resize(120, 40, 0, 0); err != nil {
t.Fatal(err)
}
if _, err := p.Write([]byte("typed\r")); err != nil {
t.Fatal(err)
}
out := readAll(t, p)
for _, want := range []string{"got typed\r\n", "40 120\r\n"} {
if !strings.Contains(out, want) {
t.Errorf("output %q lacks %q", out, want)
}
}
}
func TestClose(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses sh")
}
p, err := Start(Options{Path: "/bin/sh", Args: []string{"sh", "-c", "sleep 30"}})
if err != nil {
t.Fatal(err)
}
// Closing the terminal hangs up the process.
p.Close()
select {
case <-p.Exited():
case <-time.After(5 * time.Second):
p.Kill()
t.Fatal("the process outlived its terminal")
}
}
func TestConPTY(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("ConPTY")
}
cmd := os.Getenv("COMSPEC")
p, err := Start(Options{Path: cmd, Args: []string{"cmd", "/c", "echo hello& exit /b 3"}, Cols: 100, Rows: 30})
if err != nil {
t.Fatal(err)
}
if out := readAll(t, p); !strings.Contains(out, "hello") {
t.Errorf("output %q lacks hello", out)
}
if code, err := p.Wait(); code != 3 || err != nil {
t.Errorf("exit = %d, %v", code, err)
}
}
@@ -0,0 +1,158 @@
//go:build (darwin && !ios) || (linux && !android)
package pty
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"syscall"
"unsafe"
)
type sys struct {
master *os.File
cmd *exec.Cmd
}
func (p *PTY) start(o Options) error {
master, slaveName, err := openMaster()
if err != nil {
return err
}
slave, err := os.OpenFile(slaveName, os.O_RDWR|syscall.O_NOCTTY, 0)
if err != nil {
master.Close()
return fmt.Errorf("pty: opening %s: %w", slaveName, err)
}
defer slave.Close() // the child has its own copies
if err := setSize(master, o.Cols, o.Rows, o.Width, o.Height); err != nil {
master.Close()
return err
}
cmd := &exec.Cmd{Path: o.Path, Args: o.Args, Dir: o.Dir, Env: o.Env, Stdin: slave, Stdout: slave, Stderr: slave}
// A session of its own, whose controlling terminal is the slave (the
// child's descriptor 0), so that the terminal's signals reach the
// process group in the foreground.
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true, Ctty: 0}
if err := cmd.Start(); err != nil {
master.Close()
return err
}
p.master, p.cmd = master, cmd
return nil
}
func (p *PTY) wait() (int, error) {
err := p.cmd.Wait()
if e, ok := errors.AsType[*exec.ExitError](err); ok {
if ws, ok := e.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
return 128 + int(ws.Signal()), nil
}
return e.ExitCode(), nil
}
return 0, err
}
// Read reads the output of the process; it returns io.EOF once no process
// has the terminal open any more, or after Close.
func (p *PTY) Read(b []byte) (int, error) {
for {
n, err := p.master.Read(b)
if n > 0 {
return n, nil
}
if err == nil {
return 0, nil
}
// Nothing to read yet, which a read on a master that the os package
// cannot wait on says with EAGAIN: that is not the end of the
// program. A reader that takes it for the end closes the master,
// and the kernel then hangs the program up with SIGHUP, before it
// runs a single command.
if errors.Is(err, syscall.EAGAIN) || errors.Is(err, syscall.EINTR) {
if werr := p.waitReadable(); werr != nil {
return 0, werr
}
continue
}
// Linux reports EIO when the last process with the terminal
// open closes it.
if errors.Is(err, syscall.EIO) || errors.Is(err, os.ErrClosed) {
err = io.EOF
}
return 0, err
}
}
// Write types b into the terminal.
func (p *PTY) Write(b []byte) (int, error) {
n, err := p.master.Write(b)
if errors.Is(err, os.ErrClosed) {
err = ErrClosed
}
return n, err
}
// Resize sets the size of the terminal, which sends the process SIGWINCH.
func (p *PTY) Resize(cols, rows, width, height int) error {
return setSize(p.master, cols, rows, width, height)
}
// ClearScreen does nothing: the terminal has no screen of its own to
// clear, unlike ConPTY's console.
func (p *PTY) ClearScreen() error { return nil }
// Pid returns the process's ID.
func (p *PTY) Pid() int { return p.cmd.Process.Pid }
// Foreground returns the ID of the process group in the foreground of
// the terminal, 0 when it can't tell.
func (p *PTY) Foreground() int {
var pgrp int32
if ioctl(p.master, syscall.TIOCGPGRP, unsafe.Pointer(&pgrp)) != nil {
return 0
}
return int(pgrp)
}
// Close closes the terminal, which hangs up the processes that have it:
// they get SIGHUP. It does not wait for them to exit.
func (p *PTY) Close() error { return p.master.Close() }
// Kill kills the process and those of its process group, which it leads.
func (p *PTY) Kill() error {
if err := syscall.Kill(-p.cmd.Process.Pid, syscall.SIGKILL); err == nil {
return nil
}
return p.cmd.Process.Kill()
}
func setSize(f *os.File, cols, rows, width, height int) error {
ws := struct{ row, col, xpixel, ypixel uint16 }{clamp(rows), clamp(cols), clamp(width), clamp(height)}
return ioctl(f, syscall.TIOCSWINSZ, unsafe.Pointer(&ws))
}
func clamp(v int) uint16 { return uint16(max(0, min(v, 0xFFFF))) }
// ioctl calls ioctl on f with a pointer, which it converts in the system
// call, so that what it points to stays put meanwhile.
func ioctl(f *os.File, req uintptr, arg unsafe.Pointer) error {
c, err := f.SyscallConn()
if err != nil {
return err
}
var errno syscall.Errno
err = c.Control(func(fd uintptr) {
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, fd, req, uintptr(arg))
})
if err != nil {
return err
}
if errno != 0 {
return errno
}
return nil
}
@@ -0,0 +1,264 @@
package pty
import (
"errors"
"fmt"
"os"
"strings"
"sync"
"syscall"
"unicode/utf16"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll") // a KnownDLL
procCreatePseudoConsole = kernel32.NewProc("CreatePseudoConsole")
procResizePseudoConsole = kernel32.NewProc("ResizePseudoConsole")
procClosePseudoConsole = kernel32.NewProc("ClosePseudoConsole")
procInitializeProcThreadAttributeList = kernel32.NewProc("InitializeProcThreadAttributeList")
procUpdateProcThreadAttribute = kernel32.NewProc("UpdateProcThreadAttribute")
procDeleteProcThreadAttributeList = kernel32.NewProc("DeleteProcThreadAttributeList")
procRtlGetVersion = syscall.NewLazyDLL("ntdll.dll").NewProc("RtlGetVersion") // a KnownDLL
)
const (
procThreadAttributePseudoConsole = 0x00020016
extendedStartupInfoPresent = 0x00080000
createUnicodeEnvironment = 0x00000400
)
type startupInfoEx struct {
syscall.StartupInfo
attributes uintptr
}
type sys struct {
mu sync.Mutex
console uintptr // the HPCON, 0 once closed
in *os.File
out *os.File
process syscall.Handle
pid int
}
func (p *PTY) start(o Options) error {
if err := procCreatePseudoConsole.Find(); err != nil {
return errors.New("pty: ConPTY needs Windows 10 1809 or later")
}
// The console reads what is typed from inR and writes the output to
// outW; this side writes to inW and reads outR.
var inR, inW, outR, outW syscall.Handle
if err := syscall.CreatePipe(&inR, &inW, nil, 0); err != nil {
return fmt.Errorf("pty: %w", err)
}
if err := syscall.CreatePipe(&outR, &outW, nil, 0); err != nil {
syscall.CloseHandle(inR)
syscall.CloseHandle(inW)
return fmt.Errorf("pty: %w", err)
}
var console uintptr
r, _, _ := procCreatePseudoConsole.Call(coord(o.Cols, o.Rows), uintptr(inR), uintptr(outW), 0, uintptr(unsafe.Pointer(&console)))
// The console has its own copies of its ends.
syscall.CloseHandle(inR)
syscall.CloseHandle(outW)
if r != 0 {
syscall.CloseHandle(inW)
syscall.CloseHandle(outR)
return fmt.Errorf("pty: CreatePseudoConsole: %w", syscall.Errno(r&0xFFFF))
}
p.console = console
p.in, p.out = os.NewFile(uintptr(inW), "conpty-in"), os.NewFile(uintptr(outR), "conpty-out")
if err := p.spawn(o); err != nil {
p.Close()
p.out.Close()
return err
}
return nil
}
func (p *PTY) spawn(o Options) error {
var size uintptr
procInitializeProcThreadAttributeList.Call(0, 1, 0, uintptr(unsafe.Pointer(&size)))
list := make([]byte, size)
if r, _, err := procInitializeProcThreadAttributeList.Call(uintptr(unsafe.Pointer(&list[0])), 1, 0, uintptr(unsafe.Pointer(&size))); r == 0 {
return fmt.Errorf("pty: InitializeProcThreadAttributeList: %w", err)
}
defer procDeleteProcThreadAttributeList.Call(uintptr(unsafe.Pointer(&list[0])))
if r, _, err := procUpdateProcThreadAttribute.Call(uintptr(unsafe.Pointer(&list[0])), 0, procThreadAttributePseudoConsole, p.console, unsafe.Sizeof(p.console), 0, 0); r == 0 {
return fmt.Errorf("pty: UpdateProcThreadAttribute: %w", err)
}
si := startupInfoEx{attributes: uintptr(unsafe.Pointer(&list[0]))}
si.Cb = uint32(unsafe.Sizeof(si))
// The console's own standard handles: without invalid ones, a child of
// a process whose output is redirected would write there instead.
si.Flags = syscall.STARTF_USESTDHANDLES
si.StdInput, si.StdOutput, si.StdErr = syscall.InvalidHandle, syscall.InvalidHandle, syscall.InvalidHandle
cmdline, err := syscall.UTF16PtrFromString(commandLine(o.Path, o.Args))
if err != nil {
return err
}
var dir *uint16
if o.Dir != "" {
if dir, err = syscall.UTF16PtrFromString(o.Dir); err != nil {
return err
}
}
var env *uint16
if o.Env != nil {
block := environmentBlock(o.Env)
env = &block[0]
}
var pi syscall.ProcessInformation
err = syscall.CreateProcess(nil, cmdline, nil, nil, false, extendedStartupInfoPresent|createUnicodeEnvironment, env, dir, &si.StartupInfo, &pi)
if err != nil {
return fmt.Errorf("pty: starting %s: %w", o.Path, err)
}
syscall.CloseHandle(pi.Thread)
p.process, p.pid = pi.Process, int(pi.ProcessId)
return nil
}
func (p *PTY) wait() (int, error) {
if _, err := syscall.WaitForSingleObject(p.process, syscall.INFINITE); err != nil {
return 0, err
}
var code uint32
err := syscall.GetExitCodeProcess(p.process, &code)
syscall.CloseHandle(p.process)
return int(code), err
}
// Read reads the output of the process; it returns io.EOF after Close, once
// the console wrote what it had.
func (p *PTY) Read(b []byte) (int, error) { return p.out.Read(b) }
// Write types b into the terminal.
func (p *PTY) Write(b []byte) (int, error) {
n, err := p.in.Write(b)
if errors.Is(err, os.ErrClosed) {
err = ErrClosed
}
return n, err
}
// Resize sets the size of the terminal.
func (p *PTY) Resize(cols, rows, width, height int) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.console == 0 {
return ErrClosed
}
if r, _, _ := procResizePseudoConsole.Call(p.console, coord(cols, rows)); r != 0 {
return fmt.Errorf("pty: ResizePseudoConsole: %w", syscall.Errno(r&0xFFFF))
}
return nil
}
// ClearScreen tells the console that the terminal cleared its screen, as
// Windows Terminal's ClearPseudoConsole does: the console clears its
// buffer and repaints with the cursor's line at the top. Without it, the
// console keeps the prompt on its old row and, as it redraws with
// absolute cursor moves (PSReadLine's predictions), takes the cursor back
// down there. It does nothing before Windows 11 24H2, whose console may
// shut down on a signal it doesn't know, or once the console is closed.
func (p *PTY) ClearScreen() error {
if windowsBuild() < 26100 {
return nil
}
p.mu.Lock()
defer p.mu.Unlock()
if p.console == 0 {
return nil
}
// kernel32 doesn't export ClearPseudoConsole. The HPCON points at the
// console's handles, first the pipe of its signals, which take a
// 16-bit code: PTY_SIGNAL_CLEAR_WINDOW is 2.
signals := **(**syscall.Handle)(unsafe.Pointer(&p.console))
var n uint32
if err := syscall.WriteFile(signals, []byte{2, 0}, &n, nil); err != nil {
return fmt.Errorf("pty: clearing the console: %w", err)
}
return nil
}
// windowsBuild returns the build of Windows 10 or 11, the maximum on a
// later major version. RtlGetVersion tells the version whatever the
// executable's manifest declares.
var windowsBuild = sync.OnceValue(func() uint32 {
var v struct {
size, major, minor, build, platform uint32
servicePack [128]uint16
}
v.size = uint32(unsafe.Sizeof(v))
procRtlGetVersion.Call(uintptr(unsafe.Pointer(&v)))
switch {
case v.major > 10:
return ^uint32(0)
case v.major < 10:
return 0
}
return v.build
})
// Pid returns the process's ID.
func (p *PTY) Pid() int { return p.pid }
// Foreground returns 0: a console has no process groups in its foreground.
func (p *PTY) Foreground() int { return 0 }
// Close closes the console, which ends the processes attached to it. Read
// returns io.EOF once it wrote what it had.
func (p *PTY) Close() error {
p.mu.Lock()
console := p.console
p.console = 0
p.mu.Unlock()
if console == 0 {
return nil
}
p.in.Close()
// ClosePseudoConsole waits for the output to be read on Windows
// before 11 24H2: Read keeps reading meanwhile, until the end of the
// output, then the pipe goes.
go func() {
procClosePseudoConsole.Call(console)
p.out.Close()
}()
return nil
}
// Kill kills the process.
func (p *PTY) Kill() error { return syscall.TerminateProcess(p.process, 1) }
// coord packs a COORD, which ConPTY takes by value.
func coord(cols, rows int) uintptr {
return uintptr(uint16(max(1, min(cols, 0x7FFF)))) | uintptr(uint16(max(1, min(rows, 0x7FFF))))<<16
}
// commandLine joins a program and its arguments as the C runtime splits
// them; args[0] is the program's name.
func commandLine(path string, args []string) string {
parts := []string{syscall.EscapeArg(path)}
if len(args) > 1 {
for _, a := range args[1:] {
parts = append(parts, syscall.EscapeArg(a))
}
}
return strings.Join(parts, " ")
}
// environmentBlock encodes env as CreateProcess takes it: NUL-terminated
// UTF-16 strings, then another NUL.
func environmentBlock(env []string) []uint16 {
var b []uint16
for _, kv := range env {
b = append(b, utf16.Encode([]rune(kv))...)
b = append(b, 0)
}
if len(b) == 0 {
b = append(b, 0)
}
return append(b, 0)
}
@@ -0,0 +1,76 @@
package pty
import (
"bytes"
"io"
"os/exec"
"regexp"
"strings"
"sync"
"testing"
"github.com/egoist/mygo/internal/wait"
)
// TestConPTYClearScreen clears the screen of PowerShell, whose prompt sat
// on the console's last row: the console repaints it on the first, which
// PSReadLine's redraws then keep to.
func TestConPTYClearScreen(t *testing.T) {
if windowsBuild() < 26100 {
t.Skip("ClearScreen needs Windows 11 24H2")
}
shell, err := exec.LookPath("pwsh")
if err != nil {
if shell, err = exec.LookPath("powershell"); err != nil {
t.Skip("no PowerShell")
}
}
p, err := Start(Options{Path: shell, Args: []string{"pwsh", "-NoLogo", "-NoProfile"}, Cols: 80, Rows: 10})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
p.Kill()
p.Close()
})
var mu sync.Mutex
var out bytes.Buffer
go io.Copy(writerFunc(func(b []byte) (int, error) {
mu.Lock()
defer mu.Unlock()
return out.Write(b)
}), p)
since := func(n int) string {
mu.Lock()
defer mu.Unlock()
return out.String()[n:]
}
length := func() int {
mu.Lock()
defer mu.Unlock()
return out.Len()
}
wait.Until(t, "the prompt", func() bool { return strings.Contains(since(0), "PS ") })
n := length()
if _, err := p.Write([]byte("1..20\r")); err != nil {
t.Fatal(err)
}
// The numbers, then the prompt again, on the last row.
wait.Until(t, "the numbers and the prompt", func() bool {
s := since(n)
i := strings.Index(s, "20")
return i >= 0 && strings.Contains(s[i:], "PS ")
})
n = length()
if err := p.ClearScreen(); err != nil {
t.Fatal(err)
}
top := regexp.MustCompile(`\x1b\[1;\d+H`)
wait.Until(t, "the prompt repainted on the first row", func() bool { return top.MatchString(since(n)) })
}
type writerFunc func([]byte) (int, error)
func (f writerFunc) Write(b []byte) (int, error) { return f(b) }