From 7443c116a622aac4d3cb1d13f6de453df5224f7f Mon Sep 17 00:00:00 2001 From: JustasM <59362982+JustasMonkev@users.noreply.github.com> Date: Thu, 8 Oct 2026 07:20:17 +0300 Subject: [PATCH 1/5] Migrate recorder hub to the Playwright 1.64 recording contract --- src/context.ts | 46 +++---- tests/browserSessions.test.ts | 4 +- tests/context.test.ts | 194 +++++++++++++++++------------ tests/recorder.integration.test.ts | 37 +++++- 4 files changed, 175 insertions(+), 106 deletions(-) diff --git a/src/context.ts b/src/context.ts index 578323ac..34868a61 100644 --- a/src/context.ts +++ b/src/context.ts @@ -103,7 +103,7 @@ class ContextRegistry { const contextRegistry = new ContextRegistry(); -type TraceHub = { users: number, ready: Promise }; +type TraceHub = { users: number, ready: ReturnType }; const traceHubs = new WeakMap(); type IdleGroup = { @@ -890,14 +890,14 @@ export class Context { } } -// Playwright's _enableRecorder supports a single event sink per browser +// Playwright's _startRecording supports a single event sink per browser // context, and a shared (non-isolated CDP) context can serve several sessions -// at once — a second _enableRecorder call would silently replace the first -// session's callbacks, and a departing session would leave the sink pointing +// at once — a second start replaces the client sink before the server rejects +// it, and a departing session would leave the sink pointing // at its disposed Context. One hub therefore owns a dispatching sink per // context. Session logs and on-demand recordings register and deregister with // it. The hub carries the enablement promise: a session -// joining while (or after) another session's _enableRecorder call is in +// joining while (or after) another session's _startRecording call is in // flight must not report recording as ready before it is, and a failed // enablement evicts the hub so the next session retries instead of silently // recording nothing. When the last consumer leaves, the recorder returns to @@ -1063,12 +1063,6 @@ export class InputRecorder { } } }; - const params = { - mode: 'recording', - recorderMode: 'api', - omitCallTracking: true, - language: 'javascript', - }; const sink = { actionAdded: (page: playwright.Page, data: actions.Action | actions.ActionInContext, code: string) => { const sequence = ++actionSequence; @@ -1097,12 +1091,16 @@ export class InputRecorder { const action = 'action' in data ? data.action : data; dispatch( true, - true, + actionIsBuffered(action), recorder => recorder._actionUpdated(page, action, code, sequence), target => { const recorded = target.actions.findLast(action => action.sequence === sequence); - if (recorded) + if (recorded) { recorded.code = code; + } else if (action.name === 'fill') { + addMissingPageAlias(target.actions, page, code, target.pageIndexes, browserContext); + target.actions.push({ page, code, sequence }); + } }, ); }, @@ -1123,8 +1121,15 @@ export class InputRecorder { ); }, }; + // SAFETY: Paired Playwright 1.64.0 exposes this private contract; the real recorder gate verifies its events and lifecycle. + const recordingContext = browserContext as playwright.BrowserContext & { + _startRecording(params: { language: 'javascript' }, eventSink: typeof sink): Promise; + _stopRecording(): Promise; + }; const arm = async () => { - await (browserContext as any)._enableRecorder(params, sink); + if (armed) + return; + await recordingContext._startRecording({ language: 'javascript' }, sink); armed = true; }; const created: RecorderHub = { @@ -1133,16 +1138,12 @@ export class InputRecorder { starting: 0, ready: enqueue(arm), arm: () => enqueue(arm), - ensureArmed: () => enqueue(async () => { - if (armed) - return; - await arm(); - }), + ensureArmed: () => enqueue(arm), standbyIfIdle: () => enqueue(async () => { if (created.starting || recorders.size || recordings.size) return; try { - await (browserContext as any)._disableRecorder(); + await recordingContext._stopRecording(); } finally { armed = false; } @@ -1164,8 +1165,11 @@ export class InputRecorder { } private _actionUpdated(page: playwright.Page, action: actions.Action, code: string, sequence: number) { - if (this._lastActions.get(page)?.sequence !== sequence) + if (this._lastActions.get(page)?.sequence !== sequence) { + if (action.name === 'fill') + this._actionAdded(page, action, code, sequence); return; + } this._lastActions.set(page, { action, sequence }); const tab = this._context.tabForPage(page); if (tab) diff --git a/tests/browserSessions.test.ts b/tests/browserSessions.test.ts index 473d0691..88f70969 100644 --- a/tests/browserSessions.test.ts +++ b/tests/browserSessions.test.ts @@ -44,7 +44,7 @@ function makeFactory() { browserContext.pages = vi.fn().mockReturnValue([]); browserContext.route = vi.fn().mockResolvedValue(undefined); // Only exercised when a test enables --save-session (the input recorder). - browserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + browserContext._startRecording = vi.fn().mockResolvedValue(undefined); const close = vi.fn().mockResolvedValue(undefined); created.push({ browserContext, close, newPage }); return { browserContext, close }; @@ -321,7 +321,7 @@ describe('browser sessions', () => { page.setDefaultTimeout = vi.fn(); page.url = () => 'about:blank'; created[0].browserContext.emit('page', page); - const sink = created[0].browserContext._enableRecorder.mock.calls[0][1]; + const sink = created[0].browserContext._startRecording.mock.calls[0][1]; sink.actionAdded(page, { name: 'click', signals: [] }, 'await page.click();'); sink.signalAdded(page, { name: 'navigation', url: 'https://example.com' }, "await page.goto('https://example.com');"); diff --git a/tests/context.test.ts b/tests/context.test.ts index 8fed14f3..3e96bba6 100644 --- a/tests/context.test.ts +++ b/tests/context.test.ts @@ -137,7 +137,7 @@ describe('Context', () => { mockBrowserContext.newPage = vi.fn().mockResolvedValue({}); mockBrowserContext.pages = vi.fn().mockReturnValue([]); mockBrowserContext.route = vi.fn().mockResolvedValue(undefined); - mockBrowserContext._disableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._stopRecording = vi.fn().mockResolvedValue(undefined); mockBrowserContext.tracing = { start: vi.fn().mockResolvedValue(undefined), stop: vi.fn().mockResolvedValue(undefined), @@ -601,10 +601,10 @@ describe('Context', () => { describe('shared context recorder', () => { it('multiplexes recorder events so a departing session does not silence the survivor', async () => { - // Playwright's _enableRecorder supports one sink per context; a second + // Playwright's _startRecording supports one sink per context; a second // session used to replace the first session's callbacks, and a closing // session left the sink pointing at its disposed Context. - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const log1 = { logUserAction: vi.fn() }; const log2 = { logUserAction: vi.fn() }; const makeContext = (sessionLog: any) => new Context({ @@ -627,8 +627,8 @@ describe('Context', () => { const context2 = makeContext(log2); await context2.newTab(); - expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(1); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(1); + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; // Session 2 leaves; the shared context (and session 1) live on. await context2.closeBrowserContext(); @@ -642,7 +642,7 @@ describe('Context', () => { // Both sessions wrap the same shared page; the departing one used to // delete the global page→tab entry it had overwritten, leaving the // survivor's recorder events without a tab to log against. - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const log1 = { logUserAction: vi.fn() }; const log2 = { logUserAction: vi.fn() }; const makeContext = (sessionLog: any) => new Context({ @@ -664,7 +664,7 @@ describe('Context', () => { mockBrowserContext.emit('page', page); await context2.closeBrowserContext(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; sink.actionAdded(page, { action: { name: 'click' } }, 'await page.click();'); expect(log1.logUserAction).toHaveBeenCalledTimes(1); @@ -676,7 +676,7 @@ describe('Context', () => { // The recorder cannot attribute a DOM event to the session that caused // it, so a tool call in one session must not be recorded as another // session's user action. - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const log1 = { logUserAction: vi.fn() }; const log2 = { logUserAction: vi.fn() }; const makeContext = (sessionLog: any) => new Context({ @@ -697,7 +697,7 @@ describe('Context', () => { page.url = () => 'about:blank'; mockBrowserContext.emit('page', page); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const endToolCall = context1.beginToolCall('browser_click'); sink.actionAdded(page, { action: { name: 'click' } }, 'await page.click();'); expect(log1.logUserAction).not.toHaveBeenCalled(); @@ -712,7 +712,7 @@ describe('Context', () => { }); it('records its own tool actions but not a sibling session\'s actions', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const makeContext = () => new Context({ tools: [], config: { timeouts: {} } as any, @@ -724,28 +724,24 @@ describe('Context', () => { const context2 = makeContext(); await context1.startRecording(); await context2.startRecording(); - expect(mockBrowserContext._enableRecorder.mock.calls[0][0]).toMatchObject({ - mode: 'recording', - recorderMode: 'api', - omitCallTracking: true, - language: 'javascript', - }); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + expect(mockBrowserContext._startRecording.mock.calls[0][0]).toEqual({ language: 'javascript' }); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(1); + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const endContext1Tool = context1.beginToolCall('browser_click'); sink.actionAdded({} as any, { action: { name: 'click' } }, 'await page.getByText(\'One\').click();'); endContext1Tool(); expect(await context1.stopRecording()).toEqual(["await page.getByText('One').click();"]); - expect(mockBrowserContext._disableRecorder).not.toHaveBeenCalled(); + expect(mockBrowserContext._stopRecording).not.toHaveBeenCalled(); expect(await context2.stopRecording()).toEqual([]); - expect(mockBrowserContext._disableRecorder).toHaveBeenCalledTimes(1); + expect(mockBrowserContext._stopRecording).toHaveBeenCalledTimes(1); }); it('keeps a sibling tool action excluded through the recorder buffer', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const makeContext = () => new Context({ tools: [], config: { timeouts: {} } as any, @@ -757,7 +753,7 @@ describe('Context', () => { const siblingContext = makeContext(); await recordingContext.startRecording(); await siblingContext.newTab(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const endSiblingTool = siblingContext.beginToolCall('browser_click'); endSiblingTool(); @@ -774,7 +770,7 @@ describe('Context', () => { }); it('does not suppress user actions while a sibling controls recording', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const makeContext = () => new Context({ tools: [], config: { timeouts: {} } as any, @@ -786,7 +782,7 @@ describe('Context', () => { const siblingContext = makeContext(); await recordingContext.startRecording(); await siblingContext.newTab(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const endControlCall = siblingContext.beginToolCall('browser_start_recording'); sink.actionAdded({} as any, { action: { name: 'click', button: 'left' } }, 'manual click'); @@ -796,7 +792,7 @@ describe('Context', () => { }); it('keeps generated assertions executable for recordings and session logs', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const sessionLog = { logUserAction: vi.fn() }; const context = new Context({ tools: [], @@ -811,7 +807,7 @@ describe('Context', () => { page.setDefaultTimeout = vi.fn(); page.url = () => 'about:blank'; mockBrowserContext.emit('page', page); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; sink.actionAdded(page, { name: 'assertVisible', selector: 'text=Done', signals: [] }, '// await expect(page.getByText(\'Done\')).toBeVisible();'); expect(await context.stopRecording()).toEqual([ @@ -827,7 +823,7 @@ describe('Context', () => { }); it('updates session-log actions with signal-generated code', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const sessionLog = { logUserAction: vi.fn() }; const context = new Context({ tools: [], @@ -842,7 +838,7 @@ describe('Context', () => { page.setDefaultTimeout = vi.fn(); page.url = () => 'about:blank'; mockBrowserContext.emit('page', page); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const action = { name: 'click', selector: 'text=Open', button: 'left', signals: [] }; sink.actionAdded(page, action, "await page.getByText('Open').click();"); sink.signalAdded(page, { name: 'popup', popupAlias: '1' }, "const page1Promise = page.waitForEvent('popup');\nawait page.getByText('Open').click();"); @@ -858,7 +854,7 @@ describe('Context', () => { it('ignores signals whose initial action was suppressed', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const sessionLog = { logUserAction: vi.fn() }; const config = await resolveConfig({}); const recordingContext = new Context({ @@ -886,7 +882,7 @@ describe('Context', () => { }); const page = createPage('about:blank'); mockBrowserContext.emit('page', page); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const manualAction = { name: 'fill', selector: '#query', text: 'manual' }; sink.actionAdded(page, manualAction, 'manual fill'); @@ -920,7 +916,7 @@ describe('Context', () => { it('replaces coalesced fills in recordings and session logs', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const sessionLog = { logUserAction: vi.fn() }; const context = new Context({ tools: [], @@ -937,7 +933,7 @@ describe('Context', () => { page.setDefaultTimeout = vi.fn(); page.url = () => 'about:blank'; mockBrowserContext.emit('page', page); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const initial = { name: 'fill', selector: '#query', text: 'a', signals: [] }; const updated = { ...initial, text: 'answer' }; @@ -965,7 +961,7 @@ describe('Context', () => { it('does not apply an update whose initial action was suppressed', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const makeContext = () => new Context({ tools: [], config: { timeouts: {} } as any, @@ -977,26 +973,64 @@ describe('Context', () => { const siblingContext = makeContext(); await recordingContext.startRecording(); await siblingContext.newTab(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const page = {} as any; - sink.actionAdded(page, { name: 'fill', selector: '#query' }, 'manual fill'); + sink.actionAdded(page, { name: 'click', button: 'left', selector: '#query' }, 'manual click'); - const endSiblingTool = siblingContext.beginToolCall('browser_fill_form'); - sink.actionAdded(page, { name: 'fill', selector: '#query' }, 'suppressed fill'); + const endSiblingTool = siblingContext.beginToolCall('browser_click'); + sink.actionAdded(page, { name: 'click', button: 'left', selector: '#query' }, 'suppressed click'); endSiblingTool(); await vi.advanceTimersByTimeAsync(501); - sink.actionUpdated(page, { name: 'fill', selector: '#query' }, 'late suppressed update'); + sink.actionUpdated(page, { name: 'click', button: 'left', selector: '#query' }, 'late suppressed update'); const stopping = recordingContext.stopRecording(); await vi.advanceTimersByTimeAsync(500); - await expect(stopping).resolves.toEqual(['manual fill']); + await expect(stopping).resolves.toEqual(['manual click']); + } finally { + vi.useRealTimers(); + } + }); + + it('records coalesced fills after restart and excludes fills delivered after stop begins', async () => { + vi.useFakeTimers(); + try { + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); + const context = new Context({ + tools: [], + config: defaultConfig, + browserContextFactory: mockBrowserContextFactory, + sessionLog: async () => ({ logUserAction: vi.fn() }) as any, + clientInfo: {}, + }); + const firstStart = context.startRecording(); + await vi.advanceTimersByTimeAsync(500); + await firstStart; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; + const page = await mockBrowserContext.newPage(); + const fill = { name: 'fill', selector: '#query' }; + sink.actionAdded(page, fill, 'first fill'); + const firstStop = context.stopRecording(); + sink.actionUpdated(page, fill, 'after stop'); + await vi.advanceTimersByTimeAsync(500); + expect(await firstStop).toEqual(['first fill']); + + const restarting = context.startRecording(); + await vi.advanceTimersByTimeAsync(500); + await restarting; + sink.actionUpdated(page, fill, 'restarted fill'); + sink.actionUpdated(page, fill, 'final fill'); + const secondStop = context.stopRecording(); + await vi.advanceTimersByTimeAsync(500); + expect(await secondStop).toEqual(['final fill']); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(1); + expect(mockBrowserContext._stopRecording).not.toHaveBeenCalled(); } finally { vi.useRealTimers(); } }); it('starts a fresh recording after stop', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1005,7 +1039,7 @@ describe('Context', () => { clientInfo: {}, }); await context.startRecording(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const page = {} as any; sink.actionAdded(page, { action: { name: 'click' } }, 'old code'); @@ -1014,12 +1048,12 @@ describe('Context', () => { await context.startRecording(); sink.actionAdded({} as any, { action: { name: 'fill' } }, 'new code'); expect(await context.stopRecording()).toEqual(['new code']); - expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(2); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(2); }); it('returns captured actions when recorder standby fails', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); - mockBrowserContext._disableRecorder = vi.fn().mockRejectedValue(new Error('browser disconnected')); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._stopRecording = vi.fn().mockRejectedValue(new Error('browser disconnected')); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1028,14 +1062,14 @@ describe('Context', () => { clientInfo: {}, }); await context.startRecording(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; sink.actionAdded({} as any, { name: 'press', signals: [] }, "await page.press('Enter');"); await expect(context.stopRecording()).resolves.toEqual(["await page.press('Enter');"]); }); it('re-arms an idle hub when a session logger joins', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const recordingContext = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1045,7 +1079,7 @@ describe('Context', () => { }); await recordingContext.startRecording(); await recordingContext.stopRecording(); - expect(mockBrowserContext._disableRecorder).toHaveBeenCalledTimes(1); + expect(mockBrowserContext._stopRecording).toHaveBeenCalledTimes(1); const loggingContext = new Context({ tools: [], @@ -1055,15 +1089,15 @@ describe('Context', () => { clientInfo: {}, }); await loggingContext.newTab(); - expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(2); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(2); }); it('re-arms only after an idle recorder has reached standby', async () => { vi.useFakeTimers(); try { let finishStandby: () => void; - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); - mockBrowserContext._disableRecorder = vi.fn().mockImplementation(() => new Promise(resolve => { finishStandby = resolve; })); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._stopRecording = vi.fn().mockImplementation(() => new Promise(resolve => { finishStandby = resolve; })); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1074,19 +1108,19 @@ describe('Context', () => { await context.startRecording(); const firstStop = context.stopRecording(); await vi.advanceTimersByTimeAsync(500); - expect(mockBrowserContext._disableRecorder).toHaveBeenCalledTimes(1); + expect(mockBrowserContext._stopRecording).toHaveBeenCalledTimes(1); const secondStart = context.startRecording(); await vi.advanceTimersByTimeAsync(500); - expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(1); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(1); finishStandby!(); await firstStop; await secondStart; - expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(2); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(2); const secondStop = context.stopRecording(); finishStandby = () => {}; - mockBrowserContext._disableRecorder.mockResolvedValue(undefined); + mockBrowserContext._stopRecording.mockResolvedValue(undefined); await vi.advanceTimersByTimeAsync(500); await secondStop; } finally { @@ -1097,7 +1131,7 @@ describe('Context', () => { it('keeps page declarations when recording starts before or after a tab opens', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1106,7 +1140,7 @@ describe('Context', () => { clientInfo: {}, }); await context.startRecording(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const firstPage = {} as any; const secondPage = {} as any; mockBrowserContext.pages.mockReturnValue([firstPage, secondPage]); @@ -1159,7 +1193,7 @@ describe('Context', () => { it('ignores empty signal code from an earlier tab', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1168,7 +1202,7 @@ describe('Context', () => { clientInfo: {}, }); await context.startRecording(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const firstPage = {} as any; const secondPage = {} as any; sink.actionAdded(firstPage, { name: 'click', signals: [] }, 'first action'); @@ -1186,7 +1220,7 @@ describe('Context', () => { it('does not include an action buffered before a repeated start', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1199,7 +1233,7 @@ describe('Context', () => { await vi.advanceTimersByTimeAsync(500); await stopping; - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const starting = context.startRecording(); await vi.advanceTimersByTimeAsync(499); sink.actionAdded({} as any, { action: { name: 'click' } }, 'before start'); @@ -1223,7 +1257,7 @@ describe('Context', () => { page.setDefaultTimeout = vi.fn(); page.url = () => 'about:blank'; mockBrowserContext.pages.mockReturnValue([page]); - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const close = vi.fn().mockResolvedValue(undefined); (mockBrowserContextFactory.createContext as any).mockResolvedValue({ browserContext: mockBrowserContext, close }); const context = new Context({ @@ -1234,7 +1268,7 @@ describe('Context', () => { clientInfo: {}, }); await context.startRecording(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const stopping = context.stopRecording(); page.emit('close'); @@ -1253,7 +1287,7 @@ describe('Context', () => { it('waits for an in-flight recording stop before closing the browser', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const close = vi.fn().mockResolvedValue(undefined); (mockBrowserContextFactory.createContext as any).mockResolvedValue({ browserContext: mockBrowserContext, close }); const context = new Context({ @@ -1264,7 +1298,7 @@ describe('Context', () => { clientInfo: {}, }); await context.startRecording(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const stopping = context.stopRecording(); const closing = context.closeBrowserContext(); @@ -1288,7 +1322,7 @@ describe('Context', () => { page.url = () => 'about:blank'; mockBrowserContext.pages.mockReturnValue([page]); let rejectEnable: (error: Error) => void; - mockBrowserContext._enableRecorder = vi.fn().mockImplementation(() => new Promise((_, reject) => { rejectEnable = reject; })); + mockBrowserContext._startRecording = vi.fn().mockImplementation(() => new Promise((_, reject) => { rejectEnable = reject; })); const close = vi.fn().mockResolvedValue(undefined); (mockBrowserContextFactory.createContext as any).mockResolvedValue({ browserContext: mockBrowserContext, close }); const context = new Context({ @@ -1300,7 +1334,7 @@ describe('Context', () => { }); const starting = context.startRecording(); - await vi.waitFor(() => expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(1)); + await vi.waitFor(() => expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(1)); page.emit('close'); rejectEnable!(new Error('recorder unavailable')); @@ -1309,7 +1343,7 @@ describe('Context', () => { }); it('rejects a second recording while one is active', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1325,7 +1359,7 @@ describe('Context', () => { it('reserves a focused start and lets an overlapping stop wait for it', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1357,7 +1391,7 @@ describe('Context', () => { }); it('releases a focused start reservation when tab focus fails', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1379,7 +1413,7 @@ describe('Context', () => { it('waits for Playwright to deliver its last buffered action', async () => { vi.useFakeTimers(); try { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = new Context({ tools: [], config: { timeouts: {} } as any, @@ -1388,7 +1422,7 @@ describe('Context', () => { clientInfo: {}, }); await context.startRecording(); - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; const stopping = context.stopRecording(); sink.actionAdded({} as any, { action: { name: 'press' } }, 'after stop'); @@ -1406,7 +1440,7 @@ describe('Context', () => { vi.useFakeTimers(); try { let resolveEnable: () => void; - mockBrowserContext._enableRecorder = vi.fn() + mockBrowserContext._startRecording = vi.fn() .mockImplementationOnce(() => new Promise(resolve => { resolveEnable = resolve; })) .mockResolvedValue(undefined); const context = new Context({ @@ -1427,7 +1461,7 @@ describe('Context', () => { await secondStart; await firstStop; - const sink = mockBrowserContext._enableRecorder.mock.calls[0][1]; + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; sink.actionAdded({} as any, { action: { name: 'click' } }, 'replacement action'); const secondStop = context.stopRecording(); await vi.advanceTimersByTimeAsync(500); @@ -1453,12 +1487,12 @@ describe('Context', () => { }); it('makes a joining session wait for the in-flight recorder enablement and share its failure', async () => { - // The first session stores the hub before _enableRecorder resolves; a + // The first session stores the hub before _startRecording resolves; a // session joining meanwhile must not report recording ready while the // one enablement is still in flight — and must fail with it, not run // unrecorded. let rejectEnable: (error: Error) => void; - mockBrowserContext._enableRecorder = vi.fn().mockImplementation(() => new Promise((_, reject) => { rejectEnable = reject; })); + mockBrowserContext._startRecording = vi.fn().mockImplementation(() => new Promise((_, reject) => { rejectEnable = reject; })); const makeContext = () => new Context({ tools: [], config: { timeouts: {} } as any, @@ -1469,7 +1503,7 @@ describe('Context', () => { const pending1 = makeContext().newTab(); const pending2 = makeContext().newTab(); - await vi.waitFor(() => expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(1)); + await vi.waitFor(() => expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(1)); rejectEnable!(new Error('recorder unavailable')); await expect(pending1).rejects.toThrow('recorder unavailable'); @@ -1477,9 +1511,9 @@ describe('Context', () => { }); it('retries recorder enablement after a failed one instead of caching the dead hub', async () => { - // A failed _enableRecorder left the hub cached: every later session + // A failed _startRecording left the hub cached: every later session // skipped enablement and silently produced no user-action recording. - mockBrowserContext._enableRecorder = vi.fn() + mockBrowserContext._startRecording = vi.fn() .mockRejectedValueOnce(new Error('recorder unavailable')) .mockResolvedValueOnce(undefined); const makeContext = () => new Context({ @@ -1493,7 +1527,7 @@ describe('Context', () => { await makeContext().newTab(); - expect(mockBrowserContext._enableRecorder).toHaveBeenCalledTimes(2); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(2); }); }); @@ -1863,7 +1897,7 @@ describe('Context', () => { }); it('keeps explicit recordings alive and rearms after the recorder stops', async () => { - mockBrowserContext._enableRecorder = vi.fn().mockResolvedValue(undefined); + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); const context = await createContext(); await context.startRecording(); await vi.advanceTimersByTimeAsync(10_000); @@ -1873,7 +1907,7 @@ describe('Context', () => { expect(close).not.toHaveBeenCalled(); await vi.advanceTimersByTimeAsync(1); await stopping; - expect(mockBrowserContext._disableRecorder).toHaveBeenCalledOnce(); + expect(mockBrowserContext._stopRecording).toHaveBeenCalledOnce(); expect(context.recordingActivityAt()).toBeUndefined(); await vi.advanceTimersByTimeAsync(999); expect(close).not.toHaveBeenCalled(); diff --git a/tests/recorder.integration.test.ts b/tests/recorder.integration.test.ts index 56656920..bb178bf8 100644 --- a/tests/recorder.integration.test.ts +++ b/tests/recorder.integration.test.ts @@ -18,7 +18,7 @@ import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; -import { chromium, type BrowserContext } from 'playwright'; +import { chromium, firefox, webkit, type BrowserContext } from 'playwright'; import { BrowserServerBackend } from '../src/browserServerBackend.js'; import { BrowserSessionRegistry } from '../src/browserSessions.js'; import { contextFactory, type BrowserContextFactory } from '../src/browserContextFactory.js'; @@ -26,6 +26,10 @@ import { resolveConfig, type FullConfig } from '../src/config.js'; const resultText = (result: Awaited>) => result.content.filter(item => item.type === 'text').map(item => item.text).join('\n'); +const browserName = process.env.MCP_TEST_BROWSER_NAME || 'chromium'; +if (browserName !== 'chromium' && browserName !== 'firefox' && browserName !== 'webkit') + throw new Error(`Unsupported MCP_TEST_BROWSER_NAME: ${browserName}`); +const browserType = { chromium, firefox, webkit }[browserName]; // Real recorder events: no mocked private methods or hand-dispatched sink events. describe('recorder compatibility with pinned Playwright (#218)', () => { @@ -67,7 +71,7 @@ describe('recorder compatibility with pinned Playwright (#218)', () => { return result; } - it('shares real CDP recording across clients, filters sibling tools, and survives stop/disconnect/restart', async () => { + it.skipIf(browserName !== 'chromium')('shares real CDP recording across clients, filters sibling tools, and survives stop/disconnect/restart', async () => { directory = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-recorder-')); const profile = path.join(directory, 'profile'); ownedContext = await chromium.launchPersistentContext(profile, { args: ['--remote-debugging-port=0'] }); @@ -127,7 +131,7 @@ describe('recorder compatibility with pinned Playwright (#218)', () => { }); it('retains explicit recording across stateless backends and rejects ephemeral recording', async () => { - const browser = await chromium.launch(); + const browser = await browserType.launch(); try { registry = new BrowserSessionRegistry(); const config = await resolveConfig({ capabilities: ['devtools'], timeouts: { settle: 50 } }); @@ -180,4 +184,31 @@ describe('recorder compatibility with pinned Playwright (#218)', () => { await browser.close(); } }); + + it('records repeated fills across restart while a session log keeps the hub armed', async () => { + directory = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-recorder-fills-')); + const browser = await browserType.launch(); + try { + ownedContext = await browser.newContext(); + const page = await ownedContext.newPage(); + await page.setContent(''); + const config = await resolveConfig({ capabilities: ['devtools'], saveSession: true, outputDir: directory, timeouts: { settle: 50 } }); + const instance = await backend(config, { + createContext: async () => ({ browserContext: ownedContext!, close: async () => {} }), + }); + for (const text of ['First recording', 'Restarted recording']) { + await call(instance, 'browser_start_recording'); + await page.getByRole('textbox').fill(text); + const folders = (await fs.readdir(directory)).filter(name => name.startsWith('session-')); + await expect.poll(async () => (await fs.readFile(path.join(directory!, folders[0], 'session.md'), 'utf8')).includes(`fill('${text}')`), { timeout: 10_000 }).toBe(true); + const recording = resultText(await call(instance, 'browser_stop_recording')); + expect(recording).toContain(`fill('${text}')`); + if (text === 'Restarted recording') + expect(recording).not.toContain("fill('First recording')"); + } + await call(instance, 'browser_close'); + } finally { + await browser.close(); + } + }); }); From d371e736f371c940c81b31902d22a73469ba245f Mon Sep 17 00:00:00 2001 From: JustasM <59362982+JustasMonkev@users.noreply.github.com> Date: Thu, 8 Oct 2026 07:20:28 +0300 Subject: [PATCH 2/5] Pair Playwright 1.64 pins and document the incomplete upgrade gate --- .github/workflows/ci.yml | 2 +- README.md | 56 ++++----- SKILL.md | 2 +- docs/playwright-1.64-validation-271.md | 112 ++++++++++++++++++ package-lock.json | 18 +-- package.json | 4 +- src/browserContextFactory.ts | 10 +- src/config.ts | 4 +- ...owser-upgrade-controls.integration.test.ts | 103 +++++++++++++++- 9 files changed, 260 insertions(+), 51 deletions(-) create mode 100644 docs/playwright-1.64-validation-271.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e3da281..9a74a60a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -256,7 +256,7 @@ jobs: env: MCP_TEST_BROWSER_NAME: ${{ matrix.browser }} - if: ${{ !cancelled() }} - run: npx vitest run tests/browser-upgrade-controls.integration.test.ts + run: npx vitest run tests/browser-upgrade-controls.integration.test.ts tests/recorder.integration.test.ts env: MCP_TEST_BROWSER_NAME: ${{ matrix.browser }} diff --git a/README.md b/README.md index 9c9322a6..a07283a2 100644 --- a/README.md +++ b/README.md @@ -245,13 +245,13 @@ Create a `config.json` file with the following options: - `browser.browserName`: Browser to use (`chromium`, `firefox`, `webkit`) - With WebKit on the pinned Playwright 1.63.0, the contents of an open `
` nested inside a closed `
` count as visible: they appear in `browser_snapshot` and `browser_find` results, and `browser_verify_element_visible` and `browser_verify_text_visible` succeed for them. Chromium and Firefox hide them until the outer `
` is opened. The [upstream fix](https://github.com/microsoft/playwright/pull/42951) is not in a stable release yet. The server does not filter snapshots or patch Playwright to work around this. See the [verification notes](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#webkit-nested-details-visibility-246). + On the previous Playwright 1.63.0 pin, open `
` nested inside closed `
` exposed their contents in WebKit snapshots, find results and visibility checks. The 1.64.0 candidate still needs the real WebKit regression before this limitation is treated as resolved. See the [migration results](docs/playwright-1.64-validation-271.md) and [historical verification notes](docs/issue-verification-2026-09.md#webkit-nested-details-visibility-246). - `browser.allowedUploadDirs`: Restrict files sent by `browser_file_upload` and `browser_drop` to regular files inside these directories, including resolved symlink targets. Restricted uploads and drops use a checked file handle and accept up to 50 MiB total per call. Unset allows any path; `[]` denies all file uploads and drops (text-only drops still work). Blank list entries are rejected. CLI: `--allowed-upload-dirs` (semicolon-separated; `""` denies all), env: `PLAYWRIGHT_MCP_ALLOWED_UPLOAD_DIRS` (empty string denies all). The list must be an array, not `null`. Roots must exist at startup: their canonical paths are resolved once and retained for the server's lifetime, so retargeting a configured symlink does not grant access to a new tree. Non-empty upload allowlists require macOS or Linux with `/proc/self/fd` available. macOS blocks ancestor symlinks during the file open; Linux checks the opened descriptor's path. Other platforms reject restricted file uploads and drops rather than rely on race-prone pathname checks. Unrestricted uploads, deny-all lists, and text-only drops keep working on all platforms. - `browser.launchOptions.headless`: Run browser in headless mode (default: `true` on Linux without display, `false` otherwise) - `browser.launchOptions.channel`: Browser channel (`chrome`, `chrome-beta`, `msedge`, etc.) -- `browser.contextOptions.clientCertificates`: With client certificates, a configured launch proxy is also applied to fresh contexts unless `browser.contextOptions.proxy` explicitly overrides it. Playwright 1.63.0 ignores certificate-interceptor proxy bypass rules, so combining certificates with a nonblank effective `proxy.bypass` is rejected before launch. For a fresh context on a remote browser, configure its proxy explicitly; a proxy inherited only from that browser cannot be inspected. Existing attached contexts retain their current settings. +- `browser.contextOptions.clientCertificates`: With client certificates, a configured launch proxy is also applied to fresh contexts unless `browser.contextOptions.proxy` explicitly overrides it. Combining certificates with a nonblank effective `proxy.bypass` remains rejected before launch until 1.64.0 routing is validated; the previous 1.63.0 interceptor ignored bypass rules. For a fresh context on a remote browser, configure its proxy explicitly; a proxy inherited only from that browser cannot be inspected. Existing attached contexts retain their current settings. - `browser.launchOptions.proxy`: Browser proxy (CLI: `--proxy-server`, `--proxy-bypass`; env: `PLAYWRIGHT_MCP_PROXY_SERVER`, `PLAYWRIGHT_MCP_PROXY_BYPASS`). Credentials in a CLI or environment proxy URL, such as `http://user:password@myproxy:3128`, are moved into `proxy.username` and `proxy.password` so the browser can answer `407 Proxy Authentication Required`; percent-encode reserved characters such as `@`, `:` or `/` in them. A proxy set in the config file keeps its explicit `username` and `password` fields. - `browser.launchOptions.chromiumSandbox`: Defaults to `false` for downloaded Chromium builds on Linux because they lack the setuid sandbox helper, and `true` otherwise. Remote and VS Code endpoints choose on the remote host. An explicit config or `PLAYWRIGHT_MCP_SANDBOX` value wins; `--no-sandbox` always disables it. - `browser.cdpEndpoint`: Attach to an already-running Chromium-family app with CDP enabled @@ -275,9 +275,9 @@ Create a `config.json` file with the following options: CLI equivalents are also available: `--cdp-launch-command`, `--cdp-launch-args`, `--cdp-launch-cwd`, `--cdp-launch-port`, `--cdp-launch-startup-timeout`, `--cdp-endpoint`, `--cdp-header` (repeat for multiple headers, e.g. `--cdp-header "Authorization: Bearer "`), and `--cdp-timeout`. The CDP headers and timeout can also be set via the `PLAYWRIGHT_MCP_CDP_HEADERS` (one `Name: Value` entry per line) and `PLAYWRIGHT_MCP_CDP_TIMEOUT` environment variables. -If CDP attachment times out after the WebSocket connects, an existing tab may be blocking Playwright's browser initialization. On the pinned Playwright 1.63.0, a tab without a renderer — one whose renderer crashed, or one discarded by Chrome's Memory Saver — is never answered, so the attach cannot succeed while that tab exists ([upstream fix, unreleased](https://github.com/microsoft/playwright/pull/42936)); a sleeping or unresponsive tab can stall it too ([upstream report](https://github.com/microsoft/playwright/issues/42730)). `--cdp-endpoint` then fails after `--cdp-timeout`, and `--cdp-launch` by `--cdp-launch-startup-timeout` (each attach attempt also stops at `--cdp-timeout`), with an error that names this cause; `--cdp-launch` stops only the application it launched. For `--cdp-endpoint`, use an explicit positive `--cdp-timeout` to bound the attempt; `0` disables it and the attach can then wait forever. Reload or close the affected tab yourself, or attach to a separate disposable browser. `noDefaults` and `--isolated` do not skip initialization of existing tabs; the server does not close or reload your tabs or bypass Playwright's initialization to work around this. See the [verification notes](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#cdp-attach-and-numpad-keys-244). +If CDP attachment times out after the WebSocket connects, a sleeping or unresponsive existing tab may be blocking initialization. Playwright 1.64.0 includes the [crashed/discarded-tab fix](https://github.com/microsoft/playwright/pull/42936), but real CDP checks remain pending in the [migration results](docs/playwright-1.64-validation-271.md). `--cdp-endpoint` fails after `--cdp-timeout`, and `--cdp-launch` by `--cdp-launch-startup-timeout` (each attempt also stops at `--cdp-timeout`); `--cdp-launch` stops only the application it launched. Use an explicit positive `--cdp-timeout` to bound attachment; `0` disables it. The server does not close or reload existing tabs to work around initialization problems. -Playwright 1.63 does not support back/forward-cache (BFCache) restoration: an attached browser with BFCache enabled can return unusable references and omit iframe contents after back navigation. This was reproduced with full Chromium, Chrome, and Edge. For a browser you launch yourself, include `--disable-back-forward-cache` before attaching, or use the server's normal browser launch mode, which retains Playwright's default flag. The server does not change an attached browser's flags or replace back navigation with a reload. See the [upstream maintainer's explanation](https://github.com/microsoft/playwright/issues/42777#issuecomment-5739095543), [Playwright's BFCache limitation](https://playwright.dev/docs/navigations#backforward-cache-bfcache), and the [verification and reproduction command](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#history-references-231). +Playwright does not support back/forward-cache (BFCache) restoration: an attached browser with BFCache enabled can return unusable references and omit iframe contents after back navigation. This was reproduced with full Chromium, Chrome, and Edge. For a browser you launch yourself, include `--disable-back-forward-cache` before attaching, or use the server's normal browser launch mode, which retains Playwright's default flag. The server does not change an attached browser's flags or replace back navigation with a reload. See the [upstream maintainer's explanation](https://github.com/microsoft/playwright/issues/42777#issuecomment-5739095543), [Playwright's BFCache limitation](https://playwright.dev/docs/navigations#backforward-cache-bfcache), and the [verification and reproduction command](https://github.com/JustasMonkev/mcp-accessibility-scanner/blob/main/docs/issue-verification-2026-09.md#history-references-231). For remote HTTP access, configure the TLS reverse proxy explicitly. For example, with the MCP server bound using `--host 127.0.0.1 --port 8931` and `PLAYWRIGHT_MCP_AUTH_TOKEN` set: @@ -341,7 +341,7 @@ Direct DOM value assignments can bypass application event handlers, and syntheti Record a session once with Playwright's codegen, then hand the file to the server: ```bash -npx playwright@1.63.0 codegen --save-storage=auth.json https://example.com/login +npx playwright@1.64.0 codegen --save-storage=auth.json https://example.com/login ``` Sign in in the opened browser, then close it — `auth.json` now holds the cookies and local storage. @@ -369,9 +369,9 @@ PLAYWRIGHT_MCP_ISOLATED=true PLAYWRIGHT_MCP_STORAGE_STATE=./auth.json npx mcp-ac > **Every supported mode handles the state — by applying it or refusing it.** > -> **Playwright 1.63.0 safety restriction:** importing into an existing context is rejected before taking a rollback snapshot or resetting any storage. On this pin, snapshot capture can execute service-worker-served scripts for a previously visited origin whose tab is no longer open ([upstream fix](https://github.com/microsoft/playwright/pull/42664)). Use a fresh context, or omit `--storage-state` and sign in interactively. Service workers are not disabled. A future dependency upgrade must also pass the recorder/shared-client checks in [#218](https://github.com/JustasMonkev/mcp-accessibility-scanner/issues/218) and IndexedDB checks in [#224](https://github.com/JustasMonkev/mcp-accessibility-scanner/issues/224) before this restriction is reconsidered. +> **Existing-context import restriction:** imports remain rejected before taking a rollback snapshot or resetting storage until the 1.64.0 service-worker, IndexedDB, failed-import rollback and shared-client gates pass. The previous 1.63.0 snapshot path could execute service-worker-served scripts ([upstream report/fix](https://github.com/microsoft/playwright/pull/42664)). Use a fresh context, or omit `--storage-state` and sign in interactively. Service workers are not disabled. See [migration results](docs/playwright-1.64-validation-271.md), [#218](https://github.com/JustasMonkev/mcp-accessibility-scanner/issues/218) and [#224](https://github.com/JustasMonkev/mcp-accessibility-scanner/issues/224). > -> **IndexedDB snapshot limitation:** on pinned Playwright 1.63.0 with Chromium 153.0.8010.12 and Firefox 155.0, `storageState({ indexedDB: true })` loses `Map` and `Set` contents. Both `newContext({ storageState })` and `setStorageState()` restore them as empty plain objects; ordinary JSON records survive. Fresh contexts protect existing browser data, but cannot recover values already lost during capture. The [upstream fix](https://github.com/microsoft/playwright/pull/42707) is merged but is not in this pin. Before allowing imports into existing contexts again, verify both restore paths preserve Map/Set types and entries on each supported engine, including after a failed import. The real-browser regression in `tests/browser-failures.integration.test.ts` checks that rejecting an import leaves the original Map/Set records intact and that isolated JSON IndexedDB imports still work. +> **IndexedDB snapshot limitation:** on the previous Playwright 1.63.0 pin with Chromium 153.0.8010.12 and Firefox 155.0, `storageState({ indexedDB: true })` loses `Map` and `Set` contents. Both `newContext({ storageState })` and `setStorageState()` restore them as empty plain objects; ordinary JSON records survive. Fresh contexts protect existing browser data, but cannot recover values already lost during capture. The [upstream fix](https://github.com/microsoft/playwright/pull/42707) must be rechecked on 1.64.0 before lifting the restriction. Before allowing imports into existing contexts again, verify both restore paths preserve Map/Set types and entries on each supported engine, including after a failed import. The real-browser regression in `tests/browser-failures.integration.test.ts` checks that rejecting an import leaves the original Map/Set records intact and that isolated JSON IndexedDB imports still work. > > - **Fresh-context modes** (`--isolated`, the remote-endpoint mode, or either CDP mode combined with `--isolated`): the context is created with the storage state directly. > - **Default persistent-profile mode with `--storage-state`**: the session runs in a fresh, disposable profile — unique to that session and removed when it closes — built from the state, so the recorded state is provably the only session data (without `--storage-state` the regular persistent profile is used and survives restarts, as before). Any page the launch opened (for example from a URL in `browser.launchOptions.args`) is parked on a blank replacement before the state lands, then the replacement is navigated to the same URL, so a still-running anonymous page cannot overwrite the recorded identity and a scan never reads its DOM. This also means `--storage-state` cannot be combined with `--user-data-dir` (a user-supplied profile carries its own session and will not be wiped; the server refuses the combination). @@ -645,7 +645,7 @@ Fill multiple fields with one call. Generated Playwright code preserves checkbox #### `browser_press_key` Press a key on the keyboard. - Parameters: `key` (e.g., 'ArrowLeft' or 'a') -- Keys are delivered by Playwright's US keyboard layout. On the pinned Playwright 1.63.0, some numpad keys differ from a physical keyboard. In Chromium, Firefox and WebKit, `NumpadDecimal` sends key `"\u0000"` instead of `Delete`; WebKit on macOS also inserts that NUL character into the focused input ([upstream fix](https://github.com/microsoft/playwright/pull/42927), merged after 1.63.0 and not in the stable pin). In Chromium only, numpad `keyup` events do not report the numpad location ([upstream fix](https://github.com/microsoft/playwright/pull/42913), merged after 1.63.0), and shifted numpad digits such as `Shift+Numpad1`, and `Shift+NumpadDecimal`, type nothing. Pages that rely on numpad `key`, `location` or shifted digits may therefore not be exercised faithfully; the server passes keys through unchanged rather than remapping them. Use `Delete` when deletion matters more than the physical numpad identity. `tests/numpad-keys.integration.test.ts` characterizes only the measured paired versions, browser builds and platforms; other environments must satisfy the intended key contract. +- Keys are delivered by Playwright's US keyboard layout and passed through unchanged. Linux Firefox 157.0 on Playwright 1.64.0 passed the intended `NumpadDecimal`, shifted-digit and numpad-location contract; Chromium and WebKit remain pending. `tests/numpad-keys.integration.test.ts` permits measured 1.63.0 deviations only on that exact old paired pin. See [migration results](docs/playwright-1.64-validation-271.md). #### `browser_start_recording` / `browser_stop_recording` Record browser actions and return them as Playwright JavaScript. Start the server with `--caps devtools`, call `browser_start_recording`, perform the flow, then call `browser_stop_recording`. @@ -895,20 +895,21 @@ npm install ### Playwright upgrade gate -The September 16, 2026 review keeps `playwright` and `playwright-core` paired at -**1.63.0**, the [latest stable release](https://github.com/microsoft/playwright/releases/tag/v1.63.0) -on that date. Keep the local `InputRecorder` hub and the existing factory reference -counts: multiple MCP clients share one client-side browser context, while the hub -multiplexes session logs and explicit recordings and excludes sibling tool actions. -A dependency bump alone must not change that ownership model. - -Before adopting a stable release containing [upstream #42627](https://github.com/microsoft/playwright/pull/42627), -adapt the hub from `_enableRecorder` / `_disableRecorder` to -`_startRecording({ language: 'javascript' }, sink)` / `_stopRecording()` and verify -the per-client event contract against the installed runtime. Do not ship a -prerelease bump or an untested method-name fallback. Migrating to the separate -connections in [#42622](https://github.com/microsoft/playwright/pull/42622) is a -separate ownership change requiring the same lifecycle checks. +This branch pairs `playwright` and `playwright-core` at stable **1.64.0** and uses +`_startRecording({ language: 'javascript' }, sink)` / `_stopRecording()`. +**Do not merge the pin change until the remaining gates in the +[validation report](docs/playwright-1.64-validation-271.md) pass.** +The local `InputRecorder` hub and factory reference counts remain: shared clients +use one sink, and active hubs are not started twice. Coalesced fills after restart +are retained; unbuffered fills delivered after stop begins are excluded. +There is no fallback to removed private methods or change to connection ownership. + +Device descriptors retain Playwright's `screen` emulation for `--device` and +`--mobile`: `window.screen` and device-size media queries see the device screen, +which may differ from its viewport. Explicit `browser.contextOptions.screen` +values remain supported; CLI/environment/file precedence is unchanged. Responsive accessibility results may change. +Screen, touch/screenshot, smooth-scroll and #257 checks are in +`tests/browser-upgrade-controls.integration.test.ts`. Install the pinned Chromium browser, then run the real recorder gate alongside its failure and concurrency tests: @@ -937,9 +938,10 @@ These are dependency limitations; the recorder gate alone does not verify them. ### Newly reported browser limitations (#251) -The September 28, 2026 validation retains the paired Playwright **1.63.0** pins; -no containing stable release is available. See the [platform results and rerun -commands](docs/browser-upgrade-validation-251.md) before upgrading. +The September 28, 2026 observations below apply to the previous paired +**1.63.0** pins. The 1.64.0 candidate does not inherit their test allowances; +see [current migration results](docs/playwright-1.64-validation-271.md) and the +[historical platform results and rerun commands](docs/browser-upgrade-validation-251.md) before upgrading. - **Preloaded CDP pages:** nested cross-site/sandboxed frames can redirect evaluation, locators and scans into an iframe even while `page.url()` shows the @@ -956,8 +958,8 @@ commands](docs/browser-upgrade-validation-251.md) before upgrading. `screenshotOnIssue: false` and `annotateScreenshot: false`. The server does not reset fonts or reload pages. - **Firefox on macOS:** `browser_press_key` with `Alt+a` inserted `a`; Chromium - and WebKit controls did not. The Firefox r1553 roll addressing Option-key and - frame-focus behavior is merged but unreleased. Keys remain passed through. + and WebKit controls did not. The candidate uses Firefox r1555; macOS Option-key and + frame-focus validation remains pending. Keys remain passed through. - **WebKit on macOS 14:** page creation fails with `Unknown setting: PushAPIEnabled` in the frozen r2251 bundle, reproduced on a hosted macOS 14.8.9 arm64 runner. The macOS 26/r2359 control passed. Use a diff --git a/SKILL.md b/SKILL.md index 1e06dba7..c94aea24 100644 --- a/SKILL.md +++ b/SKILL.md @@ -126,7 +126,7 @@ Crawl and aggregate accessibility violations across multiple pages. Writes a JSO - `excludePathPatterns` - Regex patterns to skip (default: `logout|signout`) - `reportFile` - Custom output filename -**Behind a login:** the crawl shares the browser context, so signing in with `browser_navigate` / `browser_fill_form` first is enough. Alternatively record a session with `npx playwright@1.63.0 codegen --save-storage=auth.json ` (pinned to the server's own Playwright, so the recorded state matches what it replays) and start the server with `--storage-state ./auth.json` — fresh contexts receive it at creation, and default persistent mode uses a disposable profile that cannot combine with `--user-data-dir`. Existing CDP and VS Code contexts reject imports before taking a snapshot or resetting storage; add `--isolated` for CDP, or sign in interactively. `--extension` refuses storage imports entirely. On Playwright 1.63.0, IndexedDB snapshots can lose `Map` and `Set` contents, so a captured state is not a lossless backup of those records. Extend `excludePathPatterns` with anything else that ends the session (account deletion, session revocation, account/locale switchers) — it replaces the default, so keep `logout|signout` in the list. If the crawl loses cookies it started with, the result opens with `WARNING: cookie(s) …` lines and the report carries a `sessionLosses` list naming, per lost cookie, the page reached after any redirect, even when that page failed to load; if one of them was the session cookie, everything scanned after that page was audited signed-out. Monitoring continues past the first loss (each cookie is reported once, where it vanished), and URLs discovered mid-crawl join cookie tracking before being visited. Cookie values are not compared and a cookie the browser dropped at its own expiry is ignored, but any other cookie the crawl started with and lost is reported — nothing marks a cookie as an authentication one. +**Behind a login:** the crawl shares the browser context, so signing in with `browser_navigate` / `browser_fill_form` first is enough. Alternatively record a session with `npx playwright@1.64.0 codegen --save-storage=auth.json ` (pinned to the server's own Playwright, so the recorded state matches what it replays) and start the server with `--storage-state ./auth.json` — fresh contexts receive it at creation, and default persistent mode uses a disposable profile that cannot combine with `--user-data-dir`. Existing CDP and VS Code contexts reject imports before taking a snapshot or resetting storage; add `--isolated` for CDP, or sign in interactively. `--extension` refuses storage imports entirely. The previous Playwright 1.63.0 snapshots lost `Map` and `Set` contents. The 1.64.0 candidate still requires cross-engine snapshot/restore validation; keep existing-context imports rejected until the README upgrade gate passes. Extend `excludePathPatterns` with anything else that ends the session (account deletion, session revocation, account/locale switchers) — it replaces the default, so keep `logout|signout` in the list. If the crawl loses cookies it started with, the result opens with `WARNING: cookie(s) …` lines and the report carries a `sessionLosses` list naming, per lost cookie, the page reached after any redirect, even when that page failed to load; if one of them was the session cookie, everything scanned after that page was audited signed-out. Monitoring continues past the first loss (each cookie is reported once, where it vanished), and URLs discovered mid-crawl join cookie tracking before being visited. Cookie values are not compared and a cookie the browser dropped at its own expiry is ignored, but any other cookie the crawl started with and lost is reported — nothing marks a cookie as an authentication one. ### scan_page_matrix diff --git a/docs/playwright-1.64-validation-271.md b/docs/playwright-1.64-validation-271.md new file mode 100644 index 00000000..b3ba2c0a --- /dev/null +++ b/docs/playwright-1.64-validation-271.md @@ -0,0 +1,112 @@ +# Playwright 1.64.0 migration validation (#271) + +## Decision — 2026-10-08 + +This is a **draft migration**, not approval to change the stable default in +`main`. Both dependencies and their lockfile entries move together from exact +1.63.0 to exact 1.64.0. Keep the PR unmerged until the missing browser/platform +gates pass and the #257 ARIA result is resolved or explicitly assessed. + +The recorder hub uses `_startRecording({ language: 'javascript' }, sink)` and +`_stopRecording()` with no old-name fallback. The published 1.64.0 runtime was +inspected: starting an active recorder rejects, the client has one event sink, +and consecutive fills on the same selector emit `actionUpdated`. The hub starts +once, preserves shared ownership and the 500 ms drain, retains fills that span +recording restarts, and excludes new fills after stop begins. Sibling-tool +updates retain the existing attribution buffer. `tracing.start()` now returns a +disposable; the readiness type follows that return type, while explicit shared +trace stop/refcount ownership remains unchanged. + +`--device` and `--mobile` retain the new device `screen` emulation. This gives +more faithful screen dimensions and device-size media queries, and can change +responsive scan results. Explicit screen sizes remain supported, with unchanged +configuration precedence. No browser engine is patched and no 1.63.0 test +allowance is extended to the candidate. + +## Environment and results + +Linux x64, Node **24.19.0**, TypeScript **7.0.2**, Vitest **5.0.1**, exact paired +Playwright **1.64.0**. Installed browser metadata: Chromium/headless shell r1248 +(156.0.8078.4), Firefox r1555 (157.0), WebKit r2370 (27.2). +Only Firefox actually executed page tests successfully. WebKit macOS 14 +revision overrides still select r2251; the local Linux bundle does not validate +that frozen platform bundle. + +| Check | Result / limits | +| --- | --- | +| `npm run lint`, typecheck, build | Passed. | +| Recorder/context/session/factory/config/Axe unit gate | 369 passed, 4 skipped across seven files. The skipped Axe checks require a real browser. | +| Full default `npm test` | 1497 passed, 84 failed, 62 skipped; 51 files passed, 12 failed, 6 skipped. Failures require missing Chromium/Chrome executables, including extension discovery assertions. This is not a green upgrade gate. | +| Firefox explicit four-suite run | 10 passed, 1 failed (#257 ARIA), 4 skipped: Chromium-only CDP/fonts, unsupported Firefox mobile, and macOS-only WebKit setup. | +| Mutation check | Removing the restarted-fill insertion made the new lifecycle test fail (`[]` instead of `['final fill']`); restored code passed. | +| Real Firefox recorder | Stateless explicit-session stop/restart, ephemeral rejection and repeated fills with `--save-session` passed. Chromium shared-CDP/sibling-client recorder gate remains unexecuted. | +| Firefox numpad (#244) | All four key combinations passed key, code, typed character and numpad location checks, with zero deviations. | +| Firefox device screen (#271) | Desktop screen 1920×1080, matching device-size media query and explicit 900×1100 override passed. Mobile Chromium/WebKit screen remains pending. | +| Firefox smooth-scroll retry (#235) | Fixed-header click completed with at most two scroll events. Mobile touch preservation after full-page/oversized-element capture remains pending. | +| Firefox visibility/navigation/focus | Nested-details snapshot/find/verification, Option-key no-text insertion, nested frame focus, delivered abort, bounded stall and subsequent usability passed. | +| Firefox CSS overlay (#257) | JavaScript-disabled/enabled retry and unobstructed controls passed. This does not prove Chromium behavior. | +| Firefox ARIA (#257) | **Failed intended behavior**: unslotted text produced `button "LightShadow"`; closed details exposed `Hidden direct text`. The strict regression stays failing, with no new known-deviation exemption. Upstream #42982 was closed without merging when checked. | +| Firefox crash probe (#251) | Attempted; blocked by `ENOENT` reading the launched browser PID under `/proc`. No memory-retention or native-window conclusion. | +| Chromium/headless shell | Installer exhausted retries; downloads were invalid/truncated ZIPs (`End of central directory record signature not found`). Runtime checks fail for missing r1248 executables. | +| WebKit | Bundle downloaded, but page tests fail because host libraries are missing. `playwright install-deps firefox webkit` failed on container UID/group operations. No WebKit runtime result. | +| Chrome | Explicit channel history/download and upgrade gates attempted; executable is unavailable. Edge and Windows/macOS controls remain pending on appropriate runners. | + +Firefox initially crashed on page creation because the container cannot create +its content-process user namespace. The successful **local fixture-only** run +used `MOZ_DISABLE_CONTENT_SANDBOX=1`. This is a validation-environment setting, +not a repository/browser default change. Repeat on an ordinary supported runner. + +## Restrictions and checks still required + +- **#244:** run crashed/discarded-tab raw CDP and endpoint/launch attachment, + shared-CDP recorder attribution, and Chromium/WebKit numpad contracts. +- **#230 / #231:** persistent-profile download/relaunch and idle-release bytes, + history/ref controls on bundled Chromium, Chrome and Edge. Keep BFCache guidance. +- **#235:** mobile touch/pointer properties after full-page and oversized-element + screenshots plus navigation, on Chromium and WebKit. +- **#246 / #251:** WebKit nested-details/list-box controls, preloaded CDP frame + tree, Chromium actual fonts/geometry, WebKit navigation stress and actual macOS + 14 page creation. macOS Option/focus and Windows channel checks need their own + runners; Linux Firefox passing is not evidence for those platforms. +- **#224 / #259:** keep existing-context storage imports rejected. Recheck + service-worker snapshot execution, IndexedDB Map/Set capture and both restore + paths, and failed-import rollback on each engine before lifting the guard. +- **#235 certificate/proxy routing:** keep nonblank effective `proxy.bypass` + rejected with client certificates. The existing probe verifies rejection and + non-bypass routes; allowing bypass needs a real HTTP/HTTPS/certificate routing + probe of the candidate before changing config validation. +- **#257:** ARIA failure remains actionable. Chromium no-JavaScript retry and + non-refetchable evicted response-body/error/no-extra-request and valid empty + response controls remain untested. + +The existing `knownAttachHang`, `knownWebKitLeak`, numpad tables, font/frame-tree +allowances and native-download-crash signatures still apply only to their exact +old 1.63.0 pins/builds. They do not grant candidate passes. Unit tests verify the +retained storage/proxy restrictions; error messages now describe pending 1.64.0 +validation instead of claiming the old defect is present in the current pin. + +## Rerun + +```bash +npm ci +npx playwright install --with-deps chromium firefox webkit chrome +npm run lint +npm run build +npx vitest run tests/recorder.integration.test.ts tests/context.test.ts tests/browserSessions.test.ts tests/browserContextFactory.test.ts tests/tools-recorder.test.ts tests/sessionLog.test.ts +npx vitest run tests/cdp-attach.integration.test.ts tests/cdp-frame-tree.integration.test.ts tests/numpad-keys.integration.test.ts tests/browser-upgrade-controls.integration.test.ts tests/history-downloads.integration.test.ts tests/browser-failures.integration.test.ts +MCP_TEST_BROWSER_NAME=firefox npx vitest run tests/recorder.integration.test.ts tests/numpad-keys.integration.test.ts tests/details-visibility.integration.test.ts tests/browser-upgrade-controls.integration.test.ts +MCP_TEST_BROWSER_NAME=webkit npx vitest run tests/recorder.integration.test.ts tests/numpad-keys.integration.test.ts tests/details-visibility.integration.test.ts tests/browser-upgrade-controls.integration.test.ts +MCP_TEST_BROWSER_CHANNEL=chrome npx vitest run tests/history-downloads.integration.test.ts tests/browser-upgrade-controls.integration.test.ts +MCP_TEST_BROWSER_CHANNEL=msedge npx vitest run tests/history-downloads.integration.test.ts tests/browser-upgrade-controls.integration.test.ts +node tests/client-certificate-proxy-probe.mjs +npm test +``` + +Run the crash probe only on a disposable Linux runner, as described in +[browser-upgrade-validation-251.md](browser-upgrade-validation-251.md). CI's +existing browser-controls matrix now also runs the real recorder suite, so +candidate runtime behavior is exercised outside the main Chromium job. + +Slop-check reviewed the changed TypeScript: one `any` finding remains on the +partial unit-test session-log mock, consistent with the surrounding fixture. +Production recorder calls use a narrow, runtime-verified private contract. diff --git a/package-lock.json b/package-lock.json index b74ed8ac..00ff84a5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,8 +15,8 @@ "axe-core": "4.13.0", "commander": "^15.0.0", "debug": "^4.4.3", - "playwright": "1.63.0", - "playwright-core": "1.63.0", + "playwright": "1.64.0", + "playwright-core": "1.64.0", "re2": "^1.26.1", "ws": "^8.21.3", "zod": "^4.4.3" @@ -4028,12 +4028,12 @@ } }, "node_modules/playwright": { - "version": "1.63.0", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", - "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz", + "integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==", "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.63.0" + "playwright-core": "1.64.0" }, "bin": { "playwright": "cli.js" @@ -4043,9 +4043,9 @@ } }, "node_modules/playwright-core": { - "version": "1.63.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", - "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz", + "integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==", "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" diff --git a/package.json b/package.json index 694c017d..6373ca31 100644 --- a/package.json +++ b/package.json @@ -52,8 +52,8 @@ "axe-core": "4.13.0", "commander": "^15.0.0", "debug": "^4.4.3", - "playwright": "1.63.0", - "playwright-core": "1.63.0", + "playwright": "1.64.0", + "playwright-core": "1.64.0", "re2": "^1.26.1", "ws": "^8.21.3", "zod": "^4.4.3" diff --git a/src/browserContextFactory.ts b/src/browserContextFactory.ts index 654b488e..0ed41f05 100644 --- a/src/browserContextFactory.ts +++ b/src/browserContextFactory.ts @@ -150,7 +150,7 @@ async function navigateReplacementPages(replaced: { page: playwright.Page, url: /** Existing contexts can contain service workers and storage we cannot safely snapshot. */ export function assertReusedContextStorageStateSupported(config: FullConfig): void { if (config.browser.contextOptions?.storageState) - throw new Error('Cannot apply --storage-state to an existing browser context on Playwright 1.63.0: its rollback snapshot can run service-worker-served scripts and alter storage. Use a fresh context (for CDP, add --isolated), or omit --storage-state and sign in interactively. No storage snapshot or reset was attempted.'); + throw new Error('Cannot apply --storage-state to an existing browser context: rollback snapshots and imports remain unvalidated on Playwright 1.64.0 after service-worker execution and IndexedDB loss on 1.63.0. Use a fresh context (for CDP, add --isolated), or omit --storage-state and sign in interactively. No storage snapshot or reset was attempted.'); } function createContextFactory(config: FullConfig): BrowserContextFactory { @@ -1022,13 +1022,11 @@ function cdpConnectHeaders(clientInfo: ClientInfo, browserConfig: FullConfig['br return Object.keys(headers).length ? headers : undefined; } -const cdpAttachTimeoutHint = 'The CDP WebSocket connected, but Playwright did not finish attaching before the timeout. An existing tab can block the attach: on Playwright 1.63.0 a tab without a renderer (crashed, or discarded by Memory Saver) never answers, and a sleeping or unresponsive tab can stall it. Reload or close that tab in the browser yourself, or attach to a separate browser, then retry; a longer --cdp-timeout helps only when the attach is merely slow.'; +const cdpAttachTimeoutHint = 'The CDP WebSocket connected, but Playwright did not finish attaching before the timeout. A sleeping or unresponsive existing tab can stall the attach. Reload or close that tab in the browser yourself, or attach to a separate browser, then retry; a longer --cdp-timeout helps only when the attach is merely slow.'; /** - * Playwright 1.63.0 initializes every existing tab while attaching over CDP, - * and a tab without a renderer never answers, so `connectOverCDP` runs into - * its timeout after the WebSocket connected (microsoft/playwright#42936). The - * call log's `` entry tells that apart from an endpoint that + * An unresponsive existing tab can stall CDP initialization after the + * WebSocket connected. The call log's `` entry tells that apart from an endpoint that * never answered, which must not be blamed on a tab. */ function isCdpAttachTimeout(error: unknown): error is Error { diff --git a/src/config.ts b/src/config.ts index 0c81b10c..0702ac0c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -145,12 +145,12 @@ async function validateResolvedConfig(config: FullConfig): Promise { parseFilePaths(config.filePaths); const { contextOptions, launchOptions } = config.browser; if (contextOptions.clientCertificates?.length) { - // Playwright 1.63's certificate interceptor only sees the context proxy. + // The certificate interceptor uses the context proxy. // Preserve an explicit context override, otherwise carry the launch route // into every fresh-context factory (including remote browser connections). const proxy = contextOptions.proxy ?? launchOptions.proxy; if (proxy?.bypass?.trim()) - throw new Error('clientCertificates with proxy.bypass is unsupported on Playwright 1.63.0: the certificate interceptor ignores bypass rules. Use a separate browser configuration for these routes; no browser was started.'); + throw new Error('clientCertificates with proxy.bypass is unsupported pending Playwright 1.64.0 routing validation: the 1.63.0 interceptor ignored bypass rules. Use a separate browser configuration for these routes; no browser was started.'); if (proxy) contextOptions.proxy = proxy; } diff --git a/tests/browser-upgrade-controls.integration.test.ts b/tests/browser-upgrade-controls.integration.test.ts index 75c9172a..802effbd 100644 --- a/tests/browser-upgrade-controls.integration.test.ts +++ b/tests/browser-upgrade-controls.integration.test.ts @@ -22,7 +22,7 @@ import { createRequire } from 'node:module'; import { afterEach, expect, it } from 'vitest'; import * as playwright from 'playwright'; import { BrowserServerBackend } from '../src/browserServerBackend.js'; -import { resolveConfig } from '../src/config.js'; +import { resolveCLIConfig, resolveConfig } from '../src/config.js'; const browserName = process.env.MCP_TEST_BROWSER_NAME || 'chromium'; if (browserName !== 'chromium' && browserName !== 'firefox' && browserName !== 'webkit') @@ -56,10 +56,10 @@ afterEach(async () => { } }); -async function setup() { +async function setup(contextOptions: playwright.BrowserContextOptions = {}) { directory = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-upgrade-controls-')); browser = await browserType.launch({ channel }); - const context = await browser.newContext({ viewport: { width: 1280, height: 720 } }); + const context = await browser.newContext({ viewport: { width: 1280, height: 720 }, ...contextOptions }); const page = await context.newPage(); backend = new BrowserServerBackend(await resolveConfig({ outputDir: directory, timeouts: { navigationTimeout: 3000, defaultTimeout: 3000, settle: 50 }, @@ -71,6 +71,103 @@ async function setup() { return { page, backend }; } +it('forwards device screen dimensions and preserves explicit screen overrides (#271)', async () => { + const device = browserName === 'webkit' ? 'Desktop Safari' : browserName === 'firefox' ? 'Desktop Firefox' : 'Desktop Chrome'; + const config = await resolveCLIConfig({ device, browser: browserName }); + const expectedScreen = playwright.devices[device].screen; + expect(config.browser.contextOptions.screen).toEqual(expectedScreen); + const { page } = await setup(config.browser.contextOptions); + const screen = () => page.evaluate(() => ({ width: window.screen.width, height: window.screen.height })); + expect(await screen()).toEqual(expectedScreen); + expect(await page.evaluate(size => matchMedia(`(device-width: ${size.width}px) and (device-height: ${size.height}px)`).matches, expectedScreen)).toBe(true); + + const override = { width: 900, height: 1100 }; + const overridden = await resolveConfig({ browser: { contextOptions: { ...playwright.devices[device], screen: override } } }); + const context = await browser!.newContext(overridden.browser.contextOptions); + try { + const other = await context.newPage(); + expect(await other.evaluate(() => ({ width: window.screen.width, height: window.screen.height }))).toEqual(override); + } finally { + await context.close(); + } +}); + +it.skipIf(browserName === 'firefox')('preserves mobile touch properties after full-page/element screenshots and navigation (#42617)', async () => { + const config = await resolveCLIConfig({ mobile: true, browser: browserName }); + const { page } = await setup(config.browser.contextOptions); + const html = 'data:text/html,
Oversized element
'; + await page.goto(html); + const properties = () => page.evaluate(() => ({ + touch: navigator.maxTouchPoints, + coarse: matchMedia('(pointer: coarse)').matches, + screen: { width: window.screen.width, height: window.screen.height }, + })); + const before = await properties(); + expect(before.touch).toBeGreaterThan(0); + expect(before.coarse).toBe(true); + expect(before.screen).toEqual(config.browser.contextOptions.screen); + await page.screenshot({ fullPage: true }); + expect(await properties()).toEqual(before); + await page.locator('div').screenshot(); + expect(await properties()).toEqual(before); + await page.reload(); + expect(await properties()).toEqual(before); +}); + +it('scrolls instantly on pointer retry with a fixed header and smooth scrolling (#42626)', async () => { + const { page } = await setup(); + await page.setContent(`
+
+ 0`); + await page.getByRole('button', { name: 'Target' }).click({ timeout: 5000 }); + expect(await page.locator('button').textContent()).toBe('Clicked'); + expect(Number(await page.locator('output').textContent())).toBeLessThanOrEqual(2); +}); + +it('excludes unrendered ARIA text and retains slotted/open-details controls (#257)', async () => { + const { page, backend } = await setup(); + await page.setContent(`
Light
+
Slotted
+
Hidden direct textSummary
+
Visible direct textOpen summary
+ `); + const snapshot = await backend.callTool('browser_snapshot', {}); + expect(snapshot.isError).not.toBe(true); + const text = snapshot.content.filter(item => item.type === 'text').map(item => item.text).join('\n'); + expect(text).toContain('button "Shadow"'); + expect(text).toContain('button "Slotted"'); + expect(text).toContain('Visible direct text'); + expect(text).not.toContain('Light'); + expect(text).not.toContain('Hidden direct text'); + for (const name of ['Shadow', 'Slotted']) { + const verification = await backend.callTool('browser_verify_element_visible', { role: 'button', accessibleName: name }); + expect(verification.isError, JSON.stringify(verification.content)).not.toBe(true); + } +}); + +it.each([false, true])('retries a CSS-only overlay with JavaScript enabled: %s (#257)', async javaScriptEnabled => { + const { page } = await setup({ javaScriptEnabled }); + await page.setContent(`
`); + await page.getByRole('button', { name: 'Target' }).click({ timeout: 5000 }); + expect(await page.locator('button').evaluate(element => element === document.activeElement)).toBe(true); + await page.locator('#overlay').evaluate(element => element.remove()); + await page.getByRole('button', { name: 'Target' }).click({ timeout: 5000 }); +}); + async function fontMetrics(page: playwright.Page) { const cdp = await page.context().newCDPSession(page); try { From 8e43698f0b2b4f4da4a67dd003c109df3996293e Mon Sep 17 00:00:00 2001 From: JustasM <59362982+JustasMonkev@users.noreply.github.com> Date: Thu, 8 Oct 2026 08:13:46 +0300 Subject: [PATCH 3/5] Fix delayed recorder attribution and strengthen upgrade tests --- README.md | 2 +- docs/playwright-1.64-validation-271.md | 54 ++++++++++++++++++- src/context.ts | 30 +++++++---- ...owser-upgrade-controls.integration.test.ts | 48 +++++++++++------ tests/config.test.ts | 4 ++ tests/context.test.ts | 52 +++++++++++------- 6 files changed, 145 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index a07283a2..61fffc24 100644 --- a/README.md +++ b/README.md @@ -922,7 +922,7 @@ npx vitest run tests/recorder.integration.test.ts tests/context.test.ts tests/br The real-browser tests cover concurrent starts, duplicate-start rejection, shared CDP clients, sibling-action attribution, stop/disconnect/restart, `--save-session`, and recording across stateless explicit sessions. Existing unit -tests also cover failed-start recovery and overlapping start/stop. The recorder +tests also cover failed-start recovery, overlapping start/stop, and delayed sibling-tool click/fill updates excluded from recordings and saved session logs. The recorder must receive the final input event before stop; unbuffered input delivered after stop begins is excluded, while buffered clicks/navigation get a 500 ms drain. diff --git a/docs/playwright-1.64-validation-271.md b/docs/playwright-1.64-validation-271.md index b3ba2c0a..b693ebe3 100644 --- a/docs/playwright-1.64-validation-271.md +++ b/docs/playwright-1.64-validation-271.md @@ -2,7 +2,7 @@ ## Decision — 2026-10-08 -This is a **draft migration**, not approval to change the stable default in +This is a **candidate migration**, not approval to change the stable default in `main`. Both dependencies and their lockfile entries move together from exact 1.63.0 to exact 1.64.0. Keep the PR unmerged until the missing browser/platform gates pass and the #257 ARIA result is resolved or explicitly assessed. @@ -56,6 +56,58 @@ its content-process user namespace. The successful **local fixture-only** run used `MOZ_DISABLE_CONTENT_SANDBOX=1`. This is a validation-environment setting, not a repository/browser default change. Repeat on an ordinary supported runner. +## PR #272 review follow-up — 2026-10-08 + +The hub now retains the original action's tool attribution for later updates +and signals. Suppression is per recording owner and applies to session logs; +weak references avoid retaining departed contexts. The click regression remains, +and a separate fill case checks updates at 499 ms and 501 ms, excludes sibling +input from both outputs, and accepts the next manual sequence. The genuine +coalesced-fill restart test stays separate. + +The browser-control fixture logs starts and elapsed times for launch, context +creation, page creation, backend initialization and the initial snapshot. A +stalled phase therefore remains visible in CI even if it never returns. Both +mobile screenshot operations have an explicit 15-second timeout and the case +has a 60-second total budget; other operations retain the 3-second default. +Mobile config tests assert touch and screen options for Chromium and WebKit. +The runtime test logs the resolved options and initial properties before its +strict preservation checks. + +The review's missing-iPhone-17 diagnosis is contradicted by the tagged +[v1.64.0 device registry](https://github.com/microsoft/playwright/blob/v1.64.0/packages/isomorphic/deviceDescriptorsSource.json) +and the installed package: iPhone 17 exists with `hasTouch: true`, +`isMobile: true` and a 402×874 screen. Changing the descriptor would not establish +that the Linux WebKit touch failure is fixed. Its real-browser gate stays strict. + +The ARIA test now reports all snapshot mismatches in one run using soft +assertions (which still fail the test), and enables the `verify` capability so +its positive controls can execute. It still requires `Shadow`, excludes `Light` +and closed-details text, and verifies slotted and shadow controls. No candidate +failure is converted into a skip, expected failure, or broader pin exemption. + +| Review validation | Result | +| --- | --- | +| Local seven-file unit gate | 370 passed, 4 skipped. | +| Local lint/typecheck and build | Passed. | +| Local full default suite | 1498 passed, 84 failed, 62 skipped; missing Chromium/Chrome still blocks browser checks. | +| Local Firefox four-suite gate | 10 passed, 1 failed (#257 ARIA), 4 skipped. All five fixture timing phases completed. | +| Suppression mutation checks | Removing log suppression leaked the delayed fill into the session log; removing recording suppression inserted the delayed fill into the explicit recording. Both failed the new fill regression; restored code passed. | +| Slop-check on follow-up TypeScript | Clean across four files. | + +Hosted [CI run 456](https://github.com/JustasMonkev/mcp-accessibility-scanner/actions/runs/37727045903) +validated the **previous PR head**, not these follow-up edits. Its Linux main +suite passed 1635 tests and failed three browser controls: a 3-second mobile +screenshot timeout, #257 ARIA, and changed monospace fonts/geometry. Linux +WebKit passed recorder restarts, numpad, desktop screen, overlays, focus and all +350 fresh navigation rounds, but failed initial touch (`maxTouchPoints: 0`) +and ARIA. macOS Chromium passed recorder checks but failed ARIA and font +preservation. macOS 14 WebKit stalled during page setup, including the separate +bounded setup probe. Windows Chromium and Chrome history/download gates passed; +Edge failed two persistent-profile download cases. These are remaining upgrade +blockers, not platform passes. The next hosted run must use the follow-up commit +and capture the new setup/mobile diagnostics. + ## Restrictions and checks still required - **#244:** run crashed/discarded-tab raw CDP and endpoint/launch attachment, diff --git a/src/context.ts b/src/context.ts index 34868a61..18ec4935 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1034,7 +1034,10 @@ export class InputRecorder { const recorders = new Set(); const recordings = new Map(); let actionSequence = 0; - const lastActionSequence = new WeakMap(); + // Retain attribution until the next action, including updates delivered + // after the tool's 500ms window has expired. + type Attribution = { suppressedLogs: boolean, suppressedRecordings: WeakSet }; + const lastActionSequence = new WeakMap(); let armed = false; let transition = Promise.resolve(); const enqueue = (callback: () => Promise) => { @@ -1047,32 +1050,36 @@ export class InputRecorder { flushable: boolean, log: (recorder: InputRecorder) => void, record: (target: RecordingTarget) => void, - ) => { + attribution?: Attribution, + ): Attribution => { const contexts = new Set(recorderContexts.get(browserContext)); for (const context of recordings.keys()) contexts.add(context); const running = [...contexts].filter(context => context.isRunningToolForRecording(buffered)); - if (!running.length) { + if (!running.length && !attribution?.suppressedLogs) { for (const recorder of recorders) log(recorder); } for (const [context, target] of recordings) { - if ((!target.state.stopping || flushable) && !running.some(runningContext => runningContext !== context)) { + if ((!target.state.stopping || flushable) && !attribution?.suppressedRecordings.has(context) && !running.some(runningContext => runningContext !== context)) { record(target); context.markRecordingActivity(); } } + return { + suppressedLogs: !!running.length, + suppressedRecordings: new WeakSet([...recordings.keys()].filter(context => running.some(runningContext => runningContext !== context))), + }; }; const sink = { actionAdded: (page: playwright.Page, data: actions.Action | actions.ActionInContext, code: string) => { const sequence = ++actionSequence; - lastActionSequence.set(page, sequence); const action = 'action' in data ? data.action : data; const isAssertion = action.name.startsWith('assert'); if (isAssertion) code = code.replace(/^(\s*)\/\/ ?/gm, '$1'); const buffered = actionIsBuffered(action); - dispatch( + const attribution = dispatch( buffered, buffered || action.name === 'closePage', recorder => recorder._actionAdded(page, action, isAssertion ? `${expectPrelude}\n${code}` : code, sequence), @@ -1083,11 +1090,13 @@ export class InputRecorder { target.actions.push({ page, code, sequence }); }, ); + lastActionSequence.set(page, { sequence, ...attribution }); }, actionUpdated: (page: playwright.Page, data: actions.Action | actions.ActionInContext, code: string) => { - const sequence = lastActionSequence.get(page); - if (sequence === undefined) + const attribution = lastActionSequence.get(page); + if (!attribution) return; + const { sequence } = attribution; const action = 'action' in data ? data.action : data; dispatch( true, @@ -1102,10 +1111,12 @@ export class InputRecorder { target.actions.push({ page, code, sequence }); } }, + attribution, ); }, signalAdded: (page: playwright.Page, data: actions.Signal | actions.SignalInContext, code: string) => { - const sequence = lastActionSequence.get(page); + const attribution = lastActionSequence.get(page); + const sequence = attribution?.sequence; const signal = 'signal' in data ? data.signal : data; dispatch( true, @@ -1118,6 +1129,7 @@ export class InputRecorder { if (action && code) action.code = code; }, + attribution, ); }, }; diff --git a/tests/browser-upgrade-controls.integration.test.ts b/tests/browser-upgrade-controls.integration.test.ts index 802effbd..30ad89fc 100644 --- a/tests/browser-upgrade-controls.integration.test.ts +++ b/tests/browser-upgrade-controls.integration.test.ts @@ -56,16 +56,28 @@ afterEach(async () => { } }); +/** Prints the pending phase as well as its duration, so a stalled WebKit setup is identifiable in CI. */ +async function setupStep(phase: string, operation: () => Promise): Promise { + const started = Date.now(); + const metadata = { browserName, channel: channel || 'bundled', platform: process.platform, arch: process.arch, phase, ...versions }; + process.stdout.write(JSON.stringify({ ...metadata, status: 'started' }) + '\n'); + try { + return await operation(); + } finally { + process.stdout.write(JSON.stringify({ ...metadata, status: 'finished', elapsed: Date.now() - started }) + '\n'); + } +} + async function setup(contextOptions: playwright.BrowserContextOptions = {}) { directory = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-upgrade-controls-')); - browser = await browserType.launch({ channel }); - const context = await browser.newContext({ viewport: { width: 1280, height: 720 }, ...contextOptions }); - const page = await context.newPage(); + browser = await setupStep('launch', () => browserType.launch({ channel })); + const context = await setupStep('newContext', () => browser!.newContext({ viewport: { width: 1280, height: 720 }, ...contextOptions })); + const page = await setupStep('newPage', () => context.newPage()); backend = new BrowserServerBackend(await resolveConfig({ - outputDir: directory, timeouts: { navigationTimeout: 3000, defaultTimeout: 3000, settle: 50 }, + capabilities: ['verify'], outputDir: directory, timeouts: { navigationTimeout: 3000, defaultTimeout: 3000, settle: 50 }, }), { createContext: async () => ({ browserContext: context, close: () => context.close() }) }); - await backend.initialize({ notifyToolListChanged: async () => {} }, { name: 'upgrade-controls', version: '1' }); - const snapshot = await backend.callTool('browser_snapshot', {}); + await setupStep('initialize', () => backend!.initialize({ notifyToolListChanged: async () => {} }, { name: 'upgrade-controls', version: '1' })); + const snapshot = await setupStep('browser_snapshot', () => backend!.callTool('browser_snapshot', {})); expect(snapshot.isError, JSON.stringify(snapshot.content)).not.toBe(true); process.stdout.write(JSON.stringify({ browserName, channel: channel || 'bundled', browserVersion: browser.version(), platform: process.platform, arch: process.arch, ...versions }) + '\n'); return { page, backend }; @@ -94,6 +106,9 @@ it('forwards device screen dimensions and preserves explicit screen overrides (# it.skipIf(browserName === 'firefox')('preserves mobile touch properties after full-page/element screenshots and navigation (#42617)', async () => { const config = await resolveCLIConfig({ mobile: true, browser: browserName }); + expect(config.browser.contextOptions.hasTouch).toBe(true); + expect(config.browser.contextOptions.isMobile).toBe(true); + process.stdout.write(JSON.stringify({ mobileContextOptions: config.browser.contextOptions, browserName, ...versions }) + '\n'); const { page } = await setup(config.browser.contextOptions); const html = 'data:text/html,
Oversized element
'; await page.goto(html); @@ -103,16 +118,17 @@ it.skipIf(browserName === 'firefox')('preserves mobile touch properties after fu screen: { width: window.screen.width, height: window.screen.height }, })); const before = await properties(); + process.stdout.write(JSON.stringify({ mobileProperties: before, browserName }) + '\n'); expect(before.touch).toBeGreaterThan(0); expect(before.coarse).toBe(true); expect(before.screen).toEqual(config.browser.contextOptions.screen); - await page.screenshot({ fullPage: true }); + await page.screenshot({ fullPage: true, timeout: 15000 }); expect(await properties()).toEqual(before); - await page.locator('div').screenshot(); + await page.locator('div').screenshot({ timeout: 15000 }); expect(await properties()).toEqual(before); await page.reload(); expect(await properties()).toEqual(before); -}); +}, 60000); it('scrolls instantly on pointer retry with a fixed header and smooth scrolling (#42626)', async () => { const { page } = await setup(); @@ -145,14 +161,14 @@ it('excludes unrendered ARIA text and retains slotted/open-details controls (#25 const snapshot = await backend.callTool('browser_snapshot', {}); expect(snapshot.isError).not.toBe(true); const text = snapshot.content.filter(item => item.type === 'text').map(item => item.text).join('\n'); - expect(text).toContain('button "Shadow"'); - expect(text).toContain('button "Slotted"'); - expect(text).toContain('Visible direct text'); - expect(text).not.toContain('Light'); - expect(text).not.toContain('Hidden direct text'); - for (const name of ['Shadow', 'Slotted']) { + expect.soft(text).toContain('button "Shadow"'); + expect.soft(text).toContain('button "Slotted"'); + expect.soft(text).toContain('Visible direct text'); + expect.soft(text).not.toContain('Light'); + expect.soft(text).not.toContain('Hidden direct text'); + for (const name of ['Slotted', 'Shadow']) { const verification = await backend.callTool('browser_verify_element_visible', { role: 'button', accessibleName: name }); - expect(verification.isError, JSON.stringify(verification.content)).not.toBe(true); + expect.soft(verification.isError, JSON.stringify(verification.content)).not.toBe(true); } }); diff --git a/tests/config.test.ts b/tests/config.test.ts index 389fb11e..961a795a 100644 --- a/tests/config.test.ts +++ b/tests/config.test.ts @@ -630,6 +630,8 @@ describe('Config', () => { expect(config.browser.contextOptions.isMobile).toBe(true); expect(config.browser.contextOptions.userAgent).toContain('Pixel 10'); + expect(config.browser.contextOptions.hasTouch).toBe(true); + expect(config.browser.contextOptions.screen).toEqual({ width: 360, height: 808 }); }); it('uses a WebKit mobile device for WebKit', async () => { @@ -637,6 +639,8 @@ describe('Config', () => { expect(config.browser.contextOptions.isMobile).toBe(true); expect(config.browser.contextOptions.viewport).toEqual({ width: 402, height: 681 }); + expect(config.browser.contextOptions.hasTouch).toBe(true); + expect(config.browser.contextOptions.screen).toEqual({ width: 402, height: 874 }); }); it('uses the config-file browser when selecting the mobile device', async () => { diff --git a/tests/context.test.ts b/tests/context.test.ts index 3e96bba6..96303b70 100644 --- a/tests/context.test.ts +++ b/tests/context.test.ts @@ -958,34 +958,50 @@ describe('Context', () => { } }); - it('does not apply an update whose initial action was suppressed', async () => { + it.each(['click', 'fill'])('does not apply a late %s update whose initial action was suppressed', async name => { vi.useFakeTimers(); try { mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); - const makeContext = () => new Context({ - tools: [], - config: { timeouts: {} } as any, - browserContextFactory: mockBrowserContextFactory, - sessionLog: undefined, - clientInfo: {}, + const sessionLog = { logUserAction: vi.fn() }; + const config = await resolveConfig({}); + const recordingContext = new Context({ + tools: [], config, browserContextFactory: mockBrowserContextFactory, + sessionLog: () => Promise.resolve(sessionLog), clientInfo: {}, }); - const recordingContext = makeContext(); - const siblingContext = makeContext(); - await recordingContext.startRecording(); + const siblingContext = new Context({ + tools: [], config, browserContextFactory: mockBrowserContextFactory, + sessionLog: undefined, clientInfo: {}, + }); + const starting = recordingContext.startRecording(); + await vi.advanceTimersByTimeAsync(500); + await starting; await siblingContext.newTab(); + const page = Object.assign(new EventEmitter(), { + setDefaultNavigationTimeout: vi.fn(), setDefaultTimeout: vi.fn(), url: () => 'about:blank', + }); + mockBrowserContext.emit('page', page); const sink = mockBrowserContext._startRecording.mock.calls[0][1]; - const page = {} as any; - sink.actionAdded(page, { name: 'click', button: 'left', selector: '#query' }, 'manual click'); + const action = { name, button: 'left', selector: '#query' }; + sink.actionAdded(page, action, 'manual action'); - const endSiblingTool = siblingContext.beginToolCall('browser_click'); - sink.actionAdded(page, { name: 'click', button: 'left', selector: '#query' }, 'suppressed click'); + const endSiblingTool = siblingContext.beginToolCall(name === 'fill' ? 'browser_fill_form' : 'browser_click'); + sink.actionAdded(page, action, 'suppressed action'); endSiblingTool(); - await vi.advanceTimersByTimeAsync(501); - sink.actionUpdated(page, { name: 'click', button: 'left', selector: '#query' }, 'late suppressed update'); - + await vi.advanceTimersByTimeAsync(499); + sink.actionUpdated(page, action, 'suppressed buffered update'); + await vi.advanceTimersByTimeAsync(2); + sink.actionUpdated(page, action, 'late suppressed update'); + expect(sessionLog.logUserAction).toHaveBeenCalledTimes(1); + + // A new manual sequence must still be accepted after suppression. + sink.actionAdded(page, action, 'next manual action'); + sink.actionUpdated(page, action, 'next manual update'); const stopping = recordingContext.stopRecording(); await vi.advanceTimersByTimeAsync(500); - await expect(stopping).resolves.toEqual(['manual click']); + await expect(stopping).resolves.toEqual(['manual action', 'next manual update']); + expect(sessionLog.logUserAction.mock.calls.map(call => [call[2], call[3]])).toEqual([ + ['manual action', false], ['next manual action', false], ['next manual update', true], + ]); } finally { vi.useRealTimers(); } From 2a77f0bdae2b1b048b3daff6d442d09da7ab9f93 Mon Sep 17 00:00:00 2001 From: JustasM <59362982+JustasMonkev@users.noreply.github.com> Date: Thu, 8 Oct 2026 08:59:27 +0300 Subject: [PATCH 4/5] Strengthen ARIA upgrade checks and record confirmed native blockers --- docs/playwright-1.64-validation-271.md | 77 ++++++++++++++++--- ...owser-upgrade-controls.integration.test.ts | 24 ++++-- 2 files changed, 83 insertions(+), 18 deletions(-) diff --git a/docs/playwright-1.64-validation-271.md b/docs/playwright-1.64-validation-271.md index b693ebe3..31f06519 100644 --- a/docs/playwright-1.64-validation-271.md +++ b/docs/playwright-1.64-validation-271.md @@ -95,18 +95,71 @@ failure is converted into a skip, expected failure, or broader pin exemption. | Suppression mutation checks | Removing log suppression leaked the delayed fill into the session log; removing recording suppression inserted the delayed fill into the explicit recording. Both failed the new fill regression; restored code passed. | | Slop-check on follow-up TypeScript | Clean across four files. | -Hosted [CI run 456](https://github.com/JustasMonkev/mcp-accessibility-scanner/actions/runs/37727045903) -validated the **previous PR head**, not these follow-up edits. Its Linux main -suite passed 1635 tests and failed three browser controls: a 3-second mobile -screenshot timeout, #257 ARIA, and changed monospace fonts/geometry. Linux -WebKit passed recorder restarts, numpad, desktop screen, overlays, focus and all -350 fresh navigation rounds, but failed initial touch (`maxTouchPoints: 0`) -and ARIA. macOS Chromium passed recorder checks but failed ARIA and font -preservation. macOS 14 WebKit stalled during page setup, including the separate -bounded setup probe. Windows Chromium and Chrome history/download gates passed; -Edge failed two persistent-profile download cases. These are remaining upgrade -blockers, not platform passes. The next hosted run must use the follow-up commit -and capture the new setup/mobile diagnostics. +Hosted [CI run 457](https://github.com/JustasMonkev/mcp-accessibility-scanner/actions/runs/37731336455) +validated commit `8e43698`, including the review fixes. Linux main passed +**1637 tests** and failed **two**: #257 ARIA and changed monospace fonts/geometry. +The Chromium mobile screenshot case now passes. Linux WebKit passed recorder +restarts, numpad, desktop screen, overlays, focus and all 350 fresh navigation +rounds; it failed initial touch (`maxTouchPoints: 0`) and ARIA. Its resolved +mobile options are correct (`hasTouch: true`, `isMobile: true`, screen 402×874). +macOS 14 WebKit's new diagnostics locate the stall at **`newPage`**, after +successful launch and context creation, before backend initialization or snapshot. +Windows Chromium and Chrome history/download gates passed. Edge passed 17 tests +and failed the idle-profile relaunch download: the native process exited with +`3221225477` while saving `second.txt`, rather than saving the required bytes. +This candidate does not match the exact 1.63.0 native-crash allowance. + +### Remaining ARIA review and final investigation + +The remaining review finding is valid and remains unresolved. The proposed +[upstream ARIA fix #42982](https://github.com/microsoft/playwright/pull/42982) +was **closed without merging**; stable 1.64.0 still has the defect. The linked +[#257 acceptance criteria](https://github.com/JustasMonkev/mcp-accessibility-scanner/issues/257) +require checking release inclusion and prohibit vendoring private engine code. +We must not rewrite the expected snapshot to `LightShadow`, accept hidden text, +or patch the installed Playwright bundle to manufacture a passing upgrade gate. + +The regression now also checks exact native role names and `browser_find` on +both hidden and visible controls. This closes a diagnostic blind spot: +`browser_verify_element_visible` uses substring name matching, so verifying +`Shadow` alone accepted the incorrect `LightShadow` name. The exact native +lookup finds zero matching buttons. In the repeated local Firefox four-suite +run, **10 tests passed, 1 failed, 4 skipped**. That one ARIA case reported seven +real mismatches: three snapshot assertions, the exact role name, the visible +Shadow search, and the two hidden-text searches. Slotted/open-details positive +controls passed. The visibility tool's existing matching semantics are unchanged. + +Mobile assertions also collect failures without stopping at the initial touch +check: full-page capture, oversized-element capture and navigation still execute +and compare touch, pointer and screen values. A failed initial touch assertion +continues to fail the whole test; this is not a candidate exemption. WebKit needs +a new hosted run to validate these additional diagnostic paths. + +Other native blockers remain independently confirmed: +[font-family loss #42962](https://github.com/microsoft/playwright/issues/42962) +is open and labelled for 1.65, and +[macOS 14 WebKit #42964](https://github.com/microsoft/playwright/issues/42964) +was closed as not planned. Neither supplies a validated 1.64.0 fix. +No browser job is removed, no old-pin allowance is widened, and `main` remains +on its paired stable 1.63.0 pin. + +### MCP and Luna validation + +The Luna harness unit suite passed **31 tests** locally and in hosted CI. +Those tests exercise the runner with a mocked Codex CLI; they are not proof of +a live model invoking MCP. The live single-tool `browser_snapshot` run timed out +at 20 seconds without producing a JSON event. An independent minimal Codex CLI +execution without MCP also stalled, isolating this environment's CLI problem +from the server. Live Luna validation therefore **has not passed**. + +The direct SDK harness with the built server and explicitly selected cached +Firefox passed **all 33 core tool scenarios**, then passed `browser_install` +separately using that cached browser. Its temporary validation copy only changed +the child startup to `--browser firefox` and forwarded the fixture-only +`MOZ_DISABLE_CONTENT_SANDBOX=1`; test assertions were unchanged. The normal SDK +stdio environment does not inherit those parent settings automatically, so the +default Chrome run failed for the absent executable. These results do not +validate Chrome/Chromium, a fresh browser download, or the independent ARIA gate. ## Restrictions and checks still required diff --git a/tests/browser-upgrade-controls.integration.test.ts b/tests/browser-upgrade-controls.integration.test.ts index 30ad89fc..a13f6fbe 100644 --- a/tests/browser-upgrade-controls.integration.test.ts +++ b/tests/browser-upgrade-controls.integration.test.ts @@ -119,15 +119,15 @@ it.skipIf(browserName === 'firefox')('preserves mobile touch properties after fu })); const before = await properties(); process.stdout.write(JSON.stringify({ mobileProperties: before, browserName }) + '\n'); - expect(before.touch).toBeGreaterThan(0); - expect(before.coarse).toBe(true); - expect(before.screen).toEqual(config.browser.contextOptions.screen); + expect.soft(before.touch).toBeGreaterThan(0); + expect.soft(before.coarse).toBe(true); + expect.soft(before.screen).toEqual(config.browser.contextOptions.screen); await page.screenshot({ fullPage: true, timeout: 15000 }); - expect(await properties()).toEqual(before); + expect.soft(await properties(), 'after full-page screenshot').toEqual(before); await page.locator('div').screenshot({ timeout: 15000 }); - expect(await properties()).toEqual(before); + expect.soft(await properties(), 'after element screenshot').toEqual(before); await page.reload(); - expect(await properties()).toEqual(before); + expect.soft(await properties(), 'after navigation').toEqual(before); }, 60000); it('scrolls instantly on pointer retry with a fixed header and smooth scrolling (#42626)', async () => { @@ -167,9 +167,21 @@ it('excludes unrendered ARIA text and retains slotted/open-details controls (#25 expect.soft(text).not.toContain('Light'); expect.soft(text).not.toContain('Hidden direct text'); for (const name of ['Slotted', 'Shadow']) { + // A substring role match would incorrectly accept "LightShadow" for "Shadow". + expect.soft(await page.getByRole('button', { name, exact: true }).count(), name).toBe(1); const verification = await backend.callTool('browser_verify_element_visible', { role: 'button', accessibleName: name }); expect.soft(verification.isError, JSON.stringify(verification.content)).not.toBe(true); } + for (const query of ['button "Shadow"', 'button "Slotted"', 'Visible direct text']) { + const found = await backend.callTool('browser_find', { text: query }); + expect.soft(found.isError, JSON.stringify(found.content)).not.toBe(true); + expect.soft(found.content.filter(item => item.type === 'text').map(item => item.text).join('\n')).toContain(`Found 1 match for "${query}":`); + } + for (const query of ['Light', 'Hidden direct text']) { + const found = await backend.callTool('browser_find', { text: query }); + expect.soft(found.isError, JSON.stringify(found.content)).not.toBe(true); + expect.soft(found.content.filter(item => item.type === 'text').map(item => item.text).join('\n')).toContain(`No matches found for "${query}".`); + } }); it.each([false, true])('retries a CSS-only overlay with JavaScript enabled: %s (#257)', async javaScriptEnabled => { From aaae80d912daa9dd65d48ca451e51f89efba8b60 Mon Sep 17 00:00:00 2001 From: JustasM <59362982+JustasMonkev@users.noreply.github.com> Date: Sat, 17 Oct 2026 09:20:59 +0300 Subject: [PATCH 5/5] Preserve original recording ownership for delayed fill updates --- README.md | 1 + src/context.ts | 7 +++--- tests/context.test.ts | 51 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 61fffc24..14263480 100644 --- a/README.md +++ b/README.md @@ -652,6 +652,7 @@ Record browser actions and return them as Playwright JavaScript. Start the serve Multi-tab recordings include the `context.newPage()` declarations needed by generated page aliases. Recorded assertions include the `playwright/test` `expect` setup they need to run. +Starting a recording does not claim delayed fill updates from actions the session did not originally own. Saved session logging continues independently. Handshake-free HTTP clients must first call `browser_session_open`, then pass its `browserSessionId` to both recording tools so the recording survives across requests. Modes that cannot open separate browser sessions, such as `--extension` and non-isolated CDP attach, need a stateful MCP connection for recording. diff --git a/src/context.ts b/src/context.ts index 18ec4935..2c2811b0 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1036,7 +1036,8 @@ export class InputRecorder { let actionSequence = 0; // Retain attribution until the next action, including updates delivered // after the tool's 500ms window has expired. - type Attribution = { suppressedLogs: boolean, suppressedRecordings: WeakSet }; + // Owner identity also preserves coalesced fills when that owner restarts recording. + type Attribution = { suppressedLogs: boolean, recordingOwners: WeakSet }; const lastActionSequence = new WeakMap(); let armed = false; let transition = Promise.resolve(); @@ -1061,14 +1062,14 @@ export class InputRecorder { log(recorder); } for (const [context, target] of recordings) { - if ((!target.state.stopping || flushable) && !attribution?.suppressedRecordings.has(context) && !running.some(runningContext => runningContext !== context)) { + if ((!target.state.stopping || flushable) && (!attribution || attribution.recordingOwners.has(context)) && !running.some(runningContext => runningContext !== context)) { record(target); context.markRecordingActivity(); } } return { suppressedLogs: !!running.length, - suppressedRecordings: new WeakSet([...recordings.keys()].filter(context => running.some(runningContext => runningContext !== context))), + recordingOwners: new WeakSet([...recordings.keys()].filter(context => !running.some(runningContext => runningContext !== context))), }; }; const sink = { diff --git a/tests/context.test.ts b/tests/context.test.ts index 96303b70..e538124e 100644 --- a/tests/context.test.ts +++ b/tests/context.test.ts @@ -1007,6 +1007,57 @@ describe('Context', () => { } }); + it.each(['before start', 'during start', 'between recordings'])('excludes delayed fills added %s while session logging stays active', async phase => { + vi.useFakeTimers(); + try { + mockBrowserContext._startRecording = vi.fn().mockResolvedValue(undefined); + const sessionLog = { logUserAction: vi.fn() }; + const context = new Context({ + tools: [], config: defaultConfig, browserContextFactory: mockBrowserContextFactory, + sessionLog: async () => sessionLog, clientInfo: {}, + }); + await context.newTab(); + const page = Object.assign(new EventEmitter(), { + setDefaultNavigationTimeout: vi.fn(), setDefaultTimeout: vi.fn(), url: () => 'about:blank', + }); + mockBrowserContext.emit('page', page); + const sink = mockBrowserContext._startRecording.mock.calls[0][1]; + const fill = { name: 'fill', selector: '#query', text: 'earlier' }; + if (phase === 'between recordings') { + const firstStart = context.startRecording(); + await vi.advanceTimersByTimeAsync(500); + await firstStart; + const firstStop = context.stopRecording(); + await vi.advanceTimersByTimeAsync(500); + expect(await firstStop).toEqual([]); + } + if (phase !== 'during start') + sink.actionAdded(page, fill, 'earlier fill'); + const starting = context.startRecording(); + await vi.advanceTimersByTimeAsync(499); + if (phase === 'during start') + sink.actionAdded(page, fill, 'earlier fill'); + await vi.advanceTimersByTimeAsync(1); + await starting; + sink.actionUpdated(page, fill, 'late earlier fill'); + sink.actionUpdated(page, fill, 'final earlier fill'); + + sink.actionAdded(page, { ...fill, text: 'new' }, 'new fill'); + sink.actionUpdated(page, { ...fill, text: 'newer' }, 'newer fill'); + const stopping = context.stopRecording(); + await vi.advanceTimersByTimeAsync(500); + expect(await stopping).toEqual(['newer fill']); + expect(sessionLog.logUserAction.mock.calls.map(call => [call[2], call[3]])).toEqual([ + ['earlier fill', false], ['late earlier fill', true], ['final earlier fill', true], + ['new fill', false], ['newer fill', true], + ]); + expect(mockBrowserContext._startRecording).toHaveBeenCalledTimes(1); + expect(mockBrowserContext._stopRecording).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + it('records coalesced fills after restart and excludes fills delivered after stop begins', async () => { vi.useFakeTimers(); try {