From d5ddf2e250fa6081a4a52c270b4c364f32254748 Mon Sep 17 00:00:00 2001 From: Codeman maintainer Date: Tue, 24 Nov 2026 10:36:56 +0100 Subject: [PATCH] feat(desktop): full screen over the whole display, the strip beside the camera included On a MacBook with a camera housing (the notch), macOS's full screen ends the window below the housing and paints the strip beside it black. No setting changes that, so the Mac app gets a second kind of full screen, off by default: View > Full Screen Uses the Area Beside the Camera. The app (packages/desktop/src/whole_screen.rs): - The window loses its title bar, the Dock and the menu bar auto-hide, and the window gets the display's whole frame, which reaches behind the housing. - An override of toggleFullScreen: on tao's window class decides per request, so the green button, the menu item, its shortcut and the launch into full screen all follow the option. It only applies on a display with a housing. - performClose: asks the delegate while the window has no close button. - Changes into and out of macOS's own full screen are tracked from AppKit's notifications: while one is under way the window is not restyled and its frame is not saved. The Dock and menu-bar options are reconciled, so what a native Space in front kept from being set or taken off is done afterwards. - Info.plist: NSPrefersDisplaySafeAreaCompatibilityMode = false. The page (src/web/public/host-cutout.js, styles.css): - A page is drawn behind the housing only after it said it copes (CodemanHost.cutoutReady); the app answers with where the housing is, and the toolbar's box starts left of it and pads its content past it, so the tabs end before the housing and the toolbar begins after it. - Until then the web view stays below the housing with a black strip above it, which is what full screen looked like before: an older server, the connect page and a raw file are unchanged. - With the tabs grouped by state, by case or as a ledger in the header strip the page says no: ending every row at the housing costs more height than the strip gives. Not yet seen on a MacBook with a housing: the AppKit path was type-checked, unit-tested where it is pure and reviewed, on a Mac mini without one. Co-Authored-By: Claude Fable 5.2 --- .changeset/desktop-whole-screen.md | 5 + config/test-suites.ts | 1 + docs/versioning-policy.md | 4 +- packages/desktop/Cargo.toml | 8 +- packages/desktop/README.md | 67 +- packages/desktop/macos/Info.plist | 8 + packages/desktop/src/assets.rs | 8 +- packages/desktop/src/config.rs | 15 + packages/desktop/src/main.rs | 197 +++- packages/desktop/src/menu.rs | 41 +- packages/desktop/src/policy.rs | 54 +- packages/desktop/src/whole_screen.rs | 1384 ++++++++++++++++++++++++++ scripts/build.mjs | 2 + src/web/CLAUDE.md | 2 + src/web/public/host-cutout.js | 132 +++ src/web/public/index.html | 5 + src/web/public/styles.css | 42 +- test/host-cutout.browser.test.ts | 259 +++++ test/host-cutout.test.ts | 295 ++++++ 19 files changed, 2493 insertions(+), 36 deletions(-) create mode 100644 .changeset/desktop-whole-screen.md create mode 100644 packages/desktop/src/whole_screen.rs create mode 100644 src/web/public/host-cutout.js create mode 100644 test/host-cutout.browser.test.ts create mode 100644 test/host-cutout.test.ts diff --git a/.changeset/desktop-whole-screen.md b/.changeset/desktop-whole-screen.md new file mode 100644 index 00000000..cbe8c9ac --- /dev/null +++ b/.changeset/desktop-whole-screen.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +**Mac app: full screen over the whole display.** On a MacBook with a camera housing (the notch), macOS's full screen leaves a black bar across the top of the display. With **View > Full Screen Uses the Area Beside the Camera** turned on, the Mac app's full screen covers the whole display instead: Codeman's header moves up beside the camera, the tabs to its left and the toolbar to its right, and the terminal gains the height of the bar. The green button, the menu item, ⌃⌘F and the launch into full screen all follow the option, and switching it while the window is in full screen changes it over at once. It is off until you turn it on, because it is not a macOS Space: the window covers the desktop it is on instead of sliding into a Space of its own. The page stays below the camera, as before, with a Codeman server from before this release and while the tabs are grouped by state, by case or as a ledger in the header strip, where ending every row of tabs at the camera would cost more room than the bar gives. diff --git a/config/test-suites.ts b/config/test-suites.ts index 6e523cc3..9d7c3227 100644 --- a/config/test-suites.ts +++ b/config/test-suites.ts @@ -31,6 +31,7 @@ export const BROWSER_TEST_GLOBS = [ 'test/session-sidebar-ux.browser.test.ts', 'test/header-divider.browser.test.ts', 'test/tab-strip-corner.browser.test.ts', + 'test/host-cutout.browser.test.ts', 'test/header-host-sensors.browser.test.ts', 'test/session-options-responsive.browser.test.ts', 'test/inline-rename.test.ts', diff --git a/docs/versioning-policy.md b/docs/versioning-policy.md index 7f2bab92..7e4ad397 100644 --- a/docs/versioning-policy.md +++ b/docs/versioning-policy.md @@ -63,7 +63,9 @@ These may change in a **MINOR** (or even PATCH) release without a MAJOR bump: 3. **Experimental / opt-in features**, regardless of the app's version: Gesture Control (beta), Agent Teams (`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`), the native-wrapper window bridge - (`window.CodemanHost.openWindow` / `closeWindow` / `focusWindow`), and + (`window.CodemanHost.openWindow` / `closeWindow` / `focusWindow` / + `cutoutReady`, and `window.CodemanHostCutout.apply`, which a wrapper calls + to say where a display's camera housing is), and anything labeled experimental in the UI or docs. These may change or be removed at any time. diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index 53db63bf..861f7583 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -36,18 +36,21 @@ security-framework = "3" # through wry and tao, so no new crate is added. libc = "0.2" # JavaScript dialogs, HTTP Basic challenges, clearing cookies and the window's -# content size (src/macos.rs). The versions wry already pulls in, so no new -# crate is added. +# content size (src/macos.rs), and full screen over the whole display +# (src/whole_screen.rs). The versions wry already pulls in, so no new crate is +# added. objc2 = { version = "0.6.5", default-features = false, features = ["std"] } block2 = { version = "0.6.2", default-features = false, features = ["std"] } objc2-foundation = { version = "0.3.2", default-features = false, features = [ "std", "objc2-core-foundation", "block2", + "NSArray", "NSBundle", "NSDate", "NSDictionary", "NSGeometry", + "NSNotification", "NSObject", "NSOperation", "NSProcessInfo", @@ -71,6 +74,7 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = [ "NSButton", "NSControl", "NSResponder", + "NSScreen", "NSTextField", "NSView", "NSWindow", diff --git a/packages/desktop/README.md b/packages/desktop/README.md index ab780aa6..b48a8b92 100644 --- a/packages/desktop/README.md +++ b/packages/desktop/README.md @@ -34,7 +34,7 @@ cannot do. | **Start Codeman** | On the This Mac tab, and when `http://127.0.0.1:` or `http://localhost:` answers nothing, one click runs `codeman web -d` (or `~/.codeman/app`) with your login shell's environment, so the server gets your real PATH (Homebrew, nvm) for the agents it spawns. zsh, bash and other POSIX shells run the start themselves; fish, nu, xonsh, tcsh and other shells only report their environment, and the start runs under `/bin/sh` with it. Offered for those two addresses only: `codeman web -d` listens on 127.0.0.1. | | **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected with, so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears the app's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. | | **Dialogs** | Codeman's `confirm()`, `prompt()` and `alert()` (Delete case, Kill all sessions, Update Codeman, discarding unsaved edits, ...) show as native macOS dialogs. wry implements none of them, and without them WKWebView answers Cancel without showing anything. Each dialog's first line names the page it comes from, and says so when that is an embedded frame (a web tab, a rendered HTML preview), so a frame cannot pass its text off as Codeman's. | -| **Full screen** | `⌃⌘F` or the green button. The last state is restored at launch; *Always Open in Full Screen* forces it. Leaving full screen returns to the saved window size and position. | +| **Full screen** | `⌃⌘F` or the green button. The last state is restored at launch; *Always Open in Full Screen* forces it. Leaving full screen returns to the saved window size and position. On a MacBook with a camera housing (the notch), macOS's full screen leaves a black bar across the top of the display. **View > Full Screen Uses the Area Beside the Camera** (off until you turn it on, and only in the menu on a Mac with such a display) makes full screen cover the whole display instead: Codeman's header moves up beside the camera, its tabs to the left and its toolbar to the right, and the terminal gains the height of the bar. Every way into full screen then takes it on that display (the green button, the menu item, `⌃⌘F`, the launch into full screen), and turning the option on or off while the window is in full screen changes it over at once. On a display without a housing nothing changes. See Decisions for what it trades, and Known limits. | | **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Switch Server `⇧⌘O`, Developer Tools `⌥⌘I`. The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. | | **Pop-outs** | Implements Codeman's existing native-wrapper bridge, `window.CodemanHost` (`openInHostWindow` in `src/web/public/app.js`), so popping out a session or a file preview opens a real app window, and the pop-out icon is on by default. Session and rendered-HTML pop-outs come only from Codeman's own pop-out button. A `window.open` from page script opens only Codeman's file and download windows, without taking keyboard focus, at most 3 at once and then 1 per second. Only Codeman's own pop-out pages become app windows (see Decisions); when the app refuses one, Codeman shows a toast. Each pop-out opens a step down and to the right of the window in use, never exactly on top of another one. A web tab's *Open in new tab* opens the dashboard in your default browser, as it would from a browser tab. | | **Links** | On Codeman's own pages (the dashboard and session windows), a link to another site opens in your default browser, also on `⌘`-click or a middle click. Pages can send at most 3 links to the browser at once, then 1 per second. Inside a rendered HTML preview or a web tab, a plain link to another site does nothing, while one that asks for a new window (`target="_blank"`, `window.open`) opens in your default browser within the same budget (see Known limits). | @@ -274,6 +274,51 @@ address. So the app looks for running Codeman servers of this user (`ps`) before it offers or runs a start, and offers to connect to the ones it finds instead (`found_addresses` in `src/setup.rs`, unit-tested). +**Full screen over the whole display is the app's own, not macOS's.** A native +full-screen Space never reaches behind a MacBook's camera housing: the system +ends the window below it and paints the strip beside it black, and no setting +changes that. What reaches it is the older kind of full screen, the one +terminals offer for the same reason (Ghostty's `macos-non-native-fullscreen`, +WezTerm's `macos_fullscreen_extend_behind_notch`, iTerm2's and kitty's +traditional full screen): the window loses its title bar, the Dock and the menu +bar auto-hide, and the window gets the display's whole frame +(`src/whole_screen.rs`). Every request for full screen ends in +`-[NSWindow toggleFullScreen:]`, so the app adds an override of that one method +to tao's window class and decides there, which is what makes the green button +and the menu item follow the option without the app owning either. One more +override keeps a window without a title bar usable: `⌘W` asks to close as the +close button would (AppKit's version only beeps without one). The two kinds of +full screen never overlap: AppKit says when a window begins and ends a change +into or out of its own full screen, and while one is under way the app neither +takes the title bar off nor saves the window's frame, so switching the option +while the window is in macOS's full screen waits for the Space to close first. +The Dock and the menu bar are set to auto-hide only while a window is in this +mode, and what could not be set or taken off because a native Space was in +front is done when that changes. +`NSPrefersDisplaySafeAreaCompatibilityMode` is `false` in `Info.plist`, which +tells macOS that the app handles the housing itself; without it the system may +shrink the display's active area as soon as a window reaches behind the housing. + +It is not a Space, and that is the trade: the window covers the desktop it is +on, there is no slide animation, a three-finger swipe does not lead to it, and +another app's window on that desktop comes up in front of it. That is why it is +an option. On a display without a housing macOS's full screen already uses +every pixel, so the option changes nothing there and the window keeps its Space. + +**A page is drawn behind the housing only after it said it copes.** The housing +hides whatever is behind it, so the header has to keep its controls out of the +way, and only the page can do that. Codeman's page says so through +`CodemanHost.cutoutReady()` (`src/web/public/host-cutout.js`) and is then told +where the housing is, in points from the top-left corner, and lays its header +out around it. Until a page has said so the web view stays below the housing +and the strip above it is black, as in macOS's full screen. That covers an +older Codeman server (its page never says it), the connect page, a raw file, +and a layout the page itself declines: with the tabs grouped by state, by case +or as a ledger in the header strip, every row of tabs would have to end at the +housing, which costs more height than the strip gives. Only Codeman's own app +shell may say it (`policy::parse_ipc`), so a rendered HTML file or a web tab +cannot get the page drawn behind the camera. + **Closing the main window quits the app.** Codeman's sessions keep running on the server, so nothing is lost, and reopening takes about a second. @@ -479,6 +524,26 @@ crosses, so the login is never on a command line. built-in display's brightness when the lid opens again, and an Apple display with its own light sensor. If the logo does not move under a closed lid, the menu line says "stayed dark". +- **Full screen over the whole display has not been seen on a real MacBook + yet** (as of this change). The decisions, the menu, the page's layout around + the housing and every AppKit fact the overrides rest on were checked (the + page in Chromium at the sizes of the 14 and 16 inch displays, the rest on a + Mac mini, which has no housing and no screen session). Not seen: the window + behind a real housing, the menu bar sliding in over it, the change-over from + macOS's full screen, a second display, and closing the lid. +- **In that mode the tabs get the room left of the camera only.** A wrapped tab + strip runs its later rows across the whole width, but its first row ends at + the housing, and the room between the housing and the toolbar stays empty. On + a 14 inch display that is about three tabs fewer in the first row, so with + many tabs the strip can need one row more, which takes back what the bar + gave. With the tabs in the sidebar or the rail, or with a few tabs, the whole + height of the bar is gained. +- **Minimize does nothing in that mode** (`⌘M` beeps): the window has no title + bar, as in macOS's full screen. The menu item says *Toggle Full Screen* in + both kinds of full screen. +- **A MacBook started with its lid closed has no menu item for it** until the + app is started with the built-in display open: the item only exists while a + display with a housing is connected at launch, or the option is already on. - **Self-signed HTTPS is refused.** A server started with `codeman web --https` uses a self-signed certificate, and WKWebView rejects it (wry has no trust override). Use `http://127.0.0.1:3000` for a server on this Mac. For another diff --git a/packages/desktop/macos/Info.plist b/packages/desktop/macos/Info.plist index 3f25f0f4..8b47270f 100644 --- a/packages/desktop/macos/Info.plist +++ b/packages/desktop/macos/Info.plist @@ -31,6 +31,14 @@ NSSupportsAutomaticGraphicsSwitching + + NSPrefersDisplaySafeAreaCompatibilityMode + NSHumanReadableCopyright MIT License, Codeman Contributors + + ${header}`, + }) + ); + await p.goto(ORIGIN); + await p.addScriptTag({ + content: + 'var MobileDetection = { isTouchDevice: () => false, getDeviceType: () => "desktop" }, KeyboardHandler = {}, ' + + 'SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' + + read('constants.js') + + '\n' + + read('app.js') + + '\nwindow.CodemanApp = CodemanApp;', + }); + await p.evaluate( + ({ tabs }) => { + const w = window as any; + const app = Object.create(w.CodemanApp.prototype); + app.$ = (id: string) => document.getElementById(id); + app.sessions = new Map(); + app.loadAppSettingsFromStorage = () => ({}); + app.getDefaultSettings = () => ({}); + app.isSessionSidebarActive = () => false; + app.updateConnectionLines = () => undefined; + const strip = document.getElementById('sessionTabs')!; + for (let i = 1; i <= tabs; i++) { + const id = `s${i}`; + app.sessions.set(id, { id, name: `session-${i}` }); + strip.insertAdjacentHTML( + 'beforeend', + `` + ); + } + // The module asks `window.app` to measure the toolbar again, as the page does. + w.app = app; + }, + { tabs: options.tabs } + ); + await p.addScriptTag({ content: read('host-cutout.js') }); + await relayout(); + } + + const settled = () => p.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + const relayout = async () => { + await p.evaluate(() => (window as any).app.updateTabOverflowMode()); + await settled(); + }; + const apply = async (cutout: Cutout | null) => { + expect(await p.evaluate((c) => (window as any).CodemanHostCutout.apply(c), cutout)).toBe(true); + await settled(); + }; + const toolbar = () => + p.evaluate(() => document.getElementById('headerRight')!.getBoundingClientRect().toJSON()) as Promise; + const cornered = () => p.evaluate(() => document.getElementById('sessionTabs')!.classList.contains('tabs-corner')); + + /** Everything the header row paints: tabs, the brand, the toolbar's controls. */ + const painted = () => + p.evaluate(() => { + const strip = document.getElementById('sessionTabs')!.getBoundingClientRect(); + const shown = (el: Element) => { + const s = getComputedStyle(el); + const r = el.getBoundingClientRect(); + return s.display !== 'none' && s.visibility !== 'hidden' && r.width > 0 && r.height > 0; + }; + const out: Array<{ what: string; left: number; right: number; top: number; bottom: number }> = []; + for (const el of document.querySelectorAll('#sessionTabs > .session-tab')) { + const r = el.getBoundingClientRect(); + // The strip clips what it scrolls or overflows. + const box = { + left: Math.max(r.left, strip.left), + right: Math.min(r.right, strip.right), + top: Math.max(r.top, strip.top), + bottom: Math.min(r.bottom, strip.bottom), + }; + if (box.right > box.left && box.bottom > box.top) + out.push({ what: 'tab ' + el.getAttribute('data-id'), ...box }); + } + for (const el of document.querySelectorAll('#headerRight > *, .header-brand .logo')) { + if (!shown(el) || el.classList.contains('header-divider')) continue; + const r = el.getBoundingClientRect(); + out.push({ + what: el.id || el.className.toString().slice(0, 40), + left: r.left, + right: r.right, + top: r.top, + bottom: r.bottom, + }); + } + return out; + }); + + /** What is painted behind the housing, or closer to it than `margin` px. */ + const behind = async (cutout: Cutout, margin = 4) => + (await painted()).filter( + (r) => r.top < cutout.height && r.right > cutout.left - margin && r.left < cutout.left + cutout.width + margin + ); + + for (const display of DISPLAYS) { + it(`keeps one row of tabs and the toolbar clear of the housing (${display.name})`, async () => { + await open({ tabs: 3, width: display.width, height: display.height }); + await apply(display.cutout); + expect(await behind(display.cutout)).toEqual([]); + const box = await toolbar(); + // The toolbar's box starts just left of the housing, so the tab strip ends there... + expect(box.left).toBeLessThanOrEqual(display.cutout.left); + expect(box.left).toBeGreaterThan(display.cutout.left - 16); + // ...and still ends where the header's padding begins. + expect(Math.round(display.width - box.right)).toBe(12); + await p.close(); + }); + + it(`keeps a wrapped strip clear of the housing, and its later rows full width (${display.name})`, async () => { + await open({ tabs: 34, width: display.width, height: display.height }); + await apply(display.cutout); + expect(await cornered()).toBe(true); + expect(await behind(display.cutout)).toEqual([]); + const box = await toolbar(); + const tabs = (await painted()).filter((r) => r.what.startsWith('tab ')); + const beside = tabs.filter((t) => t.top < box.bottom); + const below = tabs.filter((t) => t.top >= box.bottom); + // The rows beside the toolbar's box stop at the housing; the rows below it run on past the housing. + expect(beside.length).toBeGreaterThan(0); + expect(Math.max(...beside.map((t) => t.right))).toBeLessThan(display.cutout.left); + expect(Math.max(...below.map((t) => t.right))).toBeGreaterThan(display.cutout.left + display.cutout.width); + await p.close(); + }); + } + + it('keeps a strip that is too tall for the corner left of the housing altogether', async () => { + // Past its max-height the strip scrolls and keeps the plain wrap (_syncTabStripCorner): every row then + // ends where the toolbar's box begins, which is the housing's left edge. + const display = DISPLAYS[3]; + await open({ tabs: 40, width: display.width, height: display.height }); + await apply(display.cutout); + expect(await cornered()).toBe(false); + expect(await behind(display.cutout)).toEqual([]); + const tabs = (await painted()).filter((r) => r.what.startsWith('tab ')); + expect(Math.max(...tabs.map((t) => t.right))).toBeLessThan(display.cutout.left); + await p.close(); + }); + + it('wraps a toolbar that is wider than the room beside the housing, below the housing', async () => { + await open({ tabs: 3, width: MBP14.width, height: MBP14.height }); + // A toolbar full of readings: wider than the 660 px right of the housing. + await p.evaluate(() => { + const right = document.getElementById('headerRight')!; + for (let i = 0; i < 9; i++) { + const reading = document.createElement('div'); + reading.className = 'test-reading'; + reading.style.cssText = 'flex:0 0 auto;width:110px;height:24px;background:#345'; + right.appendChild(reading); + } + }); + await relayout(); + const before = await toolbar(); + await apply(MBP14.cutout); + const after = await toolbar(); + expect(after.bottom - after.top).toBeGreaterThan(before.bottom - before.top + 16); + expect(await behind(MBP14.cutout)).toEqual([]); + // Nothing is cut off either: every control is inside the viewport. + for (const r of await painted()) expect(r.left, r.what).toBeGreaterThanOrEqual(0); + await p.close(); + }); + + it('puts the header back exactly when the housing is gone', async () => { + await open({ tabs: 40, width: MBP14.width, height: MBP14.height }); + const before = { toolbar: await toolbar(), painted: await painted() }; + await apply(MBP14.cutout); + expect(await toolbar()).not.toEqual(before.toolbar); + await apply(null); + expect(await toolbar()).toEqual(before.toolbar); + expect(await painted()).toEqual(before.painted); + expect(await p.evaluate(() => document.documentElement.getAttribute('style') || '')).not.toContain('host-cutout'); + await p.close(); + }); + + it('sets aside a toolbar width the user chose while the housing is there', async () => { + await open({ + tabs: 3, + width: MBP14.width, + height: MBP14.height, + attrs: 'data-header-right-width="set" style="--header-right-width: 300px"', + }); + const chosen = await toolbar(); + expect(Math.round(chosen.right - chosen.left)).toBe(300); + await apply(MBP14.cutout); + // 300 px would end the toolbar right of the housing and let the tabs run behind it. + expect((await toolbar()).left).toBeLessThanOrEqual(MBP14.cutout.left); + expect(await behind(MBP14.cutout)).toEqual([]); + await apply(null); + expect(await toolbar()).toEqual(chosen); + await p.close(); + }); + + it('keeps the toolbar right of the housing where the header has no tabs (sidebar, rail, solo window)', async () => { + await open({ tabs: 0, width: MBP14.width, height: MBP14.height }); + await apply(MBP14.cutout); + expect(await behind(MBP14.cutout)).toEqual([]); + expect((await toolbar()).left).toBeLessThanOrEqual(MBP14.cutout.left); + await p.close(); + }); +}); diff --git a/test/host-cutout.test.ts b/test/host-cutout.test.ts new file mode 100644 index 00000000..0965410a --- /dev/null +++ b/test/host-cutout.test.ts @@ -0,0 +1,295 @@ +/** + * @fileoverview The camera housing module (host-cutout.js): what counts as a housing, when the page tells a + * native wrapper that it may be drawn behind one, what `apply` writes, and that the page, the build and the + * stylesheet carry it. The layout itself is measured in real Chromium (host-cutout.browser.test.ts). + */ +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; + +const publicDir = resolve(import.meta.dirname, '../src/web/public'); +const read = (name: string) => readFileSync(resolve(publicDir, name), 'utf8'); +const buildJs = readFileSync(resolve(import.meta.dirname, '../scripts/build.mjs'), 'utf8'); +const shim = readFileSync(resolve(import.meta.dirname, '../packages/desktop/src/assets.rs'), 'utf8'); + +type Cutout = { left: number; width: number; height: number }; +type Api = { + apply: (cutout: unknown) => boolean; + normalize: (cutout: unknown) => Cutout | null; + fits: () => boolean; + current: () => Cutout | null; +}; + +/** A 14-inch MacBook Pro at its default scaling. */ +const MBP14: Cutout = { left: 663.5, width: 185, height: 32 }; + +/** + * Run the module in a page that has `dataset` on and, with `host`, the bridge Codeman Desktop injects. + * Returns the module, what it told the bridge, the root's style and classes, and how to change the layout. + */ +function load(options: { dataset?: Record; host?: boolean; pathname?: string; solo?: string } = {}) { + const calls: unknown[] = []; + const relayouts: string[] = []; + const props = new Map(); + const classes = new Set(); + const dataset: Record = { + sessionList: 'header', + tabOrientation: 'horizontal', + tabArrangement: 'classic', + ...options.dataset, + }; + let observer: (() => void) | null = null; + const documentElement = { + dataset, + style: { + setProperty: (name: string, value: string) => props.set(name, value), + removeProperty: (name: string) => props.delete(name), + }, + classList: { + add: (name: string) => classes.add(name), + remove: (name: string) => classes.delete(name), + }, + }; + const window: Record = { + app: { + updateTabOverflowMode: () => relayouts.push('tabs'), + updateConnectionLines: () => relayouts.push('lines'), + }, + }; + if (options.solo !== undefined) window.__CODEMAN_SOLO__ = options.solo; + if (options.host !== false) window.CodemanHost = { cutoutReady: (ready: unknown) => calls.push(ready) }; + const context = vm.createContext({ + window, + document: { documentElement }, + location: { pathname: options.pathname ?? '/' }, + MutationObserver: class { + constructor(callback: () => void) { + observer = callback; + } + observe(target: unknown, init: { attributeFilter: string[] }) { + expect(target).toBe(documentElement); + expect(init.attributeFilter).toEqual(['data-tab-arrangement', 'data-session-list', 'data-tab-orientation']); + } + }, + }); + vm.runInContext(read('host-cutout.js'), context, { filename: 'host-cutout.js' }); + return { + api: window.CodemanHostCutout as Api, + calls, + relayouts, + props, + classes, + /** Change the layout the way the settings do, and let the observer see it. */ + setLayout(change: Record) { + Object.assign(dataset, change); + observer?.(); + }, + }; +} + +describe('camera housing: what counts as one', () => { + it('takes three finite, positive numbers', () => { + const { api } = load(); + expect(api.normalize(MBP14)).toEqual(MBP14); + expect(api.normalize({ left: '663.5', width: '185', height: '32' })).toEqual(MBP14); + expect(api.normalize({ left: 0, width: 200, height: 38 })).toEqual({ left: 0, width: 200, height: 38 }); + }); + + it('refuses anything else, so a bad message can never empty the header', () => { + const { api } = load(); + for (const bad of [ + null, + undefined, + 'notch', + 42, + {}, + { left: 663 }, + { left: NaN, width: 185, height: 32 }, + { left: 663, width: Infinity, height: 32 }, + { left: -1, width: 185, height: 32 }, + { left: 663, width: 0, height: 32 }, + { left: 663, width: 185, height: 0 }, + { left: 663, width: 185, height: 900 }, + ]) { + expect(api.normalize(bad), JSON.stringify(bad)).toBeNull(); + } + }); +}); + +describe('camera housing: laying the header out around it', () => { + it('writes the housing to and has the tab strip measure the toolbar again', () => { + const page = load(); + expect(page.api.apply(MBP14)).toBe(true); + expect(Object.fromEntries(page.props)).toEqual({ + '--host-cutout-left': '663.5px', + '--host-cutout-width': '185px', + '--host-cutout-height': '32px', + }); + expect([...page.classes]).toEqual(['host-cutout']); + expect(page.api.current()).toEqual(MBP14); + expect(page.relayouts).toEqual(['tabs', 'lines']); + }); + + it('does nothing for the housing it already has', () => { + const page = load(); + page.api.apply(MBP14); + page.relayouts.length = 0; + expect(page.api.apply({ ...MBP14 })).toBe(true); + expect(page.relayouts).toEqual([]); + }); + + it('puts everything back when the housing is gone', () => { + const page = load(); + page.api.apply(MBP14); + page.relayouts.length = 0; + expect(page.api.apply(null)).toBe(true); + expect(page.props.size).toBe(0); + expect(page.classes.size).toBe(0); + expect(page.api.current()).toBeNull(); + expect(page.relayouts).toEqual(['tabs', 'lines']); + }); + + it('treats a housing that is not a rectangle as none', () => { + const page = load(); + page.api.apply(MBP14); + page.api.apply({ left: 663, width: -4, height: 32 }); + expect(page.classes.size).toBe(0); + expect(page.props.size).toBe(0); + }); + + it('follows the housing to another display', () => { + const page = load(); + page.api.apply(MBP14); + page.api.apply({ left: 771.5, width: 185, height: 32 }); + expect(page.props.get('--host-cutout-left')).toBe('771.5px'); + expect([...page.classes]).toEqual(['host-cutout']); + }); + + it('works before the app exists (the module runs in )', () => { + const calls: unknown[] = []; + const props = new Map(); + const window: Record = { CodemanHost: { cutoutReady: (r: unknown) => calls.push(r) } }; + const context = vm.createContext({ + window, + document: { + documentElement: { + dataset: {}, + style: { setProperty: (n: string, v: string) => props.set(n, v), removeProperty: () => {} }, + classList: { add: () => {}, remove: () => {} }, + }, + }, + location: { pathname: '/' }, + }); + vm.runInContext(read('host-cutout.js'), context, { filename: 'host-cutout.js' }); + expect(calls).toEqual([true]); + expect((window.CodemanHostCutout as Api).apply(MBP14)).toBe(true); + expect(props.get('--host-cutout-width')).toBe('185px'); + }); +}); + +describe('camera housing: telling the app whether the page may be drawn behind it', () => { + it('says yes once for the classic strip, the sidebar and the rail', () => { + expect(load().calls).toEqual([true]); + expect(load({ dataset: { sessionList: 'sidebar' } }).calls).toEqual([true]); + expect(load({ dataset: { tabOrientation: 'vertical' } }).calls).toEqual([true]); + }); + + it('says no while the tabs are grouped in the header strip', () => { + for (const tabArrangement of ['state', 'case', 'ledger']) { + const page = load({ dataset: { tabArrangement } }); + expect(page.calls, tabArrangement).toEqual([false]); + expect(page.api.fits()).toBe(false); + } + }); + + it('says yes for grouped tabs that are not in the header', () => { + expect(load({ dataset: { tabArrangement: 'state', sessionList: 'sidebar' } }).calls).toEqual([true]); + expect(load({ dataset: { tabArrangement: 'ledger', tabOrientation: 'vertical' } }).calls).toEqual([true]); + }); + + it('says yes in a solo window, which has no tab strip, under any base path', () => { + expect(load({ dataset: { tabArrangement: 'state' }, pathname: '/session/abc' }).calls).toEqual([true]); + expect(load({ dataset: { tabArrangement: 'state' }, pathname: '/codeman/session/abc/' }).calls).toEqual([true]); + expect(load({ dataset: { tabArrangement: 'state' }, solo: 'abc' }).calls).toEqual([true]); + // A dashboard URL that only mentions the word is not one. + expect(load({ dataset: { tabArrangement: 'state' }, pathname: '/session/' }).calls).toEqual([false]); + }); + + it('says so again when the layout changes, and only then', () => { + const page = load(); + page.setLayout({ tabArrangement: 'classic' }); + expect(page.calls).toEqual([true]); + page.setLayout({ tabArrangement: 'state' }); + page.setLayout({ tabArrangement: 'case' }); + expect(page.calls).toEqual([true, false]); + page.setLayout({ tabOrientation: 'vertical' }); + expect(page.calls).toEqual([true, false, true]); + }); + + it('drops the layout at once when it stops fitting, without waiting for the app', () => { + const page = load(); + page.api.apply(MBP14); + page.setLayout({ tabArrangement: 'state' }); + expect(page.classes.size).toBe(0); + expect(page.props.size).toBe(0); + expect(page.api.current()).toBeNull(); + }); + + it('ignores a housing the app sent before it heard the no', () => { + const page = load({ dataset: { tabArrangement: 'ledger' } }); + expect(page.api.apply(MBP14)).toBe(true); + expect(page.classes.size).toBe(0); + expect(page.api.current()).toBeNull(); + }); + + it('is silent in a browser tab, where nothing is ever drawn behind a housing', () => { + const page = load({ host: false }); + expect(page.calls).toEqual([]); + expect(page.classes.size).toBe(0); + expect(typeof page.api.apply).toBe('function'); + }); +}); + +describe('camera housing: wiring', () => { + const html = read('index.html'); + const css = read('styles.css'); + + it('loads in , not deferred, after the layout attributes are written', () => { + const tag = ''; + const at = html.indexOf(tag); + expect(at).toBeGreaterThan(-1); + expect(at).toBeLessThan(html.indexOf('')); + // The pre-paint script that writes data-tab-arrangement and its two siblings comes first: `fits()` reads them. + expect(at).toBeGreaterThan(html.indexOf('document.documentElement.dataset.tabArrangement=')); + expect(html).not.toContain('