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 }