cli: prompts read the stdin Windows' console init reopens, not the one package init saw

tom047784 (Discord, Windows desktop build): `magpie plugin login` in a
terminal failed with "read /dev/stdin: The handle is invalid". The
desktop build is a GUI-subsystem binary; console_windows.go's init
attaches the parent console and reopens CONIN$/CONOUT$ into os.Stdin,
os.Stdout and os.Stderr. But `var stdin = bufio.NewReader(os.Stdin)` in
backup_cmd.go is a package variable, set before any init runs, so it
kept the invalid handle.

That one reader serves every CLI prompt, so all of them broke the same
way: plugin login (askPrompt, askNumber, the code and pasted callback
lines), backup/WebDAV passphrases and passwords piped in (secret), the
library and quota confirmations. stdin is now a func that makes the
reader over os.Stdin as it is when read, and remakes it if os.Stdin
changed; one reader still serves a run, so a second piped secret is
still the second line.

Sibling of the same class: lipgloss's default renderer (termenv's
default output) is made over os.Stdout at its package init, before the
reattach, so the desktop build's CLI printed every style without colour.
The init now points that renderer at CONOUT$ in place; the styles made
at package init hold it. A grep for package-level os.Stdin/os.Stdout/
os.Stderr found no other one in the repo (writers like fmt.Println and
json.NewEncoder(os.Stdout) inside functions resolve at use time).

webdav_cli_test's piped() swapped both os.Stdin and the reader, which is
why no test caught this; it now swaps os.Stdin only.

Run (at this tree, worktree off origin/main 4e3078ee4):
- go test -count=1 -timeout 45m ./internal/cli/: ok (52s)
- go test -race -count=3 TestPromptsReadStdinSetAfterInit|TestAskPrompt|TestWebdav: ok
- gofmt -l internal/cli: empty; go vet ./internal/cli, GOOS=linux go vet
  -tags nogui ./internal/cli, GOOS=windows go vet ./internal/cli: ok
