Skip to content

fix(exec): isolate exec stdout from setup and suppress auto-install clipboard (#823) - #826

Merged
linghengqian merged 6 commits into
version-fox:mainfrom
aloneangel45:fix/823-exec-install-stderr
Nov 24, 2026
Merged

linghengqian merged 6 commits into
version-fox:mainfrom
aloneangel45:fix/823-exec-install-stderr

Conversation

@aloneangel45

@aloneangel45 aloneangel45 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #823

Summary

Scoped strictly to keeping vfox exec stdout clean and disabling interactive clipboard copying during non-interactive exec auto-installs:

  • vfox exec stdout isolation and stdio protection (cmd/commands/exec.go, internal/plugin/development_output.go, internal/plugin/lua_plugin.go):
    • redirectStdoutToStderr() in resolveExecCommandEnv routes os.Stdout, pterm, and active plugin Lua io standard stream writes (io.write, io.stdout:write, io.stderr:write) to os.Stderr while resolving SDK environments and auto-installing missing versions, then restores all streams before spawning the target executable.
    • Because plugin.RedirectStdIO is only active inside resolveExecCommandEnv (execStdioWriter is nil otherwise), Lua behavior for non-exec commands (install, use, etc.) remains unchanged.
    • Refuses closing standard streams (io.stdin:close(), io.stdout:close(), io.stderr:close(), io.close(), io.output():close()) on exec and development VMs with nil, "cannot close standard <input|output|error>" so hooks cannot break the child command's stdin/stdout/stderr.
    • Delegates ordinary non-standard Lua file handles directly via callLuaOriginal (preserving closure Upvalues in wrapLuaFunction) so errors such as bad argument #1 to write (file is closed) keep the exact method name, file/line, and single traceback of main, while write failures on standard streams under exec return nil, msg, 1 without raising or disrupting print.
    • Auto-install notices use fmt.Fprintf(os.Stderr, ...).
  • Suppress clipboard copy on exec auto-install (internal/sdk/sdk.go, internal/shared/util/tty.go, cmd/commands/exec.go):
    • Added InstallOptions{Reinstall, NoClipboard} and InstallResolvedWithOptions on sdk.Sdk, passing NoClipboard: true from resolveExecSDKEnv so TTY stderr / auto-install never invokes xclip/xsel/pbcopy/clip or prints clipboard banners.

Testing

  • internal/plugin/plugin_impl_test.go:
    • TestExecRedirectStdioCloseRefusalErrorsAndWriteFailures: verifies byte-for-byte identical closed-file error output between unredirected and exec-redirected VMs, stream-specific close refusal errors (input/output/error), and io.write/io.stderr:write returning nil, msg, 1 with print unaffected on write failure.
  • cmd/commands/exec_cli_test.go & cmd/commands/cli_test.go:
    • TestExecAutoInstallSeparatesStdoutAndStderr and TestExecAutoInstallStdioCloseRefusalAndFileErrors: verify child stdin/stdout/stderr stay intact across all 5 close forms, closed-file hook error formatting during exec auto-install, unwritable stderr handling (nil, msg, 1), and stream restoration after exec.
    • TestExecAutoInstallNeverWritesClipboard: verifies forced util.IsTTY = true never invokes stub clipboard helpers or emits "Copied to clipboard".
  • cmd/commands/exec_pty_linux_test.go:
    • TestExecAutoInstallWithStderrPTYNeverWritesClipboard: verifies Linux stdout pipe + stderr PTY leaves stdout pure ("cmd-stdout") and never touches clipboard (skipped on Windows; run on Linux CI).
  • Verified locally on Windows at 5dcf64f:
    • git diff --check, gofmt -s, 3-OS go vet ./..., and linux/darwin go test -c -o NUL ./cmd/commands ./internal/plugin — passed
    • VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./internal/plugin ./internal/sdk ./internal/shared/util ./cmd ./cmd/commands — passed (3.017s, 4.452s, 2.861s, 16.440s, 94.381s)

@linghengqian linghengqian added this to the 1.1.1 milestone Nov 23, 2026
@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.17949% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.65%. Comparing base (43acf4e) to head (5aeb5e0).

Files with missing lines Patch % Lines
internal/plugin/development_output.go 88.75% 7 Missing and 2 partials ⚠️
cmd/commands/exec.go 88.88% 2 Missing and 1 partial ⚠️
internal/sdk/sdk.go 57.14% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #826      +/-   ##
==========================================
+ Coverage   61.98%   62.65%   +0.66%     
==========================================
  Files         125      125              
  Lines        9810     9876      +66     
==========================================
+ Hits         6081     6188     +107     
+ Misses       3207     3160      -47     
- Partials      522      528       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #826 (head afc8550, base 90a96e1)

Not ready to merge. The stdout split in vfox exec works. The same global os.Stdout swap also breaks two things outside exec. Both are blocking.

1. vfox install --all -y fails for any plugin that writes to Lua output

installAll sets os.Stdout and os.Stderr to nil (cmd/commands/install.go:275-276). That is already on main. Before this PR, Lua output in that loop was dropped (print: gopher-lua calls fmt.Print and ignores the error) or went to the real stdout (io.write, io.stdout: they use handles cached at startup). It never raised an error.

This PR makes print, io.write, io.stdout:write and io.stderr:write read the global on every call, and raise on write errors (internal/plugin/development_output.go:49-80). A plugin that writes during that loop now fails with:

plugin [PreInstall] method error: .../main.lua:4: write output: invalid argument

The error shows in the summary, but the SDK is not installed and the command still exits 0. I tested a plugin whose PreInstall calls each of the four functions. On 90a96e1 all four install. On this branch none do. A plugin with no Lua output installs on both.

Regression test. It fails on this branch and passes on 90a96e1:

const printingPlugin = `PLUGIN = {name="alpha", version="0.0.1", description="test", author="test", minRuntimeVersion="0.0.0"}
function PLUGIN:Available(ctx) return {{version="1.0.0"}} end
function PLUGIN:PreInstall(ctx)
  print("preinstall says hello")
  return {version=ctx.version}
end
function PLUGIN:EnvKeys(ctx) return {{key="PATH", value=ctx.path .. "/bin"}} end
`

func TestInstallAllWithPluginPrint(t *testing.T) {
	f := newCLIFixture(t, false)
	f.writePlugin(t, "alpha", printingPlugin)
	must(t, os.WriteFile(filepath.Join(f.work, ".vfox.toml"), []byte("[tools]\nalpha = \"1.0.0\"\n"), 0644))
	f.runProcess(t, "install", "--all", "-y")
	if _, err := os.Stat(filepath.Join(f.shared, "cache", "alpha", "v-1.0.0")); err != nil {
		t.Errorf("[email protected] was not installed: %v", err)
	}
}

Pointing both globals at os.DevNull instead of nil makes it pass, and the existing cmd/commands, internal/plugin and internal/sdk tests still pass with that change. It is the only fix I tried.

2. vfox exec writes the clipboard when only stderr is a terminal

When exec auto-installs, the SDK install code (impl.install, internal/sdk/sdk.go:387) copies vfox use <sdk>@<version> to the clipboard if util.IsTTY() is true. IsTTY checks os.Stdout (internal/shared/util/tty.go:29). While exec resolves the environment, this PR points os.Stdout at stderr (cmd/commands/exec.go:132-140), so the check now reads stderr.

In an interactive shell:

x=$(vfox exec [email protected] -- cmd)

On 90a96e1 the clipboard is left alone. On this branch it is overwritten with vfox use [email protected], and "Copied to clipboard" is printed. I reproduced this under a pseudo-terminal with a stub xclip. The decision also flips the other way: with stdout on a terminal and stderr redirected, 90a96e1 copies and this branch does not.

Exec is non-interactive, so its auto-install should not reach the clipboard step at all. If you keep the check, it has to read the real stdout. Either way it needs a test. Nothing in this PR covers the clipboard.

What I checked

  • go test on ./cmd/commands, ./internal/plugin/... and ./internal/sdk on Linux with go1.27.3: passes.
  • gofmt -l and go vet on the changed packages: clean.
  • Stdout split: vfox exec [email protected] -- /bin/echo cmd-stdout now writes only cmd-stdout to stdout. On 90a96e1 the install messages and plugin output are there too.

Notes, not bugs

  • The development VM error text changed from "write diagnostics" to "write output". That is fine, but mention it in the commit message.
  • The global os.Stdout swap is the common cause of both problems. Passing writers through the install and exec paths would avoid this class of bug. That refactor can wait for a later PR, but the two fixes above belong in this one.

@aloneangel45

aloneangel45 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @linghengqian! Both blocking regressions are fixed in commit 78c5c7d:

  1. install --all -y with Lua output (cmd/commands/install.go): Switched installAll to redirect os.Stdout/os.Stderr to an opened os.DevNull (with deferred restoration and close) instead of nil, and added TestInstallAllWithPluginPrint in cmd/commands/install_cli_test.go exercising print, io.write, io.stdout:write, and io.stderr:write in PreInstall.
  2. Non-interactive vfox exec clipboard suppression (internal/sdk/sdk.go, cmd/commands/exec.go): Added sdk.InstallOptions{NoClipboard: true} via InstallResolvedWithOptions and passed it from resolveExecSDKEnv so vfox exec auto-install never reaches CopyToClipboard (even when stderr is a PTY and stdout is captured). Added TestInstallResolvedWithOptionsClipboard, TestExecAutoInstallNeverWritesClipboard, and TestExecAutoInstallWithStderrPTYNeverWritesClipboard (//go:build linux using /dev/ptmx + stub xclip/xsel).
  3. Noted the write diagnostics -> write output error text change in development_output.go in the commit message as requested.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #826 at 78c5c7d (base 90a96e1, which matches current main).

Not ready to merge. The two blockers from the earlier review are fixed on Linux. The branch still has regressions, and one guard only runs on Linux.

  1. Lua write errors now fail plugin hooks

configureDevelopmentOutput used to be the only path that raised on write errors. CreateLuaPlugin now calls redirectLuaOutput for every plugin VM, so production plugins get that behavior too. On main, print ignores write errors (gopher-lua's basePrint drops the error from fmt.Print), and io.write and file:write return nil, message, errno on failure, as standard Lua does. With this PR, print and the standard stream writes call RaiseError("write output: ..."), so the hook aborts.

Repro with a PreInstall that calls print:

  • vfox install [email protected] >/dev/full : main exits 0 and installs. 78c5c7d exits 1 and installs nothing.
  • vfox exec [email protected] -- sh -c 'echo ok' 2>/dev/full : main runs the command and exits 0. 78c5c7d exits 1 and never runs the command.

exec did not depend on stderr being writable before. Now it does, because auto-install output goes there. Production plugin output should keep gopher-lua's contract: print drops write errors, and io.write and file:write return nil, message, errno. Please add a test for each case.

  1. install --all -y hides plugin stderr output that main shows

installAll now points os.Stderr at /dev/null along with os.Stdout. On main, io.stderr:write("warning\n") in a PreInstall reaches the terminal during vfox install --all -y. On this branch it does not. io.write output is hidden too, and main shows it on stdout. Stderr does not need redirecting to avoid the reported failure, so keep it as it was. The PR should also say what happens to io.write output.

  1. The /dev/null fallback brings back the reported failure

If os.OpenFile(os.DevNull, ...) fails, installAll sets both streams to nil. That is the state that produced "write output: invalid argument" in the earlier review. I forced the open to fail in a scratch copy, and TestInstallAllWithPluginPrint fails with that error. Return an error from installAll instead of falling back.

  1. Wrong text for io.stderr:close()

development_output.go returns "cannot close standard output" for both streams, so io.stderr:close() returns nil, "cannot close standard output". Use the stream's own name.

  1. The clipboard guard is only tested on Linux

TestExecAutoInstallWithStderrPTYNeverWritesClipboard is the only test that fails when NoClipboard: true is removed from resolveExecSDKEnv, and it has a linux build tag. I removed that file in a scratch copy, and every TestExec* test still passed. TestExecAutoInstallNeverWritesClipboard also passes on the unfixed code, because its stdio are pipes and IsTTY() is false, so its name claims more than it checks. macOS and Windows CI would not catch this regression. Let the test force the TTY condition on every platform (for example by making util.IsTTY overridable from tests), and assert that exec never copies to the clipboard. Or rename the test and state in the PR that the guard is Linux-only.

What I checked

  • go build ./..., go vet ./..., and gofmt -l on the changed files: clean.
  • go test ./... on Linux with HOME isolated: all packages pass.
  • Reverting the installAll change, removing the per-VM Lua redirect, not restoring os.Stdout after exec, and removing the pterm redirect each make a targeted test fail.
  • With stderr sent to /dev/null, exec's stdout contains only the command output, including output from os.execute children.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks again @linghengqian for the detailed review! All five points are fixed in commit 94a2049 and the PR description has been updated:

  1. Production Lua write error contract (internal/plugin/development_output.go, internal/plugin/lua_plugin.go): Parameterized redirectLuaOutput(..., raiseOnWriteError bool) so CreateLuaPlugin passes false while development mode keeps true ("write output: %s", updated from "write diagnostics"). Production print drops write errors (and guards nil writers), and io.write / io.stdout:write / io.stderr:write / file:write return nil, message, errno on failure without aborting hooks. Added TestProductionLuaOutputErrorsAndClose and TestInstallAndExecIgnoreUnwritableStdioStreams (unwritable read-only *os.File for both install stdout and exec stderr).
  2. install --all -y keeps os.Stderr (cmd/commands/install.go): Removed the os.Stderr redirect so io.stderr:write reaches stderr as on main, while print, io.write, and io.stdout:write follow os.Stdout to os.DevNull (noted in the PR description and asserted in TestInstallAllWithPluginPrint).
  3. No nil fallback when os.DevNull fails (cmd/commands/install.go): installAll now returns the open ... error from openInstallAllDevNull instead of setting os.Stdout = nil, tested in TestInstallAllFailsWhenDevNullOpenFails.
  4. Stream-specific close() error (internal/plugin/development_output.go): io.stderr:close() now returns nil, "cannot close standard error" while io.stdout:close() keeps "cannot close standard output".
  5. Cross-platform TTY clipboard test (internal/shared/util/tty.go, internal/sdk/sdk.go, cmd/commands/exec_cli_test.go): Made util.IsTTY overridable via a package var and wired internal/sdk.isTTY dynamically to call it, so TestExecAutoInstallNeverWritesClipboard/forced_TTY_cross-platform fails whenever NoClipboard: true is removed on Windows, macOS, or Linux.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #826 (head 94a2049, base 90a96e1)

Not ready to merge.

The exec fixes and the other earlier blockers are fixed. The stderr change for install --all over-corrects, and that is a visible regression.

  1. install --all -y now draws download progress on the terminal

installAll used to set os.Stderr to nil, so Go-level writes to stderr failed silently for the whole loop, including the download progress bar. This PR removes that assignment. The bar in (*impl).Download (internal/sdk/sdk.go:1294, completion newline at :1299) writes to os.Stderr, so it now reaches the terminal while the spinner runs.

Repro: a plugin whose PreInstall returns a url to a 6 MB .tar.gz on localhost, then vfox install --all -y.

  • Run in a pty: main shows the spinner and no download output. This PR draws Downloading... frames over the spinner line.
  • Run with stderr redirected to a file: main writes 0 bytes. This PR writes 33,234 bytes, 100 progress frames. That ends up in CI logs.

The PR description says os.Stderr is "unchanged from main". It is not, and that is how this got past review. Plugin io.stderr:write still reaches stderr on both builds, so that part is fine. The problem is the Go-level writers.

Expected: install --all -y prints no download progress, as on main. The spinner should be the only live output during the loop.

Direction: have Download take its progress writer from something installAll can point at a discard writer for the loop, without touching os.Stderr. Plugin io.stderr:write keeps going to stderr.

Test: add an install --all -y case whose plugin downloads from an httptest server. Assert that stderr has no "Downloading" text and still contains a plugin io.stderr:write line. No existing test covers a download inside install --all, so this regression is not caught today.

If progress bars are meant to show during install --all, say so in the description and explain how they share the terminal with the spinner.

What I checked (Linux, Go 1.27.3):

  • go build, go vet, go test ./... pass.
  • GOOS=windows and GOOS=darwin go vet ./... pass. The Windows and macOS tests were not run.
  • gofmt is clean on the changed files. internal/plugin/model_test.go is listed, but this PR does not touch it, and it is unformatted on main too.
  • vfox exec with auto-install: stdout holds only the command output when it is a pipe. Install messages and plugin print, io.write, io.stdout:write and io.stderr:write go to stderr. Checked with the Linux pty test and a file-redirect run.
  • Removing NoClipboard: true makes TestExecAutoInstallNeverWritesClipboard/forced_TTY_cross-platform and TestExecAutoInstallWithStderrPTYNeverWritesClipboard fail on Linux. The guard is covered.
  • vfox install [email protected] >/dev/full exits 0 and installs. vfox exec [email protected] -- sh -c 'echo ok' 2>/dev/full exits 0 and prints ok.
  • install --all -y discards plugin print, io.write and io.stdout:write output, as the description says.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for catching that! Addressed in commit 619f999 and updated the PR description accordingly:

  1. Discard Download progress bar output during install --all -y (internal/sdk/sdk.go, cmd/commands/install.go):
    • Added ProgressWriter io.Writer to sdk.InstallOptions (defaulting to os.Stderr in Download and when omitted) and internal downloadWithProgressWriter / moveRemoteFileWithProgressWriter helpers.
    • Updated installAll to invoke lookupSdk.InstallResolvedWithOptions(sdk.Version(version), sdk.InstallOptions{ProgressWriter: io.Discard}) without touching os.Stderr, so progressbar frames and its completion newline go to io.Discard while plugin io.stderr:write(...) still writes to stderr.
  2. Test coverage (cmd/commands/install_cli_test.go):
    • Added TestInstallAllSuppressesDownloadProgress using an httptest archive download + io.stderr:write, verifying stderr contains preinstall-stderr and no "Downloading" frames while the archive extracts cleanly.

Re-verified locally after 619f999:

  • gofmt -l and git diff --check: clean
  • go vet ./... (Windows host and GOOS=linux GOARCH=amd64) and GOOS=linux GOARCH=amd64 go test -c ./cmd/commands: passed
  • go test -count=1 ./internal/plugin ./internal/sdk ./internal/shared/util ./cmd/commands: passed

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes

Most of the earlier blockers are fixed. vfox exec keeps stdout clean, auto-install no longer reaches the clipboard, plugin print and io.write failures no longer abort hooks, a failed /dev/null open is now returned as an error, and the Go-side download bar is silent during install --all -y. Three problems remain.

  1. http.download_file still draws progress during install --all -y

The ProgressWriter added here only reaches the Go download path. The Lua bar from http.download_file still writes to stderr. newModule captures os.Stderr when the module is created (internal/plugin/luai/module/http/http.go:301).

Repro: a plugin whose PreInstall calls require("http").download_file on a 6 MB file, then vfox install --all -y with stderr redirected to a file.

  • main: 0 bytes on stderr
  • this branch: 31,416 bytes on stderr, 298 progress redraws

On main the output is silent only because require("http") runs inside the install loop, after installAll has set os.Stderr to nil, so the module captures nil. This branch removes that side effect. When require runs at plugin load time, both branches print the bar, so the Lua path has never been silenced on purpose.

Please route the Lua progress output through the same install-time discard as the Go path, regardless of when the module was created. Add a test where the plugin calls require("http").download_file inside a hook under install --all -y. It should assert that stderr has no progress frames and still contains the plugin's io.stderr:write line.

  1. Write errors return the OS errno, not gopher-lua's value

luaWriteErrorErrno (internal/plugin/development_output.go:48-54) returns the real errno. gopher-lua always returns 1 in that position (fileWriteAux, "C-Lua compatibility"), and main does the same. Repro: io.stdout:write in PreInstall with stdout on /dev/full returns nil, "write /dev/stdout: no space left on device", 28 here and 1 on main.

The description says this branch preserves gopher-lua's contract. Either return 1, or change the description and explain why the value differs. TestProductionLuaOutputErrorsAndClose only checks that errno is a number, so it should check the value too.

  1. The description attributes the close behavior to gopher-lua

The description lists io.stderr:close() returning nil, "cannot close standard error" under "preserve gopher-lua's standard IO contract". gopher-lua has no such message: it closes the underlying file. On main, a plugin calling io.stdout:close() closes the host's stdout, and everything vfox prints afterwards is lost (exit code 0). Refusing the close is a good change, but it is a change. Please describe it as one, with the reason, and take it off the list of preserved behavior.

Suggestions, to address before approval

  • moveRemoteFile (internal/sdk/sdk.go:520) has no production caller now. Either remove it and have download_test.go call moveRemoteFileWithProgressWriter, or keep it and say why.

What I checked

Build, go vet ./... and go test ./... pass on Linux. Removing NoClipboard makes both clipboard tests fail. Removing ProgressWriter makes TestInstallAllSuppressesDownloadProgress fail. With stdout captured, vfox exec writes only the command output. A PTY run with a stub xclip on PATH does not invoke it.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for the detailed follow-up review! Addressed all three blocking items, the moveRemoteFile suggestion, and updated the PR description:

  1. Discard Lua http.download_file progress during install --all -y (internal/plugin/luai/module/http/http.go, internal/plugin/luai/module/module.go, internal/plugin/lua_plugin.go, internal/sdk/sdk.go):
    • Added OutputFunc func() io.Writer to http.Options (and ProgressOutput func() io.Writer to module.PreloadOptions), backed by a mutex-protected progressWriter on LuaPlugin (SetProgressWriter) wired in sdk.impl.install whenever opts.ProgressWriter != nil.
    • http.Module.progressWriter() resolves outputFunc() -> output -> dynamic os.Stderr, so install --all -y suppresses http.download_file progress frames whether require("http") ran at plugin load time or inside a hook, while plugin io.stderr:write(...) still writes to os.Stderr.
    • Added TestDownloadFileUsesOutputFuncDynamically (internal/plugin/luai/module/http/http_test.go) and TestInstallAllSuppressesLuaHTTPDownloadProgress (cmd/commands/install_cli_test.go, covering both hook-time and load-time require("http") with chunked httptest downloads).
  2. Preserve gopher-lua's errno == 1 on write errors (internal/plugin/development_output.go, internal/plugin/development_test.go):
    • Removed luaWriteErrorErrno so production io.write / io.stdout:write / io.stderr:write / file:write failures push 1 (lua.LNumber(1)), matching gopher-lua's fileWriteAux, and updated TestProductionLuaOutputErrorsAndClose to assert == 1 directly.
  3. Clarify io.stdout:close() / io.stderr:close() in PR description & comments:
    • Moved the io.stdout:close() / io.stderr:close() refusal out of "preserved gopher-lua behavior" and documented it explicitly as an intentional change preventing plugins from closing host stdio and swallowing subsequent vfox output.
  4. Remove unused moveRemoteFile wrapper (internal/sdk/sdk.go, internal/sdk/download_test.go):
    • Removed moveRemoteFile and updated TestSdk_MoveRemoteFileRedactsParseError to call moveRemoteFileWithProgressWriter(..., os.Stderr).

Re-verified locally after final edits (gofmt, git diff --check, Windows/linux/amd64/darwin/arm64 go vet, GOOS=linux GOARCH=amd64 go test -c ./cmd/commands, and go test -count=1 ./internal/plugin ./internal/plugin/luai ./internal/plugin/luai/codec ./internal/plugin/luai/module ./internal/plugin/luai/module/http ./internal/sdk ./internal/shared/util ./cmd/commands).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: #826 (head 2adebab)

Not ready to merge. The exec fix itself works. With the command from #823, stdout on this branch contains only the tool's output. On main it also gets the install messages and the plugin's print/io.write output. Two things still block.

1. io.stdin:close() still closes the host's stdin

redirectLuaOutput in internal/plugin/development_output.go refuses close() for stdout and stderr, and the comments say the goal is that plugins cannot close host stdio. Stdin is not covered, so io.stdin:close(), io.close(io.stdin) and io.input():close() still close fd 0.

Repro: a plugin whose PreInstall calls io.stdin:close(), then run printf 'hello-from-stdin\n' | vfox exec [email protected] -- readtool, where readtool does read line; echo "read: [$line]". On this branch the output is read: [] and io.stdin:close() returns true. Main behaves the same.

I tried a fix on a scratch copy: refuse close for the stdin file in both the method wrapper and the io.close wrapper, returning nil, "cannot close standard input". All three forms return that, and the repro prints read: [hello-from-stdin]. The existing production and exec tests pass. Please add the three forms to TestProductionLuaOutputErrorsAndClose.

2. Data race in the install --all spinner, which the new tests hit

installAll in cmd/commands/install.go (spinner from line 291 to 328) calls UpdateText and Stop from the main goroutine, while pterm's animation goroutine reads Text and IsActive. pterm v0.12.79 does not lock these fields.

Under go test -race ./cmd/commands, TestInstallAllWithPluginPrint, TestInstallAllSuppressesDownloadProgress and both subtests of TestInstallAllSuppressesLuaHTTPDownloadProgress fail, all with DATA RACE reports from the spinner.

This predates the PR. The same install --all -y run on main reports the same race. The new tests are what exposes it here. CI does not run with -race, so the checks stay green. The other packages are clean under -race.

Bumping pterm to v0.12.84, which locks the spinner, removes the race for these tests. But the bump also changes the vfox ls tree format. TestInstalledSdksOutputMatchesClinkFixture and TestInstalledSdksWithLinksAndAliasesOutputMatchesClinkFixture then fail, and internal/shell/clink_vfox.lua parses that format. So it cannot land as a drive-by version bump. Either:

  • replace the spinner in installAll with one plain line per step (it is the only pterm spinner in the repo), or
  • make the pterm upgrade its own change, with the Clink parser and fixtures updated and checked on the Windows Clink job.

Checked, no problem found

  • go test ./... passes on Linux. go vet passes on linux, and on windows and darwin for ./cmd/... and ./internal/....
  • Changed files are gofmt-clean. internal/plugin/model_test.go is unformatted on main too.
  • The Lua write results match gopher-lua's source: nil, msg, 1 on failure, true on success, and print drops write errors.
  • Removing NoClipboard: true makes TestExecAutoInstallNeverWritesClipboard/forced_TTY_cross-platform and TestExecAutoInstallWithStderrPTYNeverWritesClipboard fail on Linux.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for the catch on both items! Addressed in commit 546e1ac:

  1. Protect host io.stdin from close() (internal/plugin/development_output.go, internal/plugin/development_test.go, cmd/commands/exec_cli_test.go):
    • Extended redirectLuaOutput so file:close() and io.close(file) on io.stdin (including io.input():close()) return nil, "cannot close standard input" instead of closing fd 0.
    • Added all three forms (io.stdin:close(), io.close(io.stdin), io.input():close()) to TestProductionLuaOutputErrorsAndClose, plus an end-to-end TestExecPreservesStdinWhenPluginClosesStdin CLI test confirming piped stdin still reaches the vfox exec child process.
  2. Eliminate pterm spinner data race in installAll (cmd/commands/install.go):
    • Replaced the unsynchronized pterm.DefaultSpinner in installAll with plain single-line progress output written to stdout ([%v/%v] ... installing... and [%v/%v] Installation completed.), removing the data race without bumping pterm or altering Clink vfox ls output.

Re-verified after 546e1ac:

  • gofmt -l and git diff --check: clean
  • go vet ./... (Windows host, GOOS=linux GOARCH=amd64, and GOOS=darwin GOARCH=arm64) and GOOS=linux GOARCH=amd64 go test -c ./cmd/commands: passed
  • go test -race -count=1 ./internal/plugin ./internal/plugin/luai ./internal/plugin/luai/codec ./internal/plugin/luai/module ./internal/plugin/luai/module/http ./internal/sdk ./internal/shared/util ./cmd/commands: passed

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 546e1ac. Four items.

What works. The stdin close refusal and the spinner removal are in place. The #823 case works: with vfox exec [email protected] -- sh -c 'echo cmd-stdout; echo cmd-stderr >&2', stdout holds only cmd-stdout, and the install messages, plugin print/io.write output and os.execute output all go to stderr. A plugin that calls io.stdout:close(), io.stderr:close(), io.stdin:close(), io.close() or io.output():close() no longer stops the command from running. go test -race passes on the affected packages.

  1. install --all -y drops plugin io.write and io.stdout:write output

With PreInstall calling io.write("x\n") and io.stdout:write("y\n"), main prints both lines on stdout. This branch discards both: installAll points os.Stdout at DevNull (cmd/commands/install.go:283) and the Lua writers follow os.Stdout (internal/plugin/lua_plugin.go:287). Only io.stderr:write reaches the terminal.

The 94a2049 review accepted this because the description gave the spinner collision as the reason. 546e1ac removed the spinner, so that reason no longer applies. print is dropped on main too, so keeping print dropped is fine. io.write is different: a plugin that writes a prompt with io.write and then reads stdin now waits for input with no prompt on screen.

Please either send io.write and io.stdout:write to stdout again, as main does, or keep them discarded and state the real reason in the description. Either way the description has to change (see item 3).

  1. installAll returns nil when NewSdkManager fails

cmd/commands/install.go:243

manager, err := internal.NewSdkManager()
if err != nil {
    return nil
}

With a malformed config.yaml, vfox list exits 1 and prints "load config failed". vfox install --all -y exits 0 and prints nothing, on main and on this branch. This predates the PR, but installAll is rewritten here, so return the error. installCmd has the same pattern at cmd/commands/install.go:120. That line is outside this diff, so fix it here too or open an issue for it.

  1. The PR body, commit messages and title do not match the code
  • The body says print, io.write and io.stdout:write are discarded "instead of colliding with the spinner". The spinner is gone.
  • The body does not mention the spinner removal or the new plain progress lines, the io.stdin:close() refusal, or the new InstallResolvedWithOptions method on the Sdk interface.
  • The Verification section describes an earlier Windows run, not 546e1ac.
  • Commit 78c5c7d says installAll sends os.Stdout and os.Stderr to DevNull. 94a2049 reverted the os.Stderr part.
  • The title covers exec only. The diff also changes install --all, the Lua stdio contract for every command, HTTP progress routing and TTY detection. Retitle the PR, or move the install --all and Lua contract changes into their own PR.
  1. cmd/commands/install.go:287 _ = devNull.Close() has no comment

AGENTS.md asks for best-effort errors to be handled or explained. A one-line comment is enough.

Checked on Linux at 546e1ac: go build ./..., go vet ./..., go test and go test -race on the packages this PR touches, and the new targeted tests run three times in a row. All pass. gofmt -l lists internal/plugin/model_test.go, which is also unformatted on main.

@aloneangel45 aloneangel45 changed the title fix(exec): route auto-install and plugin output to stderr fix(exec,install,plugin): keep exec stdout clean and stabilize install --all / Lua stdio Nov 24, 2026
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed your review feedback in 853e631 and updated the PR title/body:

  1. installAll os.Stdout redirection (cmd/commands/install.go): Kept Lua print, io.write, and io.stdout:write directed to os.DevNull alongside Go SDK stdout during install --all -y so per-plugin/SDK stdout output does not clutter the batch progress lines and summary (while keeping os.Stderr / io.stderr:write attached to stderr), and updated the PR description with that real reason instead of the outdated spinner explanation.
  2. Returning NewSdkManager() errors (cmd/commands/install.go): Changed both installAll and installCmd to return err instead of return nil when internal.NewSdkManager() fails (for example on malformed config.yaml), matching use and add, and added TestInstallFailsOnMalformedConfig in cmd/commands/install_cli_test.go.
  3. PR title, body & verification: Retitled the PR to cover exec, install, and plugin changes cleanly; removed the stale spinner claim; documented the plain progress lines from 546e1ac, os.Stderr restoration from 94a2049, io.stdin:close() refusal (cannot close standard input), adding InstallResolvedWithOptions to the sdk.Sdk interface, and latest -race verification at 853e631.
  4. _ = devNull.Close() comment (cmd/commands/install.go): Added a one-line comment explaining the best-effort close in installAll's defer.

Verified locally at 853e631 with gofmt -s -l, git diff --check, cross-OS go vet ./cmd/... ./internal/... (windows/linux/darwin), go test -c (linux/darwin for ./cmd/commands), and go test -race -count=1 ./internal/plugin ./internal/plugin/luai ./internal/plugin/luai/codec ./internal/plugin/luai/module ./internal/plugin/luai/module/http ./internal/sdk ./internal/shared/util ./cmd ./cmd/commands.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 853e631.

The exec part works: with vfox exec [email protected] -- sh -c 'echo CMD-OUT; echo CMD-ERR >&2', stdout holds only CMD-OUT. The blockers are in the install --all changes and in one test. Items 1 to 5 block the merge. The description items at the end must also be fixed before it lands.

What I ran: go build; go vet for linux, windows and darwin; gofmt -s; git diff --check; go test ./... with HOME isolated; go test -race on ./cmd/..., ./internal/plugin/..., ./internal/sdk/... and ./internal/shared/util/.... All pass. I also built main (90a96e1) and this head and ran one probe plugin through both.

  1. install --all -y drops plugin io.write and io.stdout:write output that main prints.

With PreInstall calling io.write("P-iowrite\n") and io.stdout:write("P-stdout\n"), main prints both lines to stdout during install --all -y. This head prints neither line anywhere. io.stderr:write still reaches stderr. A single vfox install [email protected] on this head still prints both lines to stdout, so the two commands now disagree about the same plugin.

The body gives clutter in the batch output as the reason. The spinner that collided with plugin output went away in 546e1ac, so that reason no longer holds. Sending this output to stderr keeps it visible and keeps stdout for the progress lines, which is what exec already does for the same kind of output. If it goes back to stdout instead, a plugin write without a trailing newline runs into the next [n/m] line. Pick one, and update TestInstallAllWithPluginPrint and the body to match.

  1. install --all -y exits 0 when an install fails. This predates the PR, but the PR rewrites this function.

installAll ends with return nil after it prints the error list (cmd/commands/install.go:334). A PreInstall that calls error() exits 0 on main and on this head, and so does a 404 on the archive URL. A single vfox install [email protected] exits 1 for the same plugin. A CI job that runs install --all -y passes after a failed install. Return an error when errorStr is not empty.

  1. The success line is printed whatever happens.

fmt.Fprintf(stdout, "[%v/%v] Installation completed.\n", count, count) (line 323) runs after the loop regardless of the results. A failing run prints "[1/1] Installation completed." and then the failure summary. Print it only when everything succeeded, or use wording that is true when something failed.

  1. Failure details go to stdout.

fmt.Println(errorStr) (line 332) sends every install error to stdout. With vfox install --all -y 2>err.log, err.log is empty. Returning the collected errors from installAll fixes this and item 2 together: cmd/cmd.go:41-43 prints a returned error to stderr and exits 1.

  1. The PTY clipboard test can pass without checking its message.

In cmd/commands/exec_pty_linux_test.go the reader goroutine can still be running when master.Close() runs (lines 92-94: cmd.Wait(), master.Close(), <-doneDrain). Bytes still in the PTY buffer are then lost, so the "Copied to clipboard" assertion proves nothing. The marker-file check still catches a real clipboard call, so the test is not useless, but the message check cannot be trusted. Wait for doneDrain before closing master.

Before merge (the code is fine here, the description is not):

  • The body says TestExecAutoInstallNeverWritesClipboard covers the Linux PTY case. The PTY case is TestExecAutoInstallWithStderrPTYNeverWritesClipboard, in another file.
  • The body lists io.stdin:close(), io.stdout:close() and io.stderr:close() as refused. io.close(io.stdin) and io.input():close() are refused too, and the tests check them.
  • The body does not mention that os.execute output is discarded during install --all. Neither stdout nor stderr gets it.

Not bugs, but worth a look:

  • installAll skips the clipboard only because os.Stdout points at /dev/null, so IsTTY() is false. Pass NoClipboard: true explicitly, so a later change to the redirect cannot bring the copy back.
  • The diff is about 970 lines across 16 files. #823 is about exec stdout. The install --all and Lua stdio contract changes could go in a separate PR.
  • CI does not run -race. This PR adds an RWMutex and goroutine-based tests. Consider -race for the touched packages.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all five blockers and the description notes in 1c9d19e:

  1. install --all Lua print / io.write / io.stdout:write (internal/plugin/lua_plugin.go, internal/sdk/sdk.go, cmd/commands/install.go): Added LuaPlugin.SetOutputWriter and sdk.InstallOptions.OutputWriter, and passed OutputWriter: os.Stderr from installAll so plugin stdout (print, io.write, io.stdout:write) reaches stderr alongside io.stderr:write (matching exec and keeping stdout strictly for progress lines and the summary); updated TestInstallAllWithPluginPrint.
  2. Non-zero exit on install --all failure (cmd/commands/install.go): Returned collected failures (errors.New(...)) from installAll instead of return nil.
  3. Truthful summary line on failure (cmd/commands/install.go): Changed the completion line to [%v/%v] Installation finished with failures. whenever len(errorStr) > 0 instead of always printing Installation completed..
  4. Failure details to stderr (cmd/commands/install.go, cmd/commands/install_cli_test.go): Removed fmt.Println(errorStr) to stdout so returning the error sends failures through cmd/cmd.go to os.Stderr with exit status 1; added TestInstallAllReturnsErrorAndWritesFailureToStderr.
  5. Linux PTY drain order (cmd/commands/exec_pty_linux_test.go): Waited on <-doneDrain (with ctx.Done() fallback) before closing master so buffered PTY bytes are drained before checking stderr.
  6. Additional notes: Passed NoClipboard: true explicitly in installAll, and updated the PR body to name TestExecAutoInstallWithStderrPTYNeverWritesClipboard in exec_pty_linux_test.go, list io.close(io.stdin) / io.input():close(), and note that os.execute stdout is discarded to os.DevNull during install --all.

Verified locally at 1c9d19e with gofmt -s -l, git diff --check, 3-OS go vet ./cmd/... ./internal/..., linux/darwin go test -c (./cmd/commands, ./internal/sdk, ./internal/plugin), and go test -race -count=1 across all 9 affected packages.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #826 at 1c9d19e (base 90a96e1)

Not ready to merge.

Most earlier blockers look fixed on this head: exit status, error output on stderr, the stdout split for exec, NoClipboard, the PTY drain, the stdin close, errno, and download progress during install --all -y. Three problems remain in how install --all -y routes Lua output. The first one is a regression from main.

1. Regression: output from a plugin added during the batch is dropped

Repro: add a plugin that is not on the machine yet (a local registry set through registry.address in config.yaml works), whose main.lua calls io.write("hello\n") at the top level. Run vfox install --all -y.

  • main: hello is on stdout, in the middle of the spinner line.
  • 1c9d19e: hello is on neither stream.

Cause: Manager.Add calls plugin.CreatePlugin (internal/manager.go:661) inside the loop. OutputWriter is only set inside sdk.install(), so the stdout fallback in CreateLuaPlugin (internal/plugin/lua_plugin.go:298-303) reads os.Stdout, which is /dev/null at that point.

Expected: hello on stderr, the same as PreInstall output.

2. Output from an already-added plugin's top level goes to stdout

Repro: a plugin already in the plugin directory with print("hello") at the top level, used from .vfox.toml. Run vfox install --all -y. hello is printed on stdout before the [1/1] lines.

Cause: notInstalled() (cmd/commands/install.go:247) calls LookupSdk, which loads the plugin before installAll changes any stream.

Main does the same. But the PR body says print, io.write and io.stdout:write stay on stderr during install --all, and stdout is meant to hold only the progress lines and the summary. Either route this case or correct the body.

3. os.execute output is dropped during install --all -y

Repro: PreInstall calls os.execute("echo hi"). Neither stream shows hi. With vfox install [email protected] it is on stdout, and with vfox exec it is on stderr.

Cause: gopher-lua reads os.Stdout when os.execute is called (gopher-lua v1.1.1, oslib.go:83), and that is /dev/null during the batch. The Windows override reads it the same way (internal/plugin/luai/exec.go:60).

Main drops it too, and the body now documents that. But docs/plugins/create/testing.md:75 says os.execute output goes to stderr, and a batch should not lose it.

Suggested fix for 1 to 3

exec already handles this (cmd/commands/exec.go:132): it points os.Stdout at os.Stderr while it works and restores it before it runs the command. Doing the same in installAll fixes all three with one mechanism. Scope it to notInstalled and the loop. The listing and the confirmation prompt should stay on stdout as they are. Keep the saved stdout for the [n/m] lines and the summary, and leave pterm on /dev/null.

Side effects to decide on: the fmt.Printf calls in Manager.Add ("Fetching ... manifest", "Validating ...") will show on stderr during the batch, and so will Checksum error, file: ... (internal/sdk/sdk.go:554), which is lost on main too. Both seem acceptable to me, but the body should say so.

4. None of this is tested

TestInstallAllWithPluginPrint only prints from PreInstall. Add cases to cmd/commands/install_cli_test.go:

  • top-level print and io.write in an already-added plugin: the markers must not be on stdout and must be on stderr;
  • a plugin added from a registry with top-level io.write: the marker must be on stderr;
  • a PreInstall that runs os.execute on a tool from the test's PATH: its output must be on stderr.

What I checked: go test ./cmd/commands and go test -race on the touched packages at 1c9d19e. The three repros above were run through the CLI test harness on main (90a96e1) and on this head, with the same plugins. Removing ProgressWriter makes the download-progress tests fail, and dropping the returned error makes TestInstallAllReturnsErrorAndWritesFailureToStderr fail.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all four points from the review in 90500df:

  1. notInstalled and batch loop os.Stdout redirection (cmd/commands/install.go):
    • Wrapped notInstalled(manager) with redirectStdoutToStderr() and restored streams immediately afterward, so top-level Lua print / io.write / io.stdout:write in already-added plugins go to stderr while the listing and confirmation prompt stay on stdout.
    • In the batch install loop inside installAll, kept saved stdout for [n/m] lines and the summary, kept pterm.SetDefaultOutput(devNull), and pointed os.Stdout = os.Stderr. This routes top-level Lua output from plugins added via Manager.Add, already-added plugins' PreInstall, and os.execute(...) child stdout to stderr instead of os.DevNull.
  2. PR description & side effects:
    • Updated the PR description to document that Manager.Add fmt.Printf lines ("Fetching ... manifest", "Validating ...") and internal/sdk/sdk.go "Checksum error, file: ..." now appear on stderr during install --all instead of being dropped.
  3. Tests (cmd/commands/install_cli_test.go):
    • Added TestInstallAllTopLevelAndExecLuaOutputGoesToStderr covering:
      • top-level print / io.write / io.stdout:write in an already-added plugin,
      • a plugin added from a local mock registry (registry.address) with top-level io.write, and
      • PreInstall executing an external tool from the fixture PATH via os.execute.

Verified locally at 90500df (gofmt -s -l, git diff --check, 3-OS go vet ./cmd/... ./internal/..., linux/darwin go test -c ./cmd/commands, and VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./internal/plugin ./internal/sdk ./cmd ./cmd/commands).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #826 at 90500df (base 90a96e1)

Not ready to merge.

I ran the Linux suite (go test ./...), go test -race on cmd, cmd/commands, internal/sdk, internal/plugin, the http module and internal/shared/util, go vet for linux, windows and darwin, gofmt -s, git diff --check, and test builds for windows and darwin. All pass, and CI is green.

What works: vfox exec writes only the command's output to stdout, including the #823 case. io.close() with no argument, io.output():close() and io.stdin:close() refuse as the description says. The success value of io.write and io.stdout:write is true, which matches gopher-lua's fileWriteAux.

Blocking

  1. install --all -y does not install the SDK of a tool whose plugin is not added yet.

notInstalled (cmd/commands/install.go:362-370) puts such a tool in plugins only. The batch then runs manager.Add and never installs the version from .vfox.toml. It still prints "[1/1] Installation completed." and exits 0. docs/usage/core-commands.md:53 says --all installs all SDK versions recorded in .vfox.toml.

Repro: a registry that serves remote.json and remote.lua (PreInstall returns {version=ctx.version}), a .vfox.toml with remote = "1.0.0", and no remote plugin on disk.

vfox install --all -y; echo $?    # prints 0
ls "$VFOX_HOME/cache/remote"      # no v-1.0.0 directory

Same result on 90a96e1. This PR rewrites the loop and adds a registry case to TestInstallAllTopLevelAndExecLuaOutputGoesToStderr (install_cli_test.go:411) that walks this exact path, but it only checks stderr. Install the version once Add succeeds, or report the tool as failed and exit 1. The registry case should also assert that v-1.0.0 exists.

  1. The batch clipboard guard has no test.

installAll passes NoClipboard: true (install.go:321). Inside the batch, os.Stdout is redirected to stderr, so util.IsTTY() reports the state of stderr. On a terminal with stderr attached, the batch copies "vfox use ..." to the clipboard unless the flag is set. I removed the flag and the whole cmd/commands suite still passed. With util.IsTTY forced to true, an in-process "install --all -y" calls the stub clipboard helper. Please add a forced-TTY test for install --all, like the one in TestExecAutoInstallNeverWritesClipboard (exec_cli_test.go:169).

  1. The pterm devnull redirect has no test.

Remove pterm.SetDefaultOutput(devNull) (install.go:288) and the suite still passes. The batch then prints this on stdout:

[1/1] SDK: [email protected] installing...
Preinstalling [email protected]...
Install [email protected] success!
Please use `vfox use [email protected]` to use it.
[1/1] Installation completed.

The description says stdout carries only progress lines and the summary. Please assert that these lines are absent from stdout in TestInstallAllWithPluginPrint.

  1. TestExecAutoInstallNeverWritesClipboard/process cannot fail (exec_cli_test.go:188).

The child process has a piped stdout, so IsTTY() is false and the clipboard branch never runs. I removed NoClipboard from resolveExecSDKEnv and this subtest still passed. Only the forced-TTY subtest and the PTY test caught it. Either force the TTY in this subtest too, or delete it.

  1. The side-effect list in the description is incomplete.

During the batch these also reach stderr now: "Downloading ..." (internal/manager.go:496) and "@ is already installed" (internal/sdk/sdk.go:343). The body lists only Fetching, Validating and Checksum error. The message of commit 78c5c7d says os.Stdout and os.Stderr go to os.DevNull in installAll, which the code no longer does. Please update the body and reword that commit message if the history is kept.

Notes, not bugs

  • This PR covers #823, install --all output and exit status, the Lua stdio contract, HTTP progress routing and a new Sdk method. Splitting the install --all and Lua contract changes into their own PR would make each part easier to review. I did not count this against the merge.
  • I found no bug in the exec path, the Lua write and close contract, or the progress routing.

@aloneangel45
aloneangel45 force-pushed the fix/823-exec-install-stderr branch from 90500df to cd98771 Compare November 24, 2026 07:22
…treams & missing plugins, and preserve Lua stdio

- Route vfox exec auto-install and plugin Lua output to stderr while preserving pure command stdout and safe Windows cmd.exe batch quoting / POSIX PATH checks.
- Preserve Lua io.stdout/io.stderr file contracts and ignore broken/unwritable stdio writes safely without leaking host stdin close errors.
- Redirect os.Stdout to os.Stderr and pterm to os.DevNull across install --all -y (keeping only [n/m] progress lines and summary on stdout) and queue missing plugins' SDK versions after manager.Add succeeds.
- Suppress clipboard copy during install --all and exec auto-install and add forced-TTY, PTY, registry, and os.execute tests.
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all five blocking items from the review at cd98771 (squashed onto origin/main so commit history no longer carries the stale 78c5c7d /dev/null message):

  1. install --all -y now installs SDK versions for plugins not added yet (cmd/commands/install.go):
    • notInstalled now queues missing tools in both plugins and sdks (with deterministic sorting via slices.Sort / slices.Sorted(maps.Keys(sdks))).
    • installAll adds missing plugins first and then installs their queued SDK version from .vfox.toml; if manager.Add fails, the SDK step skips lookup, keeps its failure status (red + "Installation finished with failures."), and exits 1.
    • Extended TestInstallAllTopLevelAndExecLuaOutputGoesToStderr (cmd/commands/install_cli_test.go) to verify v-1.0.0 exists on disk after registry Add, plus a failing-registry subtest verifying non-zero exit without "Installation completed.".
  2. Batch clipboard guard test (cmd/commands/install_cli_test.go): Added TestInstallAllNeverWritesClipboard forcing util.IsTTY = true with the stub clipboard binary to verify NoClipboard: true prevents clipboard writes during install --all -y.
  3. pterm os.DevNull suppression assertions (cmd/commands/install_cli_test.go): Extended TestInstallAllWithPluginPrint (and the registry subtest) to assert "Preinstalling ", "Install ... success!", and "Please use " are absent from both stdout and stderr.
  4. Removed non-failing TestExecAutoInstallNeverWritesClipboard/process (cmd/commands/exec_cli_test.go): Kept "forced TTY cross-platform" and the Linux stderr PTY test in exec_pty_linux_test.go.
  5. Updated PR description & history: Updated the PR body to list all stderr batch side effects (Fetching ... manifest, Validating ..., Downloading <file>..., <sdk>@<version> is already installed, Checksum error, file: ...) and squashed cd98771 cleanly.

Local Verification (cd98771)

  • gofmt -s -l and git diff --check: clean
  • go vet ./... (linux, windows, darwin): passed
  • go test -c -o NUL ./cmd/commands (linux, darwin): passed
  • VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./internal/plugin ./internal/sdk ./cmd ./cmd/commands: passed (3.403s, 4.098s, 16.618s, 99.223s; Linux PTY and unprivileged Windows symlink tests skipped by the harness)

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge.

The exec part works. With stdout piped, only the command's output reaches stdout, which is what #823 asks for. I also removed each guard in turn: NoClipboard in exec and in the batch, the pterm DevNull redirect, the stdout-to-stderr redirect in install --all, the notInstalled redirect, and ProgressWriter. Each removal fails a test, so those tests cover what they claim.

Three things block the merge.

  1. Installing the SDK of a missing plugin fails for category-prefixed or mixed-case keys.

installAll passes the .vfox.toml key through unchanged. Manager.Add strips a / prefix (internal/manager.go:521) and requests .json (manager.go:543). LookupSdk lowercases the name and does not strip the prefix (manager.go:81, :94). The SDK loop then calls LookupSdk with the raw key (cmd/commands/install.go:321), after the plugin was added under a different name.

Reproduced on this head with a local registry and an empty VFOX_HOME:

  • "cat/remote" = "1.0.0": exit 1, "cat/remote not installed". The plugin lands in plugin/remote and no cache/remote directory is created.
  • Remote = "1.0.0": exit 1, "Remote not installed". The plugin lands in plugin/Remote. On a case-sensitive registry without Remote.json, the add fails with "[Remote] not found in remote registry".
  • remote = "1.0.0": works.

vfox install [email protected] installs the SDK, because the single-install path lowercases its input. On main, the batch exits 0 for the first two keys and installs nothing, so this part of the feature never worked for them.

Normalize the tool names once in notInstalled (lowercase, then the same category split as Manager.Add), so plugins, sdks, pluginsResult and LookupSdk all use the name the plugin is installed under. Add a regression test with a cat/ key and a mixed-case key that checks cache//v-1.0.0 exists.

  1. A skipped SDK still prints "installing...".

The progress line is printed before the skip check (install.go:315, skip at :318). With a failed plugin the output is:

[2/2] SDK: [email protected] installing...
[2/2] Installation finished with failures.

Nothing is being installed at that point. Print the skip reason instead, or move the progress line below the check.

  1. Error chains are dropped.

AGENTS.md asks to preserve error chains with %w. installAll builds errorStr with %s (install.go:304, :306, :323, :332) and returns errors.New(...) (:350). Collect the errors in a slice and return errors.Join. This function is rewritten in this PR, so the fix belongs here.

Not blocking for this PR: on main, a plugin's top-level code already runs twice during a single "vfox install " (Manager.Add loads it to validate, then LookupSdkWithInstall loads it again). The batch now shows the same duplicate output because of the new SDK step. The fix belongs in Manager, so a separate change is fine.

Checked on this head: go build, go vet ./..., go test -count=1 ./..., and go test -race on the touched packages pass on Linux. CI is green.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for finding all three issues! Addressed them in the new commit:

  1. Category-prefixed and mixed-case keys in install --all (cmd/commands/install.go): Added normalizeToolName (lowercases the key and strips any <category>/ prefix, matching Manager.Add and Manager.LookupSdk) and normalized every entry in notInstalled, so plugins, sdks, pluginsResult, and manager.LookupSdk consistently use the directory name the plugin is installed under. Added regression tests (category-prefixed and mixed-case keys install plugin and sdk and TestInstallAllNormalizesKeysAndPreservesErrorChain) verifying cache/remote/v-1.0.0 exists.
  2. Skipped SDK status line (cmd/commands/install.go): Moved [n/m] SDK: <name>@<version> installing... below the pluginsResult[sdkName] check and printed [n/m] SDK: <name>@<version> skipped (plugin failed to install). when the plugin failed to add. Asserted in both the CLI test and TestInstallAllNormalizesKeysAndPreservesErrorChain.
  3. Preserve error chains (cmd/commands/install.go): Replaced errorStr with errs []error, preserved internal.ManifestNotFound via %w, and returned errors.Join(errs...). Verified with errors.Is(err, internal.ManifestNotFound).

Verified locally after the final edit:

  • go test -race -count=1 ./cmd ./cmd/commands ./internal/plugin ./internal/plugin/luai ./internal/plugin/luai/module ./internal/plugin/luai/module/http ./internal/sdk ./internal/shared/util — passed (cliFixture subprocess tests skip on Windows without VFOX_TEST_WINDOWS_REGISTRY=1, while TestInstallAllNormalizesKeysAndPreservesErrorChain executes directly on Windows and passed; internal/plugin/luai/module/fs requires Windows symlink privilege).
  • go vet ./... across linux/amd64, windows/amd64, and darwin/arm64 — passed.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes.

The exec part does what #823 asks, and each guard I removed made at least one of its tests fail. The install --all rework has two bugs I could reproduce, and the PR goes well past #823.

1. A key with two slashes installs an unrelated plugin

normalizeToolName (cmd/commands/install.go:353) strips only the first /. Manager.Add (internal/manager.go:520) keeps the second segment. So "a/b/c" = "1.0.0" in .vfox.toml becomes b/c. Add("b/c") fetches c.json and installs plugin c, then the SDK step fails with b/c not installed. The exit code is 1, but plugin c stays in the plugin directory.

Repro: a local registry serving c.json and c.lua, a .vfox.toml with "a/b/c" = "1.0.0", then vfox install --all -y.

Please reject keys with more than one /, and check the remaining name against the plugin name rule before calling Add. A test should check that no plugin directory gets created.

2. Keys that normalize to the same name drop a version at random

notInstalled assigns sdks[name] = version while ranging over a map (cmd/commands/install.go:375-389). With Remote = "1.0.0" and remote = "2.0.0" in .vfox.toml and the plugin installed, every call returns one entry. Over 300 calls I got 1.0.0 100 times and 2.0.0 200 times. On main both entries are kept, so this is a regression: a requested version is silently not installed, and which one is skipped changes between runs. cat/remote next to remote does the same, since both normalize to remote.

Please return an error that names both keys when two keys normalize to one name. A test should call notInstalled several times and expect that error.

3. Scope

#823 is about what vfox exec writes to stdout. This PR also rewrites install --all (spinner removal, key normalization, error chain, exit code, clipboard behavior), changes install and install --all to return the manager error instead of nil, adds a method to the sdk.Sdk interface, and changes Lua standard streams for every command. AGENTS.md asks to keep unrelated refactoring separate, so please split this into:

  • exec stdout and NoClipboard for auto-install (this closes #823);
  • the Lua standard stream changes;
  • the install --all changes.

The print override is not needed for #823. gopher-lua's print calls fmt.Print, which already follows os.Stdout. The close refusal is a real fix, since gopher-lua's io.stdout:close() closes the process's stdout file, but it changes plugin behavior for every command and should get its own review.

4. Stale comment

cmd/commands/install.go:288 still says "keeping pterm spinners/notes on os.DevNull". There is no spinner in this PR.

Pre-existing, outside this diff

  • LookupSdk joins tool names into plugin paths with no check (internal/manager.go:94). On upstream main, the key "../../outside" makes vfox install --all -y and vfox env --shell bash load and run a main.lua outside the plugin directory. This branch does the same for env. Since env runs at every prompt, this is a security problem. I would track it as its own issue, with name validation in LookupSdk.
  • Plugin print output during vfox env goes to stdout, which the shell evaluates. Not changed here.

What I ran

  • Head 8d8822e over base 90a96e1. go build, go vet ./... on Linux, go test ./..., and go test -race on the affected packages pass. go mod tidy -diff is clean. All CI jobs pass.
  • Removing each guard made a test fail: clipboard suppression in exec, install and sdk; stdout redirection in exec and install; progress suppression for Go and Lua downloads; the Lua HTTP output hook; install's error return; stdin, stdout and stderr close refusal; DevNull routing for pterm; key normalization; the skip logic; and print raising on write errors.
  • gofmt -s -l lists internal/manager.go and internal/plugin/model_test.go. Both are listed on main too.

@aloneangel45 aloneangel45 changed the title fix(exec,install,plugin): keep exec stdout clean and stabilize install --all / Lua stdio fix(exec): isolate exec stdout from setup and suppress auto-install clipboard (#823) Nov 24, 2026
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Split out all unrelated changes in commit 9cc9ca9 so #826 is now strictly scoped to #823 (exec stdout isolation and NoClipboard on auto-install):

  1. Reverted unrelated subsystems back to main: restored cmd/commands/install.go, internal/plugin/luai/module/*, internal/sdk/download_test.go, internal/sdk/install_as_test.go, and internal/plugin/development_test.go, removed install_cli_test.go and the Lua stdio-close / unwritable-stream tests, and removed ProgressWriter/OutputWriter from InstallOptions in internal/sdk/sdk.go (keeping only {Reinstall, NoClipboard}).
  2. Kept non-exec commands' Lua streams and print/close untouched: during local verification, keeping RedirectStdIO only for exec matters because gopher-lua's io.write / io.stdout:write bind Go's startup os.Stdout at package init rather than following later os.Stdout = os.Stderr assignments (TestExecAutoInstallSeparatesStdoutAndStderr failed without wrapping those writes). So redirectLuaIO in internal/plugin/development_output.go now redirects io.write / io.stdout / io.stderr writes only when plugin.RedirectStdIO is active inside vfox exec's resolveExecCommandEnv, without overriding print or io.close, leaving all other commands identical to main.
  3. Follow-ups: I will leave the install --all rework (including rejecting a/b/c with >1 / and returning an explicit error when keys normalize to the same plugin name) and the Lua io.stdin/io.stdout/io.stderr close guards for separate focused PRs.

Verified locally at 9cc9ca9: go test -race -count=1 ./cmd ./cmd/commands ./internal/sdk ./internal/shared/util ./internal/plugin passed, plus go vet ./... and go test -c ./cmd/commands passed across linux/amd64, windows/amd64, and darwin/arm64. Ready for another look whenever you have a moment!

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 9cc9ca9.

The narrower scope is easier to review, and the stdout split works for a normal auto-install. Everything below blocks the merge, including the small items.

  1. Closing the host's stdio during exec breaks the command again

On 546e1ac, closing the host's stdin, stdout or stderr was refused on the exec path: io.stdin:close(), io.stdout:close(), io.stderr:close(), io.close() and io.output():close(). 9cc9ca9 dropped those refusals, since the exec redirect is installed with close interception off. Same plugin and command, built from each commit:

  • PreInstall calls io.stdout:close(), then vfox exec [email protected] -- /bin/echo cmd-stdout. 546e1ac prints cmd-stdout. 9cc9ca9 prints nothing and exits 0. io.close() and io.output():close() do the same.
  • PreInstall calls io.stdin:close(), then printf 'hello\n' | vfox exec [email protected] -- readtool, where readtool is read line; echo "read: [$line]". 546e1ac prints read: [hello]. 9cc9ca9 prints read: [].
  • PreInstall calls io.stderr:close(), then vfox exec [email protected] -- sh -c 'echo to-stderr >&2'. 546e1ac shows to-stderr. 9cc9ca9 loses it and the command exits 2.

Main behaves the same in all of these, so the bug predates the PR. It still sits in the stdout contract this PR is meant to establish, and an earlier revision of this branch handled it. Please restore the refusals on the exec path, with a test for each form that checks stdout, stdin and stderr of the command. If you decide to leave them out, the description needs to say that a plugin can still close the command's stdio during exec.

  1. Errors from ordinary files inside exec are rewritten

redirectLuaIO wraps write, flush and setvbuf on every file handle in an exec VM, not only on stdout and stderr, and it wraps io.write and io.flush. The wrapper goes through forwardLua, which runs the function protected and re-raises the error with RaiseError("%s", err). For local f = io.open(p, "w"); f:close(); f:write("x") in PreInstall, vfox exec reports this (paths shortened):

  • main: plugin [PreInstall] method error: main.lua:6: bad argument #1 to write (file is closed), one traceback
  • 9cc9ca9: plugin [PreInstall] method error: main.lua:6: main.lua:6: bad argument #1 to (anonymous) (file is closed), and two tracebacks

The function name is lost and the position is repeated. Errors from handles that are not the standard streams should reach the plugin as they do on main. Please add a test that checks the message of a failed method call during auto-install.

  1. The exec write-error branch has no test

Changing the exec call from redirectLuaIO(vm.Instance, writer, false, false) to pass true for raiseOnWriteError leaves ./cmd/commands and ./internal/plugin passing. Please add a case with stderr closed or pointing at /dev/full. io.write and io.stderr:write should return nil, msg, 1, print should not raise, and the hook should still succeed.

  1. io.stderr:close() reports the wrong stream name

standardResult returns cannot close standard output for both streams, so io.stderr:close() in the development VM returns nil, "cannot close standard output". Main has the same message, so this is old, but this PR moves the function. Pass the stream name through.

Design note for the author

The os.Stdout swap is why the wrappers exist. gopher-lua binds the startup *os.File for io.stdin, io.stdout and io.stderr, so changing os.Stdout does not reach them. The wrappers then sit on the shared file metatable, which is how items 1 and 2 happen. I have not tried a narrower design.

What I ran

  • Head 9cc9ca9: go build ./..., go vet ./cmd/... ./internal/... and go test -count=1 ./... with HOME isolated pass. git diff --check and gofmt -l on the changed files are clean.
  • The repros above, using binaries built from 546e1ac, 9cc9ca9 and 90a96e1, with the plugin lines shown in each item.
  • Windows and macOS were not run here. CI is green on those jobs.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all four review items at 5dcf64f:

  1. Standard stream close refusals on exec (internal/plugin/development_output.go, internal/plugin/lua_plugin.go, cmd/commands/exec_cli_test.go):
    • Enabled close interception in redirectLuaIO for CreateLuaPlugin as well as development mode and added io.stdin to the close guard. io.stdin:close(), io.stdout:close(), io.stderr:close(), io.close(), and io.output():close() all return nil, "cannot close standard <input|output|error>" without closing host stdio.
    • Added TestExecAutoInstallStdioCloseRefusalAndFileErrors subtests for each of the five forms verifying child stdin (read: [hello]), stdout (cmd-stdout), and stderr (cmd-stderr).
  2. Preserve ordinary file errors (internal/plugin/development_output.go, internal/plugin/plugin_impl_test.go, cmd/commands/exec_cli_test.go):
    • Removed forwardLua/CallByParam(Protect: true) re-raising and instead delegate non-standard handles straight through callLuaOriginal (while copying origFn.Upvalues onto wrappers via wrapLuaFunction so io.output(file); io.write(...) continues sharing gopher-lua's internal state table).
    • Verified byte-for-byte identical closed-file error formatting (bad argument #1 to write (file is closed), single traceback, no (anonymous)) in both TestExecRedirectStdioCloseRefusalErrorsAndWriteFailures and TestExecAutoInstallStdioCloseRefusalAndFileErrors.
  3. Exec write-error test coverage (internal/plugin/plugin_impl_test.go, cmd/commands/exec_cli_test.go):
    • Added tests with failing writer / unwritable read-only stderr asserting io.write and io.stderr:write return nil, msg, 1, print does not raise, and PreInstall / vfox exec completes cleanly.
  4. Stream name in close error (internal/plugin/development_output.go):
    • Updated closeStandard to return "cannot close standard input", "cannot close standard output", and "cannot close standard error" matching io.stdin, io.stdout, and io.stderr.

Updated the PR description to reflect the restored close protection and new tests.

Local Verification (5dcf64f, Windows host)

  • gofmt -s, git diff --check, 3-OS go vet ./..., and linux/darwin go test -c -o NUL ./cmd/commands ./internal/plugin: passed
  • VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./internal/plugin ./internal/sdk ./internal/shared/util ./cmd ./cmd/commands: passed (3.017s, 4.452s, 2.861s, 16.440s, 94.381s; Linux PTY test runs on CI).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to resolve merge conflicts.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Merged origin/main (1953446, including #827 and #828) and resolved the conflicts on fix/823-exec-install-stderr:

  • cmd/commands/exec.go: Extracted resolveExecCommandEnv (wrapped with redirectStdoutToStderr() / defer restore()) and kept fix(exec): skip CLI flag parsing so target command flags pass through without -- #828's executeInVfoxEnvWithSeparator, execCommandNotFoundError, separator notes, and isBareSDKName.
  • cmd/commands/cli_test.go, exec_cli_test.go, exec_pty_linux_test.go: Kept Exec alongside Add in pristine and aligned the isolated fixture callers with main's newCLIFixtureWithoutRegistryGuard.
  • cmd/exec_test.go: Updated the --debug subtests in TestExecForwardsFlagsAfterCommandWithoutSeparator to assert that "Looking up SDK: etcd" is emitted to stderr rather than leaking onto stdout (since internal/shared/logger writes to os.Stdout, which redirectStdoutToStderr() routes to stderr during resolveExecCommandEnv).

Local Verification (Windows host)

  • gofmt -s and git diff --check: clean
  • go vet ./... (windows/amd64, linux/amd64, darwin/arm64) and go test -c -o NUL (./cmd/commands, ./cmd, ./internal/plugin for linux/amd64 and darwin/arm64): passed
  • go test -race -count=1 ./internal/plugin ./internal/sdk ./internal/shared/util ./cmd ./cmd/commands: passed (3.077s, 4.481s, 3.146s, 59.432s, 31.004s) and go test -v -race -count=1 ./cmd/commands -run 'TestExec' (11.201s; Windows-registry-guarded cases and Linux PTY tests skipped on Windows without VFOX_TEST_WINDOWS_REGISTRY=1).

…stderr

# Conflicts:
#	cmd/commands/cli_test.go
#	cmd/commands/exec.go
…stderr

# Conflicts:
#	cmd/commands/cli_test.go
#	internal/sdk/sdk.go
@aloneangel45

Copy link
Copy Markdown
Contributor Author

Merged origin/main (43acf4e, including #811) at 5aeb5e0 and resolved conflicts:

  • cmd/commands/cli_test.go: Kept Exec alongside Unuse in pristine.
  • internal/sdk/sdk.go: Preserved InstallResolvedWithOptions alongside Uninstall(version Version, fallbacks ...Version) on Sdk.

Local Verification (5aeb5e0, Windows host)

  • gofmt -s and git diff --check: clean
  • go vet ./... and go test -c across windows/amd64, linux/amd64, and darwin/arm64: passed
  • go test -race -count=1 ./internal/plugin ./internal/sdk ./internal/shared/util ./cmd: passed (3.340s, 5.974s, 2.652s, 59.586s)
  • VFOX_TEST_WINDOWS_REGISTRY=1 go test -v -race -count=1 ./cmd/commands -run 'TestExec|TestUninstall': passed (24.478s, POSIX read-only directory cases skipped on Windows).

@linghengqian linghengqian added bug Something isn't working and removed need-more-info labels Nov 24, 2026

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

exec prints the install of a missing version to stdout, next to the output of the command

2 participants