Skip to content
Closed
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
36 changes: 34 additions & 2 deletions scripts/smoke-browser-electron.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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"];
Expand All @@ -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(() => {
Expand All @@ -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);
});
Expand All @@ -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) {
Expand Down
50 changes: 44 additions & 6 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Update the startup lifecycle tests alongside this refactor

Running node --test tests/startup-lifecycle.test.mjs now fails three tests, whereas all 14 pass on the parent commit. Its VM harnesses extract createWindow and startApplication without providing browserSmokeDisplayName, so the new calls throw ReferenceError; the visibility assertion also still requires the removed literal show: true. Update the harness contexts and visibility assertion with this change, otherwise the root-test steps in .github/workflows/ci.yml reject the change even when the selected-display mode is not enabled.

Useful? React with 👍 / 👎.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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"),
Expand All @@ -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);
Expand Down Expand Up @@ -1065,7 +1102,7 @@ async function runStartupSmokes(window: BrowserWindow): Promise<void> {
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();
}
Expand Down Expand Up @@ -1172,7 +1209,8 @@ async function startApplication(): Promise<void> {
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);
Expand Down
23 changes: 19 additions & 4 deletions src/main/services/browser/BrowserElectronSmoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
const parsedOrigin = new URL(origin);
if (parsedOrigin.protocol !== "http:" || parsedOrigin.hostname !== "127.0.0.1") {
Expand Down Expand Up @@ -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}/`);
Expand Down Expand Up @@ -371,7 +372,11 @@ async function assertBrowserRendererZoom(service: BrowserService, url: string):
}
}

async function assertFocusAwarePhysicalWheel(service: BrowserService, url: string): Promise<void> {
async function assertFocusAwarePhysicalWheel(
service: BrowserService,
url: string,
useInactiveDisplay: boolean
): Promise<void> {
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.");
Expand All @@ -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.");
Expand Down
7 changes: 5 additions & 2 deletions tests/startup-lifecycle.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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("/"),
Expand All @@ -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}`);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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/);
Expand Down
Loading