magpie icon indicating copy to clipboard operation
magpie copied to clipboard

Windows: `magpie plugin login` fails with `read /dev/stdin: The handle is invalid` (stdin reader built before console re-attach)Windows: `magpie plugin login` fails with `read /dev/stdin: The handle is invalid` (stdin reader built before console re-attach)

Open TomXPRIME opened this issue 1 month ago • 5 comments

Environment

  • Windows 11 26H2, magpie-windows-amd64.exe (desktop build) (latest desktop build at the time of writing; release v0.1.1596 is current)
  • Run by hand in Windows Terminal / PowerShell

Repro

magpie plugin login super-xiaoai

(plugin: leset0ng/opencode-super-xiaoai-auth). The first prompt is printed, then:

magpie: read /dev/stdin: The handle is invalid.

Likely cause (from reading the code, not debugged on Windows) The desktop build is linked with -H windowsgui (Makefile#L112), so it starts with no std handles. internal/cli/console_windows.go's init() re-attaches the parent console and reassigns os.Stdin to CONIN$. But the shared prompt reader is a package-level var:

// internal/cli/backup_cmd.go#L147
var stdin = bufio.NewReader(os.Stdin)

Go initializes package-level vars before any init() runs, so stdin wraps the original invalid handle and never sees the CONIN$ one. Output works (it uses os.Stdout at call time), but every prompt that goes through stdin.ReadString (plugins_cli.go L501/L515/L566/L612, library_cli.go, quota_cli.go, backup_cmd.go) fails. The error names /dev/stdin, not CONIN$, which fits.

Suggested fix Create the reader lazily (e.g. a stdinReader() with sync.Once), or reassign stdin = bufio.NewReader(os.Stdin) at the end of the Windows init().

Workaround magpie-cli-windows-amd64.exe (console build) should not hit this.

Possibly related In the desktop GUI, signing in to the same plugin (account/password, code left empty) shows no response and no verification code is sent. I don't have logs for that yet.

TomXPRIME avatar Oct 26 '26 11:10 TomXPRIME

Confirmed — your reading of the code checks out on 4a33cf0a, and the patch below follows it.

Root cause. The desktop build is linked with -H windowsgui (the release-windows target in the Makefile), so it starts with no standard handles, and init in internal/cli/console_windows.go re-opens os.Stdin from CONIN$. Go runs package variables before any init function, so the shared prompt reader — var stdin = bufio.NewReader(os.Stdin) at internal/cli/backup_cmd.go:147 — was built from the dead handle the process began with and never saw the re-attached one. Every prompt served by that reader failed: plugin login (the code prompt, the paste-address prompt, the numbered pick, the plain and hidden questions), the library remove yes/no, the quota-spend yes/no, and piped secrets for webdav/secret. The error's name checks out too: the Go runtime creates os.Stdin as NewFile(uintptr(syscall.Stdin), "/dev/stdin") on every platform (os/file.go:72), which is why the message says /dev/stdin and not CONIN$.

Fix. The reader is now built on first use, and rebuilt whenever os.Stdin has changed since (stdinReader() in backup_cmd.go); the eight stdin.ReadString call sites go through it. I took your lazy idea but not the plain sync.Once: a once-made reader would freeze the first binding, and the package's own tests re-pipe os.Stdin several times in one process (piped() in webdav_cli_test.go), so the reader has to follow the current os.Stdin — which is exactly what the Windows console re-attach needs too. piped() now swaps os.Stdin alone and the reader follows. The terminal path was never broken (secret takes the fd at call time, so term.ReadPassword already saw the re-attached handle).

Tests. A new TestStdinReaderFollowsStdin (internal/cli/stdin_test.go) locks the contract: asked on a fresh os.Stdin, the reader reads that one, twice in a row. It cannot build before the fix (undefined: stdinReader) and passes after. The whole internal/cli package — which exercises the re-piped prompts end to end through TestWebdavCmd — stays green.

Verification (go1.26.8, darwin/arm64 host):

Check Result
go test -tags nogui ./internal/cli/ -run TestStdinReaderFollowsStdin at 4a33cf0a, before the fix FAIL, build failed: undefined: stdinReader
same test after the fix ok
go test -tags nogui ./internal/cli/ -count=1 (whole package) ok, 30.2s
gofmt -l internal/cli/ clean
go vet -tags nogui ./... (darwin/arm64) exit 0
GOOS=windows GOARCH=amd64 go vet -tags nogui ./internal/cli/ exit 0
GOOS=windows GOARCH=arm64 go vet -tags nogui ./internal/cli/ exit 0
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -tags nogui . ok
CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -tags nogui . ok
CGO_ENABLED=0 go build -tags nogui . (darwin/arm64) ok
git am of the patch on a clean 4a33cf0a worktree applies as is, author kept
magpie plugin login super-xiaoai on Windows 11, PowerShell / Windows Terminal Not verified: I have no Windows machine — please re-test with a build of this commit

Not verified on real Windows, as above. The GUI sign-in that gives no response is separate code and untouched by this patch; if it still does nothing after the CLI side is fixed, it will need its own logs.

Attribution: AI-written; I've read the whole diff and the tests pass. Please keep the author (ggbdpq) or add Co-authored-by: ggbdpq <[email protected]>.

Branch with the commit: hunt91-l4-3737-win-stdin (head 2700f17f9b0a71f08e2bb6a0c50a8fb388447df3).

patch: cli: prompted answers are read from the stdin there is when they are asked (#3737) — git am applies it as is; SHA-256 first 16: 3e8dc48c579cb687
From 2700f17f9b0a71f08e2bb6a0c50a8fb388447df3 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Mon, 26 Oct 2026 21:30:06 +0800
Subject: [PATCH] cli: prompted answers are read from the stdin there is when
 they are asked (#3737)

The desktop build for Windows is linked with -H windowsgui, so it starts
with no standard handles; its init in console_windows.go borrows the
parent console and re-opens os.Stdin from CONIN$. Package variables are
initialized before init functions run, so the shared prompt reader, a
package-level `var stdin = bufio.NewReader(os.Stdin)`, was built from
the dead stdin the process began with and never saw the reopened one:
every prompt (plugin login, library and quota yes/no, piped secrets)
failed with "read /dev/stdin: The handle is invalid." on Windows.

The reader is now built on first use, and again whenever os.Stdin has
changed since, so it always reads the stdin there is when a prompt is
asked; the tests that re-pipe stdin between prompts now swap os.Stdin
alone and the reader follows.

Fixes #3737

Generated-by: GLM-5.3-Flash (ZCode)
---
 internal/cli/backup_cmd.go      | 21 ++++++++++++++++++---
 internal/cli/library_cli.go     |  4 ++--
 internal/cli/plugins_cli.go     |  8 ++++----
 internal/cli/quota_cli.go       |  2 +-
 internal/cli/stdin_test.go      | 30 ++++++++++++++++++++++++++++++
 internal/cli/webdav_cli_test.go |  7 +++----
 6 files changed, 58 insertions(+), 14 deletions(-)
 create mode 100644 internal/cli/stdin_test.go

diff --git a/internal/cli/backup_cmd.go b/internal/cli/backup_cmd.go
index d479cb90..cebbb552 100644
--- a/internal/cli/backup_cmd.go
+++ b/internal/cli/backup_cmd.go
@@ -143,15 +143,30 @@ 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. It is built on
+// first use, and again whenever os.Stdin has changed: package variables
+// are initialized before init functions run, so one built at start-up
+// would hold the dead stdin the Windows desktop build begins with
+// instead of the parent console its init attaches (#3737).
+var (
+	stdin     *bufio.Reader
+	stdinFile *os.File
+)
+
+// stdinReader is where prompted answers are read from.
+func stdinReader() *bufio.Reader {
+	if stdin == nil || stdinFile != os.Stdin {
+		stdinFile, stdin = os.Stdin, bufio.NewReader(os.Stdin)
+	}
+	return stdin
+}
 
 // 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 := stdinReader().ReadString('\n')
 		line = strings.TrimRight(line, "\r\n")
 		if line == "" {
 			if err != nil {
diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.go
index dff88976..54b58020 100644
--- a/internal/cli/library_cli.go
+++ b/internal/cli/library_cli.go
@@ -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, _ := stdinReader().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, _ := stdinReader().ReadString('\n')
 		if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
 			return nil, fmt.Errorf("nothing removed")
 		}
diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go
index 71274862..a2297032 100644
--- a/internal/cli/plugins_cli.go
+++ b/internal/cli/plugins_cli.go
@@ -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 := stdinReader().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 := stdinReader().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 := stdinReader().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 := stdinReader().ReadString('\n')
 	if err != nil && line == "" {
 		return "", err
 	}
diff --git a/internal/cli/quota_cli.go b/internal/cli/quota_cli.go
index 7f29cf39..537e61fe 100644
--- a/internal/cli/quota_cli.go
+++ b/internal/cli/quota_cli.go
@@ -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, _ := stdinReader().ReadString('\n')
 		if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
 			return fmt.Errorf("nothing spent")
 		}
diff --git a/internal/cli/stdin_test.go b/internal/cli/stdin_test.go
new file mode 100644
index 00000000..d0929652
--- /dev/null
+++ b/internal/cli/stdin_test.go
@@ -0,0 +1,30 @@
+package cli
+
+import (
+	"os"
+	"testing"
+)
+
+// The prompt reader must be built from the os.Stdin it is asked on, not
+// from the one the process started with: the Windows desktop build starts
+// with no console, and its init re-opens os.Stdin from the parent's
+// console after package variables are set (#3737). The tests re-pipe
+// stdin the same way, a line each.
+func TestStdinReaderFollowsStdin(t *testing.T) {
+	oldStdin := os.Stdin
+	t.Cleanup(func() { os.Stdin = oldStdin })
+	for _, want := range []string{"first\n", "second\n"} {
+		r, w, err := os.Pipe()
+		if err != nil {
+			t.Fatal(err)
+		}
+		w.WriteString(want)
+		w.Close()
+		os.Stdin = r
+		t.Cleanup(func() { r.Close() })
+		line, err := stdinReader().ReadString('\n')
+		if err != nil || line != want {
+			t.Fatalf("asked on the fresh stdin, read %q: %v", line, err)
+		}
+	}
+}
diff --git a/internal/cli/webdav_cli_test.go b/internal/cli/webdav_cli_test.go
index 7e8e9dd8..42325051 100644
--- a/internal/cli/webdav_cli_test.go
+++ b/internal/cli/webdav_cli_test.go
@@ -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)
+	oldFile := os.Stdin
+	os.Stdin = r
 	t.Cleanup(func() {
-		os.Stdin, stdin = oldFile, oldReader
+		os.Stdin = oldFile
 		r.Close()
 	})
 }
-- 
2.50.1 (Apple Git-155)

ggbdpq avatar Oct 26 '26 13:10 ggbdpq

Thanks for the quick fix (9298d2a, in v0.1.1605+). With the new build the The handle is invalid error is gone and the prompt (小米账号(手机号 / 邮箱 / ID)) now shows — but on Windows 11 (PowerShell 7 in Windows Terminal) the login still can't be completed, for a different reason:

Symptom

  • The PowerShell prompt comes back before magpie's output: PS C:\Users\...> is printed, then magpie's prompt appears after it.
  • magpie --help prints its text after the shell prompt has already returned, so I have to press Enter once more to get a clean prompt.
  • magpie plugin login super-xiaoai gets stuck at the password question: typing there does nothing useful.

Cause (as far as I can tell) The desktop exe is linked with -H windowsgui (Makefile release-windows), so cmd/PowerShell don't wait for it — a shell only waits for console-subsystem children. console_windows.go then AttachConsole(ATTACH_PARENT_PROCESS)s the console the shell keeps using, so the shell (PSReadLine) and magpie read the same CONIN$ at the same time. Plain line prompts can sometimes get through, but the hidden password read (term.ReadPassword) loses its keystrokes to the shell. #3719 (magpie tui on the GUI binary) looks like the same root.

Workarounds that avoid it

  • Start-Process magpie -ArgumentList 'plugin','login','super-xiaoai' -NoNewWindow -Wait (the shell waits, so nothing competes for input)
  • or the console build magpie-cli-windows-amd64.exe

Possible fix Ship a tiny console-subsystem launcher next to the GUI exe, e.g. magpie.com (the devenv.com/devenv.exe trick): PATHEXT lists .COM before .EXE, so typing magpie in a terminal runs the console launcher, which the shell waits for and which simply runs magpie.exe with inherited handles and returns its exit code, while double-clicking still opens the GUI. Alternatively the installer could put the nogui CLI build on PATH as magpie.

TomXPRIME avatar Oct 26 '26 15:10 TomXPRIME

The second half (the shell not waiting, and keys lost at a password prompt) is fixed in 2afacd7d1, released in v0.1.1680. The v0.1.1679 tag never published: an Intel Mac notarisation step lost its connection.

The Windows app still opens with no console window when double-clicked. It now writes a small console program, magpie.com, beside itself. PowerShell and cmd find magpie.com before magpie.exe (PATHEXT order), and they wait for it. It runs the app on the same console, so:

  • output comes before the prompt;
  • $LASTEXITCODE and %ERRORLEVEL% are set;
  • > file and pipes work;
  • hidden prompts such as the magpie plugin login password read what you type.

magpie with no arguments, or magpie app, still opens the window and returns at once.

Nothing needs setting up. After updating, the first magpie <command> in a terminal (or the app's next start) writes magpie.com beside the app, and every later command is waited for. Settings › Command line shows "magpie runs this app: …\magpie.com (which runs magpie.exe)".

What was tested on a Windows 11 machine, in PowerShell 7.5.4 and cmd, with typed input:

  • version and exit codes;
  • redirection;
  • backup and restore passphrases;
  • a piped passphrase;
  • Ctrl+C at a prompt.

The same steps on v0.1.1675 showed the bug.

Leaving this open until @TomXPRIME confirms it works.

yetone avatar Oct 27 '26 04:10 yetone

For the record: commit 9298d2a is a rework of the patch I posted in this thread yesterday (https://github.com/yetone/magpie/issues/3737#issuecomment-6417229915) — the same lazy-rebuild guard (stdinFile != os.Stdin, variable names aside), the same call-site swaps in backup_cmd.go, library_cli.go, plugins_cli.go and quota_cli.go, and the same piped() correction in webdav_cli_test.go, reworked with a mutex and an extra lipgloss renderer fix on top. It landed about an hour after that post and was not applied with git am, so no attribution survived the port. Following the practice recorded in #1643, a Co-authored-by trailer (or a straight git am) on ports like this would keep the author on the commit. Thanks for landing the fix for Windows users so quickly.

ggbdpq avatar Oct 27 '26 20:10 ggbdpq

更新后在 Windows 11(Windows Terminal 里的 PowerShell 7)上确认了:magpie plugin login super-xiaoai 现在 shell 会正常等待,密码提示能读到输入,登录成功。非常感谢这么快的修复和 magpie.com 启动器,也感谢 @ggbdpq 的 stdin 补丁。这个 issue 我先关了。

TomXPRIME avatar Oct 28 '26 05:10 TomXPRIME