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
94 changes: 70 additions & 24 deletions desktop/src-tauri/src/docker_desktop_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,19 +254,34 @@ pub fn powershell_with_path(script: &str, variable: &str, path: &Path) -> std::p
command
}

/// The exit code that means the person said no to Windows' approval prompt: `ERROR_CANCELLED`, as
/// the WSL fix reads it (`windows::DECLINED`).
const ERROR_CANCELLED: i32 = 1223;

/// The all-users install: Windows' approval prompt, then Docker's installer as an administrator,
/// waited for, its exit code PowerShell's. The installer's path is `INSTALLER_PATH`.
pub fn elevated_install(installer: &Path, arguments: &[String]) -> std::process::Command {
let quoted: Vec<String> = arguments
.iter()
.map(|argument| format!("'{}'", argument.replace('\'', "''")))
.collect();
let script = format!(
let start = format!(
"$p = Start-Process -FilePath $env:{INSTALLER_PATH} -ArgumentList {} -Verb RunAs -Wait \
-PassThru; exit $p.ExitCode",
-PassThru",
quoted.join(",")
);
powershell_with_path(&script, INSTALLER_PATH, installer)
powershell_with_path(&elevated_script(&start), INSTALLER_PATH, installer)
}

/// `start`, which raises Windows' approval prompt and sets `$p`, exiting with `$p`'s exit code. A
/// no to the prompt exits `ERROR_CANCELLED`, found by its Win32 code in the error, never by its
/// words, which are in Windows' own language.
fn elevated_script(start: &str) -> String {
format!(
"$ErrorActionPreference = 'Stop'; try {{ {start}; exit $p.ExitCode }} catch {{ \
$e = $_.Exception; while ($e) {{ if ($e.NativeErrorCode -eq {ERROR_CANCELLED}) \
{{ exit {ERROR_CANCELLED} }}; $e = $e.InnerException }}; throw }}"
)
}

/// Whether the answer to `AUTHENTICODE_QUERY` is a valid signature by Docker Inc.
Expand Down Expand Up @@ -776,11 +791,12 @@ fn run_installer(mounted: &Mounted) -> Installed {
}
}

/// Whether `elevated_install` stopped because the person said no to Windows' approval prompt:
/// `Start-Process -Verb RunAs` then fails with "The operation was canceled by the user."
/// Whether `elevated_install` stopped because the person said no to Windows' approval prompt: it
/// then exits `ERROR_CANCELLED` (`elevated_script`). What PowerShell said is in Windows' own
/// language, so it is never read for this.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn closed_the_prompt(said: &str) -> bool {
said.contains("canceled by the user") || said.contains("cancelled by the user")
fn closed_the_prompt(code: Option<i32>) -> bool {
code == Some(ERROR_CANCELLED)
}

