Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ This repo builds the Grill CLI and project setup tooling. The generated map-proj

## Test Commands

Use `HotReloadTests` for Grill's hot-run and reload transaction. For automated Warcraft III engine tests, use the `wc3-e2e-harness` sibling and follow its `docs/AgentQuickstart.md` for launch, loading-screen input and cleanup.
Use `HotReloadTests` for Grill's hot-run and reload transaction.

Run the full WurstSetup suite before publishing:

Expand Down
300 changes: 223 additions & 77 deletions src/main/kotlin/file/BattleNetSignIn.kt

Large diffs are not rendered by default.

112 changes: 112 additions & 0 deletions src/main/kotlin/file/OutsideStart.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package file

import global.Log
import java.io.IOException
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit

/**
* Starts processes on Windows in the user's own registry view.
*
* A child process sees the registry its parent sees. Under a packaged (MSIX) app, such as the Claude desktop app or a
* VS Code started from a terminal inside it, that is the package's private copy of `HKCU`: what such a process writes
* there no other process reads, and once it has written a value it no longer reads the user's. Battle.net, the sign-in
* renewal and the game pass the sign-in between them through `HKCU` ([BattleNetSignIn]), so each of them started from
* inside such an app would keep it where the rest of the machine never sees it. A process created through WMI
* (`Win32_Process.Create`) starts in the user's own context instead, in the same session and on the same desktop.
*/
internal object OutsideStart {
/** The `SW_` value WMI passes to the new process's first window. */
enum class Show(val value: Int) { HIDDEN(0), NORMAL(1), MINIMIZED(7) }

private const val WMI_TIMEOUT_SECONDS = 30L
private val CREATED = Regex("""^created (\d+) (\d+)\s*$""", RegexOption.MULTILINE)

// The command line, window and directory travel in the environment, so nothing in them needs PowerShell quoting.
private val CREATE_SCRIPT = listOf(
"\$ErrorActionPreference = 'Stop'",
"\$ProgressPreference = 'SilentlyContinue'",
"[Console]::OutputEncoding = [Text.Encoding]::UTF8",
"\$startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]\$env:GRILL_OUTSIDE_SHOW }",
"\$arguments = @{ CommandLine = \$env:GRILL_OUTSIDE_COMMAND; ProcessStartupInformation = \$startup }",
"if (\$env:GRILL_OUTSIDE_CWD) { \$arguments.CurrentDirectory = \$env:GRILL_OUTSIDE_CWD }",
"\$created = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments \$arguments",
"'created {0} {1}' -f \$created.ReturnValue, \$created.ProcessId",
).joinToString("; ")

/** One argument quoted for a Windows command line, as CommandLineToArgvW and the C runtime split it. */
fun quoteWindowsArg(arg: String): String {
if (arg.isNotEmpty() && arg.none { it == '"' || it.isWhitespace() }) return arg
val quoted = StringBuilder("\"")
var backslashes = 0
for (c in arg) {
if (c == '\\') {
backslashes++
continue
}
quoted.append("\\".repeat(if (c == '"') backslashes * 2 + 1 else backslashes)).append(c)
backslashes = 0
}
return quoted.append("\\".repeat(backslashes * 2)).append('"').toString()
}

fun commandLine(command: List<String>): String = command.joinToString(" ") { quoteWindowsArg(it) }

/**
* Starts [command] through WMI, in the user's own registry view, and returns its pid. Throws when WMI cannot
* create it.
*
* @param directory the new process's working directory; null for WMI's default
*/
fun start(command: List<String>, directory: Path?, show: Show): Long {
val builder = ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", CREATE_SCRIPT)
.redirectErrorStream(true)
builder.environment()["GRILL_OUTSIDE_COMMAND"] = commandLine(command)
builder.environment()["GRILL_OUTSIDE_SHOW"] = show.value.toString()
builder.environment()["GRILL_OUTSIDE_CWD"] = directory?.toString() ?: ""
val process = builder.start()
val output = try {
process.outputStream.close()
// Read while it runs: an error record could fill the pipe and stall PowerShell until the timeout.
val read = CompletableFuture.supplyAsync {
try {
process.inputStream.use { String(it.readAllBytes(), Charsets.UTF_8) }
} catch (_: IOException) {
""
}
}
if (!process.waitFor(WMI_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
throw IOException("WMI did not answer within $WMI_TIMEOUT_SECONDS s")
}
read.get(5, TimeUnit.SECONDS)
} finally {
process.destroyForcibly()
}
val name = Path.of(command[0]).fileName.toString()
val created = CREATED.find(output)
?: throw IOException("WMI could not start $name: ${output.trim().lineSequence().firstOrNull() ?: "no answer"}")
if (created.groupValues[1] != "0") {
throw IOException("WMI could not start $name (Win32_Process.Create returned ${created.groupValues[1]})")
}
return created.groupValues[2].toLong()
}

/**
* [start] if WMI can, else a direct start from this process (whose registry view the process then shares).
* Returns the pid.
*/
fun startOrHere(command: List<String>, directory: Path?, show: Show): Long {
return try {
start(command, directory, show)
} catch (e: Exception) {
if (e is InterruptedException) throw e
Log.println("Starting ${Path.of(command[0]).fileName} from grill instead: ${e.message}")
val builder = ProcessBuilder(command)
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD)
if (directory != null) builder.directory(directory.toFile())
builder.start().pid()
}
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/file/SetupApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ object SetupApp {
get() = "Tests: $passed/$total passed"
}

internal const val AGENTS_TEMPLATE_VERSION = "2026-11-06"
internal const val AGENTS_TEMPLATE_VERSION = "2026-11-17"
private const val AGENTS_TEMPLATE_MARKER_PREFIX = "<!-- WURST_AGENTS_TEMPLATE_VERSION:"
private const val AGENTS_TEMPLATE_MARKER = "<!-- WURST_AGENTS_TEMPLATE_VERSION: $AGENTS_TEMPLATE_VERSION -->"
private const val AGENTS_TEMPLATE_SOURCE_HINT = "WurstScript Warcraft III map project notes"
Expand Down
15 changes: 10 additions & 5 deletions src/main/kotlin/file/Wc3MapRunner.kt
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,16 @@ internal object Wc3MapRunner {
val command = launchCommand(client, launchMap)
val renewal = renewSignIn(client, command, launchMode, report)
try {
ProcessBuilder(command)
.directory(client.root.toFile())
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start()
if (System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) {
// In the user's own registry view, where the sign-in is renewed, whatever view grill has.
OutsideStart.startOrHere(command, client.root, OutsideStart.Show.NORMAL)
} else {
ProcessBuilder(command)
.directory(client.root.toFile())
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start()
}
} catch (e: Exception) {
renewal?.close()
throw e
Expand Down
28 changes: 28 additions & 0 deletions src/main/resources/battlenet-signin.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Waits, in the registry view it runs in, until the launched client replaces EDITOR_TOKEN, which it does as it signs in.
#
# Prints "ready" once it has read the token the renewal stored, then "signed-in" when that token changes, or "timeout".
# Never prints a token.
param(
[int]$TimeoutSeconds = 120,
[string]$Key = "HKCU:\Software\Blizzard Entertainment\Warcraft III"
)
$ErrorActionPreference = "Stop"

function Read-EditorToken {
$value = (Get-ItemProperty -Path $Key -Name EDITOR_TOKEN -ErrorAction SilentlyContinue).EDITOR_TOKEN
if ($value -is [byte[]]) { return [BitConverter]::ToString($value) }
return ""
}

$before = Read-EditorToken
"ready"
$watch = [Diagnostics.Stopwatch]::StartNew()
while ($watch.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
if ((Read-EditorToken) -ne $before) {
"signed-in"
exit 0
}
Start-Sleep -Milliseconds 250
}
"timeout"
exit 1
90 changes: 90 additions & 0 deletions src/main/resources/battlenet-token.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Renews the session that -editor launches sign in with, from the Battle.net desktop app.
#
# The app signs Warcraft III in with a one-time WEB_TOKEN it writes just before it starts the game. A client given
# -editor signs in with EDITOR_TOKEN instead, which only the client itself renews (on each sign-in), so once it has
# lapsed every -editor launch stops at the login panel. This asks the app to start the game, closes that game the
# moment it appears - before it can spend the token - and stores the token as EDITOR_TOKEN.
#
# Prints one line per step and ends with "result <outcome>"; never prints a token.
param(
[Parameter(Mandatory = $true)][string]$BattleNetExe,
[int]$TimeoutSeconds = 90,
[int]$AskAgainSeconds = 25
)
$ErrorActionPreference = "Stop"
$launchKey = "HKCU:\Software\Blizzard Entertainment\Battle.net\Launch Options\W3"
$gameKey = "HKCU:\Software\Blizzard Entertainment\Warcraft III"

function Read-WebToken {
$value = (Get-ItemProperty -Path $launchKey -Name WEB_TOKEN -ErrorAction SilentlyContinue).WEB_TOKEN
if ($value -is [byte[]]) { return $value }
return $null
}

function Test-AppGame([int]$id) {
# A client the app started: its parent is a Battle.net.exe process. Anything else is someone else's client.
$process = Get-CimInstance Win32_Process -Filter "ProcessId=$id" -ErrorAction SilentlyContinue
if (-not $process) { return $false }
$parent = Get-Process -Id $process.ParentProcessId -ErrorAction SilentlyContinue
return [bool]($parent -and $parent.ProcessName -eq "Battle.net")
}

function Get-GamePids {
@(Get-Process -Name "Warcraft III" -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
}

$before = Read-WebToken
$beforeHex = if ($before) { [BitConverter]::ToString($before) } else { "" }
$existing = Get-GamePids
# The app does not start a second client while its own is running, so it would never write a token.
if (@($existing | Where-Object { Test-AppGame $_ }).Count -gt 0) {
"result app-game-running"
exit 3
}

$watch = [Diagnostics.Stopwatch]::StartNew()
$askedAt = -1e9
$token = $null
$tokenAt = 0
$closed = 0
while ($watch.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
if (-not $token -and $watch.Elapsed.TotalSeconds - $askedAt -ge $AskAgainSeconds) {
$askedAt = $watch.Elapsed.TotalSeconds
Start-Process -FilePath $BattleNetExe -ArgumentList '--exec="launch W3"'
"asked {0:N1}" -f $askedAt
}
foreach ($id in Get-GamePids) {
if ($existing -contains $id) { continue }
$existing += $id
if (Test-AppGame $id) {
Stop-Process -Id $id -Force -ErrorAction SilentlyContinue
$closed++
"closed {0} {1:N1}" -f $id, $watch.Elapsed.TotalSeconds
}
}
if (-not $token) {
$now = Read-WebToken
if ($now -and [BitConverter]::ToString($now) -ne $beforeHex) {
$token = $now
$tokenAt = $watch.Elapsed.TotalSeconds
"token {0:N1}" -f $tokenAt
}
}
# The app writes the token, then starts the game: wait briefly for that game so it is closed, not left running.
if ($token -and ($closed -gt 0 -or $watch.Elapsed.TotalSeconds - $tokenAt -ge 10)) { break }
Start-Sleep -Milliseconds 50
}
if (-not $token -and $closed -gt 0) {
# The app started the game, so it wrote a token, but not where this script reads: the app keeps a private copy of
# the registry, as one started from a packaged (MSIX) app does.
"result token-not-visible"
exit 4
}
if (-not $token) {
"result no-token"
exit 2
}
if (-not (Test-Path $gameKey)) { New-Item -Path $gameKey -Force | Out-Null }
Set-ItemProperty -Path $gameKey -Name EDITOR_TOKEN -Value ([byte[]]$token) -Type Binary
"result refreshed"
exit 0
Loading
Loading