Skip to content

feat(build, syncthing): dynamic console allocation for Windows - #10335

Closed
Shablone wants to merge 41 commits into
syncthing:mainfrom
Shablone:main
Closed

Shablone wants to merge 41 commits into
syncthing:mainfrom
Shablone:main

Conversation

@Shablone

@Shablone Shablone commented Sep 1, 2025

Copy link
Copy Markdown
Contributor

Dynamic Console Allocation for Windows

Purpose

Windows GUI builds either always show a short console pupup on windows systemstart implementation or never show one (CLI users can't see output).
See PR10334 , PR926 and many more

Solution

Implement dynamic console allocation:

  • No console when double-clicked from Explorer
  • Console appears when launched with CLI arguments
  • --no-console flag to explicitly disable console
  • Console behavior preserved across monitor restarts

Testing

syncthing.exe              # No console (GUI)
syncthing.exe --help       # Shows console + help
syncthing.exe --no-console # No console even with args

Opening from explorer won't show a console.

Implementation

  • Uses Windows API (AllocConsole/AttachConsole) to create console on demand
  • Monitor process passes --no-console to child processes when appropriate
  • Windows-only using build constraints

Fixes console window appearing briefly when launched from Explorer while maintaining proper CLI functionality.

Authorship

@Shablone Shablone changed the title Dynamic Console Allocation for Windows feat: Dynamic Console Allocation for Windows Sep 1, 2025
@github-actions github-actions Bot added the enhancement New features or improvements of some kind, as opposed to a problem (bug) label Sep 1, 2025
@Shablone
Shablone force-pushed the main branch 3 times, most recently from 78cad68 to c2552bf Compare September 1, 2025 21:57
@rafaeloledo

Copy link
Copy Markdown

Did you have success running it?

Comment thread cmd/syncthing/monitor.go Outdated
}

// Check if --no-console was passed or if we have no args (double-clicked)
noConsole := len(args) <= 1 // No args means launched from GUI

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.

noConsole := slices.Contains(args, "--no-console")

Comment thread cmd/syncthing/monitor.go Outdated
childArgs := args[1:] // Start with original args (excluding binary name)
if noConsole {
// Check if --no-console is already in the args
hasNoConsole := false

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.

hasNoConsole := slices.Contains(childArgs, "--no-console")

Comment thread cmd/syncthing/console_windows.go Outdated
procFreeConsole = kernel32.NewProc("FreeConsole")
procGetConsoleWindow = kernel32.NewProc("GetConsoleWindow")
procSetStdHandle = kernel32.NewProc("SetStdHandle")
procCreateFileW = kernel32.NewProc("CreateFileW")

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.

CreateFile and SetStdHandle are in sys/x/windows

Comment thread lib/osutil/console_windows.go Resolved
Comment thread cmd/syncthing/console_windows.go Outdated
return nil // No command line arguments, don't allocate console
}

// Check if --no-console flag is present

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.

if slices.Contains(os.Args[1:], "--no-console") {
return nil
}

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.

(Prefer if they actually used the arguments parser we have...)

@rasa

rasa commented Sep 2, 2025

Copy link
Copy Markdown
Member

One issue with this is if a user runs this GUI version from inside an SSH session, they won't see any output. The console window will appear on the desktop.

@calmh calmh 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.

This is the approach that we didn't get to work previously. If it does work, i.e. behaves reasonably in a normal terminal etc, that's cool. I don't see why you're reinventing command line parsing multiple times instead of using the parsed command line though?

@tomasz1986 tomasz1986 changed the title feat: Dynamic Console Allocation for Windows feat(build, syncthing): dynamic console allocation for Windows Sep 2, 2025
@Shablone

Shablone commented Sep 2, 2025

Copy link
Copy Markdown
Contributor Author

Thank you for the review :)
I will rework that changes accordingly.

I was reinventing the stuff because

  • It was late
  • I'm not familiar with Go
  • I didn't get familiar with the remaining codebase
    Sorry for that

