From 18d0a9e24341325304aa66f30c34c62de3617e0a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 16:14:45 -0600 Subject: [PATCH 1/2] improvement(desktop): final cleanup across the desktop fixes --- apps/desktop/src/main/app-links.ts | 15 +----- .../src/main/browser-agent/page-prompts.ts | 2 +- .../src/main/browser-agent/session.test.ts | 13 ++++-- .../desktop/src/main/browser-agent/session.ts | 24 ++++++---- apps/desktop/src/main/config.ts | 19 ++------ .../desktop/src/main/desktop-settings.test.ts | 4 +- apps/desktop/src/main/in-flight-work.ts | 4 +- apps/desktop/src/main/index.ts | 37 +++++++++------ apps/desktop/src/main/menu.test.ts | 19 -------- apps/desktop/src/main/quick-chat.ts | 2 +- apps/desktop/src/main/resource-shortcuts.ts | 1 - apps/desktop/src/main/settings-repair.test.ts | 4 +- apps/desktop/src/main/settings-repair.ts | 30 +++--------- apps/desktop/src/main/terminal/index.ts | 7 +-- .../main/terminal/shell-integration.test.ts | 46 ++++++++++++++----- .../src/main/terminal/shell-integration.ts | 25 ++++++---- apps/desktop/src/main/terminal/tmux.test.ts | 10 ++-- apps/desktop/src/main/terminal/tmux.ts | 2 +- apps/desktop/src/main/updater.ts | 17 ++----- apps/desktop/src/main/visible-dialog.ts | 29 ++++++++++++ apps/desktop/src/main/windows.test.ts | 2 +- apps/desktop/src/main/windows.ts | 4 +- 22 files changed, 159 insertions(+), 157 deletions(-) create mode 100644 apps/desktop/src/main/visible-dialog.ts diff --git a/apps/desktop/src/main/app-links.ts b/apps/desktop/src/main/app-links.ts index 72ec7e4a151..846f788abe7 100644 --- a/apps/desktop/src/main/app-links.ts +++ b/apps/desktop/src/main/app-links.ts @@ -1,16 +1,12 @@ import { createLogger } from '@sim/logger' -import { truncate } from '@sim/utils/string' import type { WebContents } from 'electron' import { app, BrowserWindow } from 'electron' +import { displayText } from '@/main/browser-agent/page-prompts' import { showShellDialog } from '@/main/dialogs' import { appLinkTarget, openExternalSafe } from '@/main/navigation' const logger = createLogger('DesktopAppLinks') -/** C0/C1 controls and bidi overrides: an app name must not reorder or hide the prompt text. */ -const DISPLAY_NAME_CONTROLS = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g -const MAX_APP_NAME_LENGTH = 80 - let promptOpen = false /** @@ -28,14 +24,7 @@ export async function openAppLinkWithConsent( if (!target || promptOpen) return false let appName = '' try { - appName = truncate( - app - .getApplicationNameForProtocol(target.url) - .replace(DISPLAY_NAME_CONTROLS, ' ') - .replace(/\s+/g, ' ') - .trim(), - MAX_APP_NAME_LENGTH - ) + appName = displayText(app.getApplicationNameForProtocol(target.url), 80) } catch {} if (!appName) { logger.warn('No app handles this link', { scheme: target.scheme }) diff --git a/apps/desktop/src/main/browser-agent/page-prompts.ts b/apps/desktop/src/main/browser-agent/page-prompts.ts index 822c703ba84..f1938a28e05 100644 --- a/apps/desktop/src/main/browser-agent/page-prompts.ts +++ b/apps/desktop/src/main/browser-agent/page-prompts.ts @@ -125,7 +125,7 @@ function recentAttempts(contents: WebContents, key: string, windowMs: number): n } /** Untrusted page or server text, reduced to one bounded display line. */ -function displayText(value: unknown, maxLength = MAX_DISPLAY_TEXT_LENGTH): string { +export function displayText(value: unknown, maxLength = MAX_DISPLAY_TEXT_LENGTH): string { if (typeof value !== 'string') return '' return truncate( value.replace(UNTRUSTED_TEXT_CONTROLS, ' ').replace(/\s+/g, ' ').trim(), diff --git a/apps/desktop/src/main/browser-agent/session.test.ts b/apps/desktop/src/main/browser-agent/session.test.ts index c236802e78b..7d9a9265d12 100644 --- a/apps/desktop/src/main/browser-agent/session.test.ts +++ b/apps/desktop/src/main/browser-agent/session.test.ts @@ -2502,25 +2502,30 @@ describe('browser-agent session', () => { expect(readdirSync(directory)).toEqual([]) }) - it('sweeps staging files a previous run left behind, and nothing else', async () => { + it('sweeps staging files a previous run abandoned, and nothing else', async () => { const directory = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-')) const stale = [ '.sim-download-abcDEF123_-xyzABCDEFG', '.sim-download-abcDEF123_-xyzABCDEFG.crdownload', ] + // The other release channel may be downloading into the same folder right now. + const recent = '.sim-download-otherChannel123456789.crdownload' const kept = ['.sim-download-notes.txt', '.hidden', 'report.csv'] - const longAgo = new Date(Date.now() - 60_000) + const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000) for (const name of [...stale, ...kept]) { writeFileSync(join(directory, name), 'x') - utimesSync(join(directory, name), longAgo, longAgo) + utimesSync(join(directory, name), twoDaysAgo, twoDaysAgo) } + const aMinuteAgo = new Date(Date.now() - 60_000) + writeFileSync(join(directory, recent), 'x') + utimesSync(join(directory, recent), aMinuteAgo, aMinuteAgo) session = freshSession(win, {}, undefined, { getDirectory: () => directory, getFreeDiskBytes: () => Number.MAX_SAFE_INTEGER, }) - await vi.waitFor(() => expect(readdirSync(directory).sort()).toEqual([...kept].sort())) + await vi.waitFor(() => expect(readdirSync(directory).sort()).toEqual([...kept, recent].sort())) }) it('cancels every active download on profile wipe without reviving late work', async () => { diff --git a/apps/desktop/src/main/browser-agent/session.ts b/apps/desktop/src/main/browser-agent/session.ts index 2f77a4915a3..ca66701bc8a 100644 --- a/apps/desktop/src/main/browser-agent/session.ts +++ b/apps/desktop/src/main/browser-agent/session.ts @@ -906,9 +906,16 @@ function removeBrowserDownloadPlaceholder(active: ActiveBrowserDownload): void { */ const STAGING_FILE_PATTERN = /^\.sim-download-[A-Za-z0-9_-]{21}(?:\.crdownload)?$/ +/** + * How long a staging file must sit untouched before it counts as abandoned. A shorter cutoff + * could delete an in-flight download of this run or of the other release channel, which + * stages into the same Downloads folder. + */ +const ABANDONED_STAGING_AGE_MS = 24 * 60 * 60 * 1000 + /** * Deletes staging files an earlier run left when it quit or crashed mid-download. Files modified - * since `before` may belong to a download this run has started, so they stay. + * since `before` may belong to a download still in progress, so they stay. */ async function removeStaleBrowserDownloadStaging( directories: readonly string[], @@ -1241,7 +1248,10 @@ export function initSession( const downloadDirectories = new Set([app.getPath('downloads')]) const configuredDownloadDirectory = downloadSettings?.getDirectory() if (configuredDownloadDirectory) downloadDirectories.add(configuredDownloadDirectory) - void removeStaleBrowserDownloadStaging([...downloadDirectories], Date.now()) + void removeStaleBrowserDownloadStaging( + [...downloadDirectories], + Date.now() - ABANDONED_STAGING_AGE_MS + ) setPagePromptHost({ tabContext: (contents) => { const scoped = scopedTabForContents(contents) @@ -4161,13 +4171,10 @@ export function handleFocusedShortcut( // Accelerators and mouse buttons arrive before any chat has opened a browser. if (!getActiveBrowserScopeId()) return false // Tab-management accelerators belong to the visible Browser even after - // focus moves into Sim chrome. Otherwise Cmd-T/L/Shift-T silently stop + // focus moves into Sim chrome. Otherwise Cmd-T/Shift-T silently stop // behaving like browser shortcuts, and Cmd-W becomes especially unsafe. const visibleBrowserShortcut = - shortcut === 'close-tab' || - shortcut === 'new-tab' || - shortcut === 'reopen-closed-tab' || - shortcut === 'focus-omnibox' + shortcut === 'close-tab' || shortcut === 'new-tab' || shortcut === 'reopen-closed-tab' const shortcutTab = focusedTabForShortcut(ownerWindow) ?? (visibleBrowserShortcut ? visibleActiveTab(ownerWindow) : null) @@ -4191,9 +4198,6 @@ export function handleFocusedShortcut( case 'close-tab': closeTabFromUser(shortcutTab.id) return true - case 'focus-omnibox': - focusRendererOmnibox('select') - return true case 'reload-or-clear': userNavigate(shortcutTab.view.webContents, 'reload') return true diff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.ts index f0efe4372d5..4eff90ebe78 100644 --- a/apps/desktop/src/main/config.ts +++ b/apps/desktop/src/main/config.ts @@ -269,15 +269,6 @@ const DEFAULT_SETTINGS: DesktopSettings = { */ export interface SettingsLoadProblem { kind: 'read-error' | 'unparseable' | 'invalid-origin' - /** The usable server URL the rejected file names, when one can be read from it. */ - storedOrigin: string | null -} - -/** Finds the server a damaged file still names, so a repair can say what it replaces. */ -function findStoredOrigin(raw: string): string | null { - const match = /"origin"\s*:\s*"([^"]*)"/.exec(raw) - const validated = match ? validateOriginInput(match[1]) : null - return validated?.ok ? canonicalOrigin(validated.origin) : null } export interface ConfigStore { @@ -334,7 +325,7 @@ export function createConfigStore( raw = readFileSync(filePath, 'utf8') } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { - loadProblem = { kind: 'read-error', storedOrigin: null } + loadProblem = { kind: 'read-error' } } } if (raw !== null) { @@ -345,7 +336,7 @@ export function createConfigStore( parsed = null } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - loadProblem = { kind: 'unparseable', storedOrigin: findStoredOrigin(raw) } + loadProblem = { kind: 'unparseable' } } else { const loadedSettings = { ...DEFAULT_SETTINGS, ...(parsed as Partial) } const validated = @@ -355,7 +346,6 @@ export function createConfigStore( if (!validated?.ok) { loadProblem = { kind: typeof loadedSettings.origin === 'string' ? 'invalid-origin' : 'unparseable', - storedOrigin: null, } } else { const loaded = validated.origin @@ -392,8 +382,9 @@ export function createConfigStore( /** Changes a failed write left only in memory; every later write retries them. */ let unsavedChanges = false /** - * Sticky for the session: account-bearing stores were gated on persistence - * when they opened, so a write that recovers does not re-admit them mid-run. + * Set by a failed write and cleared only when `setOrigin` writes: account-bearing stores were + * gated on persistence when they opened, so an ordinary write that recovers does not re-admit + * them mid-run. */ let writeFailedThisSession = false diff --git a/apps/desktop/src/main/desktop-settings.test.ts b/apps/desktop/src/main/desktop-settings.test.ts index 8ab48a58540..0ad9b2ba099 100644 --- a/apps/desktop/src/main/desktop-settings.test.ts +++ b/apps/desktop/src/main/desktop-settings.test.ts @@ -10,7 +10,7 @@ function service( window: { url: string; focused: boolean } | null, overrides: Partial[0]> = {}, config = new Map(), - store: { flush?: () => boolean; loadProblem?: { kind: 'unparseable'; storedOrigin: null } } = {} + store: { flush?: () => boolean; loadProblem?: { kind: 'unparseable' } } = {} ) { return createDesktopSettingsService({ existingInstall: false, @@ -210,7 +210,7 @@ describe('preference writes while the settings file is rejected', () => { const setTrayEnabled = vi.fn() const settings = service(null, { setTrayEnabled }, undefined, { flush: () => false, - loadProblem: { kind: 'unparseable', storedOrigin: null }, + loadProblem: { kind: 'unparseable' }, }) expect(settings.setPreference('trayEnabled', false).trayEnabled).toBe(false) diff --git a/apps/desktop/src/main/in-flight-work.ts b/apps/desktop/src/main/in-flight-work.ts index eb7cd63df15..addd754e12e 100644 --- a/apps/desktop/src/main/in-flight-work.ts +++ b/apps/desktop/src/main/in-flight-work.ts @@ -161,8 +161,8 @@ export interface QuitGuard { /** * Called from every `before-quit`: true when this quit must wait while the guard checks for * work, false when it was cleared to go through. A cleared quit is let through once. `bypass` - * lets through a quit the guard must not hold (a committed relaunch, or one resuming after - * account teardown); it still uses up a clearance, so none carries over to a later quit. + * lets through a quit the guard must not hold (a committed relaunch); it still uses up a + * clearance, so none carries over to a later quit. */ holdQuit: (options?: { bypass?: boolean }) => boolean /** Whether the user chose to quit despite work in progress, so unload guards need not ask again. */ diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 826ad2895b1..7a38e4c8a31 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -78,7 +78,6 @@ import { createDesktopToolRunner } from '@/main/desktop-executor/runner' import { createDesktopExecutorService } from '@/main/desktop-executor/service' import { createSleepBlocker } from '@/main/desktop-executor/sleep-blocker' import { createDesktopSettingsService, wasOpenedAtLogin } from '@/main/desktop-settings' -import { showShellDialog } from '@/main/dialogs' import { attachDownloadHandling, countProgressingAppDownloads } from '@/main/downloads' import { createAuthFlow, createConnectFlow, createHandoffManager } from '@/main/handoff' import { @@ -126,6 +125,7 @@ import { createRunLedger } from '@/main/terminal/run-ledger' import { installTray, type TrayHandle } from '@/main/tray' import { checkForUpdatesInteractive, initUpdater, type UpdaterHandle } from '@/main/updater' import { installBrowserUserAgent } from '@/main/user-agent' +import { showShellDialogOver } from '@/main/visible-dialog' import { createMainWindow, guardVisibilityListenersAfterDestroy, @@ -318,6 +318,8 @@ function main(): void { let appSession: Session | null = null let sessionLifecycle: ReturnType | null = null let resumingQuitAfterTeardown = false + let quitPromptOpen = false + let reopeningWindowAfterQuitCancel = false let committedRelaunchPending = false let tray: TrayHandle | null = null let updater: UpdaterHandle | null = null @@ -559,7 +561,7 @@ function main(): void { if (activate) void opened.then(showMainWindow) }, allowHttpLocalhost: allowHttpLocalhost(), - isCommittedRelaunchPending: isExitCommitted, + isExitCommitted, } } @@ -965,17 +967,22 @@ function main(): void { defaultId: 1, cancelId: 1, } - // A sheet on a hidden or minimized window would be a prompt nobody can see. - const win = getMainWindow() - const { response } = await (win?.isVisible() && !win.isMinimized() - ? showShellDialog(win, options) - : showShellDialog(options)) - return response === 0 + quitPromptOpen = true + try { + const { response } = await showShellDialogOver(getMainWindow(), options) + return response === 0 + } finally { + quitPromptOpen = false + } }, quit: () => app.quit(), onCancel: () => { // Closing the last window quit Sim on Windows and Linux; staying means keeping a window. - if (process.platform !== 'darwin' && getWindows().length === 0) void ensureMainWindow() + if (process.platform === 'darwin' || getWindows().length > 0) return + reopeningWindowAfterQuitCancel = true + void ensureMainWindow().finally(() => { + reopeningWindowAfterQuitCancel = false + }) }, }) @@ -989,7 +996,8 @@ function main(): void { }) app.on('window-all-closed', () => { - if (process.platform !== 'darwin') { + // The quit prompt closing, or a cancelled quit's window still opening, is not a new quit. + if (process.platform !== 'darwin' && !quitPromptOpen && !reopeningWindowAfterQuitCancel) { app.quit() } }) @@ -1018,12 +1026,11 @@ function main(): void { }) return } - // A committed relaunch has already asked about, or deliberately skipped, the work it - // interrupts, and a quit resuming after teardown was already let through. The resume is - // one quit only: if something cancels it, the next quit is checked again. - const resumedAfterTeardown = resumingQuitAfterTeardown + // Waiting on teardown is one quit only: if something cancels it, the next quit waits again. resumingQuitAfterTeardown = false - if (quitGuard.holdQuit({ bypass: committedRelaunchPending || resumedAfterTeardown })) { + // A committed relaunch has already asked about, or deliberately skipped, the work it + // interrupts. Every other quit, including one resuming after teardown, is checked here. + if (quitGuard.holdQuit({ bypass: committedRelaunchPending })) { event.preventDefault() return } diff --git a/apps/desktop/src/main/menu.test.ts b/apps/desktop/src/main/menu.test.ts index 5302f17f427..fc5eaed5b98 100644 --- a/apps/desktop/src/main/menu.test.ts +++ b/apps/desktop/src/main/menu.test.ts @@ -46,23 +46,4 @@ describe('buildMenuTemplate', () => { const view = submenu(buildMenuTemplate(makeDeps()), 'View') expect(view.some((item) => item.role === 'toggleDevTools')).toBe(false) }) - - /** - * A menu accelerator reaches the menu before the page, so a chord the web app - * binds itself (Cmd+B bold in the editor, Cmd+K link, Cmd+L logs) must not be - * claimed here or the page never sees it. - */ - it('leaves the web app its own Mod+B, Mod+K and Mod+L shortcuts', () => { - const accelerators: string[] = [] - const collect = (items: MenuItemConstructorOptions[]) => { - for (const item of items) { - if (typeof item.accelerator === 'string') accelerators.push(item.accelerator) - if (Array.isArray(item.submenu)) collect(item.submenu) - } - } - collect(buildMenuTemplate(makeDeps())) - for (const owned of ['CmdOrCtrl+B', 'CmdOrCtrl+K', 'CmdOrCtrl+L']) { - expect(accelerators).not.toContain(owned) - } - }) }) diff --git a/apps/desktop/src/main/quick-chat.ts b/apps/desktop/src/main/quick-chat.ts index a274e5e94f6..aff25f2ec26 100644 --- a/apps/desktop/src/main/quick-chat.ts +++ b/apps/desktop/src/main/quick-chat.ts @@ -94,7 +94,7 @@ export function createQuickChat(deps: QuickChatDeps): QuickChat { // A crashed page cannot recover in place; the next toggle builds a fresh window instead. created.webContents.on('render-process-gone', () => created.destroy()) created.webContents.on('will-prevent-unload', (event) => { - handleWillPreventUnload(created, event, deps.windowPolicy.isCommittedRelaunchPending()) + handleWillPreventUnload(created, event, deps.windowPolicy.isExitCommitted()) }) attachWindowOpenPolicy(created.webContents, deps.windowPolicy) attachContextMenu(created.webContents, deps.contextMenu) diff --git a/apps/desktop/src/main/resource-shortcuts.ts b/apps/desktop/src/main/resource-shortcuts.ts index cfcff836a47..13dcb1aeaf3 100644 --- a/apps/desktop/src/main/resource-shortcuts.ts +++ b/apps/desktop/src/main/resource-shortcuts.ts @@ -9,7 +9,6 @@ export type FocusedResourceShortcut = | 'new-tab' | 'reopen-closed-tab' | 'close-tab' - | 'focus-omnibox' | ResourceTabSelectionShortcut | 'reload-or-clear' | 'hard-reload' diff --git a/apps/desktop/src/main/settings-repair.test.ts b/apps/desktop/src/main/settings-repair.test.ts index ff1889a8168..f5bf2d26977 100644 --- a/apps/desktop/src/main/settings-repair.test.ts +++ b/apps/desktop/src/main/settings-repair.test.ts @@ -57,7 +57,7 @@ describe('offerSettingsRepair', () => { expect(config.getLoadProblem()).toBeNull() }) - it('defaults to keeping the file and names the self-hosted server a reset leaves', async () => { + it('defaults to keeping the file and warns that a reset leaves a self-hosted server', async () => { const { config } = storeWith('{ "origin": "https://sim.example.com", }') dialog.mockResolvedValue({ response: 0, checkboxChecked: false }) const setOrigin = vi.fn() @@ -71,7 +71,7 @@ describe('offerSettingsRepair', () => { const options = optionsOf(0) expect(options.buttons?.[options.defaultId ?? -1]).toBe('Not Now') - expect(options.detail).toContain(`from https://sim.example.com back to ${DEFAULT_ORIGIN}`) + expect(options.detail).toContain('a self-hosted server must be entered again') expect(setOrigin).not.toHaveBeenCalled() }) diff --git a/apps/desktop/src/main/settings-repair.ts b/apps/desktop/src/main/settings-repair.ts index d4417d98d87..7aa1bb3bf5c 100644 --- a/apps/desktop/src/main/settings-repair.ts +++ b/apps/desktop/src/main/settings-repair.ts @@ -1,9 +1,9 @@ import type { DesktopServerChangeResult } from '@sim/desktop-bridge' import { createLogger } from '@sim/logger' import type { BrowserWindow, MessageBoxOptions } from 'electron' -import { app, shell } from 'electron' +import { shell } from 'electron' import type { ConfigStore, SettingsLoadProblem } from '@/main/config' -import { showShellDialog } from '@/main/dialogs' +import { showShellDialogOver } from '@/main/visible-dialog' const logger = createLogger('DesktopSettingsRepair') @@ -30,12 +30,8 @@ function describeProblem(problem: SettingsLoadProblem): string { } /** What a reset does to the server, which is easy to miss for a self-hosted install. */ -function describeReset(problem: SettingsLoadProblem, defaultOrigin: string): string { - const server = - problem.storedOrigin && problem.storedOrigin !== defaultOrigin - ? `moves Sim from ${problem.storedOrigin} back to ${defaultOrigin}` - : `points Sim at ${defaultOrigin}, so a self-hosted server must be entered again` - return `Reset Settings keeps a copy of this file, ${server}, clears folder access and built-in browser sign-ins, and restarts Sim.` +function describeReset(defaultOrigin: string): string { + return `Reset Settings keeps a copy of this file, points Sim at ${defaultOrigin}, so a self-hosted server must be entered again, clears folder access and built-in browser sign-ins, and restarts Sim.` } /** @@ -50,20 +46,8 @@ function describeReset(problem: SettingsLoadProblem, defaultOrigin: string): str export async function offerSettingsRepair(deps: SettingsRepairDeps): Promise { const problem = deps.config.getLoadProblem() if (!problem) return - const show = (prompt: MessageBoxOptions) => { - // Quitting answers the prompt with its cancel button; an open prompt would otherwise hold the quit. - const quit = new AbortController() - const abort = () => quit.abort() - app.once('before-quit', abort) - const options = { ...prompt, signal: quit.signal } - // A launch at login starts hidden; a sheet on a hidden window is never seen. - const win = deps.getWindow() - return ( - win?.isVisible() && !win.isMinimized() - ? showShellDialog(win, options) - : showShellDialog(options) - ).finally(() => app.removeListener('before-quit', abort)) - } + const show = (prompt: MessageBoxOptions) => + showShellDialogOver(deps.getWindow(), prompt, { dismissOnQuit: true }) const message = `${describeProblem(problem)} ${SESSION_ONLY}` if (problem.kind === 'read-error') { @@ -84,7 +68,7 @@ export async function offerSettingsRepair(deps: SettingsRepairDeps): Promise boolean | Promise ): boolean { // Hard reload and history have no terminal meaning — leave them to the Browser or shell. - if ( - shortcut === 'focus-omnibox' || - shortcut === 'hard-reload' || - shortcut === 'back' || - shortcut === 'forward' - ) { + if (shortcut === 'hard-reload' || shortcut === 'back' || shortcut === 'forward') { return false } const visibleTabShortcut = diff --git a/apps/desktop/src/main/terminal/shell-integration.test.ts b/apps/desktop/src/main/terminal/shell-integration.test.ts index 298a39159ac..2e6ffd37102 100644 --- a/apps/desktop/src/main/terminal/shell-integration.test.ts +++ b/apps/desktop/src/main/terminal/shell-integration.test.ts @@ -15,7 +15,7 @@ const NONCE = 'testnonce' /** * Whether bash can run a temp home's startup files here. The generated rc reads /etc/profile as a - * login shell does, and on some CI images an interactive shell's /etc/profile moves HOME or never + * macOS login shell does, and on some CI images an interactive shell's /etc/profile moves HOME or never * returns, so a temp home's files would never run whatever the rc did. */ function bashKeepsHome(): boolean { @@ -211,11 +211,22 @@ describe('startup marker', () => { * way it does at a terminal. */ describe.skipIf(!BASH_KEEPS_HOME)('bash integration', () => { - function runBash(files: Record, input: string) { + function runBash( + files: Record, + input: string, + platform: NodeJS.Platform = process.platform + ) { const home = mkdtempSync(join(tmpdir(), 'sim-shell-home-')) for (const [name, content] of Object.entries(files)) writeFileSync(join(home, name), content) const env = { PATH: '/usr/bin:/bin', HOME: home } - const launch = buildShellLaunch('bash', mkdtempSync(join(tmpdir(), 'sim-bash-')), NONCE, env) + const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: platform }) + let launch: ReturnType + try { + launch = buildShellLaunch('bash', mkdtempSync(join(tmpdir(), 'sim-bash-')), NONCE, env) + } finally { + if (realPlatform) Object.defineProperty(process, 'platform', realPlatform) + } const stdout = spawnSync('/bin/bash', launch.args, { env: { ...env, ...launch.env }, input: `${input}exit\n`, @@ -259,13 +270,16 @@ describe.skipIf(!BASH_KEEPS_HOME)('bash integration', () => { expect(text).toContain('status=1') }) - it("runs the login files a terminal's bash would, reading .bashrc once", () => { + const loginAndRcFiles = { + '.bash_profile': 'export FROM_PROFILE=1\n[ -f ~/.bashrc ] && . ~/.bashrc\n', + '.bashrc': 'RC_RUNS=$((RC_RUNS + 1))\n', + } + + it("runs the login files a macOS terminal's bash would, reading .bashrc once", () => { const { text } = runBash( - { - '.bash_profile': 'export FROM_PROFILE=1\n[ -f ~/.bashrc ] && . ~/.bashrc\n', - '.bashrc': 'RC_RUNS=$((RC_RUNS + 1))\n', - }, - 'echo "profile=$FROM_PROFILE rc=$RC_RUNS path=$PATH"\n' + loginAndRcFiles, + 'echo "profile=$FROM_PROFILE rc=$RC_RUNS path=$PATH"\n', + 'darwin' ) expect(text).toContain('profile=1 rc=1') @@ -273,11 +287,21 @@ describe.skipIf(!BASH_KEEPS_HOME)('bash integration', () => { if (existsSync('/usr/libexec/path_helper')) expect(text).toMatch(/path=.*\/usr\/sbin/) }) - it('still reads .bashrc when the user has no login files', () => { - const { text } = runBash({ '.bashrc': 'RC_RUNS=$((RC_RUNS + 1))\n' }, 'echo "rc=$RC_RUNS"\n') + it('still reads .bashrc on macOS when the user has no login files', () => { + const { text } = runBash( + { '.bashrc': 'RC_RUNS=$((RC_RUNS + 1))\n' }, + 'echo "rc=$RC_RUNS"\n', + 'darwin' + ) expect(text).toContain('rc=1') }) + + it('reads only .bashrc on Linux, whose terminals start non-login shells', () => { + const { text } = runBash(loginAndRcFiles, 'echo "profile=$FROM_PROFILE rc=$RC_RUNS"\n', 'linux') + + expect(text).toContain('profile= rc=1') + }) }) describe.skipIf(process.platform !== 'darwin')('the locale the shell starts with on macOS', () => { diff --git a/apps/desktop/src/main/terminal/shell-integration.ts b/apps/desktop/src/main/terminal/shell-integration.ts index e1c3b2ae531..40dad660ca3 100644 --- a/apps/desktop/src/main/terminal/shell-integration.ts +++ b/apps/desktop/src/main/terminal/shell-integration.ts @@ -246,6 +246,21 @@ add-zsh-hook precmd __sim_precmd ) } +/** + * The startup files bash reads as a macOS terminal's login shell: /etc/profile puts the system + * paths on PATH, and ~/.bash_profile (which conventionally sources ~/.bashrc) is where Homebrew, + * nvm and PATH changes usually live. ~/.bashrc is read directly only when there is no login file. + */ +const MACOS_BASH_STARTUP = `[ -r /etc/profile ] && builtin source /etc/profile +if [ -r "$HOME/.bash_profile" ]; then builtin source "$HOME/.bash_profile" +elif [ -r "$HOME/.bash_login" ]; then builtin source "$HOME/.bash_login" +elif [ -r "$HOME/.profile" ]; then builtin source "$HOME/.profile" +elif [ -r "$HOME/.bashrc" ]; then builtin source "$HOME/.bashrc" +fi` + +/** Terminals elsewhere, like Linux's, start non-login shells, which read only ~/.bashrc. */ +const NON_LOGIN_BASH_STARTUP = '[ -f "$HOME/.bashrc" ] && builtin source "$HOME/.bashrc"' + /** * bash has no preexec hook, so command start is detected with a DEBUG trap and command end from * PROMPT_COMMAND, the way bash-preexec does it (and through bash-preexec itself when the user loads @@ -259,15 +274,7 @@ function writeBashFile(dir: string, nonce: string): string { rcPath, `builtin printf '\\e]633;SimStartup;%s\\a' '${nonce}' -# The startup files bash reads as a terminal's login shell: /etc/profile puts the system paths on -# PATH, and ~/.bash_profile (which conventionally sources ~/.bashrc) is where Homebrew, nvm and -# PATH changes usually live. ~/.bashrc is read directly only when there is no login file at all. -[ -r /etc/profile ] && builtin source /etc/profile -if [ -r "$HOME/.bash_profile" ]; then builtin source "$HOME/.bash_profile" -elif [ -r "$HOME/.bash_login" ]; then builtin source "$HOME/.bash_login" -elif [ -r "$HOME/.profile" ]; then builtin source "$HOME/.profile" -elif [ -r "$HOME/.bashrc" ]; then builtin source "$HOME/.bashrc" -fi +${process.platform === 'darwin' ? MACOS_BASH_STARTUP : NON_LOGIN_BASH_STARTUP} __sim_nonce='${nonce}' __sim_in_cmd='' diff --git a/apps/desktop/src/main/terminal/tmux.test.ts b/apps/desktop/src/main/terminal/tmux.test.ts index 02a0dc437e9..681c2f04576 100644 --- a/apps/desktop/src/main/terminal/tmux.test.ts +++ b/apps/desktop/src/main/terminal/tmux.test.ts @@ -7,13 +7,13 @@ import { awaitRun, closeRunPane, isDescendantOf, + isTmuxUnavailable, listPanes, parseFormatLines, pollRun, recordedRunState, resolveAttachment, runPaneState, - runTmux, startRun, stopRecordedRun, stopRun, @@ -418,7 +418,7 @@ describe('finding the tmux binary', () => { }) it('finds tmux once it is installed, after a lookup that came up empty', async () => { - await runTmux(['-V'], { PATH: '/nonexistent' }) + isTmuxUnavailable({ PATH: '/nonexistent' }) const tmux = fakeTmux() dirs.push(tmux.dir) @@ -430,10 +430,8 @@ describe('finding the tmux binary', () => { const homebrewTmux = ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux'].some(existsSync) it.skipIf(!homebrewTmux)( 'finds a Homebrew tmux when the app was opened from Finder, without it on PATH', - async () => { - const result = await runTmux(['-V'], { PATH: '/usr/bin:/bin:/usr/sbin:/sbin' }) - - expect(result).toMatchObject({ ok: true, stdout: expect.stringMatching(/^tmux /) }) + () => { + expect(isTmuxUnavailable({ PATH: '/usr/bin:/bin:/usr/sbin:/sbin' })).toBe(false) } ) }) diff --git a/apps/desktop/src/main/terminal/tmux.ts b/apps/desktop/src/main/terminal/tmux.ts index ed05976d15e..da0c846eee3 100644 --- a/apps/desktop/src/main/terminal/tmux.ts +++ b/apps/desktop/src/main/terminal/tmux.ts @@ -123,7 +123,7 @@ export function isTmuxUnavailable(env: NodeJS.ProcessEnv): boolean { * bad target all arrive as `ok: false` with tmux's own message, which is more * useful to the model than an exception. */ -export function runTmux(args: string[], env: NodeJS.ProcessEnv): Promise { +function runTmux(args: string[], env: NodeJS.ProcessEnv): Promise { return new Promise((resolve) => { const binary = findTmux(env) if (!binary) { diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.ts index c5d9bfa1e49..53970447f7a 100644 --- a/apps/desktop/src/main/updater.ts +++ b/apps/desktop/src/main/updater.ts @@ -13,6 +13,7 @@ import { readFileWithinLimitSync, writeJsonFileAtomicallySync } from '@/main/ato import { showShellDialog } from '@/main/dialogs' import { isSafeExternalUrl, openExternalSafe } from '@/main/navigation' import type { EventRecorder } from '@/main/observability' +import { showShellDialogOver } from '@/main/visible-dialog' const logger = createLogger('DesktopUpdater') @@ -407,16 +408,7 @@ async function offerMoveToApplications( defaultId: 0, cancelId: 1, } - // A launch at login starts hidden; a sheet on a hidden window is never seen. - const win = getWindow() - // Quitting answers the prompt as Not Now; an open prompt would otherwise hold the quit. - const quit = new AbortController() - const abort = () => quit.abort() - app.once('before-quit', abort) - const { response } = await (win?.isVisible() && !win.isMinimized() - ? showShellDialog(win, { ...options, signal: quit.signal }) - : showShellDialog({ ...options, signal: quit.signal }) - ).finally(() => app.removeListener('before-quit', abort)) + const { response } = await showShellDialogOver(getWindow(), options, { dismissOnQuit: true }) if (response !== 0) return try { app.moveToApplicationsFolder({ @@ -612,10 +604,7 @@ export function initUpdater(deps: UpdaterDeps): UpdaterHandle { defaultId: 0, cancelId: 1, } - const win = deps.getWindow() - const { response } = await (win - ? showShellDialog(win, options) - : showShellDialog(options)) + const { response } = await showShellDialogOver(deps.getWindow(), options) if (response !== 0) return } if (state.status === 'ready') quitAndInstall() diff --git a/apps/desktop/src/main/visible-dialog.ts b/apps/desktop/src/main/visible-dialog.ts new file mode 100644 index 00000000000..6635d64aa13 --- /dev/null +++ b/apps/desktop/src/main/visible-dialog.ts @@ -0,0 +1,29 @@ +import type { BrowserWindow, MessageBoxOptions, MessageBoxReturnValue } from 'electron' +import { app } from 'electron' +import { showShellDialog } from '@/main/dialogs' + +/** + * Shows a shell dialog over `win` only while the user can see it: a sheet on a hidden or + * minimized window (a launch at login starts hidden) is a prompt nobody sees, so otherwise + * it stands alone. `dismissOnQuit` answers the prompt with its cancel button when the app + * starts quitting, so an open prompt never holds the quit; a prompt shown from inside + * `before-quit` must leave it off. + */ +export async function showShellDialogOver( + win: BrowserWindow | null, + options: MessageBoxOptions, + { dismissOnQuit = false }: { dismissOnQuit?: boolean } = {} +): Promise { + const parent = win?.isVisible() && !win.isMinimized() ? win : null + const show = (prompt: MessageBoxOptions) => + parent ? showShellDialog(parent, prompt) : showShellDialog(prompt) + if (!dismissOnQuit) return show(options) + const quit = new AbortController() + const abort = () => quit.abort() + app.once('before-quit', abort) + try { + return await show({ ...options, signal: quit.signal }) + } finally { + app.removeListener('before-quit', abort) + } +} diff --git a/apps/desktop/src/main/windows.test.ts b/apps/desktop/src/main/windows.test.ts index c8af090c531..7202a7aab76 100644 --- a/apps/desktop/src/main/windows.test.ts +++ b/apps/desktop/src/main/windows.test.ts @@ -41,7 +41,7 @@ describe('attachWindowOpenPolicy', () => { appOrigin: () => APP, openAppWindow, allowHttpLocalhost, - isCommittedRelaunchPending: () => false, + isExitCommitted: () => false, }) return { contents, openAppWindow } } diff --git a/apps/desktop/src/main/windows.ts b/apps/desktop/src/main/windows.ts index 5b720e48ac2..f12308bddb8 100644 --- a/apps/desktop/src/main/windows.ts +++ b/apps/desktop/src/main/windows.ts @@ -46,7 +46,7 @@ export interface WindowPolicyDeps { appOrigin: () => string openAppWindow: (url: string) => void allowHttpLocalhost: boolean - isCommittedRelaunchPending: () => boolean + isExitCommitted: () => boolean } /** @@ -90,7 +90,7 @@ export function attachWindowOpenPolicy(contents: WebContents, deps: WindowPolicy registerPopupContents(child.webContents) attachWindowOpenPolicy(child.webContents, deps) child.webContents.on('will-prevent-unload', (event) => { - handleWillPreventUnload(child, event, deps.isCommittedRelaunchPending()) + handleWillPreventUnload(child, event, deps.isExitCommitted()) }) const kind = classifyWindowOpen(details.url, details.frameName, deps.appOrigin()) if (kind === 'popup-blank') { From 5a9eb457fb7115b817fdef5845bad87f483eea33 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 16:22:26 -0600 Subject: [PATCH 2/2] improvement(desktop): run the linux bash startup test without the login-file gate --- .../main/terminal/shell-integration.test.ts | 49 +++++++++++-------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/apps/desktop/src/main/terminal/shell-integration.test.ts b/apps/desktop/src/main/terminal/shell-integration.test.ts index 2e6ffd37102..89f234d255d 100644 --- a/apps/desktop/src/main/terminal/shell-integration.test.ts +++ b/apps/desktop/src/main/terminal/shell-integration.test.ts @@ -210,11 +210,12 @@ describe('startup marker', () => { * Lines are fed on stdin to an interactive shell, which runs PROMPT_COMMAND and the DEBUG trap the * way it does at a terminal. */ -describe.skipIf(!BASH_KEEPS_HOME)('bash integration', () => { +describe.skipIf(!existsSync('/bin/bash'))('bash integration', () => { function runBash( files: Record, input: string, - platform: NodeJS.Platform = process.platform + // Linux's startup reads no /etc/profile, which on some CI images moves HOME off the temp home. + platform: NodeJS.Platform = 'linux' ) { const home = mkdtempSync(join(tmpdir(), 'sim-shell-home-')) for (const [name, content] of Object.entries(files)) writeFileSync(join(home, name), content) @@ -275,27 +276,33 @@ describe.skipIf(!BASH_KEEPS_HOME)('bash integration', () => { '.bashrc': 'RC_RUNS=$((RC_RUNS + 1))\n', } - it("runs the login files a macOS terminal's bash would, reading .bashrc once", () => { - const { text } = runBash( - loginAndRcFiles, - 'echo "profile=$FROM_PROFILE rc=$RC_RUNS path=$PATH"\n', - 'darwin' - ) - - expect(text).toContain('profile=1 rc=1') - // /etc/profile's path_helper puts the system paths on PATH, as it does in Terminal. - if (existsSync('/usr/libexec/path_helper')) expect(text).toMatch(/path=.*\/usr\/sbin/) - }) + it.skipIf(!BASH_KEEPS_HOME)( + "runs the login files a macOS terminal's bash would, reading .bashrc once", + () => { + const { text } = runBash( + loginAndRcFiles, + 'echo "profile=$FROM_PROFILE rc=$RC_RUNS path=$PATH"\n', + 'darwin' + ) + + expect(text).toContain('profile=1 rc=1') + // /etc/profile's path_helper puts the system paths on PATH, as it does in Terminal. + if (existsSync('/usr/libexec/path_helper')) expect(text).toMatch(/path=.*\/usr\/sbin/) + } + ) - it('still reads .bashrc on macOS when the user has no login files', () => { - const { text } = runBash( - { '.bashrc': 'RC_RUNS=$((RC_RUNS + 1))\n' }, - 'echo "rc=$RC_RUNS"\n', - 'darwin' - ) + it.skipIf(!BASH_KEEPS_HOME)( + 'still reads .bashrc on macOS when the user has no login files', + () => { + const { text } = runBash( + { '.bashrc': 'RC_RUNS=$((RC_RUNS + 1))\n' }, + 'echo "rc=$RC_RUNS"\n', + 'darwin' + ) - expect(text).toContain('rc=1') - }) + expect(text).toContain('rc=1') + } + ) it('reads only .bashrc on Linux, whose terminals start non-login shells', () => { const { text } = runBash(loginAndRcFiles, 'echo "profile=$FROM_PROFILE rc=$RC_RUNS"\n', 'linux')