Skip to content

Commit c18e447

Browse files
authored
improvement(desktop): final cleanup across the desktop fixes (#10679)
1 parent ec57cac commit c18e447

22 files changed

Lines changed: 174 additions & 165 deletions

‎apps/desktop/src/main/app-links.ts‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
11
import { createLogger } from '@sim/logger'
2-
import { truncate } from '@sim/utils/string'
32
import type { WebContents } from 'electron'
43
import { app, BrowserWindow } from 'electron'
4+
import { displayText } from '@/main/browser-agent/page-prompts'
55
import { showShellDialog } from '@/main/dialogs'
66
import { appLinkTarget, openExternalSafe } from '@/main/navigation'
77

88
const logger = createLogger('DesktopAppLinks')
99

10-
/** C0/C1 controls and bidi overrides: an app name must not reorder or hide the prompt text. */
11-
const DISPLAY_NAME_CONTROLS = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g
12-
const MAX_APP_NAME_LENGTH = 80
13-
1410
let promptOpen = false
1511

1612
/**
@@ -28,14 +24,7 @@ export async function openAppLinkWithConsent(
2824
if (!target || promptOpen) return false
2925
let appName = ''
3026
try {
31-
appName = truncate(
32-
app
33-
.getApplicationNameForProtocol(target.url)
34-
.replace(DISPLAY_NAME_CONTROLS, ' ')
35-
.replace(/\s+/g, ' ')
36-
.trim(),
37-
MAX_APP_NAME_LENGTH
38-
)
27+
appName = displayText(app.getApplicationNameForProtocol(target.url), 80)
3928
} catch {}
4029
if (!appName) {
4130
logger.warn('No app handles this link', { scheme: target.scheme })

‎apps/desktop/src/main/browser-agent/page-prompts.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ function recentAttempts(contents: WebContents, key: string, windowMs: number): n
125125
}
126126

127127
/** Untrusted page or server text, reduced to one bounded display line. */
128-
function displayText(value: unknown, maxLength = MAX_DISPLAY_TEXT_LENGTH): string {
128+
export function displayText(value: unknown, maxLength = MAX_DISPLAY_TEXT_LENGTH): string {
129129
if (typeof value !== 'string') return ''
130130
return truncate(
131131
value.replace(UNTRUSTED_TEXT_CONTROLS, ' ').replace(/\s+/g, ' ').trim(),

‎apps/desktop/src/main/browser-agent/session.test.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2502,25 +2502,30 @@ describe('browser-agent session', () => {
25022502
expect(readdirSync(directory)).toEqual([])
25032503
})
25042504

2505-
it('sweeps staging files a previous run left behind, and nothing else', async () => {
2505+
it('sweeps staging files a previous run abandoned, and nothing else', async () => {
25062506
const directory = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-'))
25072507
const stale = [
25082508
'.sim-download-abcDEF123_-xyzABCDEFG',
25092509
'.sim-download-abcDEF123_-xyzABCDEFG.crdownload',
25102510
]
2511+
// The other release channel may be downloading into the same folder right now.
2512+
const recent = '.sim-download-otherChannel123456789.crdownload'
25112513
const kept = ['.sim-download-notes.txt', '.hidden', 'report.csv']
2512-
const longAgo = new Date(Date.now() - 60_000)
2514+
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000)
25132515
for (const name of [...stale, ...kept]) {
25142516
writeFileSync(join(directory, name), 'x')
2515-
utimesSync(join(directory, name), longAgo, longAgo)
2517+
utimesSync(join(directory, name), twoDaysAgo, twoDaysAgo)
25162518
}
2519+
const aMinuteAgo = new Date(Date.now() - 60_000)
2520+
writeFileSync(join(directory, recent), 'x')
2521+
utimesSync(join(directory, recent), aMinuteAgo, aMinuteAgo)
25172522

25182523
session = freshSession(win, {}, undefined, {
25192524
getDirectory: () => directory,
25202525
getFreeDiskBytes: () => Number.MAX_SAFE_INTEGER,
25212526
})
25222527

2523-
await vi.waitFor(() => expect(readdirSync(directory).sort()).toEqual([...kept].sort()))
2528+
await vi.waitFor(() => expect(readdirSync(directory).sort()).toEqual([...kept, recent].sort()))
25242529
})
25252530

25262531
it('cancels every active download on profile wipe without reviving late work', async () => {

‎apps/desktop/src/main/browser-agent/session.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -906,9 +906,16 @@ function removeBrowserDownloadPlaceholder(active: ActiveBrowserDownload): void {
906906
*/
907907
const STAGING_FILE_PATTERN = /^\.sim-download-[A-Za-z0-9_-]{21}(?:\.crdownload)?$/
908908

909+
/**
910+
* How long a staging file must sit untouched before it counts as abandoned. A shorter cutoff
911+
* could delete an in-flight download of this run or of the other release channel, which
912+
* stages into the same Downloads folder.
913+
*/
914+
const ABANDONED_STAGING_AGE_MS = 24 * 60 * 60 * 1000
915+
909916
/**
910917
* Deletes staging files an earlier run left when it quit or crashed mid-download. Files modified
911-
* since `before` may belong to a download this run has started, so they stay.
918+
* since `before` may belong to a download still in progress, so they stay.
912919
*/
913920
async function removeStaleBrowserDownloadStaging(
914921
directories: readonly string[],
@@ -1241,7 +1248,10 @@ export function initSession(
12411248
const downloadDirectories = new Set([app.getPath('downloads')])
12421249
const configuredDownloadDirectory = downloadSettings?.getDirectory()
12431250
if (configuredDownloadDirectory) downloadDirectories.add(configuredDownloadDirectory)
1244-
void removeStaleBrowserDownloadStaging([...downloadDirectories], Date.now())
1251+
void removeStaleBrowserDownloadStaging(
1252+
[...downloadDirectories],
1253+
Date.now() - ABANDONED_STAGING_AGE_MS
1254+
)
12451255
setPagePromptHost({
12461256
tabContext: (contents) => {
12471257
const scoped = scopedTabForContents(contents)
@@ -4161,13 +4171,10 @@ export function handleFocusedShortcut(
41614171
// Accelerators and mouse buttons arrive before any chat has opened a browser.
41624172
if (!getActiveBrowserScopeId()) return false
41634173
// Tab-management accelerators belong to the visible Browser even after
4164-
// focus moves into Sim chrome. Otherwise Cmd-T/L/Shift-T silently stop
4174+
// focus moves into Sim chrome. Otherwise Cmd-T/Shift-T silently stop
41654175
// behaving like browser shortcuts, and Cmd-W becomes especially unsafe.
41664176
const visibleBrowserShortcut =
4167-
shortcut === 'close-tab' ||
4168-
shortcut === 'new-tab' ||
4169-
shortcut === 'reopen-closed-tab' ||
4170-
shortcut === 'focus-omnibox'
4177+
shortcut === 'close-tab' || shortcut === 'new-tab' || shortcut === 'reopen-closed-tab'
41714178
const shortcutTab =
41724179
focusedTabForShortcut(ownerWindow) ??
41734180
(visibleBrowserShortcut ? visibleActiveTab(ownerWindow) : null)
@@ -4191,9 +4198,6 @@ export function handleFocusedShortcut(
41914198
case 'close-tab':
41924199
closeTabFromUser(shortcutTab.id)
41934200
return true
4194-
case 'focus-omnibox':
4195-
focusRendererOmnibox('select')
4196-
return true
41974201
case 'reload-or-clear':
41984202
userNavigate(shortcutTab.view.webContents, 'reload')
41994203
return true

‎apps/desktop/src/main/config.ts‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -269,15 +269,6 @@ const DEFAULT_SETTINGS: DesktopSettings = {
269269
*/
270270
export interface SettingsLoadProblem {
271271
kind: 'read-error' | 'unparseable' | 'invalid-origin'
272-
/** The usable server URL the rejected file names, when one can be read from it. */
273-
storedOrigin: string | null
274-
}
275-
276-
/** Finds the server a damaged file still names, so a repair can say what it replaces. */
277-
function findStoredOrigin(raw: string): string | null {
278-
const match = /"origin"\s*:\s*"([^"]*)"/.exec(raw)
279-
const validated = match ? validateOriginInput(match[1]) : null
280-
return validated?.ok ? canonicalOrigin(validated.origin) : null
281272
}
282273

283274
export interface ConfigStore {
@@ -334,7 +325,7 @@ export function createConfigStore(
334325
raw = readFileSync(filePath, 'utf8')
335326
} catch (error) {
336327
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
337-
loadProblem = { kind: 'read-error', storedOrigin: null }
328+
loadProblem = { kind: 'read-error' }
338329
}
339330
}
340331
if (raw !== null) {
@@ -345,7 +336,7 @@ export function createConfigStore(
345336
parsed = null
346337
}
347338
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
348-
loadProblem = { kind: 'unparseable', storedOrigin: findStoredOrigin(raw) }
339+
loadProblem = { kind: 'unparseable' }
349340
} else {
350341
const loadedSettings = { ...DEFAULT_SETTINGS, ...(parsed as Partial<DesktopSettings>) }
351342
const validated =
@@ -355,7 +346,6 @@ export function createConfigStore(
355346
if (!validated?.ok) {
356347
loadProblem = {
357348
kind: typeof loadedSettings.origin === 'string' ? 'invalid-origin' : 'unparseable',
358-
storedOrigin: null,
359349
}
360350
} else {
361351
const loaded = validated.origin
@@ -392,8 +382,9 @@ export function createConfigStore(
392382
/** Changes a failed write left only in memory; every later write retries them. */
393383
let unsavedChanges = false
394384
/**
395-
* Sticky for the session: account-bearing stores were gated on persistence
396-
* when they opened, so a write that recovers does not re-admit them mid-run.
385+
* Set by a failed write and cleared only when `setOrigin` writes: account-bearing stores were
386+
* gated on persistence when they opened, so an ordinary write that recovers does not re-admit
387+
* them mid-run.
397388
*/
398389
let writeFailedThisSession = false
399390

‎apps/desktop/src/main/desktop-settings.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ function service(
1010
window: { url: string; focused: boolean } | null,
1111
overrides: Partial<Parameters<typeof createDesktopSettingsService>[0]> = {},
1212
config = new Map<string, unknown>(),
13-
store: { flush?: () => boolean; loadProblem?: { kind: 'unparseable'; storedOrigin: null } } = {}
13+
store: { flush?: () => boolean; loadProblem?: { kind: 'unparseable' } } = {}
1414
) {
1515
return createDesktopSettingsService({
1616
existingInstall: false,
@@ -210,7 +210,7 @@ describe('preference writes while the settings file is rejected', () => {
210210
const setTrayEnabled = vi.fn()
211211
const settings = service(null, { setTrayEnabled }, undefined, {
212212
flush: () => false,
213-
loadProblem: { kind: 'unparseable', storedOrigin: null },
213+
loadProblem: { kind: 'unparseable' },
214214
})
215215

216216
expect(settings.setPreference('trayEnabled', false).trayEnabled).toBe(false)

‎apps/desktop/src/main/in-flight-work.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,8 @@ export interface QuitGuard {
161161
/**
162162
* Called from every `before-quit`: true when this quit must wait while the guard checks for
163163
* work, false when it was cleared to go through. A cleared quit is let through once. `bypass`
164-
* lets through a quit the guard must not hold (a committed relaunch, or one resuming after
165-
* account teardown); it still uses up a clearance, so none carries over to a later quit.
164+
* lets through a quit the guard must not hold (a committed relaunch); it still uses up a
165+
* clearance, so none carries over to a later quit.
166166
*/
167167
holdQuit: (options?: { bypass?: boolean }) => boolean
168168
/** Whether the user chose to quit despite work in progress, so unload guards need not ask again. */

‎apps/desktop/src/main/index.ts‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ import { createDesktopToolRunner } from '@/main/desktop-executor/runner'
7878
import { createDesktopExecutorService } from '@/main/desktop-executor/service'
7979
import { createSleepBlocker } from '@/main/desktop-executor/sleep-blocker'
8080
import { createDesktopSettingsService, wasOpenedAtLogin } from '@/main/desktop-settings'
81-
import { showShellDialog } from '@/main/dialogs'
8281
import { attachDownloadHandling, countProgressingAppDownloads } from '@/main/downloads'
8382
import { createAuthFlow, createConnectFlow, createHandoffManager } from '@/main/handoff'
8483
import {
@@ -126,6 +125,7 @@ import { createRunLedger } from '@/main/terminal/run-ledger'
126125
import { installTray, type TrayHandle } from '@/main/tray'
127126
import { checkForUpdatesInteractive, initUpdater, type UpdaterHandle } from '@/main/updater'
128127
import { installBrowserUserAgent } from '@/main/user-agent'
128+
import { showShellDialogOver } from '@/main/visible-dialog'
129129
import {
130130
createMainWindow,
131131
guardVisibilityListenersAfterDestroy,
@@ -318,6 +318,8 @@ function main(): void {
318318
let appSession: Session | null = null
319319
let sessionLifecycle: ReturnType<typeof createSessionLifecycleCoordinator> | null = null
320320
let resumingQuitAfterTeardown = false
321+
let quitPromptOpen = false
322+
let reopeningWindowAfterQuitCancel = false
321323
let committedRelaunchPending = false
322324
let tray: TrayHandle | null = null
323325
let updater: UpdaterHandle | null = null
@@ -559,7 +561,7 @@ function main(): void {
559561
if (activate) void opened.then(showMainWindow)
560562
},
561563
allowHttpLocalhost: allowHttpLocalhost(),
562-
isCommittedRelaunchPending: isExitCommitted,
564+
isExitCommitted,
563565
}
564566
}
565567

@@ -965,17 +967,22 @@ function main(): void {
965967
defaultId: 1,
966968
cancelId: 1,
967969
}
968-
// A sheet on a hidden or minimized window would be a prompt nobody can see.
969-
const win = getMainWindow()
970-
const { response } = await (win?.isVisible() && !win.isMinimized()
971-
? showShellDialog(win, options)
972-
: showShellDialog(options))
973-
return response === 0
970+
quitPromptOpen = true
971+
try {
972+
const { response } = await showShellDialogOver(getMainWindow(), options)
973+
return response === 0
974+
} finally {
975+
quitPromptOpen = false
976+
}
974977
},
975978
quit: () => app.quit(),
976979
onCancel: () => {
977980
// Closing the last window quit Sim on Windows and Linux; staying means keeping a window.
978-
if (process.platform !== 'darwin' && getWindows().length === 0) void ensureMainWindow()
981+
if (process.platform === 'darwin' || getWindows().length > 0) return
982+
reopeningWindowAfterQuitCancel = true
983+
void ensureMainWindow().finally(() => {
984+
reopeningWindowAfterQuitCancel = false
985+
})
979986
},
980987
})
981988

@@ -989,7 +996,8 @@ function main(): void {
989996
})
990997

991998
app.on('window-all-closed', () => {
992-
if (process.platform !== 'darwin') {
999+
// The quit prompt closing, or a cancelled quit's window still opening, is not a new quit.
1000+
if (process.platform !== 'darwin' && !quitPromptOpen && !reopeningWindowAfterQuitCancel) {
9931001
app.quit()
9941002
}
9951003
})
@@ -1018,12 +1026,11 @@ function main(): void {
10181026
})
10191027
return
10201028
}
1021-
// A committed relaunch has already asked about, or deliberately skipped, the work it
1022-
// interrupts, and a quit resuming after teardown was already let through. The resume is
1023-
// one quit only: if something cancels it, the next quit is checked again.
1024-
const resumedAfterTeardown = resumingQuitAfterTeardown
1029+
// Waiting on teardown is one quit only: if something cancels it, the next quit waits again.
10251030
resumingQuitAfterTeardown = false
1026-
if (quitGuard.holdQuit({ bypass: committedRelaunchPending || resumedAfterTeardown })) {
1031+
// A committed relaunch has already asked about, or deliberately skipped, the work it
1032+
// interrupts. Every other quit, including one resuming after teardown, is checked here.
1033+
if (quitGuard.holdQuit({ bypass: committedRelaunchPending })) {
10271034
event.preventDefault()
10281035
return
10291036
}

‎apps/desktop/src/main/menu.test.ts‎

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -46,23 +46,4 @@ describe('buildMenuTemplate', () => {
4646
const view = submenu(buildMenuTemplate(makeDeps()), 'View')
4747
expect(view.some((item) => item.role === 'toggleDevTools')).toBe(false)
4848
})
49-
50-
/**
51-
* A menu accelerator reaches the menu before the page, so a chord the web app
52-
* binds itself (Cmd+B bold in the editor, Cmd+K link, Cmd+L logs) must not be
53-
* claimed here or the page never sees it.
54-
*/
55-
it('leaves the web app its own Mod+B, Mod+K and Mod+L shortcuts', () => {
56-
const accelerators: string[] = []
57-
const collect = (items: MenuItemConstructorOptions[]) => {
58-
for (const item of items) {
59-
if (typeof item.accelerator === 'string') accelerators.push(item.accelerator)
60-
if (Array.isArray(item.submenu)) collect(item.submenu)
61-
}
62-
}
63-
collect(buildMenuTemplate(makeDeps()))
64-
for (const owned of ['CmdOrCtrl+B', 'CmdOrCtrl+K', 'CmdOrCtrl+L']) {
65-
expect(accelerators).not.toContain(owned)
66-
}
67-
})
6849
})

‎apps/desktop/src/main/quick-chat.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ export function createQuickChat(deps: QuickChatDeps): QuickChat {
9494
// A crashed page cannot recover in place; the next toggle builds a fresh window instead.
9595
created.webContents.on('render-process-gone', () => created.destroy())
9696
created.webContents.on('will-prevent-unload', (event) => {
97-
handleWillPreventUnload(created, event, deps.windowPolicy.isCommittedRelaunchPending())
97+
handleWillPreventUnload(created, event, deps.windowPolicy.isExitCommitted())
9898
})
9999
attachWindowOpenPolicy(created.webContents, deps.windowPolicy)
100100
attachContextMenu(created.webContents, deps.contextMenu)

0 commit comments

Comments
 (0)