diff --git a/README.md b/README.md index 7bbf41d93..b7db91c68 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,16 @@ npm run typecheck npm run build ``` +### Browser smoke on macOS + +After building, run `npm run smoke:browser` for the standard browser smoke. To keep the smoke window off your working display, connect a virtual display in extended mode and pass its exact name: + +```sh +CANVASTTY_TEST_DISPLAY="Virtual 16:9" npm run smoke:browser +``` + +Keep your working display set as the primary display. The virtual display needs a usable work area of at least 1440 × 900. The smoke opens its window without taking focus. If the name is missing from the display list, matches multiple displays, or identifies the primary display, the smoke exits before showing a window. + ## Contributor acknowledgements Thanks to [@kootik](https://github.com/kootik) for [PR #51](https://github.com/howdeploy/CanvasTTY/pull/51): integrating the open pull requests, resolving conflicts, addressing review findings, and improving agent orchestration. The original commits are preserved in the repository history; `.mailmap` associates their `s079891` author identity with kootik. diff --git a/scripts/smoke-browser-electron.mjs b/scripts/smoke-browser-electron.mjs index 38dd7c5ac..2d8bf8634 100644 --- a/scripts/smoke-browser-electron.mjs +++ b/scripts/smoke-browser-electron.mjs @@ -8,6 +8,8 @@ import electronPath from "electron"; const PROJECT_ROOT = resolve(fileURLToPath(new URL("..", import.meta.url))); const READY_MARKER = "CANVASTTY_BROWSER_SMOKE_READY"; +const FOCUS_MARKER = "CANVASTTY_BROWSER_SMOKE_FOCUS "; +const OUTPUT_CLOSE_TIMEOUT_MS = 2_000; const TIMEOUT_MS = 60_000; const MAX_OUTPUT_BYTES = 128 * 1024; @@ -19,6 +21,7 @@ const smokeTempRoot = process.platform === "win32" ? tmpdir() : "/tmp"; const userDataPath = await mkdtemp(join(smokeTempRoot, "ctb-")); let child; let output = ""; +let focusViolation = false; try { const electronArgs = [PROJECT_ROOT, `--user-data-dir=${userDataPath}`, "--disable-gpu"]; @@ -33,6 +36,7 @@ try { }, stdio: ["ignore", "pipe", "pipe"] }); + const outputClosed = new Promise(resolveClosed => child.once("close", resolveClosed)); await new Promise((resolveReady, reject) => { let settled = false; const timer = setTimeout(() => { @@ -58,8 +62,15 @@ try { resolveReady(); } }; - child.stdout.on("data", consume); - child.stderr.on("data", consume); + for (const stream of [child.stdout, child.stderr]) { + let tail = ""; + stream.on("data", (chunk) => { + const text = tail + chunk.toString("utf8"); + focusViolation ||= text.includes(FOCUS_MARKER); + tail = text.slice(1 - FOCUS_MARKER.length); + consume(chunk); + }); + } child.once("error", (error) => { fail(error); }); @@ -72,6 +83,27 @@ try { if (exit.code !== 0 || exit.signal !== null) { throw new Error(`Browser smoke exited unsuccessfully (code=${exit.code}, signal=${exit.signal}). Output:\n${output}`); } + if (process.env.CANVASTTY_TEST_DISPLAY) { + // Output can arrive after exit, including a focus marker just before shutdown. + let timer; + try { + await Promise.race([ + outputClosed, + new Promise((_, reject) => { + timer = setTimeout(() => { + child.stdout.destroy(); + child.stderr.destroy(); + reject(new Error(`Electron output did not close within ${OUTPUT_CLOSE_TIMEOUT_MS} ms.`)); + }, OUTPUT_CLOSE_TIMEOUT_MS); + }) + ]); + } finally { + clearTimeout(timer); + } + if (focusViolation) { + throw new Error(`Browser smoke activated the app or focused a window. Output:\n${output}`); + } + } process.stdout.write(output); } finally { if (child && child.exitCode === null && child.signalCode === null) { diff --git a/src/main/index.ts b/src/main/index.ts index 32869a595..056e5508b 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -6,7 +6,7 @@ import { randomUUID } from "node:crypto"; import { dirname, isAbsolute } from "node:path"; import { EvenG2Controller } from "./services/companion/EvenG2Controller"; import { join } from "node:path"; -import { app, BrowserWindow, dialog, Menu, net, Notification, protocol, safeStorage, session } from "electron"; +import { app, BrowserWindow, dialog, Menu, net, Notification, protocol, safeStorage, screen, session } from "electron"; import { IPC, type LocaleId, @@ -236,17 +236,40 @@ if (!hasSingleInstanceLock) app.quit(); * could begin, and replacing a page that is still loading races its ERR_ABORTED * into the next load's promise; with one navigation there is nothing to race.) */ +function browserSmokeDisplayName(): string | undefined { + return process.env.CANVASTTY_BROWSER_SMOKE_URL ? process.env.CANVASTTY_TEST_DISPLAY : undefined; +} + function createWindow(): BrowserWindow { if (process.platform === "darwin" && !app.isPackaged) app.dock?.setIcon(appIcon); markMainBoot("windowCreateStart"); + const displayName = browserSmokeDisplayName(); + const matchingDisplays = displayName ? screen.getAllDisplays().filter(display => display.label === displayName) : []; + const display = matchingDisplays[0]; + if (displayName && (matchingDisplays.length !== 1 || display.id === screen.getPrimaryDisplay().id)) { + throw new Error(`Expected one non-primary display named "${displayName}". Available displays: ${screen.getAllDisplays().map(item => item.label).join(", ")}.`); + } + const workArea = display?.workArea; + const width = 1440; + const height = 900; + // Keep the standard window size so the smoke's zoom fixture fits without clipping. + if (workArea && (workArea.width < width || workArea.height < height)) { + throw new Error(`Display "${displayName}" needs a work area of at least ${width} × ${height}.`); + } + const window = new BrowserWindow({ icon: appIcon, - width: 1440, - height: 900, + width, + height, minWidth: 920, minHeight: 620, - show: true, ...mainWindowChromeOptions(), + show: !workArea, + ...(workArea ? { + x: workArea.x + Math.floor((workArea.width - width) / 2), + y: workArea.y + Math.floor((workArea.height - height) / 2), + focusable: false + } : {}), backgroundColor: "#aaa7a2", webPreferences: { preload: join(__dirname, "../preload/index.cjs"), @@ -255,6 +278,20 @@ function createWindow(): BrowserWindow { sandbox: true } }); + if (display && workArea) { + const bounds = window.getBounds(); + if (screen.getDisplayMatching(bounds).id !== display.id + || bounds.x < workArea.x || bounds.y < workArea.y + || bounds.x + bounds.width > workArea.x + workArea.width + || bounds.y + bounds.height > workArea.y + workArea.height) { + window.destroy(); + throw new Error(`Could not place the browser smoke window inside "${display.label}".`); + } + app.once("did-become-active", () => console.log("CANVASTTY_BROWSER_SMOKE_FOCUS app")); + window.once("focus", () => console.log("CANVASTTY_BROWSER_SMOKE_FOCUS window")); + window.showInactive(); + console.log("CANVASTTY_BROWSER_SMOKE_DISPLAY", JSON.stringify({ id: display.id, label: display.label, bounds, focused: window.isFocused() })); + } mainWindow = window; markMainBoot("windowCreated"); observeMainWindowState?.(window); @@ -1065,7 +1102,7 @@ async function runStartupSmokes(window: BrowserWindow): Promise { if (browserSmokeUrl && browserService) { // The smoke runners are test code: they load only when a smoke run asks for them. const { runBrowserElectronSmoke } = await import("./services/browser/BrowserElectronSmoke"); - await runBrowserElectronSmoke(browserService, browserSmokeUrl, app.getPath("userData")); + await runBrowserElectronSmoke(browserService, browserSmokeUrl, app.getPath("userData"), Boolean(browserSmokeDisplayName())); console.log("CANVASTTY_BROWSER_SMOKE_READY"); app.quit(); } @@ -1172,7 +1209,8 @@ async function startApplication(): Promise { return; } diagnostics.record("error", "startup", "failed", { error, marks: mainBootMarks() }); - if (startupWindow) await showStartupFailure(startupWindow, error); + if (browserSmokeDisplayName()) console.error("CanvasTTY startup failed.", error); + else if (startupWindow) await showStartupFailure(startupWindow, error); else { const detail = error instanceof Error ? error.stack ?? error.message : String(error); console.error("CanvasTTY could not create its startup window.", error); diff --git a/src/main/services/browser/BrowserElectronSmoke.ts b/src/main/services/browser/BrowserElectronSmoke.ts index fb8bf9c7c..69f346c1c 100644 --- a/src/main/services/browser/BrowserElectronSmoke.ts +++ b/src/main/services/browser/BrowserElectronSmoke.ts @@ -23,7 +23,8 @@ const SENTINEL = "canvastty-secret-must-not-leak"; export async function runBrowserElectronSmoke( service: BrowserService, origin: string, - userDataPath: string + userDataPath: string, + useInactiveDisplay = false ): Promise { const parsedOrigin = new URL(origin); if (parsedOrigin.protocol !== "http:" || parsedOrigin.hostname !== "127.0.0.1") { @@ -64,7 +65,7 @@ export async function runBrowserElectronSmoke( if (!tabId) throw new Error("Browser smoke did not create a tab."); await execute("browser_list_tabs"); await waitUntil(async () => service.getState().tabs.find((tab) => tab.id === tabId)?.status === "ready"); - await assertFocusAwarePhysicalWheel(service, `${origin}/`); + await assertFocusAwarePhysicalWheel(service, `${origin}/`, useInactiveDisplay); await assertBrowserOriginPanCrossesBoundary(service, `${origin}/`); await assertOwnerWheelFreezesCrossingBrowser(service); await assertRendererPanCrossesBrowser(service, `${origin}/`); @@ -371,7 +372,11 @@ async function assertBrowserRendererZoom(service: BrowserService, url: string): } } -async function assertFocusAwarePhysicalWheel(service: BrowserService, url: string): Promise { +async function assertFocusAwarePhysicalWheel( + service: BrowserService, + url: string, + useInactiveDisplay: boolean +): Promise { const contents = webContents.getAllWebContents().find((candidate) => candidate.getURL() === url); const owner = BrowserWindow.getAllWindows().find((candidate) => candidate.getParentWindow() === null); if (!contents || !owner) throw new Error("Browser smoke could not resolve the wheel ownership WebContents."); @@ -386,7 +391,17 @@ async function assertFocusAwarePhysicalWheel(service: BrowserService, url: strin service.setCanvasWheelCaptureMode("off"); service.setInputFocused(true); service.setViewport({ x: 0, y: 0, width: 820, height: 620, surface: "native", canvasScale: 1 }); - await preparePhysicalWheelSmoke(owner, contents); + if (useInactiveDisplay) { + await waitUntil(async () => { + const page = await browserSmokePageState(contents); + return owner.isVisible() && page.readyState === "complete" && page.visibilityState === "visible"; + }); + const page = await browserSmokePageState(contents); + if (owner.isFocused() || page.focused) throw new Error("Inactive display browser smoke gained focus."); + console.log("CANVASTTY_BROWSER_SMOKE_INACTIVE_READY", JSON.stringify(page)); + } else { + await preparePhysicalWheelSmoke(owner, contents); + } await waitForWheelIdle(); const pageScrollY = await sendWheelUntilPageScrolls(contents, { x: 700, y: 300 }); if (pageScrollY === 400) throw new Error("Focused Browser plain wheel did not scroll the page."); diff --git a/tests/startup-lifecycle.test.mjs b/tests/startup-lifecycle.test.mjs index c829bd3de..87a70b7e1 100644 --- a/tests/startup-lifecycle.test.mjs +++ b/tests/startup-lifecycle.test.mjs @@ -28,12 +28,14 @@ test("Mac window close keeps the renderer; quit and other platforms still close const create = source.slice(source.indexOf("function createWindow"), source.indexOf("function shellWindowGone")); for (const [platform, quitting, hidden] of [["darwin", false, true], ["darwin", true, false], ["linux", false, false], ["win32", false, false]]) { class Window extends EventEmitter { + constructor(options) { super(); this.options = options; } hidden = false; webContents = Object.assign(new EventEmitter(), { setWindowOpenHandler() {} }); hide() { this.hidden = true; } } const context = { process: { platform }, app: { isPackaged: true }, BrowserWindow: Window, + browserSmokeDisplayName: () => undefined, shutdownRunning: quitting, shutdownComplete: false, mainWindow: null, mainWindowClosing: false, appSurfaceReady: false, appIcon: null, __dirname: "/tmp", join: (...parts) => parts.join("/"), @@ -42,6 +44,7 @@ test("Mac window close keeps the renderer; quit and other platforms still close }; const createWindow = runInNewContext(`${stripTypeScriptTypes(create)}; createWindow`, context); const window = createWindow(); + assert.equal(window.options.show, true); const event = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; } }; window.emit("close", event); assert.equal(event.defaultPrevented, hidden, `${platform}, quitting=${quitting}`); @@ -92,6 +95,7 @@ function startupContext(events, overrides = {}) { checkUpdatesFromMenu: null, mainWindow: null, process: { env: {} }, + browserSmokeDisplayName: () => undefined, shellWindowGone: () => false, createWindow: () => { events.push("window"); return {}; }, ipcGate: gate, @@ -258,10 +262,9 @@ test("background plugin requests never activate the desktop window", async () => } }); -test("startup window is visible immediately and failures remain visible", async () => { +test("startup uses one surface navigation and failures remain visible", async () => { const source = await readFile(mainPath, "utf8"); - assert.match(source, /show: true/); // One navigation at startup: the application surface itself, no intermediate startup page to race. const createWindow = source.slice(source.indexOf("function createWindow"), source.indexOf("function shellWindowGone")); assert.doesNotMatch(createWindow, /loadURL|loadFile/);