diff --git a/src/main/crash-reporting/crash-report-store.test.ts b/src/main/crash-reporting/crash-report-store.test.ts index 44e6c83fd..2dc9a87aa 100644 --- a/src/main/crash-reporting/crash-report-store.test.ts +++ b/src/main/crash-reporting/crash-report-store.test.ts @@ -87,6 +87,35 @@ describe('CrashReportStore', () => { await expect(store.markSent(report.id)).resolves.toMatchObject({ status: 'dismissed' }) }) + it('dismisses sibling pending records from the same Electron crash event', async () => { + const { store } = await createStore() + await store.record(input()) + await store.record(input()) + const renderer = await store.record(input()) + + await expect(store.dismiss(renderer.id)).resolves.toMatchObject({ status: 'dismissed' }) + await expect(store.getLatestPending()).resolves.toBeNull() + }) + + it('dismisses sibling pending records after one crash report is sent', async () => { + const { store } = await createStore() + await store.record(input()) + await store.record(input()) + const renderer = await store.record(input()) + + await expect(store.markSent(renderer.id)).resolves.toMatchObject({ status: 'sent' }) + + const reports = await store.listRecent() + expect(reports).toEqual( + expect.arrayContaining([ + expect.objectContaining({ id: renderer.id, status: 'sent' }), + expect.objectContaining({ status: 'dismissed' }), + expect.objectContaining({ status: 'dismissed' }) + ]) + ) + await expect(store.getLatestPending()).resolves.toBeNull() + }) + it('persists a submitted dismissed report as sent', async () => { const { store, filePath } = await createStore() const report = await store.record(input()) diff --git a/src/main/crash-reporting/crash-report-store.ts b/src/main/crash-reporting/crash-report-store.ts index 695ecca57..e1791398e 100644 --- a/src/main/crash-reporting/crash-report-store.ts +++ b/src/main/crash-reporting/crash-report-store.ts @@ -13,11 +13,30 @@ import { } from '../../shared/crash-reporting' const MAX_REPORTS = 5 +const RELATED_CRASH_WINDOW_MS = 5_000 type CrashReportFile = { reports: CrashReportRecord[] } +function isRelatedCrashEvent(anchor: CrashReportRecord, candidate: CrashReportRecord): boolean { + if (anchor.id === candidate.id || candidate.status !== 'pending') { + return false + } + const anchorTime = Date.parse(anchor.createdAt) + const candidateTime = Date.parse(candidate.createdAt) + if (!Number.isFinite(anchorTime) || !Number.isFinite(candidateTime)) { + return false + } + return ( + Math.abs(anchorTime - candidateTime) <= RELATED_CRASH_WINDOW_MS && + anchor.reason === candidate.reason && + anchor.exitCode === candidate.exitCode && + anchor.appVersion === candidate.appVersion && + anchor.platform === candidate.platform + ) +} + export class CrashReportStore { private writeChain = Promise.resolve() @@ -90,8 +109,15 @@ export class CrashReportStore { ): Promise { return this.withWrite(async (reports) => { let result: CrashReportRecord | null = null + const anchor = reports.find((report) => report.id === id) const nextReports = reports.map((report) => { if (report.id !== id) { + // Why: one Electron crash can emit GPU/Network/renderer exits in a + // burst. Once one report is handled, sibling pending records should + // not re-open the crash prompt as separate crashes. + if (anchor && anchor.status === from && isRelatedCrashEvent(anchor, report)) { + return { ...report, status: 'dismissed' as const } + } return report } if (report.status !== from) { diff --git a/src/main/ipc/filesystem-watcher-local-unsubscribe.test.ts b/src/main/ipc/filesystem-watcher-local-unsubscribe.test.ts new file mode 100644 index 000000000..4384b6a87 --- /dev/null +++ b/src/main/ipc/filesystem-watcher-local-unsubscribe.test.ts @@ -0,0 +1,90 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { handleMock } = vi.hoisted(() => ({ + handleMock: vi.fn() +})) + +vi.mock('electron', () => ({ + ipcMain: { + handle: handleMock + } +})) + +vi.mock('fs/promises', () => ({ + stat: vi.fn() +})) + +vi.mock('@parcel/watcher', () => ({ + subscribe: vi.fn() +})) + +vi.mock('./filesystem-watcher-wsl', () => ({ + createWslWatcher: vi.fn() +})) + +vi.mock('../providers/ssh-filesystem-dispatch', () => ({ + getSshFilesystemProvider: vi.fn() +})) + +import { closeAllWatchers, registerFilesystemWatcherHandlers } from './filesystem-watcher' +import { stat } from 'fs/promises' +import { subscribe as subscribeParcelWatcher } from '@parcel/watcher' + +type HandlerMap = Record Promise | unknown> + +describe('local filesystem watcher shutdown', () => { + const handlers: HandlerMap = {} + + beforeEach(() => { + vi.useRealTimers() + handleMock.mockReset() + vi.mocked(stat).mockReset() + vi.mocked(subscribeParcelWatcher).mockReset() + for (const key of Object.keys(handlers)) { + delete handlers[key] + } + handleMock.mockImplementation((channel, handler) => { + handlers[channel] = handler + }) + registerFilesystemWatcherHandlers() + }) + + it('awaits unsubscribe already started by sender cleanup during shutdown', async () => { + vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as never) + let resolveUnsubscribe: () => void = () => {} + const unsubscribeMock = vi.fn( + () => + new Promise((resolve) => { + resolveUnsubscribe = resolve + }) + ) + vi.mocked(subscribeParcelWatcher).mockResolvedValue({ unsubscribe: unsubscribeMock } as never) + const destroyedCallbacks: (() => void)[] = [] + const sender = { + isDestroyed: () => false, + send: vi.fn(), + once: vi.fn((event: string, callback: () => void) => { + if (event === 'destroyed') { + destroyedCallbacks.push(callback) + } + }), + id: 1 + } + + await handlers['fs:watchWorktree']({ sender }, { worktreePath: '/tmp/repo' }) + destroyedCallbacks[0]() + + let shutdownResolved = false + const shutdownPromise = closeAllWatchers().then(() => { + shutdownResolved = true + }) + await Promise.resolve() + + expect(unsubscribeMock).toHaveBeenCalledTimes(1) + expect(shutdownResolved).toBe(false) + + resolveUnsubscribe() + await shutdownPromise + expect(shutdownResolved).toBe(true) + }) +}) diff --git a/src/main/ipc/filesystem-watcher.ts b/src/main/ipc/filesystem-watcher.ts index 030c28472..79d3d38b1 100644 --- a/src/main/ipc/filesystem-watcher.ts +++ b/src/main/ipc/filesystem-watcher.ts @@ -62,6 +62,9 @@ const senderCleanupRegistered = new Set() // Key: rootKey, Value: pending teardown timer. const WATCHER_TEARDOWN_GRACE_MS = 30_000 const pendingTeardowns = new Map>() +// Why: @parcel/watcher unsubscribe completes native async work. Sender-destroy +// cleanup can start it before app shutdown, so will-quit must still await it. +const pendingLocalUnsubscribes = new Set>() // ── Path normalization ─────────────────────────────────────────────── @@ -324,15 +327,26 @@ function cleanupLocalWatchersForSender(senderId: number): void { if (watchedRoot.batch.timer) { clearTimeout(watchedRoot.batch.timer) } - void watchedRoot.subscription.unsubscribe().catch((err: unknown) => { - console.error(`[filesystem-watcher] unsubscribe error for ${key}:`, err) - }) + trackLocalUnsubscribe(key, watchedRoot) watchedRoots.delete(key) } } } } +function trackLocalUnsubscribe(rootKey: string, root: WatchedRoot): Promise { + const unsubscribePromise = Promise.resolve() + .then(() => root.subscription.unsubscribe()) + .catch((err: unknown) => { + console.error(`[filesystem-watcher] unsubscribe error for ${rootKey}:`, err) + }) + .finally(() => { + pendingLocalUnsubscribes.delete(unsubscribePromise) + }) + pendingLocalUnsubscribes.add(unsubscribePromise) + return unsubscribePromise +} + function registerSenderCleanup(sender: WebContents): void { if (senderCleanupRegistered.has(sender.id)) { return @@ -424,9 +438,7 @@ function unsubscribe(worktreePath: string, senderId: number): void { if (!currentRoot || currentRoot.listeners.size > 0) { return } - void currentRoot.subscription.unsubscribe().catch((err: unknown) => { - console.error(`[filesystem-watcher] unsubscribe error for ${rootKey}:`, err) - }) + void trackLocalUnsubscribe(rootKey, currentRoot) watchedRoots.delete(rootKey) }, WATCHER_TEARDOWN_GRACE_MS) @@ -729,13 +741,10 @@ export async function closeAllWatchers(): Promise { if (root.batch.timer) { clearTimeout(root.batch.timer) } - try { - await root.subscription.unsubscribe() - } catch (err) { - console.error(`[filesystem-watcher] shutdown unsubscribe error for ${rootKey}:`, err) - } + await trackLocalUnsubscribe(rootKey, root) } watchedRoots.clear() + await Promise.allSettled(Array.from(pendingLocalUnsubscribes)) // Why: remote watchers are tracked separately from local @parcel/watcher // subscriptions. Without cleaning them up here, their unwatch callbacks