stage-browser 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # Stage
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A minimal Chromium browser for screen sharing. The page fills the whole window. Tabs stay out of sight until you move the cursor to the top edge, then slide in over the page and hide again when you move away.
4
+
5
+ Built for workshops, webinars, and demos: share just the Stage window and your audience sees the site, nothing else.
6
+
7
+ - **Viewport first.** No toolbar, no address bar, no bookmarks bar. Tabs float in a small capsule that appears only when you reach for it.
8
+ - **Chrome extensions.** Install from the Chrome Web Store, including the Okta Browser Plugin (Extensions menu → Install Okta Browser Plugin).
9
+ - **Runs from the terminal.** No `.app` to build, sign, or notarize.
10
+ - **Presenter helpers.** Window-size presets (1280×720, 1440×900, 1600×900, 1920×1080), zoom shortcuts, and a pinned-bar mode when you want the tabs visible.
11
+
12
+ macOS only.
13
+
14
+ ## Install and run
15
+
16
+ ```sh
17
+ npx stage-browser https://example.com # try it without installing
18
+ npm i -g stage-browser # or install the `stage` command
19
+ stage https://example.com docs.example.com
20
+ ```
21
+
22
+ From a clone:
23
+
24
+ ```sh
25
+ npm install
26
+ npm run cli:install # links bin/stage.js to ~/.local/bin/stage
27
+ stage
28
+ ```
29
+
30
+ The first install downloads Electron's Chromium build (about 100 MB).
31
+
32
+ ## Usage
33
+
34
+ ```
35
+ stage open Stage (restores the last session)
36
+ stage <url|domain|words> … open each argument as a tab; bare words become a Google search
37
+ stage --size 1280x720 … set the window's content size
38
+ stage --pin start with the tab bar pinned
39
+ stage --fresh skip the saved session
40
+ stage --fg run in the foreground with logs in the terminal
41
+ ```
42
+
43
+ If Stage is already running, `stage <url>` opens the URL as a tab in the running window.
44
+
45
+ ## Shortcuts
46
+
47
+ | Shortcut | Action |
48
+ | --- | --- |
49
+ | ⌘T | new tab (opens the omnibox) |
50
+ | ⌘L | go to an address or search |
51
+ | ⌘W / ⇧⌘T | close tab / reopen closed tab |
52
+ | ⌘1 … ⌘9 | jump to a tab (⌘9 = last) |
53
+ | ⌃Tab, ⇧⌘] / ⇧⌘[ | next / previous tab |
54
+ | ⌘[ / ⌘] | back / forward |
55
+ | ⌘R / ⇧⌘R | reload / hard reload |
56
+ | ⌘= / ⌘- / ⌘0 | zoom in / out / reset |
57
+ | ⇧⌘B | pin or unpin the tab bar |
58
+ | ⌃⌘F | full screen |
59
+ | ⇧⌘O | open the current page in Google Chrome |
60
+ | ⌥⌘I | developer tools |
61
+
62
+ In the tab bar, click the active tab to edit its address, middle-click a tab to close it, drag tabs to reorder, and right-click a tab for more.
63
+
64
+ ## Extensions and Okta
65
+
66
+ Use **Extensions → Install Okta Browser Plugin**, or open the Chrome Web Store from the same menu and click "Add to Chrome" on any extension. Extension icons appear on the right of the tab bar.
67
+
68
+ Stage uses [electron-chrome-extensions](https://github.com/samuelmaddock/electron-browser-shell/tree/master/packages/electron-chrome-extensions), which covers most of the `chrome.*` APIs extensions rely on, but not every one. An extension that needs a missing API may only partly work. When that happens, ⇧⌘O opens the page in Google Chrome.
69
+
70
+ Links to apps (Zoom, Slack, Okta Verify) open in those apps.
71
+
72
+ ## Where things live
73
+
74
+ - Profile (cookies, logins, extensions, saved session, history): `~/Library/Application Support/Stage`. A clone, a global install, and npx all share it.
75
+ - Errors are logged to `~/Library/Application Support/Stage/stage.log` instead of interrupting you with a dialog.
76
+
77
+ ## Known limitations
78
+
79
+ - The bold app name in the macOS menu bar reads "Electron", because Stage runs the stock Electron binary rather than a renamed `.app`. Sharing only the Stage window hides it.
80
+ - One window. Links that open new windows become tabs; sign-in pop-ups (OAuth) open as small separate windows so the sign-in flow keeps working.
81
+
82
+ ## Development
83
+
84
+ ```sh
85
+ npm start # run from source
86
+ npm run selftest # scripted end-to-end checks; writes selftest-out/results.json and screenshots
87
+ npm run ui:preview # renders the tab bar and omnibox in mock mode with headless Chrome
88
+ ```
89
+
90
+ `docs/CONTRACT.md` describes the window layout and the interface between the main process (`src/main/`) and the overlay UI (`src/ui/`).
package/bin/stage.js ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+ const fs = require('fs')
4
+ const path = require('path')
5
+ const { spawn } = require('child_process')
6
+
7
+ const root = path.resolve(path.dirname(fs.realpathSync(__filename)), '..')
8
+ const args = process.argv.slice(2)
9
+ const pkg = require(path.join(root, 'package.json'))
10
+
11
+ const HELP = `Stage ${pkg.version} - a minimal browser for screen sharing
12
+
13
+ Usage:
14
+ stage open Stage (restores the last session)
15
+ stage <url|domain|words> ... open each argument as a tab; bare words become a Google search
16
+ stage --size 1280x720 ... set the window's content size
17
+ stage --pin start with the tab bar pinned
18
+ stage --fresh skip the saved session
19
+ stage --fg run in the foreground with logs in the terminal
20
+ stage --help | --version
21
+ `
22
+
23
+ if (args.includes('--help') || args.includes('-h')) {
24
+ process.stdout.write(HELP)
25
+ process.exit(0)
26
+ }
27
+ if (args.includes('--version') || args.includes('-v')) {
28
+ console.log(pkg.version)
29
+ process.exit(0)
30
+ }
31
+
32
+ let electron
33
+ try {
34
+ electron = require('electron')
35
+ } catch (e) {
36
+ console.error('stage: could not find Electron. Run `npm install` in ' + root)
37
+ process.exit(1)
38
+ }
39
+
40
+ const fg = args.includes('--fg')
41
+ const child = spawn(electron, [root, ...args], fg ? { stdio: 'inherit' } : { detached: true, stdio: 'ignore' })
42
+ child.on('error', (e) => {
43
+ console.error('stage: failed to launch: ' + e.message)
44
+ process.exit(1)
45
+ })
46
+ if (fg) {
47
+ child.on('exit', (code, signal) => process.exit(signal ? 1 : code || 0))
48
+ } else {
49
+ child.unref()
50
+ // spawn errors surface asynchronously; give them a tick before exiting
51
+ setImmediate(() => process.exit(0))
52
+ }
package/build/icon.png ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "stage-browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "productName": "Stage",
4
+ "version": "0.1.0",
5
+ "description": "A minimal Chromium browser for screen sharing: the page fills the window, tabs hide until you reach for them.",
6
+ "main": "src/main/main.js",
7
+ "scripts": {
8
+ "start": "electron .",
9
+ "selftest": "STAGE_SELFTEST=1 electron .",
10
+ "ui:preview": "node scripts/ui-preview.js",
11
+ "cli:install": "sh scripts/install-cli.sh"
12
+ },
13
+ "dependencies": {
14
+ "electron": "^45.4.1",
15
+ "electron-chrome-extensions": "^4.10.0",
16
+ "electron-chrome-web-store": "^0.13.0"
17
+ },
18
+ "bin": {
19
+ "stage": "bin/stage.js"
20
+ },
21
+ "files": [
22
+ "bin/",
23
+ "src/",
24
+ "build/icon.png",
25
+ "README.md"
26
+ ],
27
+ "os": [
28
+ "darwin"
29
+ ],
30
+ "engines": {
31
+ "node": ">=18"
32
+ },
33
+ "keywords": [
34
+ "browser",
35
+ "electron",
36
+ "chromium",
37
+ "screen-sharing",
38
+ "presentation",
39
+ "demo"
40
+ ],
41
+ "license": "MIT"
42
+ }
@@ -0,0 +1,28 @@
1
+ 'use strict'
2
+ // Parses Stage's CLI arguments out of an argv array shaped like
3
+ // [electronBinary, appPath, ...userArgs] (also what second-instance delivers).
4
+ // Chromium/Electron switches (--inspect, --remote-debugging-port=..., etc.) are ignored.
5
+
6
+ function parseArgs(argv, appRoot) {
7
+ const out = { urls: [], size: null, pin: false, fresh: false }
8
+ // argv is [electron, appPath, ...args]; second-instance may carry extra leading entries,
9
+ // so anchor on the app path when we know it.
10
+ const at = appRoot ? argv.findIndex((a) => a === appRoot || a === '.') : -1
11
+ const args = at >= 0 ? argv.slice(at + 1) : argv.slice(2)
12
+ for (let i = 0; i < args.length; i++) {
13
+ const a = args[i]
14
+ if (!a) continue
15
+ if (a === '--pin') out.pin = true
16
+ else if (a === '--fresh') out.fresh = true
17
+ else if (a === '--fg') continue
18
+ else if (a === '--size' || a.startsWith('--size=')) {
19
+ const v = a === '--size' ? args[++i] : a.slice(7)
20
+ const m = /^(\d{2,5})x(\d{2,5})$/i.exec(v || '')
21
+ if (m) out.size = { width: +m[1], height: +m[2] }
22
+ } else if (a.startsWith('--') || a.startsWith('-psn_')) continue
23
+ else out.urls.push(a)
24
+ }
25
+ return out
26
+ }
27
+
28
+ module.exports = { parseArgs }
@@ -0,0 +1,64 @@
1
+ 'use strict'
2
+ const { Menu, MenuItem, clipboard } = require('electron')
3
+
4
+ function showPageMenu(ctx, tab, params) {
5
+ const wc = tab.wc
6
+ const nav = wc.navigationHistory
7
+ const f = params.editFlags
8
+ const items = []
9
+ const sep = () => items.length && items[items.length - 1].type !== 'separator' && items.push({ type: 'separator' })
10
+
11
+ if (params.linkURL) {
12
+ items.push({ label: 'Open Link in New Tab', click: () => ctx.tabs.create({ url: params.linkURL, activate: false, index: ctx.tabs.insertIndexAfterActive() }) })
13
+ items.push({ label: 'Copy Link Address', click: () => clipboard.writeText(params.linkURL) })
14
+ sep()
15
+ }
16
+ if (params.mediaType === 'image') {
17
+ items.push({ label: 'Copy Image', click: () => wc.copyImageAt(params.x, params.y) })
18
+ sep()
19
+ }
20
+ if (params.isEditable || params.selectionText) {
21
+ if (params.isEditable) items.push({ label: 'Cut', enabled: f.canCut, role: 'cut' })
22
+ items.push({ label: 'Copy', enabled: f.canCopy, role: 'copy' })
23
+ if (params.isEditable) items.push({ label: 'Paste', enabled: f.canPaste, role: 'paste' })
24
+ items.push({ label: 'Select All', enabled: f.canSelectAll, role: 'selectAll' })
25
+ sep()
26
+ }
27
+ if (!params.isEditable) {
28
+ items.push({ label: 'Back', enabled: nav.canGoBack(), click: () => nav.goBack() })
29
+ items.push({ label: 'Forward', enabled: nav.canGoForward(), click: () => nav.goForward() })
30
+ items.push({ label: 'Reload', click: () => wc.reload() })
31
+ sep()
32
+ if (!params.selectionText) items.push({ label: 'Select All', enabled: f.canSelectAll, role: 'selectAll' })
33
+ }
34
+ sep()
35
+ items.push({ label: 'Inspect Element', click: () => wc.inspectElement(params.x, params.y) })
36
+
37
+ const menu = Menu.buildFromTemplate(items)
38
+ if (ctx.ext) {
39
+ const extItems = ctx.ext.getContextMenuItems(wc, params)
40
+ if (extItems.length) {
41
+ menu.append(new MenuItem({ type: 'separator' }))
42
+ for (const i of extItems) menu.append(i)
43
+ }
44
+ }
45
+ menu.popup({ window: ctx.win })
46
+ }
47
+
48
+ function showTabMenu(ctx, id) {
49
+ const tab = ctx.tabs.get(id)
50
+ if (!tab) return
51
+ const i = ctx.tabs.list.indexOf(tab)
52
+ Menu.buildFromTemplate([
53
+ { label: 'Reload', click: () => tab.wc.reload() },
54
+ { label: 'Duplicate', click: () => ctx.tabs.duplicate(id) },
55
+ { label: tab.muted ? 'Unmute Tab' : 'Mute Tab', click: () => ctx.tabs.toggleMute(id) },
56
+ { type: 'separator' },
57
+ { label: 'Close Other Tabs', enabled: ctx.tabs.list.length > 1, click: () => ctx.tabs.closeOthers(id) },
58
+ { label: 'Close Tabs to the Right', enabled: i < ctx.tabs.list.length - 1, click: () => ctx.tabs.closeRight(id) },
59
+ { type: 'separator' },
60
+ { label: 'Close', click: () => ctx.tabs.close(id) },
61
+ ]).popup({ window: ctx.win })
62
+ }
63
+
64
+ module.exports = { showPageMenu, showTabMenu }
@@ -0,0 +1,61 @@
1
+ 'use strict'
2
+ const path = require('path')
3
+ const { ElectronChromeExtensions } = require('electron-chrome-extensions')
4
+ const { installChromeWebStore, installExtension, uninstallExtension } = require('electron-chrome-web-store')
5
+
6
+ const OKTA_ID = 'glnpjglilkicbckjpbgcfkogebgllemb'
7
+ const WEB_STORE_URL = 'https://chromewebstore.google.com/'
8
+
9
+ function createExtensions(ctx) {
10
+ const ext = new ElectronChromeExtensions({
11
+ session: ctx.session,
12
+ createTab: async (details) => {
13
+ const tab = ctx.tabs.create({ url: details.url, activate: details.active !== false, index: ctx.tabs.insertIndexAfterActive() })
14
+ return [tab.wc, ctx.win]
15
+ },
16
+ selectTab: (wc) => ctx.tabs.activate(wc.id),
17
+ removeTab: (wc) => ctx.tabs.close(wc.id),
18
+ })
19
+ // Registered after the library's preload (which the constructor above registers), so it runs
20
+ // second and can fill in constants on the chrome.* objects the library created.
21
+ const compat = path.join(__dirname, '..', 'preload', 'extension-compat.js')
22
+ ctx.session.registerPreloadScript({ id: 'stage-extension-compat-frame', type: 'frame', filePath: compat })
23
+ ctx.session.registerPreloadScript({ id: 'stage-extension-compat-sw', type: 'service-worker', filePath: compat })
24
+ // <browser-action-list> in the UI view loads icons over crx://
25
+ ElectronChromeExtensions.handleCRXProtocol(ctx.uiView.webContents.session)
26
+
27
+ ext.on('browser-action-popup-created', (popup) => {
28
+ const bw = popup.browserWindow
29
+ ctx.reveal.setPopupOpen(true)
30
+ if (!ctx.quitting) ctx.reveal.show()
31
+ const done = () => {
32
+ ctx.reveal.setPopupOpen(false)
33
+ if (!ctx.win.isDestroyed()) ctx.win.off('focus', onFocus)
34
+ }
35
+ // the library's own blur handling can miss when focus moves to a BaseWindow
36
+ const onFocus = () => !popup.isDestroyed() && popup.destroy()
37
+ ctx.win.on('focus', onFocus)
38
+ if (bw) bw.once('closed', done)
39
+ else done()
40
+ })
41
+ return ext
42
+ }
43
+
44
+ async function setupWebStore(ctx) {
45
+ await installChromeWebStore({ session: ctx.session })
46
+ }
47
+
48
+ function installed(ctx) {
49
+ const exts = ctx.session.extensions ? ctx.session.extensions.getAllExtensions() : ctx.session.getAllExtensions()
50
+ return exts.map((e) => ({ id: e.id, name: e.name, version: e.version }))
51
+ }
52
+
53
+ function install(ctx, id) {
54
+ return installExtension(id, { session: ctx.session })
55
+ }
56
+
57
+ function remove(ctx, id) {
58
+ return uninstallExtension(id, { session: ctx.session })
59
+ }
60
+
61
+ module.exports = { createExtensions, setupWebStore, installed, install, remove, OKTA_ID, WEB_STORE_URL }
@@ -0,0 +1,310 @@
1
+ 'use strict'
2
+ const path = require('path')
3
+ const fs = require('fs')
4
+ const { app, ipcMain, nativeImage, screen, session } = require('electron')
5
+
6
+ // ---- profile and identity: must happen before `ready` ----------------------
7
+ app.setName('Stage')
8
+ if (process.env.STAGE_SELFTEST && !process.env.STAGE_USER_DATA) {
9
+ process.env.STAGE_USER_DATA = fs.mkdtempSync(path.join(require('os').tmpdir(), 'stage-selftest-'))
10
+ }
11
+ app.setPath('userData', process.env.STAGE_USER_DATA || path.join(app.getPath('appData'), 'Stage'))
12
+
13
+ // Sites like Google and Okta reject "Electron" user agents as embedded browsers.
14
+ const cleanUA = (ua) => ua.replace(/\s(?:Electron|stage-browser|Stage)\/\S+/gi, '')
15
+ app.userAgentFallback = cleanUA(app.userAgentFallback)
16
+
17
+ const { parseArgs } = require('./cli-args')
18
+ const { resolveInput } = require('./url')
19
+ const store = require('./store')
20
+ const { createWindow, bgColor, BAR_HEIGHT } = require('./window')
21
+ const { Tabs } = require('./tabs')
22
+ const { Reveal } = require('./reveal')
23
+ const { suggest } = require('./suggest')
24
+ const { showTabMenu } = require('./context-menu')
25
+ const { installMenu } = require('./menu')
26
+ const extensions = require('./extensions')
27
+
28
+ const APP_ROOT = path.resolve(__dirname, '..', '..')
29
+ const SELFTEST = !!process.env.STAGE_SELFTEST
30
+ const log = (msg) => {
31
+ if (process.env.STAGE_LOG) {
32
+ try {
33
+ fs.appendFileSync(process.env.STAGE_LOG, msg + '\n')
34
+ } catch {}
35
+ }
36
+ }
37
+
38
+ // A modal error dialog in the middle of a live demo is worse than a lost click, so errors go
39
+ // to <userData>/stage.log instead. The selftest installs its own handler to record them.
40
+ if (!SELFTEST) {
41
+ const errorLog = path.join(app.getPath('userData'), 'stage.log')
42
+ const record = (kind) => (err) => {
43
+ const line = `${new Date().toISOString()} ${kind} ${(err && err.stack) || err}\n`
44
+ try {
45
+ if (fs.existsSync(errorLog) && fs.statSync(errorLog).size > 1_000_000) fs.truncateSync(errorLog, 0)
46
+ fs.appendFileSync(errorLog, line)
47
+ } catch {}
48
+ if (process.stderr.isTTY) process.stderr.write(line)
49
+ }
50
+ process.on('uncaughtException', record('uncaughtException'))
51
+ process.on('unhandledRejection', record('unhandledRejection'))
52
+ }
53
+
54
+ const ctx = {
55
+ session: null,
56
+ win: null,
57
+ uiView: null,
58
+ tabs: null,
59
+ reveal: null,
60
+ ext: null,
61
+ bar: { visible: false, pinned: false, hover: false },
62
+ overlay: null,
63
+ popupOpen: false,
64
+ quitting: false,
65
+ bgColor,
66
+ log,
67
+ }
68
+
69
+ if (!SELFTEST && !app.requestSingleInstanceLock()) {
70
+ app.exit(0)
71
+ }
72
+
73
+ // ---- state hub: coalesced pushes to the UI ------------------------------------
74
+ let pushTimer = null
75
+ let lastSent = ''
76
+ ctx.getState = () => ({
77
+ ...ctx.tabs.snapshot(),
78
+ bar: { visible: ctx.bar.visible, pinned: ctx.bar.pinned },
79
+ overlay: ctx.overlay,
80
+ barHeight: BAR_HEIGHT,
81
+ fullscreen: !!ctx.win && !ctx.win.isDestroyed() && ctx.win.isFullScreen(),
82
+ })
83
+ ctx.flush = () => {
84
+ clearTimeout(pushTimer)
85
+ pushTimer = null
86
+ if (ctx.quitting || !ctx.win || ctx.win.isDestroyed()) return
87
+ if (!ctx.uiView || ctx.uiView.webContents.isDestroyed() || ctx.uiView.webContents.isLoading()) return
88
+ const s = ctx.getState()
89
+ const j = JSON.stringify(s)
90
+ if (j === lastSent) return
91
+ lastSent = j
92
+ ctx.uiView.webContents.send('stage:state', s)
93
+ }
94
+ ctx.push = () => {
95
+ if (pushTimer || ctx.quitting) return
96
+ pushTimer = setTimeout(ctx.flush, 16)
97
+ }
98
+
99
+ // ---- session persistence ---------------------------------------------------------
100
+ let saveTimer = null
101
+ const writeSession = () => {
102
+ if (ctx.quitting || !ctx.tabs || !ctx.win || ctx.win.isDestroyed()) return
103
+ const urls = ctx.tabs.list.map((t) => t.url)
104
+ const active = Math.max(0, ctx.tabs.list.findIndex((t) => t.id === ctx.tabs.activeId))
105
+ const prev = store.readJson('session.json', {})
106
+ const bounds = ctx.win.isFullScreen() || ctx.win.isMinimized() ? prev.bounds : ctx.win.getBounds()
107
+ store.writeJson('session.json', { tabs: urls, active, pinned: ctx.bar.pinned, bounds })
108
+ }
109
+ ctx.saveSession = () => {
110
+ if (ctx.quitting || !ctx.win || ctx.win.isDestroyed()) return
111
+ clearTimeout(saveTimer)
112
+ saveTimer = setTimeout(writeSession, 500)
113
+ }
114
+
115
+ // Stop every timer so nothing touches the window after teardown begins.
116
+ ctx.teardown = () => {
117
+ ctx.quitting = true
118
+ clearTimeout(pushTimer)
119
+ pushTimer = null
120
+ clearTimeout(saveTimer)
121
+ saveTimer = null
122
+ endDrag()
123
+ if (ctx.reveal) ctx.reveal.stop()
124
+ }
125
+
126
+ // ---- args ------------------------------------------------------------------------
127
+ function applyArgs(args, { initial = false } = {}) {
128
+ log('args ' + JSON.stringify(args))
129
+ if (args.size) {
130
+ ctx.win.setContentSize(args.size.width, args.size.height)
131
+ ctx.win.center()
132
+ }
133
+ if (args.pin) ctx.reveal.setPinned(true)
134
+ const urls = args.urls.map(resolveInput).filter(Boolean)
135
+ urls.forEach((u, i) => {
136
+ // initial launch keeps the first tab active; later invocations jump to the newest
137
+ ctx.tabs.create({ url: u, activate: initial ? i === 0 : i === urls.length - 1 })
138
+ })
139
+ }
140
+
141
+ // ---- downloads -----------------------------------------------------------------
142
+ function setupDownloads() {
143
+ ctx.session.on('will-download', (_e, item) => {
144
+ const dir = app.getPath('downloads')
145
+ const ext = path.extname(item.getFilename())
146
+ const base = path.basename(item.getFilename(), ext)
147
+ let target = path.join(dir, item.getFilename())
148
+ for (let n = 1; fs.existsSync(target); n++) target = path.join(dir, `${base} (${n})${ext}`)
149
+ item.setSavePath(target)
150
+ item.once('done', (_ev, state) => {
151
+ if (state === 'completed' && app.dock) app.dock.downloadFinished(target)
152
+ })
153
+ })
154
+ }
155
+
156
+ // ---- IPC -------------------------------------------------------------------------
157
+ let endDrag = () => {}
158
+ function setupIpc() {
159
+ const fromUI = (e) => ctx.uiView && e.sender === ctx.uiView.webContents
160
+ const on = (ch, fn) => ipcMain.on(ch, (e, ...a) => fromUI(e) && fn(...a))
161
+ ipcMain.handle('stage:getState', (e) => (fromUI(e) ? ctx.getState() : null))
162
+ ipcMain.handle('stage:suggest', (e, q) => (fromUI(e) ? suggest(ctx, q) : []))
163
+
164
+ on('stage:activateTab', (id) => ctx.tabs.activate(id))
165
+ on('stage:closeTab', (id) => ctx.tabs.close(id))
166
+ on('stage:moveTab', (id, i) => ctx.tabs.move(id, i))
167
+ on('stage:showTabMenu', (id) => showTabMenu(ctx, id))
168
+ on('stage:openOmnibox', (mode) => ctx.reveal.openOverlay(mode === 'edit' ? 'edit' : 'new', mode === 'edit' && ctx.tabs.active ? ctx.tabs.active.url : ''))
169
+ on('stage:closeOverlay', () => ctx.reveal.closeOverlay())
170
+ on('stage:submitOmnibox', (input, opts) => {
171
+ const url = resolveInput(input)
172
+ ctx.reveal.closeOverlay(false)
173
+ if (url) ctx.tabs.open(url, { newTab: !!(opts && opts.newTab) })
174
+ ctx.tabs.focusActive()
175
+ })
176
+ on('stage:back', () => ctx.tabs.active && ctx.tabs.active.wc.navigationHistory.goBack())
177
+ on('stage:forward', () => ctx.tabs.active && ctx.tabs.active.wc.navigationHistory.goForward())
178
+ on('stage:reload', () => ctx.tabs.active && ctx.tabs.active.wc.reload())
179
+ on('stage:setPinned', (p) => ctx.reveal.setPinned(!!p))
180
+ on('stage:setBarHover', (h) => ctx.reveal.setHover(h))
181
+
182
+ // Window drag fallback: move the window by the cursor delta while the UI holds the mouse down.
183
+ let drag = null
184
+ endDrag = () => {
185
+ if (drag) clearInterval(drag.timer)
186
+ drag = null
187
+ }
188
+ on('stage:startWindowDrag', () => {
189
+ if (drag || ctx.win.isFullScreen()) return
190
+ const p0 = screen.getCursorScreenPoint()
191
+ const [x0, y0] = ctx.win.getPosition()
192
+ const started = Date.now()
193
+ drag = {
194
+ timer: setInterval(() => {
195
+ if (Date.now() - started > 60000) return endDrag()
196
+ if (ctx.win.isDestroyed()) return endDrag()
197
+ const p = screen.getCursorScreenPoint()
198
+ ctx.win.setPosition(x0 + p.x - p0.x, y0 + p.y - p0.y)
199
+ }, 8),
200
+ }
201
+ })
202
+ on('stage:endWindowDrag', endDrag)
203
+ }
204
+
205
+ // ---- boot --------------------------------------------------------------------------
206
+ async function boot() {
207
+ ctx.session = session.fromPartition('persist:stage')
208
+ ctx.session.setUserAgent(cleanUA(ctx.session.getUserAgent()))
209
+ setupDownloads()
210
+
211
+ const args = parseArgs(process.argv, APP_ROOT)
212
+ if (SELFTEST) {
213
+ args.fresh = true
214
+ args.urls = []
215
+ args.size = null
216
+ args.pin = false
217
+ }
218
+ const saved = args.fresh ? {} : store.readJson('session.json', {})
219
+
220
+ if (app.dock) {
221
+ const icon = path.join(__dirname, '..', '..', 'build', 'icon.png')
222
+ if (fs.existsSync(icon)) app.dock.setIcon(nativeImage.createFromPath(icon))
223
+ }
224
+
225
+ createWindow(ctx, saved.bounds, args.size)
226
+ ctx.bar.pinned = !!saved.pinned || args.pin
227
+ ctx.tabs = new Tabs(ctx)
228
+ ctx.reveal = new Reveal(ctx)
229
+ ctx.ext = extensions.createExtensions(ctx)
230
+ setupIpc()
231
+ installMenu(ctx)
232
+
233
+ const { win, uiView } = ctx
234
+ uiView.webContents.on('did-finish-load', () => {
235
+ lastSent = ''
236
+ ctx.flush()
237
+ })
238
+ uiView.webContents.loadFile(path.join(__dirname, '..', 'ui', 'index.html')).catch((e) => console.error('[stage] UI load failed', e.message))
239
+
240
+ const relayout = () => {
241
+ if (ctx.quitting) return
242
+ ctx.layout()
243
+ ctx.push()
244
+ }
245
+ win.on('resize', () => {
246
+ relayout()
247
+ ctx.saveSession()
248
+ })
249
+ win.on('move', ctx.saveSession)
250
+ win.on('enter-full-screen', relayout)
251
+ win.on('leave-full-screen', relayout)
252
+ win.on('close', () => {
253
+ writeSession()
254
+ store.flushHistory()
255
+ ctx.teardown()
256
+ })
257
+ win.on('closed', () => !ctx.holdQuit && app.quit())
258
+ ctx.layout()
259
+
260
+ // Load installed extensions before the first page so content scripts attach to it.
261
+ await Promise.race([extensions.setupWebStore(ctx).catch((e) => console.error('[stage] web store setup failed', e.message)), new Promise((r) => setTimeout(r, 5000))])
262
+ ctx.rebuildMenu()
263
+
264
+ win.show()
265
+ ctx.reveal.syncPolling()
266
+ if (ctx.bar.pinned) {
267
+ ctx.reveal.show()
268
+ ctx.rebuildMenu()
269
+ }
270
+
271
+ if (SELFTEST) {
272
+ require('./selftest').run(ctx)
273
+ return
274
+ }
275
+
276
+ const first = args.urls.map(resolveInput).filter(Boolean)
277
+ if (first.length) {
278
+ applyArgs({ ...args, pin: false, size: null }, { initial: true })
279
+ } else if (saved.tabs && saved.tabs.length) {
280
+ saved.tabs.forEach((u, i) => ctx.tabs.create(u ? { url: u, activate: false } : { activate: false }))
281
+ ctx.tabs.activate(ctx.tabs.list[Math.min(saved.active || 0, ctx.tabs.list.length - 1)].id)
282
+ } else {
283
+ ctx.tabs.create({})
284
+ }
285
+ log('ready tabs=' + ctx.tabs.list.length)
286
+ }
287
+
288
+ app.on('second-instance', (_e, argv) => {
289
+ if (!ctx.win || ctx.win.isDestroyed()) return
290
+ if (ctx.win.isMinimized()) ctx.win.restore()
291
+ ctx.win.show()
292
+ ctx.win.focus()
293
+ app.focus({ steal: true })
294
+ applyArgs(parseArgs(argv, APP_ROOT))
295
+ })
296
+
297
+ app.on('before-quit', () => {
298
+ writeSession()
299
+ store.flushHistory()
300
+ ctx.teardown()
301
+ })
302
+
303
+ app.on('window-all-closed', () => !ctx.holdQuit && app.quit())
304
+
305
+ app.whenReady().then(boot).catch((e) => {
306
+ console.error('[stage] boot failed', e)
307
+ app.exit(1)
308
+ })
309
+
310
+ module.exports = ctx