From d73921e4199330e8996056f639d68fd9c3c62781 Mon Sep 17 00:00:00 2001 From: Ashvin Singh <136104771+ashvin-to@users.noreply.github.com> Date: Wed, 29 Jul 2026 19:58:48 +0530 Subject: [PATCH] fix: stdin handling and exit command (#58) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Summary of Changes Fixes **#53** (*Fish shell integration panics with `inappropriate ioctl for device`*). #### 1. Fixed Non-TTY Stdin (`panic: inappropriate ioctl for device`) — Fixes #53 - **Root Cause**: When executing `iris init fish | source` (or sourcing shell configs), `os.Stdin` (FD 0) is connected to a pipe instead of a TTY. Calling `term.MakeRaw()` on a pipe returns `ENOTTY`. - **Fix**: Guarded `term.MakeRaw()` with `term.IsTerminal()` checks across `root/wrapper.go` and `root/root.go`. Added fallback to open and use `/dev/tty` when `os.Stdin` is not a terminal device. - **Fish IPC Hooks**: Added `fish_preexec` and `fish_postexec` event handlers to `iris init fish` to send `IRIS_CMD_START` / `IRIS_CMD_STOP` IPC signals over `$IRIS_FD`. #### 2. Fixed Shell Setup Order (Duplicate `fastfetch` / startup executions) — Fixes #53 - **Root Cause**: `iris setup` appended the init script to the bottom of shell configs (`config.fish`, `.zshrc`, `.bashrc`), causing pre-existing interactive startup commands to run twice. - **Fix**: Updated `setupCmd` in `root/init.go` to **prepend** `# Iris Autocomplete` to the top of shell configuration files. #### 3. Fixed Terminal Exit Loop Handling — Relates to #50 - **Root Cause**: When typing `exit` in the wrapped shell, Linux PTY returns `syscall.EIO` (`Input/output error`) on `ptmx.Read()` rather than `io.EOF`. `runWrapper()` was ignoring non-EOF errors and looping indefinitely without restoring the terminal or calling `os.Exit(0)`. - **Fix**: Updated the `ptmx.Read` error handler in `root/wrapper.go` to handle `syscall.EIO` and exit cleanly. --- ### Issues Addressed - Closes #53 - Relates to #50, #55 --- ### Verification Tested - [x] Verified `iris setup fish` / `iris init fish | source` initializes without `ioctl` panic. - [x] Verified typing `exit` in Fish, Zsh, and Bash terminates IRIS cleanly and restores standard terminal state. - [x] Ran `go test ./...` — all tests pass. --------- Co-authored-by: verse91 Co-authored-by: VERSE --- root/crash.go | 3 ++- root/init.go | 35 ++++++++++++++++++++++++--------- root/root.go | 23 ++++++++++++++++------ root/wrapper.go | 52 ++++++++++++++++++++++++++++++++++++------------- 4 files changed, 83 insertions(+), 30 deletions(-) diff --git a/root/crash.go b/root/crash.go index cc68e40..f8eea44 100644 --- a/root/crash.go +++ b/root/crash.go @@ -20,7 +20,8 @@ func startRescueShell() { if shell == "" { shell = "/bin/sh" } - _ = syscall.Exec(shell, []string{shell}, os.Environ()) + env := append(os.Environ(), "IRIS_RESCUE=1") + _ = syscall.Exec(shell, []string{shell}, env) } var ( diff --git a/root/init.go b/root/init.go index d2a4837..7d5fd76 100644 --- a/root/init.go +++ b/root/init.go @@ -31,7 +31,7 @@ if [ -n "$TMUX" ] && [ -n "$IRIS_PID" ]; then fi fi -if [ -z "$IRIS_PID" ]; then +if [ -z "$IRIS_PID" ] && [ -z "$IRIS_RESCUE" ]; then export IRIS_ACTIVE_SHELL="zsh" exec iris fi @@ -67,7 +67,7 @@ if [ -n "$TMUX" ] && [ -n "$IRIS_PID" ]; then fi fi -if [ -z "$IRIS_PID" ]; then +if [ -z "$IRIS_PID" ] && [ -z "$IRIS_RESCUE" ]; then export IRIS_ACTIVE_SHELL="bash" exec iris fi @@ -83,10 +83,20 @@ if set -q TMUX; and set -q IRIS_PID end end -if not set -q IRIS_PID +if status is-interactive; and not set -q IRIS_PID; and not set -q IRIS_RESCUE set -gx IRIS_ACTIVE_SHELL "fish" exec iris end + +# Iris Autocomplete Hook +if set -q IRIS_PID; and set -q IRIS_FD + function _iris_fish_postexec --on-event fish_postexec + echo -n -e "IRIS_CMD_STOP\x00" >&$IRIS_FD 2>/dev/null + end + function _iris_fish_preexec --on-event fish_preexec + echo -n -e "IRIS_CMD_START\x00" >&$IRIS_FD 2>/dev/null + end +end `) } }, @@ -149,19 +159,26 @@ var setupCmd = &cobra.Command{ return } - content, _ := os.ReadFile(configFile) + content, readErr := os.ReadFile(configFile) if strings.Contains(string(content), "iris init") { fmt.Printf("Iris is already configured in %s\n", configFile) } else { - f, err := os.OpenFile(configFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) + var newContent string + if readErr == nil && len(content) > 0 { + newContent = "# Iris Autocomplete\n" + evalCmd + "\n\n" + string(content) + } else { + newContent = "# Iris Autocomplete\n" + evalCmd + "\n" + } + if mkdirErr := os.MkdirAll(filepath.Dir(configFile), 0755); mkdirErr != nil { + fmt.Printf("Failed to create directory for %s: %v\n", configFile, mkdirErr) + return + } + err = os.WriteFile(configFile, []byte(newContent), 0644) if err != nil { fmt.Printf("Failed to update %s: %v\n", configFile, err) return } - defer func() { _ = f.Close() }() - - _, _ = f.WriteString("\n# Iris Autocomplete\n" + evalCmd + "\n") - fmt.Printf("✓ Added iris integration to %s\n", configFile) + fmt.Printf("✓ Added iris integration to top of %s\n", configFile) } // initialize default config file if it does not exist diff --git a/root/root.go b/root/root.go index 23f87d4..353f78d 100644 --- a/root/root.go +++ b/root/root.go @@ -80,10 +80,21 @@ func runWatchdog() { return } - // save original terminal settings in parent process - watchdogOldState, errState := term.MakeRaw(int(os.Stdin.Fd())) - if errState == nil { - _ = term.Restore(int(os.Stdin.Fd()), watchdogOldState) + cmdStdin := os.Stdin + if !term.IsTerminal(int(cmdStdin.Fd())) { + if tty, ttyErr := os.OpenFile("/dev/tty", os.O_RDWR, 0); ttyErr == nil { + cmdStdin = tty + } + } + + // save original terminal settings in parent process if Stdin is a terminal + var watchdogOldState *term.State + if term.IsTerminal(int(cmdStdin.Fd())) { + var errState error + watchdogOldState, errState = term.MakeRaw(int(cmdStdin.Fd())) + if errState == nil { + _ = term.Restore(int(cmdStdin.Fd()), watchdogOldState) + } } r, w, err := os.Pipe() @@ -94,7 +105,7 @@ func runWatchdog() { cmd := exec.CommandContext(context.Background(), exe, os.Args[1:]...) cmd.Env = append(os.Environ(), "IRIS_IS_CHILD=true") - cmd.Stdin = os.Stdin + cmd.Stdin = cmdStdin cmd.Stdout = os.Stdout cmd.Stderr = w @@ -160,7 +171,7 @@ func runWatchdog() { WriteCrashLog(string(content)) // restore terminal state if watchdog saved it if watchdogOldState != nil { - _ = term.Restore(int(os.Stdin.Fd()), watchdogOldState) + _ = term.Restore(int(cmdStdin.Fd()), watchdogOldState) } printCrashNotice() startRescueShell() diff --git a/root/wrapper.go b/root/wrapper.go index d2a268c..652d919 100644 --- a/root/wrapper.go +++ b/root/wrapper.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "context" + "errors" "fmt" "io" "os" @@ -83,6 +84,7 @@ func saveMode(mode string) { var ( oldState *term.State + oldStateFd int oldStateMu sync.Mutex activeMode string activeModeMu sync.RWMutex @@ -103,7 +105,7 @@ func restoreTerminal() { oldStateMu.Lock() defer oldStateMu.Unlock() if oldState != nil { - _ = term.Restore(int(os.Stdin.Fd()), oldState) + _ = term.Restore(oldStateFd, oldState) oldState = nil } } @@ -152,20 +154,39 @@ func runWrapper() { } defer func() { _ = ptmx.Close() }() - _ = pty.InheritSize(os.Stdin, ptmx) + stdinFile := os.Stdin + if !term.IsTerminal(int(stdinFile.Fd())) { + if tty, ttyErr := os.OpenFile("/dev/tty", os.O_RDWR, 0); ttyErr == nil { + stdinFile = tty + } + } + + _ = pty.InheritSize(stdinFile, ptmx) spec.ShellPID = c.Process.Pid logger.Infof("PTY child shell started: shell=%s, path=%s, pid=%d", shellName, adapter.GetShellPath(), c.Process.Pid) // put terminal in raw mode to intercept every keystroke var errMakeRaw error - oldState, errMakeRaw = term.MakeRaw(int(os.Stdin.Fd())) - if errMakeRaw != nil { - logger.Errorf("Failed to set terminal raw mode: %v", errMakeRaw) - panic(errMakeRaw) + if term.IsTerminal(int(stdinFile.Fd())) { + oldState, errMakeRaw = term.MakeRaw(int(stdinFile.Fd())) + if errMakeRaw != nil { + logger.Errorf("Failed to set terminal raw mode: %v", errMakeRaw) + panic(errMakeRaw) + } + oldStateFd = int(stdinFile.Fd()) + logger.Debugf("Terminal set to raw mode successfully") + defer func() { + oldStateMu.Lock() + defer oldStateMu.Unlock() + if oldState != nil { + _ = term.Restore(int(stdinFile.Fd()), oldState) + oldState = nil + } + }() + } else { + logger.Warnf("stdinFile is not a terminal, skipping raw mode") } - logger.Debugf("Terminal set to raw mode successfully") - defer restoreTerminal() sigCh := make(chan os.Signal, 2) signal.Notify(sigCh, syscall.SIGWINCH, syscall.SIGUSR1) @@ -183,7 +204,7 @@ func runWrapper() { switch s { case syscall.SIGWINCH: logger.Debugf("Received SIGWINCH terminal resize signal") - _ = pty.InheritSize(os.Stdin, ptmx) // handle terminal window resize + _ = pty.InheritSize(stdinFile, ptmx) // handle terminal window resize // this is the core feature of reloading // it helps IRIS reload itself that you dont need to restart the shell manually // SIGUSR1 is the signal to active reload when you type "just reload" @@ -263,7 +284,7 @@ func runWrapper() { config.AutoDetectConfigChange(func(cfg *config.Config) { disableGhostText.Store(!cfg.UI.GhostText) }) - var renderOverlay func() + renderOverlay := func() {} isExecuting := func() bool { if isCommandActive.Load() { return true @@ -291,11 +312,12 @@ func runWrapper() { for { n, err := ptmx.Read(buf) if err != nil { - if err == io.EOF { - restoreTerminal() + restoreTerminal() + if err == io.EOF || errors.Is(err, syscall.EIO) || strings.Contains(err.Error(), "input/output error") { os.Exit(0) } - continue + logger.Errorf("Unexpected PTY read error: %v", err) + os.Exit(1) } writeStdout(buf[:n]) @@ -319,6 +341,8 @@ func runWrapper() { } }() + + // listen for suggestion requests from shell scripts via the ipc pipe go func() { defer func() { @@ -599,7 +623,7 @@ func runWrapper() { inBracketedPaste := false for { inputSlice := make([]byte, 128) - n, err := os.Stdin.Read(inputSlice) + n, err := stdinFile.Read(inputSlice) if err != nil { break }