fix: stdin handling and exit command (#58)

### 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 <versedev.store@proton.me>
Co-authored-by: VERSE <sunnyone0901@gmail.com>
This commit is contained in:
Ashvin Singh
2026-07-29 21:28:48 +07:00
committed by GitHub
co-authored by verse91 VERSE
parent d6cfb9c909
commit d73921e419
4 changed files with 83 additions and 30 deletions
+2 -1
View File
@@ -20,7 +20,8 @@ func startRescueShell() {
if shell == "" { if shell == "" {
shell = "/bin/sh" shell = "/bin/sh"
} }
_ = syscall.Exec(shell, []string{shell}, os.Environ()) env := append(os.Environ(), "IRIS_RESCUE=1")
_ = syscall.Exec(shell, []string{shell}, env)
} }
var ( var (
+26 -9
View File
@@ -31,7 +31,7 @@ if [ -n "$TMUX" ] && [ -n "$IRIS_PID" ]; then
fi fi
fi fi
if [ -z "$IRIS_PID" ]; then if [ -z "$IRIS_PID" ] && [ -z "$IRIS_RESCUE" ]; then
export IRIS_ACTIVE_SHELL="zsh" export IRIS_ACTIVE_SHELL="zsh"
exec iris exec iris
fi fi
@@ -67,7 +67,7 @@ if [ -n "$TMUX" ] && [ -n "$IRIS_PID" ]; then
fi fi
fi fi
if [ -z "$IRIS_PID" ]; then if [ -z "$IRIS_PID" ] && [ -z "$IRIS_RESCUE" ]; then
export IRIS_ACTIVE_SHELL="bash" export IRIS_ACTIVE_SHELL="bash"
exec iris exec iris
fi fi
@@ -83,10 +83,20 @@ if set -q TMUX; and set -q IRIS_PID
end end
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" set -gx IRIS_ACTIVE_SHELL "fish"
exec iris exec iris
end 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 return
} }
content, _ := os.ReadFile(configFile) content, readErr := os.ReadFile(configFile)
if strings.Contains(string(content), "iris init") { if strings.Contains(string(content), "iris init") {
fmt.Printf("Iris is already configured in %s\n", configFile) fmt.Printf("Iris is already configured in %s\n", configFile)
} else { } 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 { if err != nil {
fmt.Printf("Failed to update %s: %v\n", configFile, err) fmt.Printf("Failed to update %s: %v\n", configFile, err)
return return
} }
defer func() { _ = f.Close() }() fmt.Printf("✓ Added iris integration to top of %s\n", configFile)
_, _ = f.WriteString("\n# Iris Autocomplete\n" + evalCmd + "\n")
fmt.Printf("✓ Added iris integration to %s\n", configFile)
} }
// initialize default config file if it does not exist // initialize default config file if it does not exist
+16 -5
View File
@@ -80,10 +80,21 @@ func runWatchdog() {
return return
} }
// save original terminal settings in parent process cmdStdin := os.Stdin
watchdogOldState, errState := term.MakeRaw(int(os.Stdin.Fd())) 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 { if errState == nil {
_ = term.Restore(int(os.Stdin.Fd()), watchdogOldState) _ = term.Restore(int(cmdStdin.Fd()), watchdogOldState)
}
} }
r, w, err := os.Pipe() r, w, err := os.Pipe()
@@ -94,7 +105,7 @@ func runWatchdog() {
cmd := exec.CommandContext(context.Background(), exe, os.Args[1:]...) cmd := exec.CommandContext(context.Background(), exe, os.Args[1:]...)
cmd.Env = append(os.Environ(), "IRIS_IS_CHILD=true") cmd.Env = append(os.Environ(), "IRIS_IS_CHILD=true")
cmd.Stdin = os.Stdin cmd.Stdin = cmdStdin
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = w cmd.Stderr = w
@@ -160,7 +171,7 @@ func runWatchdog() {
WriteCrashLog(string(content)) WriteCrashLog(string(content))
// restore terminal state if watchdog saved it // restore terminal state if watchdog saved it
if watchdogOldState != nil { if watchdogOldState != nil {
_ = term.Restore(int(os.Stdin.Fd()), watchdogOldState) _ = term.Restore(int(cmdStdin.Fd()), watchdogOldState)
} }
printCrashNotice() printCrashNotice()
startRescueShell() startRescueShell()
+33 -9
View File
@@ -4,6 +4,7 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@@ -83,6 +84,7 @@ func saveMode(mode string) {
var ( var (
oldState *term.State oldState *term.State
oldStateFd int
oldStateMu sync.Mutex oldStateMu sync.Mutex
activeMode string activeMode string
activeModeMu sync.RWMutex activeModeMu sync.RWMutex
@@ -103,7 +105,7 @@ func restoreTerminal() {
oldStateMu.Lock() oldStateMu.Lock()
defer oldStateMu.Unlock() defer oldStateMu.Unlock()
if oldState != nil { if oldState != nil {
_ = term.Restore(int(os.Stdin.Fd()), oldState) _ = term.Restore(oldStateFd, oldState)
oldState = nil oldState = nil
} }
} }
@@ -152,20 +154,39 @@ func runWrapper() {
} }
defer func() { _ = ptmx.Close() }() 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 spec.ShellPID = c.Process.Pid
logger.Infof("PTY child shell started: shell=%s, path=%s, pid=%d", shellName, adapter.GetShellPath(), 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 // put terminal in raw mode to intercept every keystroke
var errMakeRaw error var errMakeRaw error
oldState, errMakeRaw = term.MakeRaw(int(os.Stdin.Fd())) if term.IsTerminal(int(stdinFile.Fd())) {
oldState, errMakeRaw = term.MakeRaw(int(stdinFile.Fd()))
if errMakeRaw != nil { if errMakeRaw != nil {
logger.Errorf("Failed to set terminal raw mode: %v", errMakeRaw) logger.Errorf("Failed to set terminal raw mode: %v", errMakeRaw)
panic(errMakeRaw) panic(errMakeRaw)
} }
oldStateFd = int(stdinFile.Fd())
logger.Debugf("Terminal set to raw mode successfully") logger.Debugf("Terminal set to raw mode successfully")
defer restoreTerminal() 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")
}
sigCh := make(chan os.Signal, 2) sigCh := make(chan os.Signal, 2)
signal.Notify(sigCh, syscall.SIGWINCH, syscall.SIGUSR1) signal.Notify(sigCh, syscall.SIGWINCH, syscall.SIGUSR1)
@@ -183,7 +204,7 @@ func runWrapper() {
switch s { switch s {
case syscall.SIGWINCH: case syscall.SIGWINCH:
logger.Debugf("Received SIGWINCH terminal resize signal") 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 // this is the core feature of reloading
// it helps IRIS reload itself that you dont need to restart the shell manually // 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" // SIGUSR1 is the signal to active reload when you type "just reload"
@@ -263,7 +284,7 @@ func runWrapper() {
config.AutoDetectConfigChange(func(cfg *config.Config) { config.AutoDetectConfigChange(func(cfg *config.Config) {
disableGhostText.Store(!cfg.UI.GhostText) disableGhostText.Store(!cfg.UI.GhostText)
}) })
var renderOverlay func() renderOverlay := func() {}
isExecuting := func() bool { isExecuting := func() bool {
if isCommandActive.Load() { if isCommandActive.Load() {
return true return true
@@ -291,11 +312,12 @@ func runWrapper() {
for { for {
n, err := ptmx.Read(buf) n, err := ptmx.Read(buf)
if err != nil { 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) os.Exit(0)
} }
continue logger.Errorf("Unexpected PTY read error: %v", err)
os.Exit(1)
} }
writeStdout(buf[:n]) writeStdout(buf[:n])
@@ -319,6 +341,8 @@ func runWrapper() {
} }
}() }()
// listen for suggestion requests from shell scripts via the ipc pipe // listen for suggestion requests from shell scripts via the ipc pipe
go func() { go func() {
defer func() { defer func() {
@@ -599,7 +623,7 @@ func runWrapper() {
inBracketedPaste := false inBracketedPaste := false
for { for {
inputSlice := make([]byte, 128) inputSlice := make([]byte, 128)
n, err := os.Stdin.Read(inputSlice) n, err := stdinFile.Read(inputSlice)
if err != nil { if err != nil {
break break
} }