// ccdeck desktop (#1160): the deck in a window, a tray icon that says what the // favicon says, and notifications under ccdeck's own name. // // THE RULE THE WHOLE SHELL KEEPS: a window open is a tab open. While it is, // the page plays its sounds and the deck counts it as somebody looking. Close // it and the window is destroyed — not hidden — so the deck sees no page and // raises its closed-deck notifications, which reach this app over the tray // stream and are shown as ccdeck. Hiding instead would keep the page alive, // the deck would go on believing somebody was looking, and nothing would ever // be said (the choice made in #1160, decision 2). // // The tray icon is the favicon of a closed tab: the same four states and the // same count, computed by the page's own reducer (src/web/tray-model.ts, // bundled to dist/lib by vite.tray.config.mjs) over the same event stream. Both // wear the brand kit's mark with the kit's overlay for the state, on one map // (idle → default, waiting → waiting, running → syncing, offline → error) — // the tray in each platform's own kit images, which scripts/icons.mjs copies // into dist/icons and tray-icon.mjs names. import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, Notification, screen, shell, Tray } from "electron"; import { appendFileSync, existsSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { deckJson, findDecks, openTrayStream, restartAsked } from "./deck-link.mjs"; import { shellEnv, startDeck, withShellSettings, writeLauncher } from "./deck-host.mjs"; import { deckOrigin, navigationFor, originToFollow } from "./nav.mjs"; import { overFullScreen, windowsOnScreen } from "./fullscreen-space.mjs"; import { canInstallQuietly, idleSinceNext, isFresh, POSTPONE_MS, quietSinceNext } from "./auto-update.mjs"; import { createUpdater } from "./updater.mjs"; import { shouldOfferReadyUpdate } from "./update-notice.mjs"; import { matchesReadyUpdate, restartReadyUpdate } from "./window-update.mjs"; import { createNotificationAudioStore } from "./notification-audio-store.mjs"; import { createDesktopState } from "./desktop-state.mjs"; import { statusLine, statusWorthAsking, trayMenuItems } from "./tray-menu.mjs"; import { createMenuSwap } from "./tray-menu-swap.mjs"; import { canRestartForTray, MISSES_BEFORE_RESTART, screenLockedNow, selfRestartHeld, trayCheck, trayMissesNext, trayOutcomeNext, watcherOnBusNow } from "./tray-presence.mjs"; import { restartApp } from "./relaunch-linux.mjs"; import { openAtLogin, replaceNpmLoginItem, setOpenAtLogin } from "./login-item.mjs"; import { createOwnDeck, discoverPlan, startOwnDeck, stopChild } from "./own-deck.mjs"; import { trayIconFile } from "./tray-icon.mjs"; import { windowChrome, titlebarColors, TITLEBAR_HEIGHT } from "./window-chrome.mjs"; import { WINDOW_MIN, windowPlaceToKeep, windowPlaceToOpen } from "./window-place.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const icons = join(here, "dist", "icons"); const APP_ID = "dev.ccdeck.app"; /** Where the deck's own files are: the repo root in development, the copy * packed into the app's resources once it is built. CCDECK_DECK_ROOT points a * built app at a checkout, for testing one against the other. */ function deckRoot() { if (process.env.CCDECK_DECK_ROOT) return process.env.CCDECK_DECK_ROOT; return app.isPackaged ? join(process.resourcesPath, "deck") : join(here, ".."); } /** * The login shell's PATH and the documented variables it sets (deck-host.mjs), * read once per run of the app. * * ONTO THIS PROCESS'S OWN ENVIRONMENT, and before the first look for a deck: * findDecks reads the registry CLAUDE_CONFIG_DIR names, writeLauncher writes * the hook's launcher beside it, and the deck this app starts inherits the * rest — AGENTS_DECK_NO_REPORTS among them. An app opened from the Dock has * none of them otherwise. */ let loginShell = null; function fromLoginShell() { if (!loginShell) { loginShell = shellEnv(); withShellSettings(process.env, loginShell); } return loginShell; } // ── one app per machine ───────────────────────────────────────────────────── // The copy that finds one already running has handed it its launch by the // time the lock is refused — "second-instance" opens that one's window — and // only has to leave. It must start nothing on the way: quitting before ready // does not stop `ready` from firing, and a startup run here drew a tray icon // of its own that the panel showed as "…" until the copy was gone (#1725). const primary = app.requestSingleInstanceLock(); if (!primary) { app.quit(); } else { app.on("second-instance", () => openWindow()); } app.setAppUserModelId(APP_ID); // ── state ─────────────────────────────────────────────────────────────────── let tray = null; let win = null; let windowOrigin = null; // the deck origin the window shows, which its handlers hold links to let deck = null; // { pid, port, token, version } let stream = null; let model = null; // TrayModel from dist/lib/tray-model.mjs let chimeFiles = {}; // CHIME_FILES from dist/lib/chime-wav.mjs let snapshot = { icon: "offline", waiting: 0, running: 0, title: "ccdeck", blocked: [] }; let notifyOn = null; // the deck's own switch, read from /api/prefs let providerStatus = null; // the deck's last /api/provider-status answer (#1311) let incidentsOf = null; // the page's reading of it, from dist/lib/provider-status.mjs let safeStatusPage = null; // and the page's rule for which links are status pages let redraw = null; let menuSwap = null; // tray-menu-swap.mjs, once the tray exists const ownDeck = createOwnDeck(); // the deck process this app started, if it did let starting = null; // the start in flight, so two clicks start one deck let startFailed = null; // why the app's own deck did not start, until a deck answers let sayingStartFailed = false; let restarting = null; // since when a restart has been asked for, until a new deck answers let updater = null; // updater.mjs, created once the app is ready let quietSince = null; // since when the window is unfocused and no deck is starting (#1187) let idleSince = null; // since when no agent is working or waiting let behindSince = null; // since when an update has been ready, in this process let postponedUntil = null; // until when "Later" holds the quiet install off let updateNoticeVersion = null; // last version whose ready notice was shown (#1182) let updateNoticePrompting = false; let asking = 0; // questions from ask() on screen now // ── the tray ──────────────────────────────────────────────────────────────── function trayImage(icon) { return nativeImage.createFromPath(join(icons, trayIconFile(process.platform, icon))); } /** The menu's template for the state the app is in now — see tray-menu.mjs, * which owns its rows, and tray-menu-swap.mjs, which decides when the tray * is handed a new one. What each row does is below, and reads this file's * variables when it is clicked rather than when the menu was drawn. */ function buildMenu() { return trayMenuItems({ now: Date.now(), snapshot, deck, starting, restarting, startFailed, notifyOn, openAtLogin: openAtLogin(loginItemOptions()), appVersion: app.getVersion(), update: updater?.state ?? { status: "idle" }, updateAsksPassword: !!updater && !updater.canInstallUnattended(), // Read against now, so an answer held past its expiry leaves the menu on // the next redraw rather than at the next ask. incidents: incidentsOf?.(providerStatus, Date.now()) ?? [], }, TRAY_ACTIONS); } const TRAY_ACTIONS = { openWindow: () => openWindow(), // Only for a deck that came up: openWindow with none starts another. startDeck: () => ensureDeck().then(found => { if (found) openWindow(); }).catch(err => trace(`start failed: ${err?.message ?? err}`)), openInBrowser: () => deck && shell.openExternal(`http://127.0.0.1:${deck.port}/`), toggleNotifications: () => toggleNotifications(), setOpenAtLogin: checked => { if (!setOpenAtLogin(checked, loginItemOptions())) trace(`could not ${checked ? "set" : "clear"} start at login`); scheduleRedraw(); }, restartToUpdate: () => updater.restartNow(), checkForUpdates: () => updater?.check(), restartDeck: () => restartDeck(), // incidentsOf has already held the link to https on one of the two status // hosts, and it is asked again here, at the one call that hands a URL to the // operating system: two checks in two files cost nothing, and this one is // beside the call it guards. openStatusPage: href => { if (safeStatusPage?.(href)) shell.openExternal(href); }, quit: () => app.quit(), }; /** What login-item.mjs needs to register this app: the binary, and for a * development run the app's directory after it, or Electron would start its * own default app at login. */ function loginItemOptions() { return { platform: process.platform, app, execPath: process.execPath, args: app.isPackaged ? [] : [app.getAppPath()], env: process.env }; } /** Redraw the icon, the count, the tooltip and the menu — coalesced, because * a reconnect replays up to two thousand events and each one changes the * board. */ function scheduleRedraw() { if (redraw) return; redraw = setTimeout(() => { redraw = null; if (model) snapshot = model.snapshot(); offerReadyUpdate(); if (!tray) return; tray.setImage(trayImage(snapshot.icon)); // macOS draws text beside a menu-bar icon; nowhere else can. if (process.platform === "darwin") tray.setTitle(snapshot.waiting > 0 ? ` ${snapshot.waiting}` : ""); tray.setToolTip(`${snapshot.title} — ${statusLine({ restarting, starting, deck, snapshot, startFailed })}`); // Only when what it says has changed, and not while it is open: a new // menu closes the one somebody is reading (tray-menu-swap.mjs). menuSwap?.refresh(); }, 150); } /** * Linux: every half minute, ask the panel whether it still holds this app's * icon (#1630). A registration that fails once leaves the app with an icon * only it can see for as long as it runs, and only a new process registers * again — so a lost icon is counted here, and updateWhenQuiet restarts the app * at its next quiet spell. The same checks note whether the panel's watcher * has been seen on the bus, which is what holds every restart the app makes * by itself while the screen is locked (panelAway). See tray-presence.mjs. */ let trayMisses = 0; let trayRestartAt = null; // the last restart for the icon's sake, from desktop-state.json let trayRestartOutcomeSaid; // what it came to: tray-presence.mjs trayRestartOutcome, or "pending" let trayOutcomeToRead = false; // this process is the one that restart started let trayWatcherSeen = false; // the watcher has been on the bus in this run let trayWatcherLast = null; // and whether it was at the last check let trayStartedWithWatcher = null; let leaving = false; // a restart the app made by itself is under way function watchTray() { if (process.platform !== "linux") return; const state = desktopState.read(); trayRestartAt = state.trayRestartAt ?? null; // 3.32.1 wrote whether the icon was back as a boolean; false was a restart // not read yet. trayRestartOutcomeSaid = state.trayRestartOutcome ?? (state.trayBackAfterRestart === true ? "back" : state.trayBackAfterRestart === false ? "pending" : undefined); trayOutcomeToRead = trayRestartOutcomeSaid === "pending"; // Asked as the tray is made: whether this process had a watcher to register // with, which tells a restart that failed from one the lock screen explains. trayCheck().then(({ watcher }) => { trayStartedWithWatcher = watcher; trayWatcherLast = watcher; if (watcher) trayWatcherSeen = true; }); setInterval(async () => { if (leaving || quitting) return; const { watcher, registered } = await trayCheck(); if (watcher) trayWatcherSeen = true; // Back after a locked screen: the quiet is measured from here, so the app // does not restart in the first seconds of somebody sitting down again. if (watcher === true && trayWatcherLast === false) quietSince = null; trayWatcherLast = watcher; const before = trayMisses; trayMisses = trayMissesNext(trayMisses, registered); if (before < MISSES_BEFORE_RESTART && trayMisses >= MISSES_BEFORE_RESTART) { trace("the panel holds no tray icon of this app's; restarting at the next quiet spell"); } const outcome = trayOutcomeNext({ said: trayRestartOutcomeSaid, toRead: trayOutcomeToRead, startedWithWatcher: trayStartedWithWatcher, registered }); if (outcome) { try { desktopState.merge({ trayRestartOutcome: outcome, trayBackAfterRestart: undefined }); trayRestartOutcomeSaid = outcome; trayOutcomeToRead = false; trace(`the restart for the tray icon came to: ${outcome}`); } catch { /* read again at the next check */ } } }, 30_000); } /** * Linux: has the panel that shows tray icons gone from the bus, under a locked * screen, since this app saw it? GNOME takes it away while the screen is * locked, and a version started then never shows its icon — so no restart the * app makes by itself goes ahead until it is back. Asked of the bus at the * moment of restarting; the lock only when the watcher is gone. */ function panelAway() { if (process.platform !== "linux" || !trayWatcherSeen) return false; const watcherNow = watcherOnBusNow(); return selfRestartHeld({ watcherSeen: trayWatcherSeen, watcherNow, locked: watcherNow === false ? screenLockedNow() : null }); } // ── the deck ──────────────────────────────────────────────────────────────── /** The page's own code, bundled into dist/lib by vite.tray.config.mjs: the * board the tray counts with, and the names the tones were written under. */ async function loadModel() { const { createTrayModel } = await import(pathToFileURL(join(here, "dist", "lib", "tray-model.mjs")).href); model = createTrayModel(); ({ CHIME_FILES: chimeFiles } = await import(pathToFileURL(join(here, "dist", "lib", "chime-wav.mjs")).href)); ({ incidentsOf, safeStatusPage } = await import(pathToFileURL(join(here, "dist", "lib", "provider-status.mjs")).href)); } async function refreshPrefs() { if (!deck) { notifyOn = null; return; } try { const { json } = await deckJson(deck, "/api/prefs"); notifyOn = json?.prefs?.notifications === true; } catch { notifyOn = null; } scheduleRedraw(); } /** What the status pages say, asked of the deck (#1311), which reads them at * most once every three minutes whoever asks. Twelve seconds: the deck may * have to read a page first, and a page read has eight of its own. */ async function refreshProviderStatus() { const asked = deck; if (!asked) return; try { const { json } = await deckJson(asked, "/api/provider-status", { timeoutMs: 12_000 }); // Only for the deck it was asked of: a restart can land while this is out, // and attach() has cleared the old deck's answer for a reason. if (json?.ok && asked === deck) providerStatus = json; } catch { /* the last answer stays, and incidentsOf expires it by its own clock */ } scheduleRedraw(); } async function toggleNotifications() { if (!deck || notifyOn === null) return; try { const { json } = await deckJson(deck, "/api/prefs", { method: "POST", body: { notifications: !notifyOn } }); notifyOn = json?.prefs?.notifications === true; } catch { /* the menu keeps saying what the file says */ } scheduleRedraw(); } /** Attach to a deck, or to a different one than before (a restart gives a new * pid and a new token). */ function attach(found) { if (deck && found && deck.pid === found.pid && deck.token === found.token) return; // A different deck answering is the restart having landed, and a start that // failed before it is not what the tray has to say any more. if (found && restarting) restarting = null; if (found) startFailed = null; stream?.close(); stream = null; deck = found ?? null; // A deck on another port: an open window goes with it, or it would go on // retrying a port nobody listens on (originToFollow). const moveTo = win && !win.isDestroyed() ? originToFollow(windowOrigin, deck) : null; if (moveTo) { trace(`window follows the deck to ${moveTo}`); windowOrigin = moveTo; win.loadURL(`${moveTo}/`); } // Another deck's answer is not this one's, and no deck has none. providerStatus = null; model?.reset(); model?.setConnected(false); scheduleRedraw(); if (!deck) return; stream = openTrayStream(deck, { connected: () => { model.reset(); model.setConnected(true); scheduleRedraw(); }, hook: env => { model.apply(env); scheduleRedraw(); }, live: () => { refreshPrefs(); publishUpdateState(); refreshProviderStatus(); }, notify: n => showNotification(n), restartUpdate: request => { const version = request?.version; if (restartReadyUpdate(updater, version)) trace(`window requested verified update ${version}`); else trace(`ignored window update request ${version ?? "without a version"}`); }, // The window's dialog has put this version's Restart to update in front // of the person, which is the one notice a version gets (#1182). Without // this the native sheet still owed its own, and arrived on top of the // window's offer, or after the person had already closed it, to ask the // same question a second time. checkUpdate: () => { void updater?.check().then(() => publishUpdateState()).catch(() => publishUpdateState()); }, updateSeen: request => { if (matchesReadyUpdate(updater, request?.version)) rememberUpdateNotice(updater.state.version); }, lost: () => { model.setConnected(false); scheduleRedraw(); discoverSoon(); }, }); } function publishUpdateState() { if (!deck || !updater) return; const { status, version = null } = updater.state; deckJson(deck, "/api/desktop-update", { method: "POST", body: { status, version, canCheck: true } }) .catch(err => trace(`could not publish update state: ${err?.message ?? err}`)); } /** * A deck to attach to: the running one if there is one — started by * `npx ccdeck`, a login item, or this app last time — otherwise one of this * app's own. Waits for the new deck's discovery file, which it writes once it * is listening. */ async function ensureDeck() { await discover({ willStart: true }); if (deck) return deck; if (starting) return starting; starting = (async () => { startFailed = null; scheduleRedraw(); const logFile = join(app.getPath("logs"), "deck-app.log"); // The wait ends when the deck exits, and a start that throws is a failed // start rather than a rejection — see startOwnDeck. const started = await startOwnDeck({ logFile, start: exited => { const launcher = writeLauncher(process.execPath); ownDeck.track(startDeck({ deckRoot: deckRoot(), appBinary: process.execPath, logFile, path: fromLoginShell().PATH, launcher, }), (code, signal) => { trace(`own deck exited ${code}`); discoverSoon(); exited(code, signal); }); }, look: () => discover(), found: () => !!deck, }); if (!started.ok && started.reason) { startFailed = started.reason; trace(`own deck did not start: ${started.reason.replace(/\n/g, " | ")}`); sayStartFailed(started.reason, logFile); } return deck; })(); try { return await starting; } finally { starting = null; scheduleRedraw(); } } /** * Why the app's own deck did not start, in front of the person: in a terminal * the deck prints it where it stopped, and an app started from the Dock or at * login has nowhere else to say it. One at a time — a second failed start * while this is still up has the same reason. */ async function sayStartFailed(reason, logFile) { if (sayingStartFailed) return; sayingStartFailed = true; try { const { response } = await ask({ type: "error", message: "The deck could not start", detail: `${reason}\n\nThe deck's log is ${logFile}`, buttons: ["OK", "Show the log"], defaultId: 0, cancelId: 0, }); if (response === 1) shell.showItemInFolder(logFile); } catch (err) { trace(`could not say why the deck did not start: ${err?.message ?? err}`); } finally { sayingStartFailed = false; } } /** * Restart the deck (#1163) through the same route the page's own Restart uses, * so its supervisor brings the new one up on the same port and the tray simply * reattaches when the stream comes back. A deck that cannot restart itself — * unsupervised, with no log to replay, or hung and not answering — and was * started by this app is stopped and started again instead; one that belongs to a terminal is left * alone, and the menu says it could not. */ async function restartDeck() { if (!deck || restarting) return; // A RESTART THIS APP IS ALREADY DOING IS THE CHEAPEST MOMENT TO UPDATE // (#1187). The person asked for the deck to go down and come back; taking // the app through the same second, into the version already verified and // staged, costs them nothing more and saves the trip through the menu — // unless the install asks for a password (#1755), which is more than a // restart of the deck asked for. if (updater?.state.status === "ready" && updater.canInstallUnattended()) { trace(`restart takes the staged update ${updater.state.version}`); updater.restartNow(); return; } restarting = Date.now(); scheduleRedraw(); let asked; try { asked = restartAsked(await deckJson(deck, "/api/restart", { method: "POST", body: {}, timeoutMs: 5000 })); } catch (err) { // The socket going away mid-answer is the restart; no answer at all is a // deck that is hung (#1782), and the app's own is stopped below. asked = restartAsked(err); } if (!asked && ownDeck.current()) { await stopOwnDeck(); attach(null); await ensureDeck(); } if (!asked && !ownDeck.current()) restarting = null; // A restart that never lands is not left saying it is happening. setTimeout(() => { if (restarting && Date.now() - restarting >= 30_000) { restarting = null; scheduleRedraw(); } }, 30_000); discoverSoon(1500); scheduleRedraw(); } /** Stop the deck this app started, and only that one: a deck from a terminal * or a login item is somebody else's, and outlives the app. */ async function stopOwnDeck() { const child = ownDeck.current(); if (!child) return; try { if (deck) await deckJson(deck, "/api/shutdown", { method: "POST", body: {}, timeoutMs: 3000 }); } catch { /* asked; the kill below is the fallback */ } await stopChild(child); } /** The version of the deck packed into this app. */ function bundledDeckVersion() { try { return JSON.parse(readFileSync(join(deckRoot(), "package.json"), "utf8")).version ?? ""; } catch { return ""; } } /** * Attach to the running deck — unless it is OLDER than the one this app * carries and `willStart` says the app's own deck starts next (ensureDeck), in * which case it is replaced, exactly as a newer `ccdeck` started in a terminal * replaces an older running one (running-deck.mjs `olderVersion`, the rule * `secondStart` uses). An older deck may not know the tray connection at all, * and would count the app as a page open forever — the notifications the app * exists to deliver would never come. Every other look attaches to it rather * than leave the machine with no deck (#1783) — see discoverPlan. */ async function discover({ willStart = false } = {}) { try { fromLoginShell(); const decks = await findDecks(deckRoot()); const found = decks[0] ?? null; const { olderVersion } = await import(pathToFileURL(join(deckRoot(), "src", "server", "running-deck.mjs")).href); const ours = bundledDeckVersion(); if (discoverPlan({ found, ours, ownDeck: ownDeck.current(), starting, willStart, olderVersion }) === "replace") { trace(`replacing an older deck (${found.version || "unversioned"} on ${found.port}) with this app's ${ours}`); await deckJson(found, "/api/shutdown", { method: "POST", body: {}, timeoutMs: 3000 }).catch(() => {}); // Until it has let go of its port, so the app's deck gets 4317 rather // than a random one beside it. for (let i = 0; i < 24; i++) { if (!(await findDecks(deckRoot())).some(d => d.pid === found.pid)) break; await new Promise(r => setTimeout(r, 250)); } attach(null); return; } attach(found); } catch { attach(null); } } let discovering = null; function discoverSoon(ms = 2000) { if (discovering) return; discovering = setTimeout(async () => { discovering = null; await discover(); }, ms); } // ── notifications ─────────────────────────────────────────────────────────── /** The tone the page would have played, as the sound the notification makes: * a file in the app's Resources on macOS (scripts/chimes.mjs). Windows and * Linux take no custom sound for an unpackaged app's notification, so there it * is the system's own. * * Named by CHIME_FILES, the list scripts/chimes.mjs wrote those files under, * rather than by a copy of it: a copy that drifted would name a sound macOS * cannot find, and the notification would arrive in silence. Loaded with the * tray model, before any deck can ask for a notification. */ function showNotification({ title, body, chime, silent }) { if (!Notification.isSupported()) return; // Quiet when the deck says so — the account notifications, which are // operational news rather than a tone standing in for one — and otherwise as // before: with no file to name, Electron plays the system's default sound. const quiet = silent === true; const sound = process.platform === "darwin" ? chimeFiles[chime] : undefined; const n = new Notification({ title: String(title ?? "ccdeck"), body: String(body ?? ""), sound: quiet ? undefined : sound, silent: quiet }); n.on("click", () => openWindow()); n.show(); } // ── the window ────────────────────────────────────────────────────────────── /** macOS: a menu-bar app with no window (no Dock tile, not in Cmd+Tab), and an * ordinary app while its window is open — so the window orders, hides and * switches like every other app's. Switched here rather than declared with * LSUIElement: an app that declared itself an agent and then turned regular * kept its window in front of the app the person had just clicked. */ function setRegular(regular) { if (process.platform !== "darwin") return; app.setActivationPolicy(regular ? "regular" : "accessory"); } /** A line to ~/Library/Logs/ccdeck-desktop.log, for the window behaviour that * only shows on a real desktop. */ function trace(line) { try { appendFileSync(join(app.getPath("logs"), "ccdeck-desktop.log"), `${new Date().toISOString()} ${line}\n`); } catch { /* a log that cannot be written is not worth failing over */ } } /** @param {boolean} steal Whether to pull OS-level activation to this app on * top of showing the window — only for a person's own gesture (a tray click, * a Dock reactivation, a second launch, a notification). The one caller that * is not that is startup's own `if (deck) openWindow()`: an app relaunching * itself after a quiet auto-update, or restored at login, opens with nobody * having asked for it, and had no business pulling a person out of a * fullscreen browser Space to do it (#1214). */ function openWindow(steal = true, customChrome = true) { if (!deck) { ensureDeck().then(found => { if (found) openWindow(steal); }).catch(err => trace(`start failed: ${err?.message ?? err}`)); return; } if (win && !win.isDestroyed()) { if (win.isMinimized()) win.restore(); win.show(); win.focus(); offerReadyUpdate(); return; } // Kept where both handlers below read it when they are asked, rather than // copied into them: attach() moves it when the deck moves to another port. windowOrigin = deckOrigin(deck.port); // The way the last window was when it closed (#2466, window-place.mjs). const place = windowPlaceToOpen(desktopState.read().window, screen.getAllDisplays().map(d => d.workArea)); // On macOS full screen is a Space of its own, and entering it takes the // person there: only when they opened the window themselves (#1214). const fullScreen = place.fullScreen && (steal || process.platform !== "darwin"); win = new BrowserWindow({ ...place.bounds, minWidth: WINDOW_MIN.width, minHeight: WINDOW_MIN.height, title: "ccdeck", ...(customChrome ? windowChrome(process.platform) : {}), backgroundColor: "#1f1f1f", show: false, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true, preload: join(here, "preload.cjs"), additionalArguments: customChrome ? [] : ["--ccdeck-native-chrome"], // The page's chimes: in a browser they wait for the first click to // unlock audio. An app the person opened on purpose need not. autoplayPolicy: "no-user-gesture-required", }, }); if (customChrome && process.platform !== "darwin") win.setMenuBarVisibility(false); // Anything that leaves the deck opens in the person's own browser — a // login flow, a docs link — never inside this window, and anything that is // not a web page is not opened at all (nav.mjs). win.webContents.setWindowOpenHandler(({ url }) => { if (navigationFor(url, windowOrigin) !== "block") shell.openExternal(url); return { action: "deny" }; }); win.webContents.on("will-navigate", (event, url) => { const where = navigationFor(url, windowOrigin); if (where === "stay") return; event.preventDefault(); if (where === "external") shell.openExternal(url); }); const created = win; let shown = false; win.once("ready-to-show", async () => { // The app can attach to an older npm deck. Keep its native frame when that // page has no caption strip, so its toolbar remains clear and draggable. if (customChrome) { if (created.webContents.isLoading()) { await new Promise(resolve => created.webContents.once("did-finish-load", resolve)); } if (created.isDestroyed() || created !== win) return; const supported = await created.webContents.executeJavaScript( 'document.documentElement.dataset.desktopChrome === "true"', ).catch(() => false); if (created.isDestroyed() || created !== win) return; if (!supported) { created.once("closed", () => openWindow(steal, false)); created.close(); return; } } if (created.isDestroyed()) return; // maximize() shows the window by itself, already at its size; full screen // needs a window on screen to grow from. if (place.maximized) created.maximize(); created.show(); if (fullScreen) created.setFullScreen(true); shown = true; if (steal) app.focus({ steal: true }); offerReadyUpdate(); }); // Only a window that was shown: the one closed above for an older deck's // page never was, and its default size is not what anybody chose. win.on("close", () => { if (shown) keepWindowPlace(created); }); win.on("focus", () => { trace(`focus onTop=${win?.isAlwaysOnTop()}`); offerReadyUpdate(); }); win.on("blur", () => trace(`blur onTop=${win?.isAlwaysOnTop()} visible=${win?.isVisible()}`)); win.on("closed", () => { win = null; windowOrigin = null; setRegular(false); }); setRegular(true); // The page reads this to word itself for a window and to drop the browser // notification section it has no use for here (src/web/in-app.ts). win.webContents.setUserAgent(`${win.webContents.getUserAgent()} ccdeck-desktop/${app.getVersion()}`); win.loadURL(`${windowOrigin}/`); } /** Write down how the window is as it closes, for the next one to open the * same way (#2466, window-place.mjs). Every way the app ends goes through * app.quit(), which closes the window first, so this runs for those too. */ function keepWindowPlace(window) { const place = windowPlaceToKeep({ normal: window.getNormalBounds(), maximized: window.isMaximized(), fullScreen: window.isFullScreen(), }); if (!place) return; trace(`close: keeping ${place.width}x${place.height} at ${place.x},${place.y}${place.maximized ? ", maximized" : ""}${place.fullScreen ? ", full screen" : ""}`); try { desktopState.merge({ window: place }); } catch (err) { trace(`window place not kept: ${err?.message ?? err}`); } } /** How long after macOS says the app let go before looking: the app's own * switch from accessory to regular can take the keyboard away for a moment * and hand it straight back, and a look taken then would be wrong. */ const RESIGN_SETTLE_MS = 250; /** macOS: the window closes when another app takes the keyboard while the * window stands over that app's full-screen Space, where it cannot step back * and would only stay in front (#1214, fullscreen-space.mjs). The menu bar * opens it again over wherever the person is then. On a desktop it steps * back like any window, and nothing here happens. Never with a question on * screen: a sheet closed with its window is a question nobody answered. */ async function stepAsideFromFullScreen() { if (process.platform !== "darwin" || !win || win.isDestroyed() || !win.isVisible()) return; await new Promise(resolve => setTimeout(resolve, RESIGN_SETTLE_MS)); const here = win; if (!here || here.isDestroyed() || here.isFocused() || updateNoticePrompting || asking > 0) return; const display = screen.getDisplayMatching(here.getBounds()).bounds; if (!overFullScreen(await windowsOnScreen(), process.pid, display)) return; if (here !== win || here.isDestroyed() || here.isFocused()) return; trace("close: another app took the keyboard over its full-screen Space"); here.close(); } // ── first run ─────────────────────────────────────────────────────────────── // What this app remembers between launches — see desktop-state.mjs. const desktopState = createDesktopState(() => join(app.getPath("userData"), "desktop-state.json")); // Custom notification sounds and voices (#1207): local app data the page // reaches through preload.cjs by opaque id, never by path. What may be stored, // and how much of it, is notification-audio-store.mjs; who may ask is here. const notificationAudio = createNotificationAudioStore(() => join(app.getPath("userData"), "notification-audio.json")); /** Whether an IPC call came from the deck's own page in the deck's own window. * The preload runs in whatever this window shows, and navigation is already * held to the deck's origin (nav.mjs) — but that is the window's rule, and a * handler that trusted it would be one missed redirect from answering some * other site. So the door checks for itself, as Electron's security guidance * asks: the sender must be this window, and the frame must be on the origin * the window was opened at. */ function fromDeckPage(event) { if (!deck || !win || win.isDestroyed() || event.sender.id !== win.webContents.id) return false; const url = event.senderFrame?.url; return typeof url === "string" && navigationFor(url, `http://127.0.0.1:${deck.port}`) === "stay"; } function installWindowChromeIpc() { ipcMain.handle("ccdeck:window:colors", (event, value) => { if (!fromDeckPage(event) || event.senderFrame !== event.sender.mainFrame) return; const colors = titlebarColors(value); if (colors && process.platform !== "darwin") win.setTitleBarOverlay(colors); }); ipcMain.handle("ccdeck:window:menu", event => { if (!fromDeckPage(event) || event.senderFrame !== event.sender.mainFrame) return; Menu.getApplicationMenu()?.popup({ window: win, x: 10, y: TITLEBAR_HEIGHT }); }); } function installNotificationAudioIpc() { const handle = (name, run) => ipcMain.handle(`ccdeck:notification-audio:${name}`, (event, arg) => { if (!fromDeckPage(event)) throw new Error("Notification audio is only available to the deck."); return run(arg); }); handle("list", () => notificationAudio.list()); handle("get", id => notificationAudio.get(id)); handle("put", asset => { notificationAudio.put(asset); }); handle("remove", id => { notificationAudio.remove(id); }); } /** How long a question waits for the window to reach the screen before it is * asked app-modally instead. Longer than a deck's page takes to paint, short * enough that a window which never comes does not hold the question forever. */ const ON_SCREEN_WAIT_MS = 5_000; /** * The window once it is actually on screen, or null. * * A dialog attached to a window that has not been shown yet ENDS THE APP on * Wayland: the compositor has given that window's surface no role, and * exporting a roleless surface to parent the dialog is a protocol error * (zxdg_exporter_v2: "exported surface had an invalid role"), which kills the * process rather than the dialog. Windows are created hidden and shown on * ready-to-show, so first run — the one moment these questions are asked — is * exactly when the surface is still roleless. macOS and Windows attach to a * hidden window happily, which is why this was only ever a Linux crash, and on * first run only: the one launch a new person makes. */ function windowOnScreen(within) { const here = win; if (!here || here.isDestroyed()) return Promise.resolve(null); if (here.isVisible()) return Promise.resolve(here); return new Promise(resolve => { const settle = () => { clearTimeout(timer); here.off("show", settle); resolve(here.isDestroyed() || !here.isVisible() ? null : here); }; const timer = setTimeout(settle, within); here.on("show", settle); }); } /** A question for the person, attached to the window when one is on screen — * a sheet moves with it — and app-modal only when none arrives, which on * macOS floats above every other app until it is answered. */ async function ask(options) { const parent = await windowOnScreen(ON_SCREEN_WAIT_MS); asking += 1; try { return await (parent ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options)); } finally { asking -= 1; } } /** * This version has had its one notice, from whichever surface gave it first: * the native sheet below, or the window's own version dialog, which offers * the same Restart to update (#1187). One memory for both, kept on disk, so * "Later" in either place survives a relaunch and neither asks again. The * version chip and the tray line stay, as the places to find it afterwards. */ function rememberUpdateNotice(version) { if (updateNoticeVersion === version) return; updateNoticeVersion = version; try { desktopState.merge({ readyUpdateNoticeVersion: version }); } catch (err) { trace(`could not remember update notice ${version}: ${err?.message ?? err}`); } } /** * Say that a verified update is ready while the person is already looking at * ccdeck. The updater never opens or raises a window for this notice: if the * window is closed, unfocused, or the deck is active, the next focus/redraw * gets another chance. Dismissing it remembers the version across launches so * the sheet does not come back at every six-hour update check — and "Later" * also holds the quiet install off for a day (postponeUpdate). It used to do * only the first: the sheet went, and the app restarted into the update a * minute after the window lost focus, which is the opposite of what the * button said. * * Not routed through `ask()`: `shouldOfferReadyUpdate` already requires * `windowVisible` before this ever runs, so `target` is never the unshown, * roleless-surface window `ask()` exists to wait out. */ async function offerReadyUpdate() { const u = updater?.state ?? { status: "idle" }; const target = win; const windowOpen = !!target && !target.isDestroyed(); if (!shouldOfferReadyUpdate({ status: u.status, version: u.version, shownVersion: updateNoticeVersion, windowOpen, windowVisible: windowOpen && target.isVisible(), windowFocused: windowOpen && target.isFocused(), running: snapshot.running, waiting: snapshot.waiting, prompting: updateNoticePrompting, })) return; const version = u.version; const asksPassword = !updater.canInstallUnattended(); const menu = process.platform === "darwin" ? "the ccdeck menu in the menu bar" : "the ccdeck tray menu"; updateNoticePrompting = true; try { const { response } = await dialog.showMessageBox(target, { type: "info", message: `ccdeck v${version} is ready`, // What happens with each answer, and with none. The tray's own words for // where it lives, the ones the window's dialog uses when a restart from // there fails (trayMenuName in desktop-update.ts). detail: asksPassword ? `It has been downloaded and verified. Installing it asks for your password, so it waits for you: use Restart to update in ${menu} whenever it suits you.` : `It has been downloaded and verified. ccdeck installs it by itself once no agent is working. Later holds that off for the next 24 hours; Restart to update in ${menu} installs it at any time.`, buttons: ["Restart to update", "Later"], defaultId: 0, cancelId: 1, }); // The sheet was actually shown, so this version has had its one notice. rememberUpdateNotice(version); if (response === 1) postponeUpdate(); // A newer update may have replaced this one while the sheet was open. // Only restart for the exact verified version the person accepted. if (response === 0 && updater?.state.status === "ready" && updater.state.version === version) { updater.restartNow(); } } catch (err) { trace(`update ready notice failed: ${err?.message ?? err}`); } finally { updateNoticePrompting = false; } } async function firstRun() { if (desktopState.read().askedLogin) return; const { checkboxChecked } = await ask({ type: "question", message: "ccdeck lives in the menu bar", detail: "It tells you when a session needs you, even with the window closed.", checkboxLabel: "Start ccdeck when I log in", checkboxChecked: true, buttons: ["OK"], }); setOpenAtLogin(checkboxChecked, loginItemOptions()); // Merged into the file as it is NOW (#1695). The question stays up for as // long as nobody answers it, and the update notice can be dismissed in the // meantime — writing back the copy read before asking put that version's // notice in front of the person again at the next launch. desktopState.merge({ askedLogin: true }); } /** * The npm deck's own login item, if one is registered: `ccdeck * --install-service`, or the offer a globally installed deck makes on its * first start. Beside the app's it starts a second deck at login — an older * one, from a copy the app does not update — and whichever starts first is the * deck both end up on. The app starts the deck itself, so it offers once to * take that item away, with the deck's own code for it (login-service.mjs, * the same call `ccdeck --uninstall-service` makes). Never silently: it is * something the person, or a script of theirs, set up. */ async function offerToReplaceLoginItem() { const state = desktopState.read(); if (state.askedReplaceService) return; const root = deckRoot(); const svc = await import(pathToFileURL(join(root, "src", "server", "login-service.mjs")).href); const { deckDataDir } = await import(pathToFileURL(join(root, "src", "server", "deck-home.mjs")).href); let present = false; if (process.platform === "win32") { try { const { spawnSync } = await import("node:child_process"); present = spawnSync("schtasks", ["/Query", "/TN", svc.SERVICE_LABEL], { windowsHide: true }).status === 0; } catch { present = false; } } else { present = existsSync(svc.servicePath()); } desktopState.merge({ askedReplaceService: true }); if (!present) return; const { response } = await ask({ type: "question", message: "Another ccdeck starts when you log in", detail: "It was set up by the npm version (npx ccdeck or npm i -g) and starts an older deck of its own. The app starts the deck itself, so that login item is no longer needed.", buttons: ["Replace it with the app", "Keep it"], defaultId: 0, cancelId: 1, }); if (response !== 0) return; // The app's own login item first, and the npm one only once that reads back // as on (#1781): the other order left nothing starting at login whenever the // app's registration did not take. const out = replaceNpmLoginItem({ registerApp: () => setOpenAtLogin(true, loginItemOptions()), uninstall: () => { const removed = svc.uninstallService(); svc.writeServiceRecord(deckDataDir(), { removed: new Date().toISOString(), version: app.getVersion(), by: "ccdeck desktop" }); return removed; }, }); trace(`npm login item ${out.ok ? "removed" : `not removed: ${out.reason}`}${out.path ? ` (${out.path})` : ""}`); scheduleRedraw(); } // ── lifecycle ─────────────────────────────────────────────────────────────── app.whenReady().then(async () => { if (!primary) return; installNotificationAudioIpc(); installWindowChromeIpc(); if (process.platform !== "darwin") { Menu.setApplicationMenu(Menu.buildFromTemplate([ { label: "File", submenu: [{ role: "close" }, { role: "quit" }] }, { label: "Edit", submenu: [{ role: "undo" }, { role: "redo" }, { type: "separator" }, { role: "cut" }, { role: "copy" }, { role: "paste" }, { role: "selectAll" }] }, { label: "View", submenu: [{ role: "reload" }, { role: "toggleDevTools" }, { type: "separator" }, { role: "resetZoom" }, { role: "zoomIn" }, { role: "zoomOut" }, { role: "togglefullscreen" }] }, { label: "Window", submenu: [{ role: "minimize" }, { role: "zoom" }] }, ])); } setRegular(false); updateNoticeVersion = desktopState.read().readyUpdateNoticeVersion ?? null; postponedUntil = postponementHeld(desktopState.read()); await loadModel(); tray = new Tray(trayImage("offline")); tray.setToolTip("ccdeck"); menuSwap = createMenuSwap({ build: buildMenu, install: (template, { opened, closed }) => { const menu = Menu.buildFromTemplate(template); menu.on("menu-will-show", opened); menu.on("menu-will-close", closed); tray.setContextMenu(menu); }, }); menuSwap.refresh(); // Windows and Linux: a left click opens the window, the menu is on the right. if (process.platform !== "darwin") tray.on("click", () => openWindow()); watchTray(); updater = createUpdater({ app, onChange: s => { trace(`update: ${s.status}${s.version ? ` ${s.version}` : ""}${s.error ? ` — ${s.error}` : ""}`); // The day an update may wait for the agents counts from the first one // that was ready. A newer release staged over it is the same wait. if (s.status === "ready" && behindSince === null) behindSince = Date.now(); scheduleRedraw(); publishUpdateState(); offerReadyUpdate(); // An update that lands while the app is already quiet does not wait for // the next tick to be noticed. updateWhenQuiet(); }, log: trace, }); // AT EVERY START, and then four times a day. An app that is opened, used and // closed the same day would never have reached a check on a six-hour timer, // and the owner asked for one that is on the current version without anybody // remembering to look (#1187). Fifteen seconds in, so the check is behind the // window and the deck rather than in front of them. Only a built app looks: a // development run has nothing to update into. While an update waits to be // installed, the ten-second tick below looks again every half hour, for a // newer one to install instead (lookAgainWhileReady). setTimeout(() => updater.check(), 15_000); setInterval(() => updater.check(), 6 * 60 * 60_000); // Caught, so a start that fails still leaves the timers below, the window // and the first-run question in place. await ensureDeck().catch(err => trace(`start failed: ${err?.message ?? err}`)); // The page's housekeeping (stale sessions, evictions), and a look for a deck // that came up while none was running. setInterval(() => { model?.tick(); scheduleRedraw(); lookAgainWhileReady(); updateWhenQuiet(); }, 10_000); setInterval(() => { if (!deck) discover(); }, 5_000); // The status pages, every five minutes while there is work going on — see // statusWorthAsking. setInterval(() => { if (statusWorthAsking(snapshot)) refreshProviderStatus(); }, 5 * 60_000); // Nobody asked for this one — see openWindow's own doc on `steal`. After a // restart the app made by itself, only if the window was open before it: an // open window is a page, and the deck holds its notifications while a page // is open, so one put back that nobody had open would silence them. const { windowOpenAtSelfRestart } = desktopState.read(); if (windowOpenAtSelfRestart !== undefined) { try { desktopState.merge({ windowOpenAtSelfRestart: undefined }); } catch { /* read once more at the next start */ } } if (deck && windowOpenAtSelfRestart !== false) openWindow(false); await firstRun(); await offerToReplaceLoginItem().catch(err => trace(`login item check failed: ${err?.message ?? err}`)); }); /** * Install a verified update by itself, once the app has been left alone long * enough and no agent is working or waiting — or the update has waited a day * for that (#1187) — see auto-update.mjs for what "alone" means and why. * * Run on the same ten-second tick that redraws the tray, so the quiet and the * agents are measured from the same snapshot the icon is drawn from rather * than from a clock of its own. */ function updateWhenQuiet() { // A Quit being carried out, while its deck shuts down, is not a quiet spell. if (quitting) return; const where = { windowFocused: !!win && !win.isDestroyed() && win.isFocused(), busy: !!starting || !!restarting, now: Date.now(), }; quietSince = quietSinceNext(quietSince, where); // Waiting counts as working: a session blocked on a permission is somebody's // turn half done, and the restart would take its card away mid-question. idleSince = idleSinceNext(idleSince, { agentsBusy: snapshot.running > 0 || snapshot.waiting > 0, now: where.now }); if (!canInstallQuietly({ status: updater?.state.status ?? "idle", unattended: updater?.canInstallUnattended() ?? false, quietSince, idleSince, behindSince, postponedUntil, lookedAt: updater?.lookedAt ?? null, looking: updater?.looking ?? false, ...where, })) { restartForTrayWhenQuiet(where); return; } // Under a locked screen, the quiet starts again once it is unlocked. if (panelAway()) { quietSince = null; return; } trace(`installing ${updater.state.version} by itself after a quiet spell`); quietSince = null; try { desktopState.merge({ windowOpenAtSelfRestart: windowOpen() }); } catch { /* the window opens, as it always did */ } updater.restartNow(); } /** * While an update waits to be installed, look again for a newer one whenever * the last look is older than FRESH_MS — so what installs is the newest * release, and not one that was overtaken while it waited for the agents and * would be followed by a second update an hour later. A newer release takes * the update out of "ready" while it downloads, and nothing installs until it * is staged. On the ten-second tick, ahead of updateWhenQuiet, which also * refuses an update whose look is stale or still in flight. */ function lookAgainWhileReady() { if (!updater || updater.state.status !== "ready" || updater.looking) return; if (isFresh({ lookedAt: updater.lookedAt, looking: false, now: Date.now() })) return; void Promise.resolve(updater.check()).catch(err => trace(`update look failed: ${err?.message ?? err}`)); } /** * "Later" on the ready notice: no quiet install for POSTPONE_MS. Kept on disk * with the app's version, so a relaunch keeps the promise and an app that has * since updated — on Quit, or from the menu — does not carry it over to the * next release. */ function postponeUpdate() { postponedUntil = Date.now() + POSTPONE_MS; trace(`quiet install postponed until ${new Date(postponedUntil).toISOString()}`); try { desktopState.merge({ updatePostponedUntil: postponedUntil, updatePostponedOn: app.getVersion() }); } catch (err) { trace(`could not remember the postponement: ${err?.message ?? err}`); } } /** A "Later" written before this launch, if it still holds: unexpired, and * written by this version of the app. */ function postponementHeld(state) { const until = state?.updatePostponedUntil; if (typeof until !== "number" || until <= Date.now()) return null; return state.updatePostponedOn === app.getVersion() ? until : null; } /** Whether the window is up now, for a restart the app makes by itself to * put back as it was. */ function windowOpen() { return !!win && !win.isDestroyed() && win.isVisible(); } /** The same quiet, spent on a tray icon the panel has lost (#1630): a restart * is the one thing that registers it again — see watchTray. An update that * is ready goes first, above, and brings the icon back on its own way. */ function restartForTrayWhenQuiet(where) { const updateStatus = updater?.state.status ?? "idle"; if (!canRestartForTray({ misses: trayMisses, lastRestartAt: trayRestartAt, lastOutcome: trayRestartOutcomeSaid, updateStatus, quietSince, ...where })) return; if (panelAway()) { quietSince = null; return; } trayRestartAt = where.now; trayRestartOutcomeSaid = "pending"; // Written down before going, or the next process would not know about this // restart: the six hours between two, and what it came to, would not hold // across them. try { desktopState.merge({ trayRestartAt, trayRestartOutcome: "pending", trayBackAfterRestart: undefined, windowOpenAtSelfRestart: windowOpen() }); } catch (err) { trace(`not restarting for the tray icon: ${err?.message ?? err}`); return; } trace("restarting by itself after a quiet spell, to put the tray icon back"); quietSince = null; leaving = true; restartApp(app); } app.on("activate", () => { if (primary) openWindow(); }); app.on("did-resign-active", () => { stepAsideFromFullScreen(); }); // A window closing never ends the app: it keeps the tray, and the deck keeps // being watched. Only Quit ends it. app.on("window-all-closed", () => {}); // A verified update installs as the app leaves — the staged macOS bundle // through its swap script, a Windows or Linux download through // electron-updater (#1757) — after its own deck has been stopped, so nothing // runs from the old version. app.on("will-quit", () => { updater?.installOnQuit(); }); // Quit stops this app's own deck before leaving, once: the first before-quit // is held while the deck shuts down, the second is the real one. let quitting = false; app.on("before-quit", event => { stream?.close(); if (quitting || !ownDeck.current()) return; event.preventDefault(); quitting = true; stopOwnDeck().finally(() => app.quit()); });