|
1 | | -import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' |
| 1 | +import { |
| 2 | + existsSync, |
| 3 | + mkdtempSync, |
| 4 | + readdirSync, |
| 5 | + readFileSync, |
| 6 | + utimesSync, |
| 7 | + writeFileSync, |
| 8 | +} from 'node:fs' |
2 | 9 | import { tmpdir } from 'node:os' |
3 | 10 | import { basename, dirname, join } from 'node:path' |
4 | 11 | import type { MenuItemConstructorOptions, WebContents } from 'electron' |
@@ -1541,6 +1548,274 @@ describe('browser-agent session', () => { |
1541 | 1548 | } |
1542 | 1549 | }) |
1543 | 1550 |
|
| 1551 | + describe('media grants a page already holds', () => { |
| 1552 | + type RequestHandler = ( |
| 1553 | + wc: unknown, |
| 1554 | + permission: string, |
| 1555 | + callback: (granted: boolean) => void, |
| 1556 | + details?: unknown |
| 1557 | + ) => void |
| 1558 | + const microphone = { |
| 1559 | + isMainFrame: true, |
| 1560 | + mediaTypes: ['audio'], |
| 1561 | + requestingUrl: 'https://example.com/', |
| 1562 | + securityOrigin: 'https://example.com', |
| 1563 | + } |
| 1564 | + |
| 1565 | + function onScreenTab() { |
| 1566 | + vi.mocked(win.isFocused).mockReturnValue(true) |
| 1567 | + panel.setPanelBounds({ x: 100, y: 50, width: 800, height: 600 }) |
| 1568 | + const tab = session.ensureTab() |
| 1569 | + const contents = (tab.view as unknown as MockView).webContents |
| 1570 | + contents.isFocused.mockReturnValue(true) |
| 1571 | + const click = () => { |
| 1572 | + const handler = contents.on.mock.calls.find( |
| 1573 | + ([eventName]) => eventName === 'before-mouse-event' |
| 1574 | + )?.[1] as ((_event: unknown, mouse: { type: string }) => void) | undefined |
| 1575 | + handler?.({}, { type: 'mouseDown' }) |
| 1576 | + } |
| 1577 | + const request = contents.session.setPermissionRequestHandler.mock |
| 1578 | + .calls[0][0] as RequestHandler |
| 1579 | + return { tab, contents, click, request } |
| 1580 | + } |
| 1581 | + |
| 1582 | + async function grantMicrophone(page: ReturnType<typeof onScreenTab>) { |
| 1583 | + page.click() |
| 1584 | + const callback = vi.fn() |
| 1585 | + page.request(page.contents, 'media', callback, microphone) |
| 1586 | + const prompt = session.mediaPermissionRequestForContents( |
| 1587 | + page.contents as unknown as WebContents |
| 1588 | + ) |
| 1589 | + await session.respondToMediaPermission(prompt?.requestId ?? '', true) |
| 1590 | + expect(callback).toHaveBeenCalledWith(true) |
| 1591 | + } |
| 1592 | + |
| 1593 | + it('answers a repeat request from a granted origin without prompting again', async () => { |
| 1594 | + const page = onScreenTab() |
| 1595 | + await grantMicrophone(page) |
| 1596 | + // A route change inside the call page, then a device change with no click. |
| 1597 | + mainFrameNavigationStarted(page.contents, true, 'https://example.com/call') |
| 1598 | + |
| 1599 | + const repeat = vi.fn() |
| 1600 | + page.request(page.contents, 'media', repeat, microphone) |
| 1601 | + |
| 1602 | + expect(repeat).toHaveBeenCalledWith(true) |
| 1603 | + expect( |
| 1604 | + session.mediaPermissionRequestForContents(page.contents as unknown as WebContents) |
| 1605 | + ).toBeUndefined() |
| 1606 | + }) |
| 1607 | + |
| 1608 | + it('keeps a grant across a switch to another tab and back', async () => { |
| 1609 | + const page = onScreenTab() |
| 1610 | + await grantMicrophone(page) |
| 1611 | + const other = session.addTab() |
| 1612 | + session.switchTab(other.id) |
| 1613 | + session.switchTab(page.tab.id) |
| 1614 | + |
| 1615 | + const repeat = vi.fn() |
| 1616 | + page.request(page.contents, 'media', repeat, microphone) |
| 1617 | + |
| 1618 | + expect(repeat).toHaveBeenCalledWith(true) |
| 1619 | + }) |
| 1620 | + |
| 1621 | + it('prompts for a device kind the grant does not cover and keeps the old one', async () => { |
| 1622 | + const page = onScreenTab() |
| 1623 | + await grantMicrophone(page) |
| 1624 | + page.click() |
| 1625 | + |
| 1626 | + const camera = vi.fn() |
| 1627 | + page.request(page.contents, 'media', camera, { ...microphone, mediaTypes: ['video'] }) |
| 1628 | + |
| 1629 | + expect(camera).not.toHaveBeenCalled() |
| 1630 | + expect( |
| 1631 | + session.mediaPermissionRequestForContents(page.contents as unknown as WebContents) |
| 1632 | + ).toMatchObject({ devices: ['camera'] }) |
| 1633 | + const repeat = vi.fn() |
| 1634 | + page.request(page.contents, 'media', repeat, microphone) |
| 1635 | + expect(repeat).toHaveBeenCalledWith(true) |
| 1636 | + }) |
| 1637 | + |
| 1638 | + it('drops the grant when the tab loads another document', async () => { |
| 1639 | + const page = onScreenTab() |
| 1640 | + await grantMicrophone(page) |
| 1641 | + mainFrameNavigationStarted(page.contents, false, 'https://example.com/other-meeting') |
| 1642 | + |
| 1643 | + const repeat = vi.fn() |
| 1644 | + page.request(page.contents, 'media', repeat, microphone) |
| 1645 | + |
| 1646 | + expect(repeat).toHaveBeenCalledWith(false) |
| 1647 | + }) |
| 1648 | + |
| 1649 | + it('never answers from a grant once the agent has acted in the tab', async () => { |
| 1650 | + const page = onScreenTab() |
| 1651 | + await grantMicrophone(page) |
| 1652 | + page.tab.lastAgentInputAt = Date.now() |
| 1653 | + |
| 1654 | + const repeat = vi.fn() |
| 1655 | + page.request(page.contents, 'media', repeat, microphone) |
| 1656 | + |
| 1657 | + expect(repeat).not.toHaveBeenCalledWith(true) |
| 1658 | + }) |
| 1659 | + |
| 1660 | + it('never answers from a grant while or after the agent drives the tab', async () => { |
| 1661 | + const page = onScreenTab() |
| 1662 | + await grantMicrophone(page) |
| 1663 | + // A scripted select fires the page's change handler without any native input. |
| 1664 | + session.setAutomationActive(true) |
| 1665 | + |
| 1666 | + const during = vi.fn() |
| 1667 | + page.request(page.contents, 'media', during, microphone) |
| 1668 | + session.setAutomationActive(false) |
| 1669 | + const after = vi.fn() |
| 1670 | + page.request(page.contents, 'media', after, microphone) |
| 1671 | + |
| 1672 | + expect(during).not.toHaveBeenCalledWith(true) |
| 1673 | + expect(after).not.toHaveBeenCalledWith(true) |
| 1674 | + const check = page.contents.session.setPermissionCheckHandler.mock.calls[0][0] as ( |
| 1675 | + wc: unknown, |
| 1676 | + permission: string, |
| 1677 | + origin?: string, |
| 1678 | + details?: unknown |
| 1679 | + ) => boolean |
| 1680 | + expect( |
| 1681 | + check(page.contents, 'media', 'https://example.com', { |
| 1682 | + isMainFrame: true, |
| 1683 | + mediaType: 'audio', |
| 1684 | + }) |
| 1685 | + ).toBe(false) |
| 1686 | + }) |
| 1687 | + |
| 1688 | + it('keeps the user click across a same-document route change', () => { |
| 1689 | + const page = onScreenTab() |
| 1690 | + page.click() |
| 1691 | + mainFrameNavigationStarted(page.contents, true, 'https://example.com/channels/voice') |
| 1692 | + |
| 1693 | + const callback = vi.fn() |
| 1694 | + page.request(page.contents, 'media', callback, microphone) |
| 1695 | + |
| 1696 | + expect(callback).not.toHaveBeenCalled() |
| 1697 | + expect( |
| 1698 | + session.mediaPermissionRequestForContents(page.contents as unknown as WebContents) |
| 1699 | + ).toMatchObject({ devices: ['microphone'] }) |
| 1700 | + }) |
| 1701 | + }) |
| 1702 | + |
| 1703 | + describe('find shortcut', () => { |
| 1704 | + function pressFind(contents: MockView['webContents']) { |
| 1705 | + const keyDown = contents.on.mock.calls.find( |
| 1706 | + ([eventName]) => eventName === 'before-input-event' |
| 1707 | + )?.[1] as (event: { preventDefault: () => void }, input: Record<string, unknown>) => void |
| 1708 | + const event = { preventDefault: vi.fn() } |
| 1709 | + keyDown(event, { |
| 1710 | + type: 'keyDown', |
| 1711 | + key: 'f', |
| 1712 | + code: 'KeyF', |
| 1713 | + isAutoRepeat: false, |
| 1714 | + isComposing: false, |
| 1715 | + shift: false, |
| 1716 | + alt: false, |
| 1717 | + control: process.platform !== 'darwin', |
| 1718 | + meta: process.platform === 'darwin', |
| 1719 | + }) |
| 1720 | + return event |
| 1721 | + } |
| 1722 | + const openFindCalls = () => |
| 1723 | + vi |
| 1724 | + .mocked(win.webContents.send) |
| 1725 | + .mock.calls.filter(([channel]) => channel === 'browser-agent:open-find') |
| 1726 | + |
| 1727 | + beforeEach(() => { |
| 1728 | + panel.setPanelBounds({ x: 100, y: 50, width: 800, height: 600 }) |
| 1729 | + }) |
| 1730 | + |
| 1731 | + it('lets the page take the key first and opens find only when the page left it', () => { |
| 1732 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 1733 | + const event = pressFind(contents) |
| 1734 | + |
| 1735 | + expect(event.preventDefault).not.toHaveBeenCalled() |
| 1736 | + expect(openFindCalls()).toHaveLength(0) |
| 1737 | + |
| 1738 | + session.noteFindKeyFromPage(contents as unknown as WebContents, false) |
| 1739 | + expect(openFindCalls()).toHaveLength(1) |
| 1740 | + }) |
| 1741 | + |
| 1742 | + it('leaves find to a page that handled the key', () => { |
| 1743 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 1744 | + pressFind(contents) |
| 1745 | + |
| 1746 | + session.noteFindKeyFromPage(contents as unknown as WebContents, true) |
| 1747 | + |
| 1748 | + expect(openFindCalls()).toHaveLength(0) |
| 1749 | + }) |
| 1750 | + |
| 1751 | + it('drops a pending find key when the page loads another document', async () => { |
| 1752 | + vi.useFakeTimers() |
| 1753 | + try { |
| 1754 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 1755 | + pressFind(contents) |
| 1756 | + for (const [eventName, handler] of contents.on.mock.calls) { |
| 1757 | + if (eventName !== 'did-start-navigation') continue |
| 1758 | + handler({ isMainFrame: true, isSameDocument: false, url: 'https://example.com/next' }) |
| 1759 | + } |
| 1760 | + await vi.advanceTimersByTimeAsync(1_000) |
| 1761 | + session.noteFindKeyFromPage(contents as unknown as WebContents, false) |
| 1762 | + |
| 1763 | + expect(openFindCalls()).toHaveLength(0) |
| 1764 | + } finally { |
| 1765 | + vi.useRealTimers() |
| 1766 | + } |
| 1767 | + }) |
| 1768 | + |
| 1769 | + it('ignores a page report no user keypress asked for', () => { |
| 1770 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 1771 | + |
| 1772 | + session.noteFindKeyFromPage(contents as unknown as WebContents, false) |
| 1773 | + |
| 1774 | + expect(openFindCalls()).toHaveLength(0) |
| 1775 | + }) |
| 1776 | + |
| 1777 | + it('opens find when the page never reports, unless a web frame holds focus', async () => { |
| 1778 | + vi.useFakeTimers() |
| 1779 | + try { |
| 1780 | + const contents = (session.ensureTab().view as unknown as MockView) |
| 1781 | + .webContents as MockView['webContents'] & { |
| 1782 | + focusedFrame?: { parent: unknown; origin: string } |
| 1783 | + } |
| 1784 | + // Docs types into a same-origin about:blank frame, which inherits the page's origin. |
| 1785 | + contents.focusedFrame = { parent: {}, origin: 'https://docs.example' } |
| 1786 | + pressFind(contents) |
| 1787 | + await vi.advanceTimersByTimeAsync(1_000) |
| 1788 | + expect(openFindCalls()).toHaveLength(0) |
| 1789 | + |
| 1790 | + contents.focusedFrame = { parent: null, origin: 'https://docs.example' } |
| 1791 | + pressFind(contents) |
| 1792 | + await vi.advanceTimersByTimeAsync(1_000) |
| 1793 | + expect(openFindCalls()).toHaveLength(1) |
| 1794 | + |
| 1795 | + // The built-in PDF viewer has no find of its own. |
| 1796 | + contents.focusedFrame = { parent: {}, origin: 'chrome-extension://pdf-viewer' } |
| 1797 | + pressFind(contents) |
| 1798 | + await vi.advanceTimersByTimeAsync(1_000) |
| 1799 | + expect(openFindCalls()).toHaveLength(2) |
| 1800 | + } finally { |
| 1801 | + vi.useRealTimers() |
| 1802 | + } |
| 1803 | + }) |
| 1804 | + }) |
| 1805 | + |
| 1806 | + it('changes the default zoom only on tabs still at the previous default', () => { |
| 1807 | + const atDefault = (session.ensureTab().view as unknown as MockView).webContents |
| 1808 | + const zoomedByUser = (session.addTab().view as unknown as MockView).webContents |
| 1809 | + const previousDefault = session.getBrowserDefaultZoomFactor() |
| 1810 | + atDefault.getZoomFactor.mockReturnValue(previousDefault) |
| 1811 | + zoomedByUser.getZoomFactor.mockReturnValue(previousDefault * 1.5) |
| 1812 | + |
| 1813 | + session.setBrowserDefaultZoom(125) |
| 1814 | + |
| 1815 | + expect(atDefault.setZoomFactor).toHaveBeenCalledWith(session.getBrowserDefaultZoomFactor()) |
| 1816 | + expect(zoomedByUser.setZoomFactor).not.toHaveBeenCalled() |
| 1817 | + }) |
| 1818 | + |
1544 | 1819 | it.each(['mainFrame', 'subFrame'])( |
1545 | 1820 | 'retains private-network checks for %s navigation', |
1546 | 1821 | async (resourceType) => { |
@@ -2029,6 +2304,107 @@ describe('browser-agent session', () => { |
2029 | 2304 | await vi.waitFor(() => expect(finishedDownloadFiles(directory)).toEqual(['stream.bin'])) |
2030 | 2305 | }) |
2031 | 2306 |
|
| 2307 | + it('admits an unknown-size download without reserving the whole size cap', async () => { |
| 2308 | + const directory = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-')) |
| 2309 | + session = freshSession(win, {}, undefined, { |
| 2310 | + getDirectory: () => directory, |
| 2311 | + getFreeDiskBytes: () => 1.5 * 1024 ** 3, |
| 2312 | + }) |
| 2313 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 2314 | + const download = mockDownloadItem({ filename: 'export.csv', totalBytes: 0 }) |
| 2315 | + |
| 2316 | + startMockDownload(contents, download) |
| 2317 | + |
| 2318 | + await vi.waitFor(() => expect(download.item.resume).toHaveBeenCalledOnce()) |
| 2319 | + expect(download.item.cancel).not.toHaveBeenCalled() |
| 2320 | + }) |
| 2321 | + |
| 2322 | + it('stops an unknown-size download once its bytes eat into the free-space floor', async () => { |
| 2323 | + const directory = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-')) |
| 2324 | + let freeBytes = 1.5 * 1024 ** 3 |
| 2325 | + session = freshSession(win, {}, undefined, { |
| 2326 | + getDirectory: () => directory, |
| 2327 | + getFreeDiskBytes: () => freeBytes, |
| 2328 | + }) |
| 2329 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 2330 | + const download = mockDownloadItem({ filename: 'stream.bin', totalBytes: 0 }) |
| 2331 | + startMockDownload(contents, download) |
| 2332 | + await vi.waitFor(() => expect(download.item.resume).toHaveBeenCalledOnce()) |
| 2333 | + |
| 2334 | + freeBytes = 1024 ** 3 |
| 2335 | + download.setReceivedBytes(512 * 1024 ** 2) |
| 2336 | + vi.useFakeTimers({ toFake: ['Date'] }) |
| 2337 | + try { |
| 2338 | + vi.setSystemTime(Date.now() + 1_100) |
| 2339 | + download.emitUpdated() |
| 2340 | + } finally { |
| 2341 | + vi.useRealTimers() |
| 2342 | + } |
| 2343 | + |
| 2344 | + await vi.waitFor(() => expect(download.item.cancel).toHaveBeenCalledOnce()) |
| 2345 | + }) |
| 2346 | + |
| 2347 | + it('saves into the system Downloads folder when the chosen folder is gone', async () => { |
| 2348 | + const fallback = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-fallback-')) |
| 2349 | + const missing = join(fallback, 'unplugged-drive', 'Downloads') |
| 2350 | + vi.mocked(app.getPath).mockReturnValue(fallback) |
| 2351 | + session = freshSession(win, {}, undefined, { |
| 2352 | + getDirectory: () => missing, |
| 2353 | + getFreeDiskBytes: () => Number.MAX_SAFE_INTEGER, |
| 2354 | + }) |
| 2355 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 2356 | + const download = mockDownloadItem({ filename: 'report.csv', totalBytes: 100 }) |
| 2357 | + |
| 2358 | + startMockDownload(contents, download) |
| 2359 | + expectOnlyStagingSavePath(download.item, fallback) |
| 2360 | + await vi.waitFor(() => expect(download.item.resume).toHaveBeenCalledOnce()) |
| 2361 | + download.emitDone('completed') |
| 2362 | + |
| 2363 | + await vi.waitFor(() => expect(finishedDownloadFiles(fallback)).toEqual(['report.csv'])) |
| 2364 | + expect(existsSync(missing)).toBe(false) |
| 2365 | + }) |
| 2366 | + |
| 2367 | + it('removes an unfinished download’s placeholder and staging file when the app quits', async () => { |
| 2368 | + const directory = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-')) |
| 2369 | + session = freshSession(win, {}, undefined, { |
| 2370 | + getDirectory: () => directory, |
| 2371 | + getFreeDiskBytes: () => Number.MAX_SAFE_INTEGER, |
| 2372 | + }) |
| 2373 | + const contents = (session.ensureTab().view as unknown as MockView).webContents |
| 2374 | + const download = mockDownloadItem({ filename: 'big.zip', totalBytes: 100 }) |
| 2375 | + startMockDownload(contents, download) |
| 2376 | + const stagingPath = expectOnlyStagingSavePath(download.item, directory) |
| 2377 | + await vi.waitFor(() => expect(download.item.resume).toHaveBeenCalledOnce()) |
| 2378 | + writeFileSync(stagingPath, 'partial') |
| 2379 | + writeFileSync(`${stagingPath}.crdownload`, 'partial') |
| 2380 | + expect(readdirSync(directory)).toContain('big.zip') |
| 2381 | + |
| 2382 | + session.quiesceBrowserSessions() |
| 2383 | + |
| 2384 | + expect(readdirSync(directory)).toEqual([]) |
| 2385 | + }) |
| 2386 | + |
| 2387 | + it('sweeps staging files a previous run left behind, and nothing else', async () => { |
| 2388 | + const directory = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-')) |
| 2389 | + const stale = [ |
| 2390 | + '.sim-download-abcDEF123_-xyzABCDEFG', |
| 2391 | + '.sim-download-abcDEF123_-xyzABCDEFG.crdownload', |
| 2392 | + ] |
| 2393 | + const kept = ['.sim-download-notes.txt', '.hidden', 'report.csv'] |
| 2394 | + const longAgo = new Date(Date.now() - 60_000) |
| 2395 | + for (const name of [...stale, ...kept]) { |
| 2396 | + writeFileSync(join(directory, name), 'x') |
| 2397 | + utimesSync(join(directory, name), longAgo, longAgo) |
| 2398 | + } |
| 2399 | + |
| 2400 | + session = freshSession(win, {}, undefined, { |
| 2401 | + getDirectory: () => directory, |
| 2402 | + getFreeDiskBytes: () => Number.MAX_SAFE_INTEGER, |
| 2403 | + }) |
| 2404 | + |
| 2405 | + await vi.waitFor(() => expect(readdirSync(directory).sort()).toEqual([...kept].sort())) |
| 2406 | + }) |
| 2407 | + |
2032 | 2408 | it('cancels every active download on profile wipe without reviving late work', async () => { |
2033 | 2409 | const directory = mkdtempSync(join(tmpdir(), 'sim-browser-downloads-')) |
2034 | 2410 | const firstProbe = deferred<number>() |
|
0 commit comments