#[cfg(target_os = "windows")]
Expand All @@ -795,7 +811,7 @@ fn run_installer(installer: &Path, per_user: bool) -> Installed {
Ok(output) if output.status.success() => Installed::Done,
Ok(output) => {
let said = crate::quiet::said(&output.stderr);
if closed_the_prompt(&said) {
if closed_the_prompt(output.status.code()) {
return Installed::Declined;
}
Installed::Failed(Problem::with(
Expand Down Expand Up @@ -1719,22 +1735,52 @@ Internal requirements count=1 size=180
);
}

/// What Windows PowerShell prints when the person says no to the approval prompt that
/// `elevated_install` raises, and when Docker's installer fails behind it.
/// A no to Windows' approval prompt is told by `elevated_install`'s exit code, 1223
/// (`ERROR_CANCELLED`), as the WSL fix tells it. It was told by PowerShell's English words,
/// so on a German or Japanese Windows a no read as a failed installer, and Docker's own
/// installer was opened for the person to finish.
#[test]
fn a_no_to_windows_approval_prompt_is_told_from_a_failed_installer() {
const SAID_NO: &str = "Start-Process : This command cannot be run due to the error: The \
operation was canceled by the user.\r\nAt line:1 char:6\r\n+ $p = Start-Process \
-FilePath $env:OPENBOT_INSTALLER_PATH -ArgumentList 'install','--quiet' ...\r\n+ \
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n + \
CategoryInfo : InvalidOperation: (:) [Start-Process], \
InvalidOperationException\r\n + FullyQualifiedErrorId : \
InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand\r\n";
assert!(closed_the_prompt(SAID_NO));
assert!(!closed_the_prompt(""));
assert!(!closed_the_prompt(
"Start-Process : This command cannot be run due to the error: The system cannot find \
the file specified."
));
fn a_no_to_windows_approval_prompt_is_told_by_its_exit_code_in_any_language() {
assert!(closed_the_prompt(Some(ERROR_CANCELLED)));
// Any other exit is the installer failing, whatever the words say.
assert!(!closed_the_prompt(Some(1)));
assert!(!closed_the_prompt(Some(0)));
assert!(!closed_the_prompt(None));
// The script reads the Win32 code, never the words.
let script = elevated_script("$p = Start-Process x -Verb RunAs -Wait -PassThru");
assert!(script.contains("NativeErrorCode -eq 1223"), "{script}");
assert!(script.contains("exit 1223"), "{script}");
assert!(
script.contains("$ErrorActionPreference = 'Stop'"),
"{script}"
);
assert!(!script.contains("canceled"), "{script}");
}

/// The script `elevated_install` runs, in real Windows PowerShell, with `Start-Process` standing
/// in for by the error it throws when the person says no: a Win32 `ERROR_CANCELLED` inside the
/// `InvalidOperationException`, worded in German. It exits 1223. Any other error exits 1.
#[test]
#[cfg(windows)]
fn the_elevated_install_script_exits_1223_on_a_no_in_any_language() {
let run = |native: i32| {
let start = format!(
"throw [System.InvalidOperationException]::new('Dieser Befehl kann aufgrund des \
folgenden Fehlers nicht ausgeführt werden.', \
[System.ComponentModel.Win32Exception]::new({native}))"
);
let output = powershell_with_path(
&elevated_script(&start),
INSTALLER_PATH,
Path::new(r"C:\nowhere\Docker Desktop Installer.exe"),
)
.output()
.unwrap();
output.status.code()
};
assert_eq!(run(ERROR_CANCELLED), Some(ERROR_CANCELLED));
let other = run(2);
assert_ne!(other, Some(ERROR_CANCELLED));
assert_ne!(other, Some(0));
}
}
12 changes: 11 additions & 1 deletion desktop/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13144,9 +13144,19 @@ fn watch_connections<R: tauri::Runtime>(
}
poll_failed = true;
let since = *unanswered_since.get_or_insert_with(std::time::Instant::now);
if setup_shown || since.elapsed() < SERVER_GONE_AFTER {
if setup_shown {
continue;
}
if let Some(left) = SERVER_GONE_AFTER.checked_sub(since.elapsed()) {
// Asked again as the silence reaches `SERVER_GONE_AFTER`, not a backoff
// later: on Windows an ask to a port nobody listens on takes about 2 s to
// fail, and with the backoff on top the window went to setup only after
// about 19 s.
if !left.is_zero() {
next_ask_after = next_ask_after.min(left);
continue;
}
}
match show_setup_when_stopped(&app, &root, generation) {
Ok(Unanswered::Stopped) => setup_shown = true,
// Still up after all: ask again only after as long a silence again.
Expand Down
52 changes: 52 additions & 0 deletions desktop/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3050,6 +3050,58 @@ test("macOS's password prompt waits for Continue in the window, and a closed one
expectBehind(view, 1, PODMAN_PROMPTING);
});

// What the Docker Desktop update says after the person closed the system's prompt
// (`docker_desktop_update::declined_line`).
const DOCKER_UPDATE_DECLINED =
"OpenBot needs your approval to update Docker. Choose Try again when you're ready.";

/**
* On Windows the Docker Desktop update asks through Windows' approval prompt, not for a password.
* A closed one was headed "Your password is needed" and its row said "Waiting for your password.",
* which Windows never asked for. Both now say approval.
*/
test("a closed approval prompt on Windows asks for approval, not a password", async () => {
Object.defineProperty(navigator, "userAgent", {
configurable: true,
value:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
});
try {
setupRootConfiguration("/tmp/local-eval-docker-update-approval", async () =>
emptyConfiguration(),
);
const browser = deferred<{ signedIn: boolean }>();
withLocalCli({
prepare_installation: () => new Promise(() => {}),
local_eval_terms: () => ({ status: "engine-not-ready" }),
sign_in_to_copilotkit: () => browser.promise,
copilotkit_sign_in_page: () => null,
allow_podman_install: () => true,
});
const view = await renderApp();
await installLocal(view);
await view.findByText("Checking your OpenBot account…");
await emitProgress({
step: "engine",
ok: true,
running: true,
asks: true,
detail: DOCKER_UPDATE_DECLINED,
});
const card = await view.findByRole("region", {
name: "Your approval is needed",
});
expect(card.textContent).toContain(DOCKER_UPDATE_DECLINED);
expect(
view.queryByRole("region", { name: "Your password is needed" }),
).toBeNull();
expectBehind(view, 1, "Waiting for your approval.", { waiting: true });
expect(view.getByRole("button", { name: "Try again" })).toBeTruthy();
} finally {
delete (navigator as { userAgent?: string }).userAgent;
}
});

// What Install says on a Mac whose own Podman OpenBot can't use (`own_machine::PAUSE_OFFER`).
const PAUSE_OFFER =
"Your Podman is set up in a way OpenBot can't use. OpenBot will use its own, and pause yours while OpenBot is running. Yours starts again when you quit OpenBot.";
Expand Down
11 changes: 9 additions & 2 deletions desktop/src/PodmanGoAhead.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { invoke } from "@tauri-apps/api/core";
import { type RefObject, useEffect, useRef, useState } from "react";
import type { GoAhead } from "./SetupProgress";
import { type GoAhead, systemPromptAsks } from "./SetupProgress";

/** The heading over the explanation before macOS asks for the person's password. */
export const PASSWORD_NEXT = "Your Mac will ask for your password";

/** The heading over a password prompt the person closed. */
export const PASSWORD_AGAIN = "Your password is needed";

/** The heading over Windows' approval prompt the person closed. */
export const APPROVAL_AGAIN = "Your approval is needed";

/**
* Keep a card that waits on the person in view in a step that scrolls. Nothing goes on until they
* answer it. At the window's smallest size the button sat under the step's pinned foot
Expand Down Expand Up @@ -92,7 +95,11 @@ export function GoAheadButton({ label }: { label: "Continue" | "Try again" }) {
export function PodmanGoAhead({ goAhead }: { goAhead: GoAhead }) {
const offered = useRef<HTMLElement>(null);
useKeptInView(offered);
const heading = goAhead.beforePrompt ? PASSWORD_NEXT : PASSWORD_AGAIN;
const heading = goAhead.beforePrompt
? PASSWORD_NEXT
: systemPromptAsks() === "approval"
? APPROVAL_AGAIN
: PASSWORD_AGAIN;
return (
<section ref={offered} className="local-alert needs" aria-label={heading}>
<h2>{heading}</h2>
Expand Down
14 changes: 13 additions & 1 deletion desktop/src/SetupProgress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,16 @@ export function pauseOfferNow(steps: Progress[]): string | null {
return offering?.detail ?? null;
}

/**
* What the system's prompt asks the person for on this computer: Windows asks them to approve,
* macOS for their password.
*/
export function systemPromptAsks(
userAgent = navigator.userAgent,
): "password" | "approval" {
return /Windows/.test(userAgent) ? "approval" : "password";
}

/** Where OpenBot's own icon is, as this computer names it: macOS has a menu bar, Windows a tray. */
export function trayPlace(userAgent = navigator.userAgent): string {
return /Macintosh|Mac OS X/.test(userAgent)
Expand Down Expand Up @@ -759,7 +769,9 @@ export function installingBehind({
? "Waiting for you to pause your Podman."
: now?.beforePrompt
? "Waiting for you to choose Continue."
: "Waiting for your password.",
: systemPromptAsks() === "approval"
? "Waiting for your approval."
: "Waiting for your password.",
{
waiting,
startedAt: since ?? undefined,
Expand Down
17 changes: 14 additions & 3 deletions desktop/src/setupLayout.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4135,10 +4135,21 @@ describe.skipIf(!asked)(
await open(page, "?started#status");
await page.getByRole("region", { name: "App" }).waitFor();
await page.waitForTimeout(400);
// The main window's Start brings everything up; the window's own reading sees the parts.
// The main window's Start brings everything up, and the shell tells this window so
// (`status_changed`). The window reads every 30 s now, so it is the shell's word that
// brings the parts in, not a timer: waiting on the timer took the locator's whole 30 s
// and failed on a slow run.
await page.evaluate(() => {
(globalThis as unknown as { __fake: { up: boolean } }).__fake.up =
true;
const fake = (
globalThis as unknown as {
__fake: {
up: boolean;
emit: (name: string, payload: unknown) => void;
};
}
).__fake;
fake.up = true;
fake.emit("status:refresh", null);
});
await page
.locator('section[aria-label="App"] .status-state', {
Expand Down
Loading