Broken by hand: TestPromptsReadStdinSetAfterInit on the old backup_cmd,
plugins_cli, library_cli and quota_cli (new test file only) is red:
"askPrompt = "", EOF; want blue from the stdin set after init".
Not tried on Windows: the Windows box (10.0.0.132) timed out on ssh, so
the real desktop build's `magpie plugin login` and the lipgloss colour
change were not run there. Not run: go test ./... (only internal/cli
changed).
This commit is contained in:
yetone
2026-10-26 22:22:27 +08:00
parent b3729b8d56
commit 9298d2a7c3
7 changed files with 96 additions and 14 deletions
+22 -3
View File
@@ -8,6 +8,7 @@ import (
"os"
"slices"
"strings"
"sync"
"golang.org/x/term"
@@ -143,15 +144,33 @@ func passphrase(prompt string, confirm bool) (string, error) {
}
// stdin is read through one reader, so a second secret piped in is the
// second line and not lost to the first one's buffer.
var stdin = bufio.NewReader(os.Stdin)
// second line and not lost to the first one's buffer. The reader is made
// over os.Stdin as it is when first read, never at package init: package
// variables are set before any init runs, and on Windows the desktop
// build's init (console_windows.go) only then swaps in the terminal's
// CONIN$. A reader made earlier keeps the invalid handle, and every
// prompt fails with "read /dev/stdin: The handle is invalid".
var (
stdinMu sync.Mutex
stdinFile *os.File
stdinBuf *bufio.Reader
)
func stdin() *bufio.Reader {
stdinMu.Lock()
defer stdinMu.Unlock()
if stdinBuf == nil || stdinFile != os.Stdin {
stdinFile, stdinBuf = os.Stdin, bufio.NewReader(os.Stdin)
}
return stdinBuf
}
// secret reads what (a passphrase, a password) as passphrase does; piped
// in, it is the next line of stdin.
func secret(what, prompt string, confirm bool) (string, error) {
fd := int(os.Stdin.Fd())
if !term.IsTerminal(fd) {
line, err := stdin.ReadString('\n')
line, err := stdin().ReadString('\n')
line = strings.TrimRight(line, "\r\n")
if line == "" {
if err != nil {
+9
View File
@@ -3,6 +3,8 @@ package cli
import (
"os"
"syscall"
"github.com/charmbracelet/lipgloss"
)
// The desktop build is linked as a GUI program so double-clicking it opens
@@ -24,6 +26,13 @@ func init() {
}
if out, err := os.OpenFile("CONOUT$", os.O_RDWR, 0); err == nil {
os.Stdout, os.Stderr = out, out
// lipgloss's default renderer was made over the os.Stdout before
// this, a handle that is no terminal, so every style would print
// without colour. The styles made at package init hold that
// renderer, so it is pointed at the console in place. Anything
// else that reads or writes the standard streams takes os.Stdin,
// os.Stdout or os.Stderr when it runs, never in a package variable.
lipgloss.DefaultRenderer().SetOutput(lipgloss.NewRenderer(out).Output())
}
if in, err := os.OpenFile("CONIN$", os.O_RDWR, 0); err == nil {
os.Stdin = in
+2 -2
View File
@@ -228,7 +228,7 @@ func removeEverySkill(args []string) (*library.Result, error) {
}
fmt.Printf("Remove all %s (%s) from the library and every agent? Folders magpie keeps go to its backups; folders of your own are only unlinked. [y/N] ",
plural(len(names), "skill"), strings.Join(names, ", "))
line, _ := stdin.ReadString('\n')
line, _ := stdin().ReadString('\n')
if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
return nil, fmt.Errorf("nothing removed")
}
@@ -287,7 +287,7 @@ func removeGoneSkills(args []string) (*library.Result, error) {
}
fmt.Printf("Remove %s removed from their source (%s) from the library and every agent? The library's folders go to magpie's backups. [y/N] ",
plural(len(names), "skill"), strings.Join(shown, ", "))
line, _ := stdin.ReadString('\n')
line, _ := stdin().ReadString('\n')
if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
return nil, fmt.Errorf("nothing removed")
}
+4 -4
View File
@@ -498,7 +498,7 @@ func pluginLogin(ctx context.Context, name, method string) error {
code := ""
if a.Method == "code" {
fmt.Print("Code: ")
line, err := stdin.ReadString('\n')
line, err := stdin().ReadString('\n')
if err != nil && line == "" {
return err
}
@@ -512,7 +512,7 @@ func pluginLogin(ctx context.Context, name, method string) error {
fmt.Println("If the page the browser ends on won't load (magpie on a server or in Docker), paste its whole address here and press Enter:")
go func() {
for wait.Err() == nil {
line, err := stdin.ReadString('\n')
line, err := stdin().ReadString('\n')
if strings.TrimSpace(line) != "" && wait.Err() == nil {
if next, err := provider.PastePluginCallback(wait, a.URL, line); err != nil {
fmt.Println(err)
@@ -563,7 +563,7 @@ func keyPrompt(name string, m plugin.Method) string {
func askNumber(n int) (int, error) {
for {
fmt.Print("> ")
line, err := stdin.ReadString('\n')
line, err := stdin().ReadString('\n')
if i, e := strconv.Atoi(strings.TrimSpace(line)); e == nil && i >= 1 && i <= n {
return i - 1, nil
}
@@ -609,7 +609,7 @@ func askPrompt(q *plugin.Prompt) (string, error) {
fmt.Println()
return strings.TrimSpace(string(b)), err
}
line, err := stdin.ReadString('\n')
line, err := stdin().ReadString('\n')
if err != nil && line == "" {
return "", err
}
+1 -1
View File
@@ -246,7 +246,7 @@ func quotaResetCmd(args []string) error {
n += " (the one that runs out first, " + provider.ResetClock(*held.Resets.Until, time.Now()) + ")"
}
fmt.Printf("Spend %s on %s, starting its current windows again? It can't be undone. [y/N] ", n, who)
line, _ := stdin.ReadString('\n')
line, _ := stdin().ReadString('\n')
if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
return fmt.Errorf("nothing spent")
}
+55
View File
@@ -0,0 +1,55 @@
package cli
import (
"os"
"testing"
"github.com/yetone/magpie/internal/plugin"
)
// swapStdin sets os.Stdin to a pipe holding text, after package init, and
// touches nothing else: it is what the Windows desktop build's init does
// when it reopens the terminal's CONIN$ (console_windows.go).
func swapStdin(t *testing.T, text string) {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
w.WriteString(text)
w.Close()
old := os.Stdin
os.Stdin = r
t.Cleanup(func() {
os.Stdin = old
r.Close()
})
}
// TestPromptsReadStdinSetAfterInit: every CLI prompt reads os.Stdin as it
// is when asked, not as it was when the package's variables were set. On
// Windows a reader made at package init held the GUI binary's invalid
// handle, and `magpie plugin login` failed with "read /dev/stdin: The
// handle is invalid" (tom047784).
func TestPromptsReadStdinSetAfterInit(t *testing.T) {
// plugin login's question, as a line
swapStdin(t, "blue\n")
if v, err := askPrompt(&plugin.Prompt{Type: "text", Key: "team", Message: "Your team"}); err != nil || v != "blue" {
t.Fatalf("askPrompt = %q, %v; want blue from the stdin set after init", v, err)
}
// plugin login's choice of method or option
swapStdin(t, "2\n")
if i, err := askNumber(3); err != nil || i != 1 {
t.Fatalf("askNumber = %d, %v; want 1 from the stdin set after init", i, err)
}
// backup's and WebDAV's passphrase and password, piped: a line each,
// both from the one reader
swapStdin(t, "first\nsecond\n")
for _, want := range []string{"first", "second"} {
if v, err := secret("passphrase", "Passphrase: ", false); err != nil || v != want {
t.Fatalf("secret = %q, %v; want %s from the stdin set after init", v, err, want)
}
}
}
+3 -4
View File
@@ -1,7 +1,6 @@
package cli
import (
"bufio"
"io"
"net/http"
"net/http/httptest"
@@ -110,10 +109,10 @@ func piped(t *testing.T, lines ...string) {
w.WriteString(strings.Join(lines, "\n") + "\n")
}
w.Close()
oldFile, oldReader := os.Stdin, stdin
os.Stdin, stdin = r, bufio.NewReader(r)
old := os.Stdin
os.Stdin = r
t.Cleanup(func() {
os.Stdin, stdin = oldFile, oldReader
os.Stdin = old
r.Close()
})
}