Files
tty7/.github/scripts/windows-installer.iss
T
b2d73ec68b feat(update): update an all-users Windows install through one UAC prompt (#562)
* fix(update): surface a failed install instead of silently re-prompting (#540)

The GUI quits as soon as tty7-updater is spawned, so an install that
failed inside the helper left a trace only in update.log — and because
launching the helper had already cleared the prompt state, the next
check offered the same version again, and again. The failure mode the
user saw was an app that nagged about an update it could not install.

The helper now writes update-outcome.json beside update.json on every
terminal path it can still reach, and the next GUI launch folds it into
the update state: a failure shows in Settings with the installer's own
reason until dismissed and stops the version from re-prompting on its
own; a success at the running version retires a failure an earlier
attempt recorded. A leftover result that exists but cannot be parsed is
reported rather than dropped — something ran, and "unreadable" is a
result too.

The same change moves the config directory off the environment and onto
the command line (--config-dir). An elevated child process does not
inherit the spawner's environment, so TTY7_CONFIG_DIR would have fallen
back to the administrator's config directory exactly in the
over-the-shoulder case — the groundwork this lays for #504. The updater
re-exports the variable for the helper children it spawns itself, so
the relaunched app keeps answering for the same config directory.

* feat(update): update an all-users Windows install through one UAC prompt (#504)

An Inno install under C:\Program Files could not be replaced in place:
the updater ran the release Setup as the signed-in user, which either
installed a second, per-user copy beside the real one or let Inno
re-launch itself elevated — a bare UAC prompt for an unsigned
executable in %TEMP%, seconds after the GUI had vanished. So the
layout was refused outright and told to download by hand.

It now updates itself, with the split the design in #504 settled on:
one UAC prompt covering two privileged stages, and one watcher that
is never elevated at all.

- The GUI probes the *installed* updater for the new verbs by running
  it ("capabilities"), so a side-loaded or downgraded binary answers
  for itself instead of being trusted by version number. An updater
  that predates the verbs exits with a usage error, and the install
  falls back to pointing at the release page exactly as before — the
  first release carrying this still updates the old way, and the one
  after it updates itself.
- The prompt dialog says the UAC prompt is coming before the app
  quits, and stops offering "Install on Next Launch": nobody is there
  to answer a prompt before the first window exists. The same guard
  keeps a staged plan from being armed for the next launch, and
  apply_pending_at_launch leaves an elevation-needing plan staged
  rather than raising a windowless prompt at boot.
- "Install now" spawns the watcher first (medium integrity, the
  signed-in user's token, so the relaunched app is never elevated),
  then ShellExecuteEx "runas" on the installed updater — the trust
  root a medium-integrity process cannot rewrite. Everything the
  elevated half needs crosses as command-line arguments, because an
  over-the-shoulder child inherits neither the environment nor the
  user's profile. The package's expected SHA-256 crosses the same
  way, from the checksums the GUI already holds in memory, so a
  payload and its checksums file cannot be rewritten together behind
  the IL boundary.
- The privileged first stage re-verifies the payload against that
  digest, pins its helper byte-for-byte to the installed updater,
  stages both in a fresh administrator-only %ProgramData% directory
  (an explicit SDDL DACL, swept of stale directories first), and only
  then runs the install stage — which runs Setup silently, writes the
  outcome file, and never touches the app binary itself. The watcher
  follows the chain through the status file and pid liveness
  (ERROR_ACCESS_DENIED from OpenProcess still means "alive" across
  accounts), then relaunches the app de-elevated and probes that it
  actually came up.
- Declining the UAC prompt is not an error: the watcher is reaped,
  nothing ran elevated, and the staged package simply waits in
  Settings.

Persisted plans from before this protocol serde-default a plan
version that is_usable rejects, so a stale plan is discarded instead
of failing against a helper that would not understand its arguments.
The installer script's explorer-menu registration gains skipifsilent:
a silent run *is* this update path, and launching the app there would
write the menu into the administrator's hive under over-the-shoulder
elevation.

One note on the test suite: ui::remote_connect's
a_routed_auth_prompt_carries_the_machine_that_raised_it fails under
parallel test execution on this machine both with and without this
change — a pre-existing flake, unrelated.

* fix(update): run the UAC request off the UI thread

Real-machine verification of the elevated chain caught this on the
first click: ShellExecuteExW pumps the calling thread's message loop
while the shell raises the consent prompt (its change notifications
re-enter the window), and from the UI thread that re-enters gpui with
its App already borrowed — the process aborts on a RefCell
double-borrow before anything ever elevates. The launch — watcher
spawn included, so the pairing stays atomic — now runs on the
background executor, and only the bookkeeping (quit / decline /
failure) comes back to the UI thread.

* fix(update): throttle a failed version instead of retiring it (#540)

Per the review on #540: a failed install must not keep the version
retired via last_prompted — record last_prompted plus a fresh
remind_after deadline (the same three days "Later" uses), so the
version asks again once the reminder expires. should_prompt already
treats "last_prompted matches, reminder expired" as prompt-again, so
no logic change is needed there, and the pinned
a_failure_lets_the_version_prompt_again test still holds.

Also write update-outcome.json *before* relaunching the previous app
on the macOS/Windows/portable non-elevated paths: the GUI that comes
up next is exactly the process that absorbs the outcome, and it used
to be relaunched before the failure existed on disk. The elevated
chain is unchanged — its watcher already waited for the file.

* fix(update): let only the elevated updater's own image name the trust root

Three holes on the privileged side of the #504 chain, all of the same
shape: a value that decides what runs elevated was taken from the
medium-integrity caller.

- `elevated-stage` pinned the staged helper against
  `<install-dir>\tty7-updater.exe`, where `<install-dir>` is a
  command-line argument. Both halves of that comparison were the
  caller's to choose: name a directory holding two copies of any
  binary and the pin passes, then stage 2 runs it elevated. The stage
  now derives the installation from its own image — UAC pointed the
  prompt at `{app}\tty7-updater.exe`, so `current_exe` is the one path
  nothing below the boundary could have written — and passes that on
  to stage 2. A caller that named a different directory only gets a
  line in the log.

- The staging directory's DACL let no standard user in, but its parent
  did: `%ProgramData%` grants Users the right to create directories,
  and the creator owns what it creates. A pre-created
  `%ProgramData%\tty7` gave its owner delete-child over the
  administrator-only staging inside it — enough to rename the verified
  staging aside and drop an identical name of their own into the gap
  between the digest check and the execute. The root is now created
  with the same protected descriptor, taking down whatever holds the
  name first; `CreateDirectoryW` applies a descriptor only when it is
  the one creating the directory, so succeeding is the proof. The
  per-run sweep goes with it — the root's removal takes the leftovers.

- The GUI aimed the prompt at the updater the *plan* named, and
  `update.json` sits in the user's config directory. It now aims at
  the installation this process runs from, so the binary the prompt
  names is the binary that starts.

Also quote the elevated command line the way `CommandLineToArgvW`
reads it back: a backslash escapes only in front of a quote, so a
config directory ending in one used to escape its own closing quote
and swallow every argument after it, `--result-file` — the file the
watcher waits on — included.

* test(update): pin the elevated stage's trust root to its own image

A regression test for the shape of the hole rather than the hole: if
`installed_root` ever goes back to reading an argument, the pin the
elevated stage runs before executing the staged helper stops meaning
anything, and nothing else in the suite would notice.

* fix(update): bring tty7 back when the elevated chain never reports

The watcher's two timeouts returned without relaunching. Every other
way out of the chain ends with the app back on screen, but a stage 1
that died before writing its status or its outcome — killed, crashed,
an AppInfo service that never delivered it — left the user with the
GUI already quit, nothing to replace it, and nothing said. Same for an
install still running an hour later.

Both paths now end the way the others do: an outcome the watcher wrote
itself, then the relaunch. The synthesized outcome is written whether
or not the relaunch succeeds, which also closes the same gap on the
pre-existing "the elevated updater exited without recording a result"
path — the next launch can name what happened instead of silently
offering the version again.

What kept those paths from relaunching was the risk of a second window
beside a GUI that is still up: a declined prompt leaves this process
running, and the kill that reaps its watcher can lose. The watcher now
takes the GUI's pid and opens a handle to it at startup — while the
GUI is provably alive, since it is sitting in ShellExecuteExW waiting
on the prompt — so the number cannot be recycled out from under it.
Before relaunching, a GUI that is still alive is waited out for 30
seconds: one that is quitting (a chain that failed fast can beat it
out the door) is gone well inside that and gets its relaunch, one that
is staying is recognized as staying and gets neither a relaunch nor a
failure record it did not earn. A live process always answers to its
own pid, so the check cannot be wrong in the direction that
double-launches.

Also give the Japanese elevation notice its closing 。

* fix(update): poll the parent out across the elevation account boundary

Under an over-the-shoulder elevation the install stage runs as the
administrator, and OpenProcess on the signed-in user's GUI answers
ERROR_ACCESS_DENIED - the same boundary pid_alive already documents from
the watcher's side. wait_for_exit treated that as a fatal error, so the
chain recovered and reported a failure before Setup ever ran. The wait
now degrades to polling the pid until it stops answering, bounded so a
recycled pid cannot hold the install hostage forever.

---------

Co-authored-by: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com>
Co-authored-by: l0ng-ai <l0ng-ai@users.noreply.github.com>
2026-08-13 18:13:20 +08:00

260 lines
14 KiB
Plaintext

; tty7 Windows installer (Inno Setup 6 — preinstalled on GitHub's
; windows-latest runners). Compiled by bundle-windows.ps1, which stages the
; payload and passes every path in via /D defines:
;
; /DAppVersion=<semver> display version parsed from Cargo.toml
; /DVersionInfoVersion=<numeric version> PE-compatible file version
; /DStageDir=<abs path> staged payload (app, CLI, updater, marker, resources)
; /DOutputDir=<abs path> where the setup exe is written
; /DOutputName=<basename> setup exe filename, without ".exe"
;
; Defaults to a per-user install ({localappdata}\Programs\tty7 — no UAC
; prompt), with an "install for all users" escape hatch in the dialog. The
; build is unsigned, so SmartScreen warns on first launch either way — same as
; the portable zip.
#ifndef AppVersion
#error Missing /DAppVersion — this script is meant to be compiled via bundle-windows.ps1
#endif
#ifndef VersionInfoVersion
#error Missing /DVersionInfoVersion — this script is meant to be compiled via bundle-windows.ps1
#endif
[Setup]
; Never change AppId: it is how Windows ties upgrades + the uninstall entry
; to previous installs of tty7.
AppId={{9A3F6C1E-4B7D-4E2A-8C5F-D01B92E64A37}
AppName=tty7
AppVersion={#AppVersion}
VersionInfoVersion={#VersionInfoVersion}
AppPublisher=tty7 contributors
AppPublisherURL=https://github.com/l0ng-ai/tty7
AppSupportURL=https://github.com/l0ng-ai/tty7/issues
AppUpdatesURL=https://github.com/l0ng-ai/tty7/releases
DefaultDirName={autopf}\tty7
DisableProgramGroupPage=yes
PrivilegesRequired=lowest
PrivilegesRequiredOverridesAllowed=dialog
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
MinVersion=10.0
LicenseFile={#StageDir}\LICENSE.txt
SetupIconFile=..\..\assets\favicon.ico
UninstallDisplayIcon={app}\tty7-app.exe
OutputDir={#OutputDir}
OutputBaseFilename={#OutputName}
Compression=lzma2
SolidCompression=yes
WizardStyle=modern
; The persistent daemon (tty7-app.exe --daemon) is a detached background process
; that outlives the GUI and holds the running image of tty7-app.exe, so Windows
; locks the file and an upgrade can't replace it. We stop it explicitly in
; PrepareToInstall below; keep the Restart Manager as a backstop but don't let
; it relaunch anything (the GUI respawns the daemon itself on next start).
CloseApplications=yes
RestartApplications=no
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
; Writing shell verbs is an install-time decision, the way VS Code and Git for
; Windows treat theirs — not a runtime preference, so tty7 has no setting for
; it. Off by default: the registry is user-visible system state. The keys land
; under HKCU even for an all-users install, so this only ever affects whoever
; ran the installer. Inno restores the previous choice when upgrading.
Name: "explorermenu"; Description: "Add ""Open in tty7"" to the folder context menu"; GroupDescription: "Shell integration:"; Flags: unchecked
; Builds before the tty7/tty7-app split installed the GUI as tty7.exe. Upgrading
; only *adds* tty7-app.exe, so the old binary would stay on disk — and a taskbar
; pin (which Inno cannot rewrite, unlike the [Icons] shortcuts) still points at
; it. The user would keep launching the previous version from their pinned icon,
; against the same daemon endpoint as the new one. Delete it on upgrade; a fresh
; install simply has nothing to remove.
;
; That name is now reused by the CLI below, which lands at the very same path.
; The order saves us: [InstallDelete] runs before [Files], so the stale GUI is
; gone before the CLI is written, and what survives is never a mix of the two.
; The taskbar pin is the loose end — post-upgrade it points at a CLI, so
; clicking it flashes a console instead of opening a window. That is louder
; than the bug it replaces (silently running last release's GUI), and the pin
; is not ours to rewrite; the Start Menu entry in [Icons] is correct either way.
[InstallDelete]
Type: files; Name: "{app}\tty7.exe"
[Files]
Source: "{#StageDir}\tty7-app.exe"; DestDir: "{app}"; Flags: ignoreversion
; The CLI. `core::cli_install` adds {app} to the user's PATH at first launch,
; so this is not registered as an [Env] change here — the portable zip has no
; installer to do it, and one code path serving both is one behaviour to debug.
; The uninstaller takes that entry back out; see RemoveAppDirFromUserPath below.
Source: "{#StageDir}\tty7.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#StageDir}\tty7-updater.exe"; DestDir: "{app}"; Flags: ignoreversion skipifsourcedoesntexist
; This installer-only marker is the authority for enabling automatic Windows
; updates. The portable archive is created before the marker enters the stage.
Source: "{#StageDir}\.tty7-inno-install"; DestDir: "{app}"; Flags: ignoreversion skipifsourcedoesntexist
Source: "{#StageDir}\completions\*"; DestDir: "{app}\completions"; Flags: ignoreversion recursesubdirs
; Microsoft's redistributable ConPTY. It has to land in {app} rather than a
; subdirectory: `portable-pty` finds it through the DLL search path, which
; starts at the directory of the executable that loads it (the daemon is
; {app}\tty7-app.exe). The two files are a matched pair — never update one
; alone. See assets\windows\conpty\README.md.
Source: "{#StageDir}\conpty.dll"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#StageDir}\OpenConsole.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#StageDir}\LICENSE-ConPTY.txt"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#StageDir}\LICENSE.txt"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#StageDir}\README.md"; DestDir: "{app}"; Flags: ignoreversion
; The Linux musl tty7-server, for serving WSL distros without a download.
; `skipifsourcedoesntexist` because a build whose server-musl leg was skipped
; still has to produce an installer. See bundle-windows.ps1.
Source: "{#StageDir}\server\*"; DestDir: "{app}\server"; Flags: ignoreversion recursesubdirs skipifsourcedoesntexist
; AppUserModelID is what lets toast notifications carry the tty7 name and icon
; instead of the notify-rust PowerShell fallback: Windows only honors an
; unpackaged app's toast identity when a shortcut stamps it. Must match
; `core::aumid::AUMID` (src/core/aumid.rs), which at startup stamps the
; per-user shortcut below if some older installer left it unstamped, and
; writes one from scratch for the portable zip. It deliberately leaves an
; all-users install alone — it cannot write {commonprograms} unelevated, and a
; per-user twin would both duplicate the Start Menu entry and outlive this
; uninstaller — so an elevated install depends on the stamp right here.
[Icons]
Name: "{autoprograms}\tty7"; Filename: "{app}\tty7-app.exe"; AppUserModelID: "com.github.tty7"
Name: "{autodesktop}\tty7"; Filename: "{app}\tty7-app.exe"; Tasks: desktopicon; AppUserModelID: "com.github.tty7"
[Run]
; The registry shape lives in core::explorer_context_menu, not here: the app
; reads those same keys to decide whether an existing registration still points
; at this install, and two hand-kept copies of the layout would drift. Runs
; before the launch entry below so a first start already sees the final state.
; skipifsilent because a silent run *is* the elevated in-place update (#504):
; launching the app there would run it elevated, and under over-the-shoulder
; elevation the menu would land in the administrator's hive, not the user's.
; Skipping loses nothing: an upgrade keeps the install path, so the HKCU keys
; a ticked first install wrote still point at the right executable.
Filename: "{app}\tty7-app.exe"; Parameters: "--register-explorer-menu"; Tasks: explorermenu; Flags: runhidden waituntilterminated skipifsilent
Filename: "{app}\tty7-app.exe"; Description: "{cm:LaunchProgram,tty7}"; Flags: nowait postinstall skipifsilent
[UninstallRun]
; Stop the daemon before the uninstaller deletes tty7-app.exe — the running daemon
; is the locked image of that file, so removing it fails otherwise. Naming {app}
; widens the stop the same way PrepareToInstall's does: ConPTY hosts orphaned by
; a daemon that never got to shut down keep the installed images open, and their
; DeleteFile fails an uninstall exactly as it fails an upgrade. (The stop excludes
; the calling process itself, so the binary running this step is safe.) This runs
; at the start of uninstallation, before any files are removed. The installed
; binary is this version, which understands the flags; runhidden suppresses any
; flash and the call returns without opening a window. RunOnceId keys the entry
; so a repeated uninstall doesn't run it twice.
Filename: "{app}\tty7-app.exe"; Parameters: "--stop-daemon --update-install-dir ""{app}"""; Flags: runhidden waituntilterminated; RunOnceId: "StopDaemon"
; Unconditional, and deliberately not gated on the task: an install that had the
; menu registered and was later upgraded without the box ticked still holds the
; keys, and verbs pointing at a deleted exe are worse than a no-op. Removing keys
; that were never written succeeds silently.
Filename: "{app}\tty7-app.exe"; Parameters: "--unregister-explorer-menu"; Flags: runhidden waituntilterminated; RunOnceId: "UnregisterExplorerMenu"
[Code]
(* Gracefully stop the persistent daemon before we overwrite tty7-app.exe. We can't
run the *installed* binary here — on an upgrade from an older build it may not
understand --stop-daemon and would launch the GUI instead — so we extract the
*new* tty7-app.exe to {tmp} and run that. It connects to the running daemon, hangs
up every shell, waits for it to exit (releasing the file lock), then returns
without opening a window. Naming {app} widens the stop into "make this directory
replaceable": ConPTY hosts (OpenConsole.exe) orphaned by a daemon that never got
to shut down keep the installed images open — invisible to the daemon stop, fatal
to the DeleteFile below — so anything still running from {app} is terminated and
the call waits until the images there actually open for writing. Best effort: any
failure falls through to the Restart Manager backstop, and a fresh install simply
has nothing to stop. *)
function PrepareToInstall(var NeedsRestart: Boolean): String;
var
ResultCode: Integer;
begin
ExtractTemporaryFile('tty7-app.exe');
Exec(ExpandConstant('{tmp}\tty7-app.exe'),
'--stop-daemon --update-install-dir "' + ExpandConstant('{app}') + '"', '',
SW_HIDE, ewWaitUntilTerminated, ResultCode);
Result := '';
end;
(* Take {app} back out of the user's PATH.
`core::cli_install` puts it there at first launch rather than the installer
doing it, because the portable zip has no installer — but that leaves nobody
to undo it, and an uninstall that permanently grows the user's PATH by one
dead entry is not an uninstall. So the removal lives here, on the one install
shape that has an uninstaller at all. (Unix has no equivalent hook: deleting
the .app or the tarball leaves the symlink behind for the user to remove.)
HKCU even for an all-users install: cli_install only ever writes the user
hive, so that is the only place an entry can be. On a machine where several
users ran tty7, this clears the one uninstalling — the others keep a dead
entry, which is the price of not needing elevation to install in the first
place.
Entries are compared case-insensitively and ignoring a trailing backslash,
and every other entry is written back verbatim: this is somebody's PATH, and
we are here to remove one thing from it, not to tidy it. No
WM_SETTINGCHANGE broadcast — the entry now names a deleted directory, so
nothing is waiting on the news, and it is gone from new shells at next
sign-in regardless. *)
procedure RemoveAppDirFromUserPath();
var
Existing, Rebuilt, Raw, Entry, Target: String;
P: Integer;
begin
if not RegQueryStringValue(HKEY_CURRENT_USER, 'Environment', 'Path', Existing) then
exit;
Target := RemoveBackslashUnlessRoot(ExpandConstant('{app}'));
Rebuilt := '';
(* The trailing ';' makes the last entry look like every other one. *)
Existing := Existing + ';';
repeat
P := Pos(';', Existing);
Raw := Copy(Existing, 1, P - 1);
Existing := Copy(Existing, P + 1, Length(Existing));
Entry := Trim(Raw);
if (Entry <> '') and
(CompareText(RemoveBackslashUnlessRoot(Entry), Target) <> 0) then
begin
if Rebuilt <> '' then
Rebuilt := Rebuilt + ';';
Rebuilt := Rebuilt + Raw;
end;
until Existing = '';
if Rebuilt = '' then
RegDeleteValue(HKEY_CURRENT_USER, 'Environment', 'Path')
(* Inno cannot read a value's type back, so infer it: a PATH holding a '%' is
one that has to stay expandable, and rewriting it as REG_SZ would freeze
every other entry's variable at today's value. *)
else if Pos('%', Rebuilt) > 0 then
RegWriteExpandStringValue(HKEY_CURRENT_USER, 'Environment', 'Path', Rebuilt)
else
RegWriteStringValue(HKEY_CURRENT_USER, 'Environment', 'Path', Rebuilt);
end;
(* Remove the optional Explorer verbs if this user enabled them in Settings.
The application owns only the final `tty7` subkeys. Deleting those trees
removes their command children without touching another application's verb
or a shared `shell` parent. Missing keys are the normal default and make both
calls harmless no-ops. This cleanup is uninstall-only: upgrades keep the
user's explicit registration, and the next app launch reports "Needs update"
if an install path ever changes. *)
procedure RemoveExplorerContextMenu();
begin
RegDeleteKeyIncludingSubkeys(
HKEY_CURRENT_USER, 'Software\Classes\Directory\shell\tty7');
RegDeleteKeyIncludingSubkeys(
HKEY_CURRENT_USER, 'Software\Classes\Directory\Background\shell\tty7');
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
if CurUninstallStep = usUninstall then
begin
RemoveAppDirFromUserPath();
RemoveExplorerContextMenu();
end;
end;