I will also investigate the ssh session. Although it seems very niche to me, to ssh into a windows server.

@calmh

calmh commented Sep 2, 2025 •

Copy link
Copy Markdown
Member

I think the SSH bit is indeed extremely niche, but probably follows the same scenario as just running the command in an existing cmd? At least the latter should work, imho. (by which I mean "show output in that terminal")

@calmh

calmh commented Sep 2, 2025

Copy link
Copy Markdown
Member

This seems somewhat promising. I'll have comments on the actual code and stuff at some point, but just some behavioural notes;

  • When doubleclicking syncthing.exe from explorer, there is a console flash but it disappears. That's good, but even better if it were possible to avoid the flash? If not, no biggie, it's already at the same level as the old --no-console was while it worked.

  • This is possibly an extension for a future PR but, currently, if Syncthing is already running and is then doubleclicked again, visually nothing happens (except the flash as above). I think it would be nice and make sense if it resulted in the equivalent of synchthing.exe browser, i.e. start the UI. (Perhaps that's not on you and should just be the default behavior when launching Syncthing a second time under any platform and circumstance. Something to think about.)

@Shablone

Shablone commented Sep 2, 2025

Copy link
Copy Markdown
Contributor Author

I noticed that syncthing not only was starting in console mode, it also opened the browser at runtime via calling cmd.exe resulting in another flash if no console was present yet.
I included the fix here
I haven't checked, but I guess this was the reason for your mentioned scenario @calmh

@Shablone
Shablone force-pushed the main branch 2 times, most recently from 8357fc0 to 79e5eb0 Compare September 3, 2025 17:48
@Shablone
Shablone requested review from calmh and rasa September 3, 2025 19:34
@Shablone

Copy link
Copy Markdown
Contributor Author

Hey
I'm not sure if I just need to be patient, but is there anything missing for a merge?

@tomasz1986

Copy link
Copy Markdown
Member

I'm trying to test the PR right now, but for me, even when launched from Explorer, the console window just stays open.

This is under Windows 10 x64, and the default shell is set to Command Prompt.

@calmh calmh 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.

Some structural notes

Comment thread cmd/syncthing/console_windows.go Outdated
}

// User explicitly disabled console -> don't allocate console
if slices.Contains(os.Args[1:], "--no-console") {

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.

I see no reason to do this instead of using our command line parser? (If there is one it's fine, but requires explanation. If it's about having a console available for when --help gets called, I suspect there is a way around that using the binding callback on the --no-console option perhaps...)

Comment thread cmd/syncthing/console_windows.go Outdated
return nil
}

// SSH sessions -> don't allocate console

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.

Why not, what happens otherwise?

