Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 2 additions & 13 deletions apps/desktop/src/main/app-links.ts
Original file line number Diff line number Diff line change
@@ -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

/**
Expand All @@ -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 })
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src/main/browser-agent/page-prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
if (typeof value !== 'string') return ''
return truncate(
value.replace(UNTRUSTED_TEXT_CONTROLS, ' ').replace(/\s+/g, ' ').trim(),
Expand Down
13 changes: 9 additions & 4 deletions apps/desktop/src/main/browser-agent/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
24 changes: 14 additions & 10 deletions apps/desktop/src/main/browser-agent/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[],
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
19 changes: 5 additions & 14 deletions apps/desktop/src/main/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand All @@ -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<DesktopSettings>) }
const validated =
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/main/desktop-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function service(
window: { url: string; focused: boolean } | null,
overrides: Partial<Parameters<typeof createDesktopSettingsService>[0]> = {},
config = new Map<string, unknown>(),
store: { flush?: () => boolean; loadProblem?: { kind: 'unparseable'; storedOrigin: null } } = {}
store: { flush?: () => boolean; loadProblem?: { kind: 'unparseable' } } = {}
) {
return createDesktopSettingsService({
existingInstall: false,
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/main/in-flight-work.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
37 changes: 22 additions & 15 deletions apps/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -318,6 +318,8 @@ function main(): void {
let appSession: Session | null = null
let sessionLifecycle: ReturnType<typeof createSessionLifecycleCoordinator> | null = null
let resumingQuitAfterTeardown = false
let quitPromptOpen = false
let reopeningWindowAfterQuitCancel = false
let committedRelaunchPending = false
let tray: TrayHandle | null = null
let updater: UpdaterHandle | null = null
Expand Down Expand Up @@ -559,7 +561,7 @@ function main(): void {
if (activate) void opened.then(showMainWindow)
},
allowHttpLocalhost: allowHttpLocalhost(),
isCommittedRelaunchPending: isExitCommitted,
isExitCommitted,
}
}

Expand Down Expand Up @@ -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
})
},
})

Expand All @@ -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()
}
})
Expand Down Expand Up @@ -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
}
Expand Down
19 changes: 0 additions & 19 deletions apps/desktop/src/main/menu.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
})
2 changes: 1 addition & 1 deletion apps/desktop/src/main/quick-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion apps/desktop/src/main/resource-shortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export type FocusedResourceShortcut =
| 'new-tab'
| 'reopen-closed-tab'
| 'close-tab'
| 'focus-omnibox'
| ResourceTabSelectionShortcut
| 'reload-or-clear'
| 'hard-reload'
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/main/settings-repair.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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()
})

Expand Down
Loading
Loading