Repository navigation
fix(exec): isolate exec stdout from setup and suppress auto-install clipboard (#823) - #826
Conversation
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
linghengqian
left a comment
There was a problem hiding this comment.
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 teston./cmd/commands,./internal/plugin/...and./internal/sdkon Linux with go1.27.3: passes.gofmt -landgo veton the changed packages: clean.- Stdout split:
vfox exec [email protected] -- /bin/echo cmd-stdoutnow writes onlycmd-stdoutto stdout. On90a96e1the 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.Stdoutswap 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.
|
Thanks for the thorough review @linghengqian! Both blocking regressions are fixed in commit
|
linghengqian
left a comment
There was a problem hiding this comment.
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.
- 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.
- 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.
- 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.
- 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.
- 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.
|
Thanks again @linghengqian for the detailed review! All five points are fixed in commit
|
linghengqian
left a comment
There was a problem hiding this comment.
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.
install --all -ynow 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.
|
Thanks @linghengqian for catching that! Addressed in commit
Re-verified locally after
|
linghengqian
left a comment
There was a problem hiding this comment.
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.
- 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.
- 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.
- 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.
|
Thanks @linghengqian for the detailed follow-up review! Addressed all three blocking items, the
Re-verified locally after final edits ( |
linghengqian
left a comment
There was a problem hiding this comment.
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
installAllwith 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 vetpasses on linux, and on windows and darwin for./cmd/...and./internal/....- Changed files are gofmt-clean.
internal/plugin/model_test.gois unformatted on main too. - The Lua write results match gopher-lua's source:
nil, msg, 1on failure,trueon success, andprintdrops write errors. - Removing
NoClipboard: truemakesTestExecAutoInstallNeverWritesClipboard/forced_TTY_cross-platformandTestExecAutoInstallWithStderrPTYNeverWritesClipboardfail on Linux.
|
Thanks
Re-verified after
|
linghengqian
left a comment
There was a problem hiding this comment.
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.
- 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).
- 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.
- 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.
- 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.
|
Addressed your review feedback in
Verified locally at |
linghengqian
left a comment
There was a problem hiding this comment.
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.
- 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.
- 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.
- 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.
- 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.
- 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.
|
Addressed all five blockers and the description notes in
Verified locally at |
linghengqian
left a comment
There was a problem hiding this comment.
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:
hellois on stdout, in the middle of the spinner line. - 1c9d19e:
hellois 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
printandio.writein 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.executeon 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.
|
Addressed all four points from the review in
Verified locally at |
linghengqian
left a comment
There was a problem hiding this comment.
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
- 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.
- 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).
- 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.
- 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.
- 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.
90500df to
cd98771
Compare
…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.
|
Addressed all five blocking items from the review at
Local Verification (
|
linghengqian
left a comment
There was a problem hiding this comment.
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.
- 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.
- 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.
- 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.
|
Thanks
Verified locally after the final edit:
|
… and join errors with %w
linghengqian
left a comment
There was a problem hiding this comment.
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
NoClipboardfor auto-install (this closes #823); - the Lua standard stream changes;
- the
install --allchanges.
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
LookupSdkjoins tool names into plugin paths with no check (internal/manager.go:94). On upstreammain, the key"../../outside"makesvfox install --all -yandvfox env --shell bashload and run amain.luaoutside the plugin directory. This branch does the same forenv. Sinceenvruns at every prompt, this is a security problem. I would track it as its own issue, with name validation inLookupSdk.- Plugin
printoutput duringvfox envgoes to stdout, which the shell evaluates. Not changed here.
What I ran
- Head
8d8822eover base90a96e1.go build,go vet ./...on Linux,go test ./..., andgo test -raceon the affected packages pass.go mod tidy -diffis 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
printraising on write errors. gofmt -s -llistsinternal/manager.goandinternal/plugin/model_test.go. Both are listed onmaintoo.
|
Split out all unrelated changes in commit
Verified locally at |
linghengqian
left a comment
There was a problem hiding this comment.
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.
- 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(), thenvfox exec [email protected] -- /bin/echo cmd-stdout. 546e1ac printscmd-stdout. 9cc9ca9 prints nothing and exits 0.io.close()andio.output():close()do the same. - PreInstall calls
io.stdin:close(), thenprintf 'hello\n' | vfox exec [email protected] -- readtool, where readtool isread line; echo "read: [$line]". 546e1ac printsread: [hello]. 9cc9ca9 printsread: []. - PreInstall calls
io.stderr:close(), thenvfox exec [email protected] -- sh -c 'echo to-stderr >&2'. 546e1ac showsto-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.
- 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.
- 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.
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/...andgo test -count=1 ./...with HOME isolated pass.git diff --checkandgofmt -lon 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.
…e errors, and fix close stream name
|
Addressed all four review items at
Updated the PR description to reflect the restored close protection and new tests. Local Verification (
|
linghengqian
left a comment
There was a problem hiding this comment.
You need to resolve merge conflicts.
|
Merged
Local Verification (Windows host)
|
…stderr # Conflicts: # cmd/commands/cli_test.go # cmd/commands/exec.go
…stderr # Conflicts: # cmd/commands/cli_test.go # internal/sdk/sdk.go
|
Merged
Local Verification (
|
Fixes #823
Summary
Scoped strictly to keeping
vfox execstdoutclean and disabling interactive clipboard copying during non-interactiveexecauto-installs:vfox execstdout isolation and stdio protection (cmd/commands/exec.go,internal/plugin/development_output.go,internal/plugin/lua_plugin.go):redirectStdoutToStderr()inresolveExecCommandEnvroutesos.Stdout,pterm, and active plugin Luaiostandard stream writes (io.write,io.stdout:write,io.stderr:write) toos.Stderrwhile resolving SDK environments and auto-installing missing versions, then restores all streams before spawning the target executable.plugin.RedirectStdIOis only active insideresolveExecCommandEnv(execStdioWriterisnilotherwise), Lua behavior for non-execcommands (install,use, etc.) remains unchanged.io.stdin:close(),io.stdout:close(),io.stderr:close(),io.close(),io.output():close()) onexecand development VMs withnil, "cannot close standard <input|output|error>"so hooks cannot break the child command'sstdin/stdout/stderr.callLuaOriginal(preserving closureUpvaluesinwrapLuaFunction) so errors such asbad argument #1 to write (file is closed)keep the exact method name, file/line, and single traceback ofmain, while write failures on standard streams underexecreturnnil, msg, 1without raising or disruptingprint.fmt.Fprintf(os.Stderr, ...).execauto-install (internal/sdk/sdk.go,internal/shared/util/tty.go,cmd/commands/exec.go):InstallOptions{Reinstall, NoClipboard}andInstallResolvedWithOptionsonsdk.Sdk, passingNoClipboard: truefromresolveExecSDKEnvso TTYstderr/ auto-install never invokesxclip/xsel/pbcopy/clipor prints clipboard banners.Testing
internal/plugin/plugin_impl_test.go:TestExecRedirectStdioCloseRefusalErrorsAndWriteFailures: verifies byte-for-byte identical closed-file error output between unredirected andexec-redirected VMs, stream-specific close refusal errors (input/output/error), andio.write/io.stderr:writereturningnil, msg, 1withprintunaffected on write failure.cmd/commands/exec_cli_test.go&cmd/commands/cli_test.go:TestExecAutoInstallSeparatesStdoutAndStderrandTestExecAutoInstallStdioCloseRefusalAndFileErrors: verify childstdin/stdout/stderrstay intact across all 5 close forms, closed-file hook error formatting duringexecauto-install, unwritablestderrhandling (nil, msg, 1), and stream restoration afterexec.TestExecAutoInstallNeverWritesClipboard: verifies forcedutil.IsTTY = truenever invokes stub clipboard helpers or emits"Copied to clipboard".cmd/commands/exec_pty_linux_test.go:TestExecAutoInstallWithStderrPTYNeverWritesClipboard: verifies Linuxstdoutpipe +stderrPTY leavesstdoutpure ("cmd-stdout") and never touches clipboard (skipped on Windows; run on Linux CI).5dcf64f:git diff --check,gofmt -s, 3-OSgo vet ./..., andlinux/darwingo test -c -o NUL ./cmd/commands ./internal/plugin— passedVFOX_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)