Comment thread cmd/syncthing/console_windows.go Outdated
// Try to attach to parent consol
if ret, _, err := procAttachConsole.Call(uintptr(ATTACH_PARENT_PROCESS)); ret != 0 {
return redirectStdHandles()
} else if err != syscall.Errno(0) {

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.

This should probably be !errors.Is(err, syscall.Errno(0)) and errors.As below instead of the direct case

Comment thread cmd/syncthing/console_windows.go Outdated
if ret, _, err := procAllocConsole.Call(); ret != 0 {
consoleAllocated = true
return redirectStdHandles()
} else if err != syscall.Errno(0) {

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.

(As above)

Comment thread cmd/syncthing/console_windows.go Outdated

// FreeConsole releases the console
func FreeConsole() {
if consoleAllocated {

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.

I'd rather see this as a return value from InitConsole, to avoid keeping the global around...

@Shablone
Shablone marked this pull request as draft September 16, 2025 16:22
@Shablone

Shablone commented Sep 28, 2025 •

Copy link
Copy Markdown
Contributor Author

Please keep in mind, that for testing there should be no newer version online, which does not have this feature implemented. Or auto-upgrade should be disabled.
Otherwise it will upgrade itself and run as console again

@syncthing syncthing deleted a comment from calmh Sep 29, 2025
Comment thread cmd/syncthing/openurl_windows.go Outdated
Comment on lines +21 to +23
// 2. cmd.exe /C start (fallback): Traditional approach that spawns a command
// shell. Less secure (potential command injection) but works on all Windows
// versions including very old ones.

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.

I'm pretty sure we don't run on those Windows versions...

@calmh calmh 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.

Thanks, sorry for taking some time on this, I do want to get it in. Can you sort out the various style/linter complaints please, and then I think this is ready given it passes some manual testing 🙏

Comment thread cmd/syncthing/main.go Outdated
Comment on lines +220 to +223
var consoleAttached = false
if err := osutil.AttachConsole(); err == nil {
consoleAttached = true
}

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.

Suggested change
var consoleAttached = false
if err := osutil.AttachConsole(); err == nil {
consoleAttached = true
}
consoleAttached := osutil.AttachConsole() == nil

if we don't care about the error, I guess

@Shablone

Copy link
Copy Markdown
Contributor Author

Thanks, sorry for taking some time on this, I do want to get it in. Can you sort out the various style/linter complaints please, and then I think this is ready given it passes some manual testing 🙏

Thank you. There is no hurry 🙂

@calmh

calmh commented Oct 23, 2025

Copy link
Copy Markdown
Member

Actual Windows users who want this, can we have some testing? 🙏

@calmh

calmh commented Apr 5, 2026

Copy link
Copy Markdown
Member

I want this merged, but I want people who run Windows and want this to actually test it.

@dotacow

dotacow commented Apr 5, 2026

Copy link
Copy Markdown

I want this merged, but I want people who run Windows and want this to actually test it.

One of the near extinct windows users here, I'll test and report back, will take me some time.

@dotacow dotacow left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Tested on Windows 10; LGTM.

built using go run build -no-upgrade.

CLI behavior is as expected.

double clicking on the primary executable functions as expected (no console).

double clicking on a shortcut:
double clicking with property modifications shows the console. (as explained in the other comment)
double clicking with the --no-console flag added to properties starts the GUI and no console, no console flash for me in any double-clicked case.

Comment thread cmd/syncthing/main.go
Comment on lines +339 to +344
// No command line arguments without parent (Main should have called AttachConsole already)
// means binary was probably double-clicked -> don't allocate console
if len(os.Args) <= 1 {
return false
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This method works for detecting launching directly from the primary .exe/search bar.
But for users who use shortcuts with target flags, there is more than one argument. I stumbled upon testing while trying to separate the PR's config version from my installation, I had to pass the -home flag. example of the use case:
C:\Users\dotacow\syncthing-test\bin\syncthing.exe --home="C:\Users\dotacow\syncthing-test\test_env" "--no-console"
it is quite a niche use case (modifying target properties through a shortcut), and anyone who wants to modify target flags, should be able to add --no-console as they wish, and IMO it is better to have this be the default behavior, but I have to point it out anyways.

@dotacow

dotacow commented May 22, 2026 •

Copy link
Copy Markdown

Issue (potentially blocking): when using the CLI, pressing Enter is required to get a clean prompt afterward.

example:

PS C:\Users\dotac\syncthing> .\bin\syncthing.exe --version
PS C:\Users\dotac\syncthing> syncthing v2.0.12-dev.40.g8a267223-pr10335 "Hafnium Hornet" (go1.26.2 windows-amd64) DESKTOP-6NU0CQ9\dotac@DESKTOP-6NU0CQ9 2025-10-27 14:57:37 UTC [modernc-sqlite, noupgrade]
# <--- (cursor blinks here, and needs manual flushing)

and when you try typing the next command:

PS C:\Users\dotac\syncthing> .\bin\syncthing.exe --version
PS C:\Users\dotac\syncthing> [this is me typing the next command]0.g8a267223-pr10335 "Hafnium Hornet" (go1.26.2 windows-amd64) DESKTOP-6NU0CQ9\dotac@DESKTOP-6NU0CQ9 2025-10-27 14:57:37 UTC [modernc-sqlite, noupgrade]

compare this to the current binary's output:

PS C:\Users\dotac\OneDrive\Desktop\syncthing-windows-amd64-v1.28.1> .\syncthing.exe --version
syncthing v2.1.0 "Hafnium Hornet" (go1.25.9 windows-amd64) builder@github.syncthing.net 2026-05-12 05:59:47 UTC
PS C:\Users\dotac\OneDrive\Desktop\syncthing-windows-amd64-v1.28.1> # <--- cursor appears here (i.e.e normal every day terminal behaviour)

Hello, sorry for not catching this earlier. it wasn't really apparent through the log output, I only caught it when I recently wanted to check if I was running the latest version and accidentally ran --version with this PR's binary.

if my concerns are unfounded please let me know, been a while since I kept up with this PR, but this could potentially break piping and other automated logging systems.

I'll investigate this further.

(@calmh @Shablone quiet ping)

@Shablone

Copy link
Copy Markdown
Contributor Author

Thank you for investigating!
This behavior seems familiar to me. I think I experienced it earlier in dev too. But I also thought I fixed that already :/
It really shouldn't do that. I'll take a look

@Shablone
Shablone marked this pull request as draft May 22, 2026 18:25
@Shablone

Copy link
Copy Markdown
Contributor Author

Ok, this is much more troublesome than I initially thought.

Flushing the output does not really help. There is actually a bigger culprit here.

Returning the user input is not the issue. In fact, it is returned to the user even before Syncthing outputs anything.

With console attachment, Syncthing starts and is able to communicate asynchronously. Meaning the console does not wait for Syncthing to terminate. It allows new user input while still receiving output from the attached Syncthing process. For example, when using the serve command, it can continue outputting text over time while the user is still able to interact with the parent console — not with Syncthing itself.

Unfortunately, on Windows there are only two options. The subsystem (CUI vs GUI) is baked into the PE header at compile time. Windows either:

  • CUI: allocates a console if not present, shell waits synchronously → console flashes on double-click
  • GUI: no console, shell returns immediately. Even if we attach to the console → async output issue

(For our case GUI would be without actual graphics)

See the Microsoft documentation on console allocation policy.

There are several forum posts about this and no real solution. There are some hacky workarounds that simulate the user prompt or kill the parent process, but I would not want to go down that path.

However, the link above also presents a suitable solution, although it is unfortunately only available on Windows 11 24H2+:
-> using a new windows manifest. It tells Windows exactly what we want: On CUI don't open a new console if there is no parent console.

I think this PR can be closed. Dynamic console allocation would solve the GUI issue, but it would make the CUI behavior unusable.

I would open another PR solely for the change in cmd/syncthing/openurl_windows.go, which is still valid for skipping cmd when opening the browser. However, that is actually unrelated to dynamic console allocation.

I could also open another PR for the manifest approach once I have looked into it further. That would also be unrelated to dynamic console allocation.

Still there is the possibility to ship two binaries: one CUI and one GUI.

There are also Syncthing installers, although I have not looked into them yet. They may want to check out
some process creation flags

  • CREATE_NO_WINDOW
  • DETACHED_PROCESS

(@calmh quiet ping)

@dotacow

dotacow commented May 25, 2026 •

Copy link
Copy Markdown

Firstly, thanks for your work on this, it is quite a niche feature but I am nonetheless grateful to you.

but yeah your reasoning checks out to me, seems like a race condition between syncthing and the shell over the console's output buffer, but we are limited by the available Windows APIs to solve it.

regarding the multiple binary approach, I actually was going to suggest that myself, though I am sure a design choice like that requires it's own careful consideration by the maintainers.

@calmh

calmh commented May 25, 2026

Copy link
Copy Markdown
Member

We've discussed the multiple binaries approach a few times. I even had a PR open for it for quite a while. It didn't attract a lot of positive vibes.

I could also open another PR for the manifest approach once I have looked into it further. That would also be unrelated to dynamic console allocation.

This ^ sounds good to me.

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

Labels

enhancement New features or improvements of some kind, as opposed to a problem (bug)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants