From f0084191098aee257974beba792a86f8d4581057 Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Mon, 10 Aug 2026 22:12:44 +0300 Subject: [PATCH 1/2] fix(embed): close every page in a try/finally in the it() sweep Playwright pages acquired inside an it() body and closed only as the last happy-path statement leak a live tab into the file's shared browser on assertion failure, compounding memory pressure across the suite (audit on #389, finding 4). Wrap every page acquisition without existing try/finally protection, following the pattern already used in connection-pool.it.test.ts and transport-selection.it.test.ts. Left alone: the two reload-simulation tests in embed.it.test.ts ("a reload restores the panel open on the same view" and "a reload after closing the panel boots shut") where page.close() mid-body is the reload trigger itself, not incidental cleanup; and the shared beforeAll/afterAll pages in page-dispatch-boot.it.test.ts and page-dispatch-parity.it.test.ts, which are not per-test. PR 2 of 2 for #389, under epic #409. Co-Authored-By: Claude Fable 5 --- .../embed/test/composer-rich-input.it.test.ts | 327 +++++++------- .../test/composer-trigger-menu.it.test.ts | 175 ++++---- packages/embed/test/create-conciv.it.test.ts | 177 ++++---- .../embed/test/draft-selection.it.test.ts | 43 +- packages/embed/test/embed.it.test.ts | 399 ++++++++++-------- packages/embed/test/model-selector.it.test.ts | 23 +- .../embed/test/native-live-region.it.test.ts | 148 ++++--- packages/embed/test/native-widget.it.test.ts | 156 ++++--- .../embed/test/navigation-hold.it.test.ts | 173 ++++---- packages/embed/test/page-plane.it.test.ts | 31 +- packages/embed/test/panel-focus.it.test.ts | 80 ++-- packages/embed/test/rebind.it.test.ts | 220 +++++----- .../test/recording-attachment.it.test.ts | 131 +++--- .../embed/test/reload-continuity.it.test.ts | 57 +-- packages/embed/test/rpc-fault.it.test.ts | 39 +- packages/embed/test/rpc-observer.it.test.ts | 300 +++++++------ 16 files changed, 1355 insertions(+), 1124 deletions(-) diff --git a/packages/embed/test/composer-rich-input.it.test.ts b/packages/embed/test/composer-rich-input.it.test.ts index 722e5dbedc..bbaf3cda8a 100644 --- a/packages/embed/test/composer-rich-input.it.test.ts +++ b/packages/embed/test/composer-rich-input.it.test.ts @@ -66,197 +66,224 @@ async function pickSuggestion(page: Page, listName: string, optionName: string): describe('the rich composer input in the live widget shadow DOM', () => { it('types multiline text with slash and mention chips and submits the exact directive string', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) - - await input.pressSequentially('please run ') - await input.pressSequentially('/config') - await pickSuggestion(page, 'Commands', '/config') - - await input.pressSequentially('then ') - await input.pressSequentially('@recording_start') - await pickSuggestion(page, 'Tools', '@recording_start') - - await page.keyboard.press('Shift+Enter') - await input.pressSequentially('second line') - - const expected = 'please run /config then @recording_start \nsecond line' - const sent = waitForSend(observer) - await page.getByRole('button', {name: 'Send message'}).click() - expect(await sent).toBe(expected) - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expectLocator(input).toHaveText('') - observer.dispose() - await page.close() + try { + await openComposer(page) + const input = composer(page) + + await input.pressSequentially('please run ') + await input.pressSequentially('/config') + await pickSuggestion(page, 'Commands', '/config') + + await input.pressSequentially('then ') + await input.pressSequentially('@recording_start') + await pickSuggestion(page, 'Tools', '@recording_start') + + await page.keyboard.press('Shift+Enter') + await input.pressSequentially('second line') + + const expected = 'please run /config then @recording_start \nsecond line' + const sent = waitForSend(observer) + await page.getByRole('button', {name: 'Send message'}).click() + expect(await sent).toBe(expected) + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expectLocator(input).toHaveText('') + observer.dispose() + } finally { + await page.close() + } }) it('backspace removes a selected command chip in two steps, never a partial directive', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) + try { + await openComposer(page) + const input = composer(page) - await input.pressSequentially('/compact') - await pickSuggestion(page, 'Commands', '/compact') - await expectLocator(input).toHaveText('/compact ') + await input.pressSequentially('/compact') + await pickSuggestion(page, 'Commands', '/compact') + await expectLocator(input).toHaveText('/compact ') - await page.keyboard.press('Backspace') - await expectLocator(input).toHaveText('/compact') + await page.keyboard.press('Backspace') + await expectLocator(input).toHaveText('/compact') - await page.keyboard.press('Backspace') - await expectLocator(input).toHaveText('') - observer.dispose() - await page.close() + await page.keyboard.press('Backspace') + await expectLocator(input).toHaveText('') + observer.dispose() + } finally { + await page.close() + } }) it('forward delete removes the chip ahead of the caret in one step', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) - - await input.pressSequentially('/compact') - await pickSuggestion(page, 'Commands', '/compact') - await expectLocator(input).toHaveText('/compact ') - - await page.keyboard.press('Home') - await input.pressSequentially('x') - await expectLocator(input).toHaveText('x/compact ') - await page.keyboard.press('Delete') - await expectLocator(input).toHaveText('x ') - observer.dispose() - await page.close() + try { + await openComposer(page) + const input = composer(page) + + await input.pressSequentially('/compact') + await pickSuggestion(page, 'Commands', '/compact') + await expectLocator(input).toHaveText('/compact ') + + await page.keyboard.press('Home') + await input.pressSequentially('x') + await expectLocator(input).toHaveText('x/compact ') + await page.keyboard.press('Delete') + await expectLocator(input).toHaveText('x ') + observer.dispose() + } finally { + await page.close() + } }) it('Escape closes the typeahead first, cancels the run next, and closes the panel last', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) - - suite.kit().harness.script.hold() try { - await input.pressSequentially('keep this running') - await page.getByRole('button', {name: 'Send message'}).click() - const stop = page.getByRole('button', {name: 'Stop generating'}) - await expectLocator(stop).toBeVisible({timeout: 30_000}) - - await input.click() - await input.pressSequentially('/config') - const listbox = page.getByRole('listbox', {name: 'Commands'}) - await expectLocator(listbox.getByRole('option', {name: '/config'})).toBeVisible({timeout: 10_000}) + await openComposer(page) + const input = composer(page) + + suite.kit().harness.script.hold() + try { + await input.pressSequentially('keep this running') + await page.getByRole('button', {name: 'Send message'}).click() + const stop = page.getByRole('button', {name: 'Stop generating'}) + await expectLocator(stop).toBeVisible({timeout: 30_000}) + + await input.click() + await input.pressSequentially('/config') + const listbox = page.getByRole('listbox', {name: 'Commands'}) + await expectLocator(listbox.getByRole('option', {name: '/config'})).toBeVisible({timeout: 10_000}) + + await page.keyboard.press('Escape') + await expectLocator(listbox).toBeHidden({timeout: 10_000}) + await expectLocator(input).toHaveText('/config') + await expectLocator(stop).toBeVisible() + await expectLocator(panel(page)).toBeVisible() + + await page.keyboard.press('Escape') + await expectLocator(stop).toBeHidden({timeout: 30_000}) + await expectLocator(panel(page)).toBeVisible() + } finally { + suite.kit().harness.script.release() + } await page.keyboard.press('Escape') - await expectLocator(listbox).toBeHidden({timeout: 10_000}) - await expectLocator(input).toHaveText('/config') - await expectLocator(stop).toBeVisible() - await expectLocator(panel(page)).toBeVisible() - - await page.keyboard.press('Escape') - await expectLocator(stop).toBeHidden({timeout: 30_000}) - await expectLocator(panel(page)).toBeVisible() + await expectLocator(panel(page)).toBeHidden({timeout: 30_000}) + observer.dispose() } finally { - suite.kit().harness.script.release() + await page.close() } - - await page.keyboard.press('Escape') - await expectLocator(panel(page)).toBeHidden({timeout: 30_000}) - observer.dispose() - await page.close() }) it('a failed send restores the full draft into the composer', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) + try { + await openComposer(page) + const input = composer(page) - suite.kit().harness.script.scriptError('the run collapsed') - await input.pressSequentially('bring me back') - await page.getByRole('button', {name: 'Send message'}).click() + suite.kit().harness.script.scriptError('the run collapsed') + await input.pressSequentially('bring me back') + await page.getByRole('button', {name: 'Send message'}).click() - await expectLocator(page.getByRole('alert', {name: 'the run collapsed'})).toBeVisible({timeout: 30_000}) - await expectLocator(input).toHaveText('bring me back') - observer.dispose() - await page.close() + await expectLocator(page.getByRole('alert', {name: 'the run collapsed'})).toBeVisible({timeout: 30_000}) + await expectLocator(input).toHaveText('bring me back') + observer.dispose() + } finally { + await page.close() + } }) it('a reload restores the draft as plain directive text with the caret at the end', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) - - await input.pressSequentially('ship ') - await input.pressSequentially('/config') - await pickSuggestion(page, 'Commands', '/config') - await waitForDraftWrite(observer, 'ship /config') - - await page.reload({waitUntil: 'domcontentloaded'}) - const restored = composer(page) - await expectLocator(restored).toHaveText('ship /config ', {timeout: 30_000}) - - await page.keyboard.type('!') - await expectLocator(restored).toHaveText('ship /config !') - observer.dispose() - await page.close() + try { + await openComposer(page) + const input = composer(page) + + await input.pressSequentially('ship ') + await input.pressSequentially('/config') + await pickSuggestion(page, 'Commands', '/config') + await waitForDraftWrite(observer, 'ship /config') + + await page.reload({waitUntil: 'domcontentloaded'}) + const restored = composer(page) + await expectLocator(restored).toHaveText('ship /config ', {timeout: 30_000}) + + await page.keyboard.type('!') + await expectLocator(restored).toHaveText('ship /config !') + observer.dispose() + } finally { + await page.close() + } }) it('a reload restores the caret where the draft left it, not at the end', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) - - await input.pressSequentially('hello world') - for (let step = 0; step < 6; step += 1) await page.keyboard.press('ArrowLeft') - await input.pressSequentially('X') - await expectLocator(input).toHaveText('helloX world') - await waitForDraftWrite(observer, 'helloX world') - - await page.reload({waitUntil: 'domcontentloaded'}) - const restored = composer(page) - await expectLocator(restored).toHaveText('helloX world', {timeout: 30_000}) - - await page.keyboard.type('Y') - await expectLocator(restored).toHaveText('helloXY world') - observer.dispose() - await page.close() + try { + await openComposer(page) + const input = composer(page) + + await input.pressSequentially('hello world') + for (let step = 0; step < 6; step += 1) await page.keyboard.press('ArrowLeft') + await input.pressSequentially('X') + await expectLocator(input).toHaveText('helloX world') + await waitForDraftWrite(observer, 'helloX world') + + await page.reload({waitUntil: 'domcontentloaded'}) + const restored = composer(page) + await expectLocator(restored).toHaveText('helloX world', {timeout: 30_000}) + + await page.keyboard.type('Y') + await expectLocator(restored).toHaveText('helloXY world') + observer.dispose() + } finally { + await page.close() + } }) it('Enter during IME composition never submits; Enter after the commit sends the composed text', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) - const cdp = await page.context().newCDPSession(page) - - await input.pressSequentially('hello') - await cdp.send('Input.imeSetComposition', {text: 'ん', selectionStart: 1, selectionEnd: 1}) - await page.keyboard.press('Enter') - await expectLocator(input).toHaveText(/hello/) - - await cdp.send('Input.insertText', {text: 'ん'}) - await expectLocator(input).toHaveText('helloん') - const sent = waitForSend(observer) - await page.keyboard.press('Enter') - expect(await sent).toBe('helloん') - - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByText('helloん', {exact: true})).toBeVisible() - observer.dispose() - await page.close() + try { + await openComposer(page) + const input = composer(page) + const cdp = await page.context().newCDPSession(page) + + await input.pressSequentially('hello') + await cdp.send('Input.imeSetComposition', {text: 'ん', selectionStart: 1, selectionEnd: 1}) + await page.keyboard.press('Enter') + await expectLocator(input).toHaveText(/hello/) + + await cdp.send('Input.insertText', {text: 'ん'}) + await expectLocator(input).toHaveText('helloん') + const sent = waitForSend(observer) + await page.keyboard.press('Enter') + expect(await sent).toBe('helloん') + + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByText('helloん', {exact: true})).toBeVisible() + observer.dispose() + } finally { + await page.close() + } }) it('the send button submits the visible draft including pending composition text', async () => { const {page, observer} = await observedPage() - await openComposer(page) - const input = composer(page) - const cdp = await page.context().newCDPSession(page) - - await input.pressSequentially('committed draft') - await cdp.send('Input.imeSetComposition', {text: 'か', selectionStart: 1, selectionEnd: 1}) - await expectLocator(input).toHaveText('committed draftか') - const sent = waitForSend(observer) - await page.getByRole('button', {name: 'Send message'}).click() - expect(await sent).toBe('committed draftか') - - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByText('committed draftか', {exact: true})).toBeVisible() - observer.dispose() - await page.close() + try { + await openComposer(page) + const input = composer(page) + const cdp = await page.context().newCDPSession(page) + + await input.pressSequentially('committed draft') + await cdp.send('Input.imeSetComposition', {text: 'か', selectionStart: 1, selectionEnd: 1}) + await expectLocator(input).toHaveText('committed draftか') + const sent = waitForSend(observer) + await page.getByRole('button', {name: 'Send message'}).click() + expect(await sent).toBe('committed draftか') + + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByText('committed draftか', {exact: true})).toBeVisible() + observer.dispose() + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/composer-trigger-menu.it.test.ts b/packages/embed/test/composer-trigger-menu.it.test.ts index a22ab3f9ac..138ffb9e8f 100644 --- a/packages/embed/test/composer-trigger-menu.it.test.ts +++ b/packages/embed/test/composer-trigger-menu.it.test.ts @@ -50,101 +50,116 @@ async function expectActiveOption(page: Page, option: Locator): Promise { describe('the composer trigger menu inside the live widget panel', () => { it('groups commands by source with a visible header and a description per command', async () => { const page = await suite.browser().newPage() - await openComposer(page) - await composer(page).pressSequentially('/co') - - const menu = commandMenu(page) - await expectLocator(menu.getByRole('option', {name: '/compact'})).toBeVisible({timeout: 10_000}) - await expectLocator(menu.getByRole('group', {name: 'Commands'})).toBeVisible() - await expectLocator(menu.getByRole('group', {name: 'MCP'})).toBeVisible() - await expectLocator(menu.getByRole('group', {name: 'Plugins'})).toBeVisible() - await expectLocator(menu.getByRole('option', {name: '/compact'})).toHaveAccessibleDescription( - 'Compact the conversation', - ) - await expectLocator(menu.getByRole('option', {name: '/mcp__probe__connect'})).toHaveAccessibleDescription( - 'Connect the probe server', - ) - await expectLocator(menu.getByText('Compact the conversation')).toBeVisible() - await page.close() + try { + await openComposer(page) + await composer(page).pressSequentially('/co') + + const menu = commandMenu(page) + await expectLocator(menu.getByRole('option', {name: '/compact'})).toBeVisible({timeout: 10_000}) + await expectLocator(menu.getByRole('group', {name: 'Commands'})).toBeVisible() + await expectLocator(menu.getByRole('group', {name: 'MCP'})).toBeVisible() + await expectLocator(menu.getByRole('group', {name: 'Plugins'})).toBeVisible() + await expectLocator(menu.getByRole('option', {name: '/compact'})).toHaveAccessibleDescription( + 'Compact the conversation', + ) + await expectLocator(menu.getByRole('option', {name: '/mcp__probe__connect'})).toHaveAccessibleDescription( + 'Connect the probe server', + ) + await expectLocator(menu.getByText('Compact the conversation')).toBeVisible() + } finally { + await page.close() + } }) it('moves the highlight with the arrow keys and commits the highlighted command with Enter', async () => { const page = await suite.browser().newPage() - await openComposer(page) - const input = composer(page) - await input.pressSequentially('/co') - - const menu = commandMenu(page) - await expectActiveOption(page, menu.getByRole('option', {name: '/compact'})) - await page.keyboard.press('ArrowDown') - await expectActiveOption(page, menu.getByRole('option', {name: '/config'})) - await page.keyboard.press('ArrowDown') - await expectActiveOption(page, menu.getByRole('option', {name: '/mcp__probe__connect'})) - await page.keyboard.press('ArrowUp') - await expectActiveOption(page, menu.getByRole('option', {name: '/config'})) - - await page.keyboard.press('Enter') - await expectLocator(menu).toBeHidden({timeout: 10_000}) - await expectLocator(input).toHaveText('/config ') - await page.close() + try { + await openComposer(page) + const input = composer(page) + await input.pressSequentially('/co') + + const menu = commandMenu(page) + await expectActiveOption(page, menu.getByRole('option', {name: '/compact'})) + await page.keyboard.press('ArrowDown') + await expectActiveOption(page, menu.getByRole('option', {name: '/config'})) + await page.keyboard.press('ArrowDown') + await expectActiveOption(page, menu.getByRole('option', {name: '/mcp__probe__connect'})) + await page.keyboard.press('ArrowUp') + await expectActiveOption(page, menu.getByRole('option', {name: '/config'})) + + await page.keyboard.press('Enter') + await expectLocator(menu).toBeHidden({timeout: 10_000}) + await expectLocator(input).toHaveText('/config ') + } finally { + await page.close() + } }) it('keeps the highlighted option inside the panel viewport while arrowing down a long list', async () => { const page = await suite.browser().newPage() - await openComposer(page) - await composer(page).pressSequentially('/task-') - - const menu = commandMenu(page) - const first = menu.getByRole('option', {name: '/task-00'}) - await expectActiveOption(page, first) - await expectLocator(first).toBeInViewport() - - const target = menu.getByRole('option', {name: '/task-30'}) - for (let step = 0; step < 30; step += 1) await page.keyboard.press('ArrowDown') - await expectActiveOption(page, target) - await expectLocator(target).toBeInViewport() - await expectLocator(first).not.toBeInViewport() - - await page.keyboard.press('Enter') - await expectLocator(composer(page)).toHaveText('/task-30 ') - await page.close() + try { + await openComposer(page) + await composer(page).pressSequentially('/task-') + + const menu = commandMenu(page) + const first = menu.getByRole('option', {name: '/task-00'}) + await expectActiveOption(page, first) + await expectLocator(first).toBeInViewport() + + const target = menu.getByRole('option', {name: '/task-30'}) + for (let step = 0; step < 30; step += 1) await page.keyboard.press('ArrowDown') + await expectActiveOption(page, target) + await expectLocator(target).toBeInViewport() + await expectLocator(first).not.toBeInViewport() + + await page.keyboard.press('Enter') + await expectLocator(composer(page)).toHaveText('/task-30 ') + } finally { + await page.close() + } }) it('groups tools in the mention menu and commits the highlighted tool with Enter', async () => { const page = await suite.browser().newPage() - await openComposer(page) - const input = composer(page) - await input.pressSequentially('@recording_') - - const menu = toolMenu(page) - await expectActiveOption(page, menu.getByRole('option', {name: '@recording_start'})) - await expectLocator(menu.getByRole('group', {name: 'recorder'})).toBeVisible() - await expectLocator(menu.getByRole('option', {name: '@recording_start'})).toHaveAccessibleDescription( - /Start a marked recording/, - ) - await page.keyboard.press('ArrowDown') - await expectActiveOption(page, menu.getByRole('option', {name: '@recording_stop'})) - await page.keyboard.press('Enter') - await expectLocator(menu).toBeHidden({timeout: 10_000}) - await expectLocator(input).toHaveText('@recording_stop ') - await page.close() + try { + await openComposer(page) + const input = composer(page) + await input.pressSequentially('@recording_') + + const menu = toolMenu(page) + await expectActiveOption(page, menu.getByRole('option', {name: '@recording_start'})) + await expectLocator(menu.getByRole('group', {name: 'recorder'})).toBeVisible() + await expectLocator(menu.getByRole('option', {name: '@recording_start'})).toHaveAccessibleDescription( + /Start a marked recording/, + ) + await page.keyboard.press('ArrowDown') + await expectActiveOption(page, menu.getByRole('option', {name: '@recording_stop'})) + await page.keyboard.press('Enter') + await expectLocator(menu).toBeHidden({timeout: 10_000}) + await expectLocator(input).toHaveText('@recording_stop ') + } finally { + await page.close() + } }) it('never hands the keyboard to the menu: Tab closes it and the next keystroke still edits the composer', async () => { const page = await suite.browser().newPage() - await openComposer(page) - const input = composer(page) - await input.pressSequentially('/co') - - const menu = commandMenu(page) - await expectActiveOption(page, menu.getByRole('option', {name: '/compact'})) - - await page.keyboard.press('Tab') - await expectLocator(menu).toBeHidden({timeout: 10_000}) - await expectLocator(input).toBeFocused() - - await input.pressSequentially('x') - await expectLocator(input).toHaveText('/cox') - await page.close() + try { + await openComposer(page) + const input = composer(page) + await input.pressSequentially('/co') + + const menu = commandMenu(page) + await expectActiveOption(page, menu.getByRole('option', {name: '/compact'})) + + await page.keyboard.press('Tab') + await expectLocator(menu).toBeHidden({timeout: 10_000}) + await expectLocator(input).toBeFocused() + + await input.pressSequentially('x') + await expectLocator(input).toHaveText('/cox') + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/create-conciv.it.test.ts b/packages/embed/test/create-conciv.it.test.ts index 96a6bddacf..aa060a5d9e 100644 --- a/packages/embed/test/create-conciv.it.test.ts +++ b/packages/embed/test/create-conciv.it.test.ts @@ -56,108 +56,129 @@ function rpcSocket(page: Page): Promise { describe('createConciv lifecycle', () => { it('mounts, unmounts, and remounts the widget', async () => { const page = await openPage() - await mountHandle(page, kit.base) - await expectLocator(fab(page)).toBeVisible({timeout: 30_000}) - await unmountHandle(page) - await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) - await remountHandle(page) - await expectLocator(fab(page)).toBeVisible({timeout: 30_000}) - await page.close() + try { + await mountHandle(page, kit.base) + await expectLocator(fab(page)).toBeVisible({timeout: 30_000}) + await unmountHandle(page) + await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) + await remountHandle(page) + await expectLocator(fab(page)).toBeVisible({timeout: 30_000}) + } finally { + await page.close() + } }) it('threads the mounted api base to extension surfaces when the host page has no pw-api-base meta', async () => { const page = await openPage() - await mountHandle(page, kit.base) - const probe = page.getByRole('status', {name: 'host api base probe'}) - await expectLocator(probe).toHaveText(kit.base, {timeout: 30_000}) - await page.close() + try { + await mountHandle(page, kit.base) + const probe = page.getByRole('status', {name: 'host api base probe'}) + await expectLocator(probe).toHaveText(kit.base, {timeout: 30_000}) + } finally { + await page.close() + } }) it('a second mount on an already-mounted handle is a no-op', async () => { const page = await openPage() - await page.evaluate((base) => { - const el = document.createElement('div') - document.body.appendChild(el) - const handle = window.ConcivHandle.makeHandle(base) - void handle.mount(el) - void handle.mount(el) - }, kit.base) - await expectLocator(fab(page)).toHaveCount(1, {timeout: 30_000}) - expect(await fab(page).count()).toBe(1) - await page.close() + try { + await page.evaluate((base) => { + const el = document.createElement('div') + document.body.appendChild(el) + const handle = window.ConcivHandle.makeHandle(base) + void handle.mount(el) + void handle.mount(el) + }, kit.base) + await expectLocator(fab(page)).toHaveCount(1, {timeout: 30_000}) + expect(await fab(page).count()).toBe(1) + } finally { + await page.close() + } }) it('unmount during mount leaves nothing behind', async () => { const page = await openPage() - await page.evaluate((base) => { - const el = document.createElement('div') - document.body.appendChild(el) - const handle = window.ConcivHandle.makeHandle(base) - void handle.mount(el) - handle.unmount() - }, kit.base) - await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) - expect(await page.evaluate(() => document.querySelector('[data-conciv-root]') === null)).toBe(true) - await page.close() + try { + await page.evaluate((base) => { + const el = document.createElement('div') + document.body.appendChild(el) + const handle = window.ConcivHandle.makeHandle(base) + void handle.mount(el) + handle.unmount() + }, kit.base) + await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) + expect(await page.evaluate(() => document.querySelector('[data-conciv-root]') === null)).toBe(true) + } finally { + await page.close() + } }) it('restores the host __TSR_ROUTER__ global on unmount', async () => { const page = await openPage() - await page.evaluate(() => { - Reflect.set(window, '__TSR_ROUTER__', {hostSentinel: true}) - }) - await mountHandle(page, kit.base) - await expectLocator(fab(page)).toBeVisible({timeout: 30_000}) - await unmountHandle(page) - const restored = await page.evaluate(() => { - const value = Reflect.get(window, '__TSR_ROUTER__') - return typeof value === 'object' && value !== null && 'hostSentinel' in value - }) - expect(restored).toBe(true) - await page.close() + try { + await page.evaluate(() => { + Reflect.set(window, '__TSR_ROUTER__', {hostSentinel: true}) + }) + await mountHandle(page, kit.base) + await expectLocator(fab(page)).toBeVisible({timeout: 30_000}) + await unmountHandle(page) + const restored = await page.evaluate(() => { + const value = Reflect.get(window, '__TSR_ROUTER__') + return typeof value === 'object' && value !== null && 'hostSentinel' in value + }) + expect(restored).toBe(true) + } finally { + await page.close() + } }) it('unmounts cleanly with an open panel and a completed turn', async () => { const page = await openPage() - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - await mountHandle(page, kit.base) - await fab(page).click() - await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) - await chatBox(page).fill('hello') - await chatBox(page).press('Enter') - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await unmountHandle(page) - await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) - expect(pageErrors).toEqual([]) - await page.close() + try { + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + await mountHandle(page, kit.base) + await fab(page).click() + await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) + await chatBox(page).fill('hello') + await chatBox(page).press('Enter') + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await unmountHandle(page) + await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) + expect(pageErrors).toEqual([]) + } finally { + await page.close() + } }) it('closes the tab rpc websocket on unmount and dials a fresh one on remount', async () => { expect(await setNavigation(kit, [{href: '/'}])).toBe(true) const page = await openPage() - const observer = rpcObserverFor(page) - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - const socketOpened = rpcSocket(page) - await mountHandle(page, kit.base) - const socket = await socketOpened - await openChatPanel(page) - await sendChatMessage(page, 'before the unmount') - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - - const closed = closedWithin(socket, SOCKET_CLOSE_TIMEOUT_MS) - await unmountHandle(page) - await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) - expect(await closed).toBe(true) - - await remountHandle(page) - await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) - const mark = observer.mark() - await sendChatMessage(page, 'after the remount') - const remounted = await observer.completed({path: ['chat', 'send'], since: mark, timeout: 30_000}) - expect(remounted.transport).toBe('websocket') - expect(pageErrors).toEqual([]) - await page.close() + try { + const observer = rpcObserverFor(page) + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + const socketOpened = rpcSocket(page) + await mountHandle(page, kit.base) + const socket = await socketOpened + await openChatPanel(page) + await sendChatMessage(page, 'before the unmount') + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + + const closed = closedWithin(socket, SOCKET_CLOSE_TIMEOUT_MS) + await unmountHandle(page) + await expectLocator(fab(page)).toHaveCount(0, {timeout: 30_000}) + expect(await closed).toBe(true) + + await remountHandle(page) + await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) + const mark = observer.mark() + await sendChatMessage(page, 'after the remount') + const remounted = await observer.completed({path: ['chat', 'send'], since: mark, timeout: 30_000}) + expect(remounted.transport).toBe('websocket') + expect(pageErrors).toEqual([]) + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/draft-selection.it.test.ts b/packages/embed/test/draft-selection.it.test.ts index a31223a56f..6fc2965835 100644 --- a/packages/embed/test/draft-selection.it.test.ts +++ b/packages/embed/test/draft-selection.it.test.ts @@ -8,27 +8,30 @@ const suite = setupWidgetSuite() describe('draft persistence carries the caret offsets', () => { it('persists the draft text with the caret position after the debounce', async () => { const page = await suite.browser().newPage() - const observer = observeRpc(page) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) + try { + const observer = observeRpc(page) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.click() - await input.pressSequentially('hello!') - for (let step = 0; step < 6; step += 1) await input.press('ArrowLeft') - const persisted = observer.completed({path: ['drafts', 'set'], input: {text: 'say hello!'}, timeout: 30_000}) - await input.pressSequentially('say ') - await persisted + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.click() + await input.pressSequentially('hello!') + for (let step = 0; step < 6; step += 1) await input.press('ArrowLeft') + const persisted = observer.completed({path: ['drafts', 'set'], input: {text: 'say hello!'}, timeout: 30_000}) + await input.pressSequentially('say ') + await persisted - const state = await suite.kit().rpc.navigation.get(undefined) - const panelEntry = state?.entries.find((entry) => entry.href.startsWith('/panel/')) - const sessionId = (panelEntry?.href.split('/')[2] ?? '').split('?')[0] ?? '' - expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({ - text: 'say hello!', - selectionStart: 4, - selectionEnd: 4, - }) - observer.dispose() - await page.close() + const state = await suite.kit().rpc.navigation.get(undefined) + const panelEntry = state?.entries.find((entry) => entry.href.startsWith('/panel/')) + const sessionId = (panelEntry?.href.split('/')[2] ?? '').split('?')[0] ?? '' + expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({ + text: 'say hello!', + selectionStart: 4, + selectionEnd: 4, + }) + observer.dispose() + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/embed.it.test.ts b/packages/embed/test/embed.it.test.ts index 1e1696c911..4240c519f2 100644 --- a/packages/embed/test/embed.it.test.ts +++ b/packages/embed/test/embed.it.test.ts @@ -80,80 +80,95 @@ describe('embed boots the conciv app against a real core', () => { const rawHarnessId = '43548fd1-0000-4220-acf0-014b10b5815f' expect(await setNavigation(kit, [{href: `/panel/${rawHarnessId}`}])).toBe(true) const page = observedPage(await browser.newPage()) - const canonicalized = waitForNavigationWrite(page) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await canonicalized - expect(await currentHref(kit)).toMatch(/^\/panel\/conciv_/) - const adopted = await kit.rpc.sessions.resolve({id: rawHarnessId}) - const persisted = await kit.rpc.navigation.get() - expect(persisted?.entries[persisted.index]?.href).toBe(`/panel/${adopted.sessionId}`) - await page.close() + try { + const canonicalized = waitForNavigationWrite(page) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await canonicalized + expect(await currentHref(kit)).toMatch(/^\/panel\/conciv_/) + const adopted = await kit.rpc.sessions.resolve({id: rawHarnessId}) + const persisted = await kit.rpc.navigation.get() + expect(persisted?.entries[persisted.index]?.href).toBe(`/panel/${adopted.sessionId}`) + } finally { + await page.close() + } }) it('a widget navigation write that lands after a newer one loses, even in flight', async () => { const page = observedPage(await browser.newPage()) - const held = await holdFirstNavigationWrite(page) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await held.arrived - - expect(await setNavigation(kit, [{href: '/reset-while-the-widget-write-is-in-flight'}])).toBe(true) - const landed = waitForNavigationWrite(page) - held.release() - await landed - - expect(await currentHref(kit)).toBe('/reset-while-the-widget-write-is-in-flight') - await page.close() + try { + const held = await holdFirstNavigationWrite(page) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await held.arrived + + expect(await setNavigation(kit, [{href: '/reset-while-the-widget-write-is-in-flight'}])).toBe(true) + const landed = waitForNavigationWrite(page) + held.release() + await landed + + expect(await currentHref(kit)).toBe('/reset-while-the-widget-write-is-in-flight') + } finally { + await page.close() + } }) it('a reloaded page outranks the previous page in-flight write when both clocks read the same', async () => { const frozen = Date.now() const before = observedPage(await browser.newPage()) - await freezeClock(before, frozen) - const held = await holdFirstNavigationWrite(before) - expect((await kit.rpc.navigation.set({entries: [{href: '/'}], index: 0, updatedAt: frozen + 5_000})).applied).toBe( - true, - ) - await before.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(before) - await held.arrived - - const after = observedPage(await browser.newPage()) - await freezeClock(after, frozen) - await after.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(after) - const switched = waitForNavigationWriteCarrying(after, '/terminal') - await after.getByRole('tab', {name: 'Terminal'}).click() - await switched - expect(await currentHref(kit)).toContain('/terminal') - - const landed = waitForNavigationWrite(before) - held.release() - await landed - - expect(await currentHref(kit)).toContain('/terminal') - await before.close() - await after.close() + try { + await freezeClock(before, frozen) + const held = await holdFirstNavigationWrite(before) + expect( + (await kit.rpc.navigation.set({entries: [{href: '/'}], index: 0, updatedAt: frozen + 5_000})).applied, + ).toBe(true) + await before.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(before) + await held.arrived + + const after = observedPage(await browser.newPage()) + try { + await freezeClock(after, frozen) + await after.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(after) + const switched = waitForNavigationWriteCarrying(after, '/terminal') + await after.getByRole('tab', {name: 'Terminal'}).click() + await switched + expect(await currentHref(kit)).toContain('/terminal') + + const landed = waitForNavigationWrite(before) + held.release() + await landed + + expect(await currentHref(kit)).toContain('/terminal') + } finally { + await after.close() + } + } finally { + await before.close() + } }) it('fab close is a shutter: reopening restores the same view without touching history', async () => { const page = await openPage() - await openPanel(page) - await page.getByRole('tab', {name: 'Terminal'}).click() - await expectLocator(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { - timeout: 30_000, - }) - await page.getByRole('button', {name: 'Minimize conciv chat'}).click() - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - const reopened = waitForNavigationWrite(page) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expectLocator(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { - timeout: 30_000, - }) - await reopened - const persisted = await kit.rpc.navigation.get() - expect(persisted?.entries.filter((entry) => entry.href.includes('/panel/'))).toHaveLength(1) - await page.close() + try { + await openPanel(page) + await page.getByRole('tab', {name: 'Terminal'}).click() + await expectLocator(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { + timeout: 30_000, + }) + await page.getByRole('button', {name: 'Minimize conciv chat'}).click() + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + const reopened = waitForNavigationWrite(page) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expectLocator(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { + timeout: 30_000, + }) + await reopened + const persisted = await kit.rpc.navigation.get() + expect(persisted?.entries.filter((entry) => entry.href.includes('/panel/'))).toHaveLength(1) + } finally { + await page.close() + } }) it('a reload restores the panel open on the same view', async () => { @@ -192,109 +207,133 @@ describe('embed boots the conciv app against a real core', () => { it('renders the fab instantly and opens the panel', async () => { const page = await openPage() - await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) - await openPanel(page) - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible() - await page.close() + try { + await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) + await openPanel(page) + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible() + } finally { + await page.close() + } }) it('opening and closing the panel keeps the host page where the reader scrolled it', async () => { const page = observedPage(await browser.newPage()) - await page.goto(longHost.base, {waitUntil: 'domcontentloaded'}) - const heading = page.getByRole('heading', {name: HOST_HEADING}) - const headingTop = async () => (await heading.boundingBox())?.y ?? Number.NaN - const unscrolled = await headingTop() - - await page.mouse.wheel(0, unscrolled - 200) - await expectLocator(heading).toBeInViewport({timeout: 30_000}) - const readerPosition = await headingTop() - expect(readerPosition).toBeLessThan(unscrolled - 1000) - - await openPanel(page) - expect(await headingTop()).toBe(readerPosition) - - await page.getByRole('textbox', {name: 'Message the conciv agent'}).press('Escape') - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - expect(await headingTop()).toBe(readerPosition) - await page.close() + try { + await page.goto(longHost.base, {waitUntil: 'domcontentloaded'}) + const heading = page.getByRole('heading', {name: HOST_HEADING}) + const headingTop = async () => (await heading.boundingBox())?.y ?? Number.NaN + const unscrolled = await headingTop() + + await page.mouse.wheel(0, unscrolled - 200) + await expectLocator(heading).toBeInViewport({timeout: 30_000}) + const readerPosition = await headingTop() + expect(readerPosition).toBeLessThan(unscrolled - 1000) + + await openPanel(page) + expect(await headingTop()).toBe(readerPosition) + + await page.getByRole('textbox', {name: 'Message the conciv agent'}).press('Escape') + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + expect(await headingTop()).toBe(readerPosition) + } finally { + await page.close() + } }) it('sends a message and renders the assistant reply from the fake harness', async () => { const page = await openPage() - await openPanel(page) - await sendMessage(page, 'hi there', ASSISTANT_TEXT) - await page.close() + try { + await openPanel(page) + await sendMessage(page, 'hi there', ASSISTANT_TEXT) + } finally { + await page.close() + } }) it('shows Stop instead of Send while a run is streaming; typing stays enabled', async () => { const page = await openPage() - await openPanel(page) - kit.harness.script.hold() - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.fill('long question') - await page.getByRole('button', {name: 'Send message'}).click() - await expectLocator(page.getByRole('button', {name: 'Stop generating'})).toBeVisible({timeout: 30_000}) - await input.fill('still typing while it runs') - await expectLocator(input).toHaveText('still typing while it runs') - kit.harness.script.release() - await expectLocator(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) - await page.close() + try { + await openPanel(page) + kit.harness.script.hold() + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.fill('long question') + await page.getByRole('button', {name: 'Send message'}).click() + await expectLocator(page.getByRole('button', {name: 'Stop generating'})).toBeVisible({timeout: 30_000}) + await input.fill('still typing while it runs') + await expectLocator(input).toHaveText('still typing while it runs') + kit.harness.script.release() + await expectLocator(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) + } finally { + await page.close() + } }) it('Escape closes the panel back to the fab', async () => { const page = await openPage() - await openPanel(page) - await page.getByRole('textbox', {name: 'Message the conciv agent'}).press('Escape') - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible() - await page.close() + try { + await openPanel(page) + await page.getByRole('textbox', {name: 'Message the conciv agent'}).press('Escape') + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible() + } finally { + await page.close() + } }) it('renders the conciv_ui blocking card from the tool part and answers via uiReply', async () => { const page = await openPage() - await openPanel(page) - kit.harness.script.scriptToolCall('execute_typescript', { - typescriptCode: "return await external_conciv_ui({kind: 'confirm', question: 'Proceed with the change?'})", - }) - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.fill('ask me something') - await page.getByRole('button', {name: 'Send message'}).click() - await expectLocator(page.getByText('Proceed with the change?')).toBeVisible({timeout: 30_000}) - await page.getByRole('button', {name: 'Approve'}).click() - await expectLocator(page.getByRole('status').getByText('yes')).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByRole('button', {name: 'Approve'})).toBeHidden({timeout: 30_000}) - await page.close() + try { + await openPanel(page) + kit.harness.script.scriptToolCall('execute_typescript', { + typescriptCode: "return await external_conciv_ui({kind: 'confirm', question: 'Proceed with the change?'})", + }) + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.fill('ask me something') + await page.getByRole('button', {name: 'Send message'}).click() + await expectLocator(page.getByText('Proceed with the change?')).toBeVisible({timeout: 30_000}) + await page.getByRole('button', {name: 'Approve'}).click() + await expectLocator(page.getByRole('status').getByText('yes')).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByRole('button', {name: 'Approve'})).toBeHidden({timeout: 30_000}) + } finally { + await page.close() + } }) it('renders catalog and code-mode parts without blanking the transcript', async () => { const page = await openPage() - await openPanel(page) - kit.harness.script.scriptToolCall('catalog', {search: 'weather'}, {blocking: false}) - kit.harness.script.scriptCustomEvent('code_mode:console', {stream: 'stdout', text: 'hello from code mode'}) - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.fill('discover and run some tools') - await page.getByRole('button', {name: 'Send message'}).click() - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - const announced = await page.getByRole('alert').allTextContents() - expect(announced.every((text) => text.trim() === '')).toBe(true) - await page.close() + try { + await openPanel(page) + kit.harness.script.scriptToolCall('catalog', {search: 'weather'}, {blocking: false}) + kit.harness.script.scriptCustomEvent('code_mode:console', {stream: 'stdout', text: 'hello from code mode'}) + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.fill('discover and run some tools') + await page.getByRole('button', {name: 'Send message'}).click() + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + const announced = await page.getByRole('alert').allTextContents() + expect(announced.every((text) => text.trim() === '')).toBe(true) + } finally { + await page.close() + } }) it('renders the new tool cards for results that do not match their payload schema', async () => { const page = await openPage() - await openPanel(page) - kit.harness.script.scriptToolCall('execute_typescript', {typescriptCode: 'return 1'}, {blocking: false}) - kit.harness.script.scriptToolCall('catalog', {search: 'weather'}, {blocking: false}) - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await sendAndRevealThought(page, 'run some code') - await expectLocator(page.getByRole('button', {name: /run code return 1/})).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByText('return 1').first()).toBeVisible({timeout: 30_000}) - await sendAndRevealThought(page, 'now check the catalog') - await expectLocator(page.getByText('Capability catalog').last()).toBeVisible({timeout: 30_000}) - await expectLocator(input).toHaveText('') - const announced = await page.getByRole('alert').allTextContents() - expect(announced.every((text) => text.trim() === '')).toBe(true) - await page.close() + try { + await openPanel(page) + kit.harness.script.scriptToolCall('execute_typescript', {typescriptCode: 'return 1'}, {blocking: false}) + kit.harness.script.scriptToolCall('catalog', {search: 'weather'}, {blocking: false}) + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await sendAndRevealThought(page, 'run some code') + await expectLocator(page.getByRole('button', {name: /run code return 1/})).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByText('return 1').first()).toBeVisible({timeout: 30_000}) + await sendAndRevealThought(page, 'now check the catalog') + await expectLocator(page.getByText('Capability catalog').last()).toBeVisible({timeout: 30_000}) + await expectLocator(input).toHaveText('') + const announced = await page.getByRole('alert').allTextContents() + expect(announced.every((text) => text.trim() === '')).toBe(true) + } finally { + await page.close() + } }) }) @@ -320,48 +359,57 @@ describe('embed at a phone viewport', () => { it('paints an opaque sheet so the host page never shows through', async () => { const page = await browser.newPage({viewport: PHONE_VIEWPORT}) - const shootOver = async (backdrop: string): Promise => { - expect(await setNavigation(phoneKit, [{href: '/'}])).toBe(true) - await page.goto(`${phoneHost.base}/?backdrop=${backdrop}`, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - return page.screenshot({animations: 'disabled', clip: SHEET_INTERIOR_CLIP}) + try { + const shootOver = async (backdrop: string): Promise => { + expect(await setNavigation(phoneKit, [{href: '/'}])).toBe(true) + await page.goto(`${phoneHost.base}/?backdrop=${backdrop}`, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + return page.screenshot({animations: 'disabled', clip: SHEET_INTERIOR_CLIP}) + } + const patterned = await shootOver('light-stripes') + const repeated = await shootOver('light-stripes') + expect(repeated.equals(patterned)).toBe(true) + const inverted = await shootOver('dark-stripes') + expect(inverted.equals(patterned)).toBe(true) + } finally { + await page.close() } - const patterned = await shootOver('light-stripes') - const repeated = await shootOver('light-stripes') - expect(repeated.equals(patterned)).toBe(true) - const inverted = await shootOver('dark-stripes') - expect(inverted.equals(patterned)).toBe(true) - await page.close() }) it('opens as a full-screen sheet with the launcher hidden and the composer reachable', async () => { const page = await browser.newPage({viewport: PHONE_VIEWPORT}) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toHaveCount(0, {timeout: 30_000}) - await sendMessage(page, 'hi there', ASSISTANT_TEXT) - await page.getByRole('button', {name: 'Close chat'}).click() - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) - await page.close() + try { + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toHaveCount(0, {timeout: 30_000}) + await sendMessage(page, 'hi there', ASSISTANT_TEXT) + await page.getByRole('button', {name: 'Close chat'}).click() + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) + } finally { + await page.close() + } }) it('keeps Stop and Send inside the sheet on a narrow phone while a run streams', async () => { const page = await browser.newPage({viewport: {width: 320, height: 800}}) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - kit.harness.script.hold() - const send = page.getByRole('button', {name: 'Send message'}) - const stop = page.getByRole('button', {name: 'Stop generating'}) - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill('a question that keeps running') - await send.click() - await expectLocator(stop).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByRole('button', {name: 'Select model'})).toBeInViewport({ratio: 1, timeout: 5_000}) - await expectLocator(stop).toBeInViewport({ratio: 1, timeout: 5_000}) - await expectLocator(send).toBeInViewport({ratio: 1, timeout: 5_000}) - kit.harness.script.release() - await expectLocator(stop).toBeHidden({timeout: 30_000}) - await page.close() + try { + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + kit.harness.script.hold() + const send = page.getByRole('button', {name: 'Send message'}) + const stop = page.getByRole('button', {name: 'Stop generating'}) + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill('a question that keeps running') + await send.click() + await expectLocator(stop).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByRole('button', {name: 'Select model'})).toBeInViewport({ratio: 1, timeout: 5_000}) + await expectLocator(stop).toBeInViewport({ratio: 1, timeout: 5_000}) + await expectLocator(send).toBeInViewport({ratio: 1, timeout: 5_000}) + kit.harness.script.release() + await expectLocator(stop).toBeHidden({timeout: 30_000}) + } finally { + await page.close() + } }) }) @@ -369,10 +417,13 @@ describe('embed settings', () => { it('modal disabled renders no fab', async () => { const disabledHost = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"modal": false}'})) const page = observedPage(await browser.newPage()) - await page.goto(disabledHost.base, {waitUntil: 'domcontentloaded'}) - await page.getByRole('status').waitFor({state: 'attached', timeout: 15_000}) - expect(await page.getByRole('button', {name: 'Open conciv chat'}).count()).toBe(0) - await page.close() - await disabledHost.close() + try { + await page.goto(disabledHost.base, {waitUntil: 'domcontentloaded'}) + await page.getByRole('status').waitFor({state: 'attached', timeout: 15_000}) + expect(await page.getByRole('button', {name: 'Open conciv chat'}).count()).toBe(0) + } finally { + await page.close() + await disabledHost.close() + } }) }) diff --git a/packages/embed/test/model-selector.it.test.ts b/packages/embed/test/model-selector.it.test.ts index 81f497967f..6a47720a37 100644 --- a/packages/embed/test/model-selector.it.test.ts +++ b/packages/embed/test/model-selector.it.test.ts @@ -14,17 +14,20 @@ const suite = setupWidgetSuite({text: 'Hello from conciv', models: HARNESS_MODEL describe('model selector error path', () => { it('offers a retry when meta.models fails and recovers on retry', async () => { const page = await suite.browser().newPage({viewport: {width: 900, height: 760}}) - const models = await failRpcCalls(page, {path: ['meta', 'models']}) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) + try { + const models = await failRpcCalls(page, {path: ['meta', 'models']}) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) - const retry = page.getByRole('button', {name: 'Retry loading models'}) - await expectLocator(retry).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByText('Couldn’t load models').first()).toBeVisible({timeout: 30_000}) + const retry = page.getByRole('button', {name: 'Retry loading models'}) + await expectLocator(retry).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByText('Couldn’t load models').first()).toBeVisible({timeout: 30_000}) - models.repair() - await retry.click() - await expectLocator(page.getByRole('button', {name: 'Select model'})).toBeVisible({timeout: 30_000}) - await page.close() + models.repair() + await retry.click() + await expectLocator(page.getByRole('button', {name: 'Select model'})).toBeVisible({timeout: 30_000}) + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/native-live-region.it.test.ts b/packages/embed/test/native-live-region.it.test.ts index d169b46fdb..ea2bffe752 100644 --- a/packages/embed/test/native-live-region.it.test.ts +++ b/packages/embed/test/native-live-region.it.test.ts @@ -63,89 +63,101 @@ async function openFromHost(page: Page): Promise { describe('native live region reporting', () => { it('reports the mascot rect on a fresh closed mount so tap-to-open stays live', async () => { const mascot = await openMascotNative() - const measured = Promise.withResolvers() - mascot.notify = (toggle) => { - if (toggle.open === false && toggle.mascotRect) measured.resolve(toggle) + try { + const measured = Promise.withResolvers() + mascot.notify = (toggle) => { + if (toggle.open === false && toggle.mascotRect) measured.resolve(toggle) + } + await mascot.page.setViewportSize({width: 1200, height: 860}) + const closed = await measured.promise + expect(closed.mascotRect?.width).toBeGreaterThan(0) + expect(closed.mascotRect?.height).toBeGreaterThan(0) + } finally { + await mascot.page.close() } - await mascot.page.setViewportSize({width: 1200, height: 860}) - const closed = await measured.promise - expect(closed.mascotRect?.width).toBeGreaterThan(0) - expect(closed.mascotRect?.height).toBeGreaterThan(0) - await mascot.page.close() }) it('re-reports the mascot rect when the launcher moves and settles on a stable value', async () => { const mascot = await openMascotNative() - const placed = Promise.withResolvers() - mascot.notify = (toggle) => { - if (toggle.open === false && toggle.mascotRect) placed.resolve(toggle) + try { + const placed = Promise.withResolvers() + mascot.notify = (toggle) => { + if (toggle.open === false && toggle.mascotRect) placed.resolve(toggle) + } + await mascot.page.setViewportSize({width: 1200, height: 860}) + await placed.promise + const beforeMove = mascot.toggles.length + + const moved = Promise.withResolvers() + mascot.notify = (toggle) => { + if (toggle.open === false && toggle.mascotRect) moved.resolve(toggle) + } + await mascot.page.setViewportSize({width: 760, height: 640}) + await moved.promise + expect(closedRects(mascot.toggles.slice(beforeMove))).not.toHaveLength(0) + + await mascot.page.evaluate( + () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))), + ) + await new Promise((resolve) => setTimeout(resolve, 400)) + + const first = closedRects(mascot.toggles).at(-1) + await new Promise((resolve) => setTimeout(resolve, 200)) + const second = closedRects(mascot.toggles).at(-1) + expect(second).toEqual(first) + expect(second?.width).toBeGreaterThan(0) + expect(second?.height).toBeGreaterThan(0) + } finally { + await mascot.page.close() } - await mascot.page.setViewportSize({width: 1200, height: 860}) - await placed.promise - const beforeMove = mascot.toggles.length - - const moved = Promise.withResolvers() - mascot.notify = (toggle) => { - if (toggle.open === false && toggle.mascotRect) moved.resolve(toggle) - } - await mascot.page.setViewportSize({width: 760, height: 640}) - await moved.promise - expect(closedRects(mascot.toggles.slice(beforeMove))).not.toHaveLength(0) - - await mascot.page.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))), - ) - await new Promise((resolve) => setTimeout(resolve, 400)) - - const first = closedRects(mascot.toggles).at(-1) - await new Promise((resolve) => setTimeout(resolve, 200)) - const second = closedRects(mascot.toggles).at(-1) - expect(second).toEqual(first) - expect(second?.width).toBeGreaterThan(0) - expect(second?.height).toBeGreaterThan(0) - await mascot.page.close() }) it('never reports closed mascot-region state once the panel is open', async () => { const mascot = await openMascotNative() - const opened = Promise.withResolvers() - mascot.notify = (toggle) => { - if (toggle.open === true) opened.resolve(toggle) - } - await openFromHost(mascot.page) - const openEvent = await opened.promise - expect(openEvent.mascotRect ?? null).toBeNull() - - const settled = mascot.toggles.length - for (const size of [ - {width: 900, height: 800}, - {width: 1100, height: 700}, - {width: 1280, height: 900}, - ]) { - await mascot.page.setViewportSize(size) + try { + const opened = Promise.withResolvers() + mascot.notify = (toggle) => { + if (toggle.open === true) opened.resolve(toggle) + } + await openFromHost(mascot.page) + const openEvent = await opened.promise + expect(openEvent.mascotRect ?? null).toBeNull() + + const settled = mascot.toggles.length + for (const size of [ + {width: 900, height: 800}, + {width: 1100, height: 700}, + {width: 1280, height: 900}, + ]) { + await mascot.page.setViewportSize(size) + } + await mascot.page.evaluate( + () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))), + ) + await new Promise((resolve) => setTimeout(resolve, 400)) + + const fresh = mascot.toggles.slice(settled) + expect(fresh.some((toggle) => toggle.open === false)).toBe(false) + expect(fresh.some((toggle) => Boolean(toggle.mascotRect))).toBe(false) + } finally { + await mascot.page.close() } - await mascot.page.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))), - ) - await new Promise((resolve) => setTimeout(resolve, 400)) - - const fresh = mascot.toggles.slice(settled) - expect(fresh.some((toggle) => toggle.open === false)).toBe(false) - expect(fresh.some((toggle) => Boolean(toggle.mascotRect))).toBe(false) - await mascot.page.close() }) it('reports open, not a closed mascot rect, once a session is opened from the host', async () => { const mascot = await openMascotNative() - const opened = Promise.withResolvers() - mascot.notify = (toggle) => { - if (toggle.open === true) opened.resolve(toggle) + try { + const opened = Promise.withResolvers() + mascot.notify = (toggle) => { + if (toggle.open === true) opened.resolve(toggle) + } + await openFromHost(mascot.page) + const latest = await opened.promise + expect(latest.open).toBe(true) + expect(latest.mascotRect ?? null).toBeNull() + expect(mascot.toggles.at(-1)).toEqual(latest) + } finally { + await mascot.page.close() } - await openFromHost(mascot.page) - const latest = await opened.promise - expect(latest.open).toBe(true) - expect(latest.mascotRect ?? null).toBeNull() - expect(mascot.toggles.at(-1)).toEqual(latest) - await mascot.page.close() }) }) diff --git a/packages/embed/test/native-widget.it.test.ts b/packages/embed/test/native-widget.it.test.ts index 59bbd2c63b..c771d71604 100644 --- a/packages/embed/test/native-widget.it.test.ts +++ b/packages/embed/test/native-widget.it.test.ts @@ -96,98 +96,116 @@ const grabPreview = (page: Page) => panel(page).locator('img') describe('native widget bridge', () => { it('installs the native bridge, re-posts readiness, and settles after the first acked call and handshake', async () => { const {page, bridge} = await openNative() - const reposted = Promise.withResolvers() - bridge.notify = () => { - if (countType(bridge.posted, 'bridge.ready') > 1 && countType(bridge.posted, 'handshake.hello') > 1) { - reposted.resolve(bridge.posted) + try { + const reposted = Promise.withResolvers() + bridge.notify = () => { + if (countType(bridge.posted, 'bridge.ready') > 1 && countType(bridge.posted, 'handshake.hello') > 1) { + reposted.resolve(bridge.posted) + } } + expect(countType(await reposted.promise, 'bridge.ready')).toBeGreaterThan(1) + + await callNative(page, 'grabCapability', {v: 1, seq: 1, grabbable: true}) + await callNative(page, 'handshake', {v: 1, seq: 2, apiBase: kit.base, token: null}) + + await new Promise((resolve) => setTimeout(resolve, 1200)) + const settled = [...bridge.posted] + await new Promise((resolve) => setTimeout(resolve, 1000)) + const later = bridge.posted + expect(countType(later, 'bridge.ready')).toBe(countType(settled, 'bridge.ready')) + expect(countType(later, 'handshake.hello')).toBe(countType(settled, 'handshake.hello')) + } finally { + await page.close() } - expect(countType(await reposted.promise, 'bridge.ready')).toBeGreaterThan(1) - - await callNative(page, 'grabCapability', {v: 1, seq: 1, grabbable: true}) - await callNative(page, 'handshake', {v: 1, seq: 2, apiBase: kit.base, token: null}) - - await new Promise((resolve) => setTimeout(resolve, 1200)) - const settled = [...bridge.posted] - await new Promise((resolve) => setTimeout(resolve, 1000)) - const later = bridge.posted - expect(countType(later, 'bridge.ready')).toBe(countType(settled, 'bridge.ready')) - expect(countType(later, 'handshake.hello')).toBe(countType(settled, 'handshake.hello')) - await page.close() }) it('opens the panel on native open and is idempotent, and closes on native close', async () => { const {page} = await openNative() - await callNative(page, 'open', {v: 1, seq: 1}) - await callNative(page, 'open', {v: 1, seq: 2}) - await expectLocator(composerBox(page)).toHaveCount(1, {timeout: 30_000}) - await expectLocator(composerBox(page)).toBeVisible() - await callNative(page, 'close', {v: 1, seq: 3}) - await expectLocator(composerBox(page)).toBeHidden({timeout: 30_000}) - await page.close() + try { + await callNative(page, 'open', {v: 1, seq: 1}) + await callNative(page, 'open', {v: 1, seq: 2}) + await expectLocator(composerBox(page)).toHaveCount(1, {timeout: 30_000}) + await expectLocator(composerBox(page)).toBeVisible() + await callNative(page, 'close', {v: 1, seq: 3}) + await expectLocator(composerBox(page)).toBeHidden({timeout: 30_000}) + } finally { + await page.close() + } }) it('drives the native grab provider: pick posts a requestId and a matching image grabResult stages the preview', async () => { const {page, bridge, observer} = await openNative() - const stagedForModel = observer.completed({ - path: ['drafts', 'set'], - input: /\[view\][\s\S]*PaymentCardCell/, - timeout: 30_000, - }) - const picked = Promise.withResolvers() - bridge.notify = (message) => { - if (message.type === 'grab.pick') picked.resolve(message) + try { + const stagedForModel = observer.completed({ + path: ['drafts', 'set'], + input: /\[view\][\s\S]*PaymentCardCell/, + timeout: 30_000, + }) + const picked = Promise.withResolvers() + bridge.notify = (message) => { + if (message.type === 'grab.pick') picked.resolve(message) + } + await callNative(page, 'open', {v: 1, seq: 1}) + await expectLocator(composerBox(page)).toBeVisible({timeout: 30_000}) + + await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) + await grabButton(page).click() + await picked.promise + const pick = findByType(bridge.posted, 'grab.pick') + expect(pick?.requestId).toBeTruthy() + expect(countType(bridge.posted, 'grab.pick')).toBe(1) + + await callNative(page, 'grabResult', {v: 1, seq: 3, requestId: pick?.requestId, grab: NEUTRAL_GRAB}) + await expectLocator(panel(page).getByText('PaymentCardCell')).toBeVisible({timeout: 30_000}) + await expectLocator(grabPreview(page)).toHaveAttribute('src', IMAGE_DATA_URL) + expect(JSON.stringify((await stagedForModel).input)).toContain('PaymentCardCell') + } finally { + await page.close() } - await callNative(page, 'open', {v: 1, seq: 1}) - await expectLocator(composerBox(page)).toBeVisible({timeout: 30_000}) - - await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) - await grabButton(page).click() - await picked.promise - const pick = findByType(bridge.posted, 'grab.pick') - expect(pick?.requestId).toBeTruthy() - expect(countType(bridge.posted, 'grab.pick')).toBe(1) - - await callNative(page, 'grabResult', {v: 1, seq: 3, requestId: pick?.requestId, grab: NEUTRAL_GRAB}) - await expectLocator(panel(page).getByText('PaymentCardCell')).toBeVisible({timeout: 30_000}) - await expectLocator(grabPreview(page)).toHaveAttribute('src', IMAGE_DATA_URL) - expect(JSON.stringify((await stagedForModel).input)).toContain('PaymentCardCell') - await page.close() }) it('ignores a grabResult whose requestId does not match the pending pick', async () => { const {page, bridge} = await openNative() - const picked = Promise.withResolvers() - bridge.notify = (message) => { - if (message.type === 'grab.pick') picked.resolve(message) + try { + const picked = Promise.withResolvers() + bridge.notify = (message) => { + if (message.type === 'grab.pick') picked.resolve(message) + } + await callNative(page, 'open', {v: 1, seq: 1}) + await expectLocator(composerBox(page)).toBeVisible({timeout: 30_000}) + await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) + await grabButton(page).click() + await picked.promise + expect(countType(bridge.posted, 'grab.pick')).toBe(1) + + await callNative(page, 'grabResult', {v: 1, seq: 3, requestId: 'not-the-pending-one', grab: NEUTRAL_GRAB}) + await new Promise((resolve) => setTimeout(resolve, 500)) + expect(await panel(page).getByText('PaymentCardCell').count()).toBe(0) + expect(await grabPreview(page).count()).toBe(0) + } finally { + await page.close() } - await callNative(page, 'open', {v: 1, seq: 1}) - await expectLocator(composerBox(page)).toBeVisible({timeout: 30_000}) - await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) - await grabButton(page).click() - await picked.promise - expect(countType(bridge.posted, 'grab.pick')).toBe(1) - - await callNative(page, 'grabResult', {v: 1, seq: 3, requestId: 'not-the-pending-one', grab: NEUTRAL_GRAB}) - await new Promise((resolve) => setTimeout(resolve, 500)) - expect(await panel(page).getByText('PaymentCardCell').count()).toBe(0) - expect(await grabPreview(page).count()).toBe(0) - await page.close() }) it('surfaces a visible error when native reports an incompatible bridge version', async () => { const {page} = await openNative() - await callNative(page, 'bridgeIncompatible', {v: 1, seq: 1, nativeMinV: 2, nativeMaxV: 3}) - await expectLocator(page.getByText('Update the conciv widget', {exact: false})).toBeVisible({timeout: 30_000}) - await page.close() + try { + await callNative(page, 'bridgeIncompatible', {v: 1, seq: 1, nativeMinV: 2, nativeMaxV: 3}) + await expectLocator(page.getByText('Update the conciv widget', {exact: false})).toBeVisible({timeout: 30_000}) + } finally { + await page.close() + } }) it('dispatches conciv:rebind when a handshake reports a different same-core base', async () => { const native = await openNative() - const rebound = Promise.withResolvers<{apiBase?: string}[]>() - native.onRebind = () => rebound.resolve(native.rebinds) - await callNative(native.page, 'handshake', {v: 1, seq: 1, apiBase: 'http://127.0.0.1:1/moved', token: null}) - expect(await rebound.promise).toEqual([{apiBase: 'http://127.0.0.1:1/moved'}]) - await native.page.close() + try { + const rebound = Promise.withResolvers<{apiBase?: string}[]>() + native.onRebind = () => rebound.resolve(native.rebinds) + await callNative(native.page, 'handshake', {v: 1, seq: 1, apiBase: 'http://127.0.0.1:1/moved', token: null}) + expect(await rebound.promise).toEqual([{apiBase: 'http://127.0.0.1:1/moved'}]) + } finally { + await native.page.close() + } }) }) diff --git a/packages/embed/test/navigation-hold.it.test.ts b/packages/embed/test/navigation-hold.it.test.ts index db44992cc0..0f7451b5b5 100644 --- a/packages/embed/test/navigation-hold.it.test.ts +++ b/packages/embed/test/navigation-hold.it.test.ts @@ -27,105 +27,114 @@ async function bootHeldNavigationPage(server: ProbeServer): Promise<{page: Page; describe('holdFirstNavigationWrite holds one websocket frame without stalling the socket', () => { it('retains the first navigation write, forwards a later call, and releases on its own response', async () => { const page = await suite.browser().newPage() - const held = await holdFirstNavigationWrite(page) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await page.evaluate((wsUrl) => window.__CONCIV_WS_PROBE__.connect(wsUrl), suite.socketUrl()) - - const {sessionId} = await suite.kit().rpc.sessions.create() - const write = page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), - navigationInput('/held-by-the-frame-tap'), - ) - await held.arrived - expect(await currentHref(suite.kit())).toBe('') - - const overtaking = await page.evaluate((payload) => window.__CONCIV_WS_PROBE__.call(['drafts', 'set'], payload), { - sessionId, - text: 'sent while the navigation frame is held', - selectionStart: 0, - selectionEnd: 0, - grabs: [], - }) - expect(overtaking).toEqual({ok: true}) - expect(await currentHref(suite.kit())).toBe('') - - await held.release() - await write - expect(await currentHref(suite.kit())).toBe('/held-by-the-frame-tap') - await page.close() + try { + const held = await holdFirstNavigationWrite(page) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await page.evaluate((wsUrl) => window.__CONCIV_WS_PROBE__.connect(wsUrl), suite.socketUrl()) + + const {sessionId} = await suite.kit().rpc.sessions.create() + const write = page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), + navigationInput('/held-by-the-frame-tap'), + ) + await held.arrived + expect(await currentHref(suite.kit())).toBe('') + + const overtaking = await page.evaluate((payload) => window.__CONCIV_WS_PROBE__.call(['drafts', 'set'], payload), { + sessionId, + text: 'sent while the navigation frame is held', + selectionStart: 0, + selectionEnd: 0, + grabs: [], + }) + expect(overtaking).toEqual({ok: true}) + expect(await currentHref(suite.kit())).toBe('') + + await held.release() + await write + expect(await currentHref(suite.kit())).toBe('/held-by-the-frame-tap') + } finally { + await page.close() + } }) it('queues a second navigation write behind the retained one and flushes both in order', async () => { const server = await startProbeServer() servers.push(server) const {page, held} = await bootHeldNavigationPage(server) - - const first = page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), - navigationInput('/first-write'), - ) - await held.arrived - const second = page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), - navigationInput('/second-write'), - ) - await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['fast'], undefined)) - expect(server.navigationWrites()).toEqual([]) - - server.releaseNavigation() - await held.release() - expect(await first).toEqual({ok: true, applied: true}) - expect(await second).toEqual({ok: true, applied: true}) - expect(server.navigationWrites()).toEqual(['/first-write', '/second-write']) - await page.close() + try { + const first = page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), + navigationInput('/first-write'), + ) + await held.arrived + const second = page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), + navigationInput('/second-write'), + ) + await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['fast'], undefined)) + expect(server.navigationWrites()).toEqual([]) + + server.releaseNavigation() + await held.release() + expect(await first).toEqual({ok: true, applied: true}) + expect(await second).toEqual({ok: true, applied: true}) + expect(server.navigationWrites()).toEqual(['/first-write', '/second-write']) + } finally { + await page.close() + } }) it('releases only after the retained write is answered, not when the gate opens', async () => { const server = await startProbeServer() servers.push(server) const {page, held} = await bootHeldNavigationPage(server) - - const write = page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), - navigationInput('/answered-late'), - ) - await held.arrived - - const settlement = {done: false} - const releasing = held.release().then(() => { - settlement.done = true - }) - await server.navigationEntered(0) - await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['fast'], undefined)) - expect(settlement.done).toBe(false) - - server.releaseNavigation() - await releasing - expect(settlement.done).toBe(true) - expect(await write).toEqual({ok: true, applied: true}) - await page.close() + try { + const write = page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), + navigationInput('/answered-late'), + ) + await held.arrived + + const settlement = {done: false} + const releasing = held.release().then(() => { + settlement.done = true + }) + await server.navigationEntered(0) + await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['fast'], undefined)) + expect(settlement.done).toBe(false) + + server.releaseNavigation() + await releasing + expect(settlement.done).toBe(true) + expect(await write).toEqual({ok: true, applied: true}) + } finally { + await page.close() + } }) it('forwards a navigation write that arrives after release instead of stranding it', async () => { const server = await startProbeServer() servers.push(server) const {page, held} = await bootHeldNavigationPage(server) - - const first = page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), - navigationInput('/first-write'), - ) - await held.arrived - server.releaseNavigation() - await held.release() - expect(await first).toEqual({ok: true, applied: true}) - - const late = page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), - navigationInput('/after-release'), - ) - await expect(late).resolves.toEqual({ok: true, applied: true}) - expect(server.navigationWrites()).toEqual(['/first-write', '/after-release']) - await page.close() + try { + const first = page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), + navigationInput('/first-write'), + ) + await held.arrived + server.releaseNavigation() + await held.release() + expect(await first).toEqual({ok: true, applied: true}) + + const late = page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['navigation', 'set'], payload), + navigationInput('/after-release'), + ) + await expect(late).resolves.toEqual({ok: true, applied: true}) + expect(server.navigationWrites()).toEqual(['/first-write', '/after-release']) + } finally { + await page.close() + } }, 8_000) }) diff --git a/packages/embed/test/page-plane.it.test.ts b/packages/embed/test/page-plane.it.test.ts index be33ec685b..e601518c94 100644 --- a/packages/embed/test/page-plane.it.test.ts +++ b/packages/embed/test/page-plane.it.test.ts @@ -40,24 +40,33 @@ async function openHostPage(): Promise { describe('startPagePlane executes registry page tools in the browser', () => { it('round-trips page.text through rpc.page.queries to the DOM dispatcher', async () => { const page = await openHostPage() - expect(await kit.rpc.registry.call({name: 'page.text', input: {selector: '#probe'}})).toMatchObject({ - text: 'page-bus-ok', - }) - await page.close() + try { + expect(await kit.rpc.registry.call({name: 'page.text', input: {selector: '#probe'}})).toMatchObject({ + text: 'page-bus-ok', + }) + } finally { + await page.close() + } }) it('a verb whose target does not exist rejects with a declared code, not a success-shaped string', async () => { const page = await openHostPage() - await expect(kit.rpc.registry.call({name: 'page.text', input: {selector: '#not-here'}})).rejects.toMatchObject({ - code: 'INVALID_ARGS', - message: 'page.text: no element for selector #not-here', - }) - await page.close() + try { + await expect(kit.rpc.registry.call({name: 'page.text', input: {selector: '#not-here'}})).rejects.toMatchObject({ + code: 'INVALID_ARGS', + message: 'page.text: no element for selector #not-here', + }) + } finally { + await page.close() + } }) it('the snapshot tool sees host page structure', async () => { const page = await openHostPage() - expect(JSON.stringify(await kit.rpc.registry.call({name: 'page.snapshot', input: {}}))).toContain('Embed page') - await page.close() + try { + expect(JSON.stringify(await kit.rpc.registry.call({name: 'page.snapshot', input: {}}))).toContain('Embed page') + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/panel-focus.it.test.ts b/packages/embed/test/panel-focus.it.test.ts index c0d33514ba..142b252f62 100644 --- a/packages/embed/test/panel-focus.it.test.ts +++ b/packages/embed/test/panel-focus.it.test.ts @@ -45,56 +45,70 @@ async function openPanelOverFocusedHostButton(): Promise { describe('panel open focuses the composer', () => { it('focuses the composer input when the panel opens', async () => { const page = await suite.browser().newPage() - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await expectLocator(composer(page)).toBeFocused({timeout: 10_000}) - await page.keyboard.type('typed without clicking') - await expectLocator(composer(page)).toHaveText('typed without clicking') - await page.close() + try { + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await expectLocator(composer(page)).toBeFocused({timeout: 10_000}) + await page.keyboard.type('typed without clicking') + await expectLocator(composer(page)).toHaveText('typed without clicking') + } finally { + await page.close() + } }) }) describe('panel close restores focus: host element captured at open wins, FAB is the fallback', () => { it('closing via the FAB restores the host element that was focused before a programmatic open', async () => { const {host, page, hostButton} = await openPanelOverFocusedHostButton() - await page.getByRole('button', {name: 'Minimize conciv chat'}).click() - await expectLocator(hostButton).toBeFocused({timeout: 10_000}) - await page.close() - await host.close() + try { + await page.getByRole('button', {name: 'Minimize conciv chat'}).click() + await expectLocator(hostButton).toBeFocused({timeout: 10_000}) + } finally { + await page.close() + await host.close() + } }) it('closing via the panel header restores the host element that was focused before the open', async () => { const {host, page, hostButton} = await openPanelOverFocusedHostButton() - await page.getByRole('button', {name: 'Close chat'}).click() - await expectLocator(hostButton).toBeFocused({timeout: 10_000}) - await page.close() - await host.close() + try { + await page.getByRole('button', {name: 'Close chat'}).click() + await expectLocator(hostButton).toBeFocused({timeout: 10_000}) + } finally { + await page.close() + await host.close() + } }) it('collapsing the panel by dragging its resize handle shut restores the host element', async () => { const {host, page, hostButton} = await openPanelOverFocusedHostButton() - - const handle = page.getByRole('separator', {name: 'Resize chat height'}) - const grip = await handle.boundingBox() - if (!grip) throw new Error('the resize handle is not laid out') - await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2) - await page.mouse.down() - await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2 + 600, {steps: 12}) - await page.mouse.up() - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - await expectLocator(hostButton).toBeFocused({timeout: 10_000}) - await page.close() - await host.close() + try { + const handle = page.getByRole('separator', {name: 'Resize chat height'}) + const grip = await handle.boundingBox() + if (!grip) throw new Error('the resize handle is not laid out') + await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2) + await page.mouse.down() + await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2 + 600, {steps: 12}) + await page.mouse.up() + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + await expectLocator(hostButton).toBeFocused({timeout: 10_000}) + } finally { + await page.close() + await host.close() + } }) it('closing via the FAB falls back to FAB focus when no host element was captured at open time', async () => { const page = await suite.browser().newPage() - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await ensurePanelClosed(page) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expectLocator(composer(page)).toBeVisible({timeout: 30_000}) - await page.getByRole('button', {name: 'Minimize conciv chat'}).click() - await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) - await page.close() + try { + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await ensurePanelClosed(page) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expectLocator(composer(page)).toBeVisible({timeout: 30_000}) + await page.getByRole('button', {name: 'Minimize conciv chat'}).click() + await expectLocator(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/rebind.it.test.ts b/packages/embed/test/rebind.it.test.ts index eaa4451cc7..7f5ce73fb6 100644 --- a/packages/embed/test/rebind.it.test.ts +++ b/packages/embed/test/rebind.it.test.ts @@ -67,45 +67,48 @@ describe('handle.rebind survives same-core port drift', () => { it('re-points rpc and SSE to the new port, keeps the panel open, the session, and delivers the next turn', async () => { const page = observedPage(await browser.newPage()) - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - - await mountHandle(page, proxyA.base) - await openChatPanel(page) - - const apiBaseProbe = page.getByRole('status', {name: 'host api base probe'}) - await expectLocator(apiBaseProbe).toHaveText(proxyA.base, {timeout: 30_000}) - - const routed = waitForNavigationWrite(page) - await sendChatMessage(page, USER_TEXT) - await expectLocator(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - await routed - const sessionBefore = await panelSession() - expect(sessionBefore).not.toBeNull() - - const beforeB = proxyB.trafficCount() - await rebindHandle(page, proxyB.base) - await proxyA.close() - - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) - - await expectLocator(apiBaseProbe).toHaveText(proxyB.base, {timeout: 30_000}) - - await expectLocator(page.getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expectLocator(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - - await sendChatMessage(page, SECOND_USER_TEXT) - await expectLocator(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) - await expectLocator(page.getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expectLocator(page.getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - - expect(proxyB.trafficCount()).toBeGreaterThan(beforeB) - expect(await panelSession()).toBe(sessionBefore) - expect(sessionBefore).not.toBeNull() - expect(pageErrors).toEqual([]) - await page.close() + try { + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + + await mountHandle(page, proxyA.base) + await openChatPanel(page) + + const apiBaseProbe = page.getByRole('status', {name: 'host api base probe'}) + await expectLocator(apiBaseProbe).toHaveText(proxyA.base, {timeout: 30_000}) + + const routed = waitForNavigationWrite(page) + await sendChatMessage(page, USER_TEXT) + await expectLocator(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + await routed + const sessionBefore = await panelSession() + expect(sessionBefore).not.toBeNull() + + const beforeB = proxyB.trafficCount() + await rebindHandle(page, proxyB.base) + await proxyA.close() + + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) + + await expectLocator(apiBaseProbe).toHaveText(proxyB.base, {timeout: 30_000}) + + await expectLocator(page.getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expectLocator(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + + await sendChatMessage(page, SECOND_USER_TEXT) + await expectLocator(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) + await expectLocator(page.getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expectLocator(page.getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + + expect(proxyB.trafficCount()).toBeGreaterThan(beforeB) + expect(await panelSession()).toBe(sessionBefore) + expect(sessionBefore).not.toBeNull() + expect(pageErrors).toEqual([]) + } finally { + await page.close() + } }) }) @@ -124,31 +127,34 @@ describe('handle.rebind remounts extension surfaces on the new core', () => { it('rebuilds the global surface and the open extension view against the new base', async () => { const page = observedPage(await browser.newPage()) - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - - await mountHandle(page, proxyC.base) - await openPanelTabs(page) - - const surfaceProbe = page.getByRole('status', {name: 'surface mount api base'}) - const viewProbe = page.getByRole('status', {name: 'view mount api base'}) - await expectLocator(surfaceProbe).toHaveText(proxyC.base, {timeout: 30_000}) - - const probeTab = page.getByRole('tab', {name: 'Mount probe'}) - await probeTab.click() - await expectLocator(viewProbe).toHaveText(proxyC.base, {timeout: 30_000}) - - const beforeD = proxyD.trafficCount() - await rebindHandle(page, proxyD.base) - await proxyC.close() - - await expectLocator(surfaceProbe).toHaveText(proxyD.base, {timeout: 15_000}) - await expectLocator(viewProbe).toHaveText(proxyD.base, {timeout: 15_000}) - await expectLocator(probeTab).toHaveAttribute('aria-selected', 'true', {timeout: 15_000}) - expect(proxyD.trafficCount()).toBeGreaterThan(beforeD) - expect(pageErrors).toEqual([]) - await page.close() + try { + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + + await mountHandle(page, proxyC.base) + await openPanelTabs(page) + + const surfaceProbe = page.getByRole('status', {name: 'surface mount api base'}) + const viewProbe = page.getByRole('status', {name: 'view mount api base'}) + await expectLocator(surfaceProbe).toHaveText(proxyC.base, {timeout: 30_000}) + + const probeTab = page.getByRole('tab', {name: 'Mount probe'}) + await probeTab.click() + await expectLocator(viewProbe).toHaveText(proxyC.base, {timeout: 30_000}) + + const beforeD = proxyD.trafficCount() + await rebindHandle(page, proxyD.base) + await proxyC.close() + + await expectLocator(surfaceProbe).toHaveText(proxyD.base, {timeout: 15_000}) + await expectLocator(viewProbe).toHaveText(proxyD.base, {timeout: 15_000}) + await expectLocator(probeTab).toHaveAttribute('aria-selected', 'true', {timeout: 15_000}) + expect(proxyD.trafficCount()).toBeGreaterThan(beforeD) + expect(pageErrors).toEqual([]) + } finally { + await page.close() + } }) }) @@ -168,34 +174,37 @@ describe('handle.rebind quiesces the old connection before tearing consumers dow it('writes nothing more to the old core once rebind is called', async () => { const page = observedPage(await browser.newPage()) - const observer = rpcObserverFor(page) - const framesSentPerSocket: number[] = [] - page.on('websocket', (socket) => { - if (!socket.url().includes('/rpc-ws')) return - const index = framesSentPerSocket.length - framesSentPerSocket.push(0) - socket.on('framesent', () => { - framesSentPerSocket[index] = (framesSentPerSocket[index] ?? 0) + 1 + try { + const observer = rpcObserverFor(page) + const framesSentPerSocket: number[] = [] + page.on('websocket', (socket) => { + if (!socket.url().includes('/rpc-ws')) return + const index = framesSentPerSocket.length + framesSentPerSocket.push(0) + socket.on('framesent', () => { + framesSentPerSocket[index] = (framesSentPerSocket[index] ?? 0) + 1 + }) }) - }) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await mountHandle(page, proxyE.base) - await openChatPanel(page) + await mountHandle(page, proxyE.base) + await openChatPanel(page) - const apiBaseProbe = page.getByRole('status', {name: 'host api base probe'}) - await expectLocator(apiBaseProbe).toHaveText(proxyE.base, {timeout: 30_000}) + const apiBaseProbe = page.getByRole('status', {name: 'host api base probe'}) + await expectLocator(apiBaseProbe).toHaveText(proxyE.base, {timeout: 30_000}) - await rebindHandle(page, proxyF.base) - await expectLocator(apiBaseProbe).toHaveText(proxyF.base, {timeout: 30_000}) + await rebindHandle(page, proxyF.base) + await expectLocator(apiBaseProbe).toHaveText(proxyF.base, {timeout: 30_000}) - const settledOnOldSocket = framesSentPerSocket[0] ?? 0 - const mark = observer.mark() - await sendChatMessage(page, SECOND_USER_TEXT) - await observer.completed({path: ['chat', 'send'], since: mark, timeout: 30_000}) + const settledOnOldSocket = framesSentPerSocket[0] ?? 0 + const mark = observer.mark() + await sendChatMessage(page, SECOND_USER_TEXT) + await observer.completed({path: ['chat', 'send'], since: mark, timeout: 30_000}) - expect(framesSentPerSocket[0]).toBe(settledOnOldSocket) - await page.close() + expect(framesSentPerSocket[0]).toBe(settledOnOldSocket) + } finally { + await page.close() + } }) }) @@ -212,23 +221,26 @@ describe('handle.rebind to the base the widget is already on re-runs the transpo it('rides the websocket after the blocked upgrade path opens up again', async () => { const page = await browser.newPage() - const observer = rpcObserverFor(page) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - - await mountHandle(page, blockedCore.base) - await openChatPanel(page) - await sendChatMessage(page, 'while upgrades are blocked') - const blocked = await observer.completed({path: ['chat', 'send'], timeout: 30_000}) - expect(blocked.transport).toBe('fetch') - - blockedCore.setUpgradesBlocked(false) - const mark = observer.mark() - await rebindHandle(page, blockedCore.base) - await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) - await sendChatMessage(page, 'after the upgrade path opens') - - const reprobed = await observer.completed({path: ['chat', 'send'], since: mark, timeout: 30_000}) - expect(reprobed.transport).toBe('websocket') - await page.close() + try { + const observer = rpcObserverFor(page) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + + await mountHandle(page, blockedCore.base) + await openChatPanel(page) + await sendChatMessage(page, 'while upgrades are blocked') + const blocked = await observer.completed({path: ['chat', 'send'], timeout: 30_000}) + expect(blocked.transport).toBe('fetch') + + blockedCore.setUpgradesBlocked(false) + const mark = observer.mark() + await rebindHandle(page, blockedCore.base) + await expectLocator(chatBox(page)).toBeVisible({timeout: 30_000}) + await sendChatMessage(page, 'after the upgrade path opens') + + const reprobed = await observer.completed({path: ['chat', 'send'], since: mark, timeout: 30_000}) + expect(reprobed.transport).toBe('websocket') + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/recording-attachment.it.test.ts b/packages/embed/test/recording-attachment.it.test.ts index 475a4a688a..59ec4cfb48 100644 --- a/packages/embed/test/recording-attachment.it.test.ts +++ b/packages/embed/test/recording-attachment.it.test.ts @@ -33,77 +33,84 @@ afterAll(async () => { describe('recording attachment end to end in the real widget', () => { it('composes the card chip, sends log text to the model, renders the durable transcript card', async () => { const page = await browser.newPage() - const observer = observeRpc(page) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + try { + const observer = observeRpc(page) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - const flushPath = ['ext', 'recorder', 'flush'] - const firstFlush = observer.completed({path: flushPath, timeout: 30_000}) - await page.getByRole('tab', {name: 'Recorder'}).click() - await firstFlush + await openPanel(page) + const flushPath = ['ext', 'recorder', 'flush'] + const firstFlush = observer.completed({path: flushPath, timeout: 30_000}) + await page.getByRole('tab', {name: 'Recorder'}).click() + await firstFlush - const interactionFlush = observer.completed({path: flushPath, since: observer.mark(), timeout: 30_000}) - await page.getByRole('button', {name: 'Embed fixture'}).click() - await page.getByRole('button', {name: 'Embed fixture'}).click() + const interactionFlush = observer.completed({path: flushPath, since: observer.mark(), timeout: 30_000}) + await page.getByRole('button', {name: 'Embed fixture'}).click() + await page.getByRole('button', {name: 'Embed fixture'}).click() - const recorderRpc = makeExtRpcClient(kit.base, 'recorder') - await interactionFlush - expect((await recorderRpc.window({})).events.length).toBeGreaterThanOrEqual(2) + const recorderRpc = makeExtRpcClient(kit.base, 'recorder') + await interactionFlush + expect((await recorderRpc.window({})).events.length).toBeGreaterThanOrEqual(2) - const send = page.getByRole('button', {name: 'Send to agent'}) - await send.waitFor({state: 'visible', timeout: 15_000}) - await send.click() + const send = page.getByRole('button', {name: 'Send to agent'}) + await send.waitFor({state: 'visible', timeout: 15_000}) + await send.click() - await page - .getByText(/Screen recording · \d+ action/) - .first() - .waitFor({state: 'visible', timeout: 15_000}) - expect(await page.getByText('recording.txt').count()).toBe(0) + await page + .getByText(/Screen recording · \d+ action/) + .first() + .waitFor({state: 'visible', timeout: 15_000}) + expect(await page.getByText('recording.txt').count()).toBe(0) - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.fill('here is what I did') - await page.getByRole('button', {name: 'Send message'}).click() - await expectLocator(page.getByText('Recording received').first()).toBeVisible({timeout: 30_000}) + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.fill('here is what I did') + await page.getByRole('button', {name: 'Send message'}).click() + await expectLocator(page.getByText('Recording received').first()).toBeVisible({timeout: 30_000}) - const sessions = await kit.rpc.sessions.list() - const chatSession = sessions[0]?.id - if (!chatSession) throw new Error('widget session not found') - const attachAbort = new AbortController() - const stream = await kit.attach(chatSession, {signal: attachAbort.signal}) - const snapshot = await stream.waitFor( - (chunk) => chunk.type === 'MESSAGES_SNAPSHOT' && JSON.stringify(chunk).includes('[click]'), - {hangGuardMs: 30_000}, - ) - expect(JSON.stringify(snapshot)).toContain('"modelOnly":true') - attachAbort.abort() + const sessions = await kit.rpc.sessions.list() + const chatSession = sessions[0]?.id + if (!chatSession) throw new Error('widget session not found') + const attachAbort = new AbortController() + const stream = await kit.attach(chatSession, {signal: attachAbort.signal}) + const snapshot = await stream.waitFor( + (chunk) => chunk.type === 'MESSAGES_SNAPSHOT' && JSON.stringify(chunk).includes('[click]'), + {hangGuardMs: 30_000}, + ) + expect(JSON.stringify(snapshot)).toContain('"modelOnly":true') + attachAbort.abort() - const transcript = page.getByRole('log') - await transcript - .getByText(/Screen recording · \d+ action/) - .first() - .waitFor({state: 'visible', timeout: 15_000}) - await transcript.getByRole('button', {name: 'Play'}).first().waitFor({state: 'visible', timeout: 15_000}) - expect(await transcript.getByText('[click]').count()).toBe(0) - expect(await page.getByRole('img').count()).toBe(0) + const transcript = page.getByRole('log') + await transcript + .getByText(/Screen recording · \d+ action/) + .first() + .waitFor({state: 'visible', timeout: 15_000}) + await transcript.getByRole('button', {name: 'Play'}).first().waitFor({state: 'visible', timeout: 15_000}) + expect(await transcript.getByText('[click]').count()).toBe(0) + expect(await page.getByRole('img').count()).toBe(0) - await page.reload({waitUntil: 'domcontentloaded'}) - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await page - .getByRole('log') - .getByText(/Screen recording · \d+ action/) - .first() - .waitFor({state: 'visible', timeout: 20_000}) - await page.getByRole('log').getByRole('button', {name: 'Play'}).first().waitFor({state: 'visible', timeout: 15_000}) + await page.reload({waitUntil: 'domcontentloaded'}) + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await page + .getByRole('log') + .getByText(/Screen recording · \d+ action/) + .first() + .waitFor({state: 'visible', timeout: 20_000}) + await page + .getByRole('log') + .getByRole('button', {name: 'Play'}) + .first() + .waitFor({state: 'visible', timeout: 15_000}) - await page.getByRole('log').getByRole('button', {name: 'Play'}).first().click() - const modal = page.getByRole('dialog', {name: 'Screen recording replay'}) - await modal.waitFor({state: 'visible', timeout: 15_000}) - await modal.getByRole('button', {name: 'Close'}).click() - await modal.waitFor({state: 'hidden', timeout: 15_000}) - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - const composerAfterModal = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await composerAfterModal.fill('still alive after replay') - await expectLocator(composerAfterModal).toHaveText('still alive after replay') - await page.close() + await page.getByRole('log').getByRole('button', {name: 'Play'}).first().click() + const modal = page.getByRole('dialog', {name: 'Screen recording replay'}) + await modal.waitFor({state: 'visible', timeout: 15_000}) + await modal.getByRole('button', {name: 'Close'}).click() + await modal.waitFor({state: 'hidden', timeout: 15_000}) + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + const composerAfterModal = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await composerAfterModal.fill('still alive after replay') + await expectLocator(composerAfterModal).toHaveText('still alive after replay') + } finally { + await page.close() + } }, 120_000) }) diff --git a/packages/embed/test/reload-continuity.it.test.ts b/packages/embed/test/reload-continuity.it.test.ts index 3e254034e3..885282b628 100644 --- a/packages/embed/test/reload-continuity.it.test.ts +++ b/packages/embed/test/reload-continuity.it.test.ts @@ -11,36 +11,39 @@ const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) describe('reload continuity through the db-backed navigation row', () => { it('restores the open panel route, the transcript, and the draft after a reload', async () => { const page = await suite.browser().newPage() - const observer = observeRpc(page) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) + try { + const observer = observeRpc(page) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.fill('remember me') - await page.getByRole('button', {name: 'Send message'}).click() - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.fill('remember me') + await page.getByRole('button', {name: 'Send message'}).click() + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await input.fill('an unsent draft survives') - await input.press('End') - await observer.completed({ - path: ['drafts', 'set'], - input: {text: 'an unsent draft survives'}, - timeout: 30_000, - }) - const state = await suite.kit().rpc.navigation.get(undefined) - const panelEntry = state?.entries.find((entry) => entry.href.startsWith('/panel/')) - const sessionId = (panelEntry?.href.split('/')[2] ?? '').split('?')[0] ?? '' - expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({text: 'an unsent draft survives'}) + await input.fill('an unsent draft survives') + await input.press('End') + await observer.completed({ + path: ['drafts', 'set'], + input: {text: 'an unsent draft survives'}, + timeout: 30_000, + }) + const state = await suite.kit().rpc.navigation.get(undefined) + const panelEntry = state?.entries.find((entry) => entry.href.startsWith('/panel/')) + const sessionId = (panelEntry?.href.split('/')[2] ?? '').split('?')[0] ?? '' + expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({text: 'an unsent draft survives'}) - await page.reload({waitUntil: 'domcontentloaded'}) + await page.reload({waitUntil: 'domcontentloaded'}) - await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expectLocator(page.getByRole('textbox', {name: 'Message the conciv agent'})).toHaveText( - 'an unsent draft survives', - {timeout: 30_000}, - ) - observer.dispose() - await page.close() + await expectLocator(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expectLocator(page.getByRole('textbox', {name: 'Message the conciv agent'})).toHaveText( + 'an unsent draft survives', + {timeout: 30_000}, + ) + observer.dispose() + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/rpc-fault.it.test.ts b/packages/embed/test/rpc-fault.it.test.ts index 5938b6951c..39850cd7b8 100644 --- a/packages/embed/test/rpc-fault.it.test.ts +++ b/packages/embed/test/rpc-fault.it.test.ts @@ -7,26 +7,29 @@ const suite = setupWsProbeSuite() describe('rpc fault injection reaches calls that ride the websocket', () => { it('fails only the targeted procedure and lets it recover after repair', async () => { const page = await suite.browser().newPage() - const models = await failRpcCalls(page, {path: ['meta', 'models']}) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await page.evaluate((wsUrl) => window.__CONCIV_WS_PROBE__.connect(wsUrl), suite.socketUrl()) + try { + const models = await failRpcCalls(page, {path: ['meta', 'models']}) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await page.evaluate((wsUrl) => window.__CONCIV_WS_PROBE__.connect(wsUrl), suite.socketUrl()) - const failed = await page.evaluate(async () => { - try { - await window.__CONCIV_WS_PROBE__.call(['meta', 'models'], undefined) - return 'answered' - } catch (error) { - return `failed: ${error instanceof Error ? error.message : String(error)}` - } - }) - expect(failed).toContain('failed:') + const failed = await page.evaluate(async () => { + try { + await window.__CONCIV_WS_PROBE__.call(['meta', 'models'], undefined) + return 'answered' + } catch (error) { + return `failed: ${error instanceof Error ? error.message : String(error)}` + } + }) + expect(failed).toContain('failed:') - const untouched = await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['meta', 'tools'], undefined)) - expect(JSON.stringify(untouched)).toContain('tools') + const untouched = await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['meta', 'tools'], undefined)) + expect(JSON.stringify(untouched)).toContain('tools') - models.repair() - const repaired = await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['meta', 'models'], undefined)) - expect(JSON.stringify(repaired)).toContain('models') - await page.close() + models.repair() + const repaired = await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['meta', 'models'], undefined)) + expect(JSON.stringify(repaired)).toContain('models') + } finally { + await page.close() + } }) }) diff --git a/packages/embed/test/rpc-observer.it.test.ts b/packages/embed/test/rpc-observer.it.test.ts index 2f9a2f368e..c83a19c846 100644 --- a/packages/embed/test/rpc-observer.it.test.ts +++ b/packages/embed/test/rpc-observer.it.test.ts @@ -58,171 +58,195 @@ function draft(sessionId: string, text: string): Record { describe('the shared rpc observer correlates calls on both transports', () => { it('correlates a websocket request id with its terminal response, not with the outbound frame', async () => { const {page, observer} = await openProbePage() - const answered = observer.completed({path: ['meta', 'tools'], timeout: 15_000}) - const payload = await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['meta', 'tools'], undefined)) - const call = await answered - expect(call.transport).toBe('websocket') - expect(call.status).toBe(200) - expect(observer.socketCount()).toBe(1) - expect(JSON.stringify(payload)).toContain('tools') - observer.dispose() - await page.close() + try { + const answered = observer.completed({path: ['meta', 'tools'], timeout: 15_000}) + const payload = await page.evaluate(() => window.__CONCIV_WS_PROBE__.call(['meta', 'tools'], undefined)) + const call = await answered + expect(call.transport).toBe('websocket') + expect(call.status).toBe(200) + expect(observer.socketCount()).toBe(1) + expect(JSON.stringify(payload)).toContain('tools') + observer.dispose() + } finally { + await page.close() + } }) it('matches a call by its decoded structured input, never by raw frame text', async () => { const {page, observer} = await openProbePage() - const {sessionId} = await suite.kit().rpc.sessions.create() - const wanted = observer.completed({ - path: ['drafts', 'set'], - input: {text: 'the second draft'}, - timeout: 15_000, - }) - await page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['drafts', 'set'], payload), - draft(sessionId, 'the first draft'), - ) - await page.evaluate( - (payload) => window.__CONCIV_WS_PROBE__.call(['drafts', 'set'], payload), - draft(sessionId, 'the second draft'), - ) - const call = await wanted - expect(call.input).toMatchObject({text: 'the second draft'}) - expect(observer.completedCount({path: ['drafts', 'set']})).toBe(2) - observer.dispose() - await page.close() + try { + const {sessionId} = await suite.kit().rpc.sessions.create() + const wanted = observer.completed({ + path: ['drafts', 'set'], + input: {text: 'the second draft'}, + timeout: 15_000, + }) + await page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['drafts', 'set'], payload), + draft(sessionId, 'the first draft'), + ) + await page.evaluate( + (payload) => window.__CONCIV_WS_PROBE__.call(['drafts', 'set'], payload), + draft(sessionId, 'the second draft'), + ) + const call = await wanted + expect(call.input).toMatchObject({text: 'the second draft'}) + expect(observer.completedCount({path: ['drafts', 'set']})).toBe(2) + observer.dispose() + } finally { + await page.close() + } }) it('stays pending while the call is in flight and settles only on the terminal response', async () => { const {page, observer, server} = await openProbeServerPage() - const answered = observer.completed({path: ['slow'], timeout: 15_000}) - const settlement = {done: false} - void answered.then(() => { - settlement.done = true - }) - const inFlight = callProbe(page, ['slow'], {tag: 'held'}) - await server.slowEntered(0) - await callProbe(page, ['fast'], undefined) - await observer.completed({path: ['fast'], timeout: 15_000}) - - expect(observer.startedCount({path: ['slow']})).toBe(1) - expect(observer.completedCount({path: ['slow']})).toBe(0) - expect(settlement.done).toBe(false) - - server.releaseSlow() - expect((await answered).status).toBe(200) - expect(await inFlight).toEqual({tag: 'held'}) - observer.dispose() - await page.close() + try { + const answered = observer.completed({path: ['slow'], timeout: 15_000}) + const settlement = {done: false} + void answered.then(() => { + settlement.done = true + }) + const inFlight = callProbe(page, ['slow'], {tag: 'held'}) + await server.slowEntered(0) + await callProbe(page, ['fast'], undefined) + await observer.completed({path: ['fast'], timeout: 15_000}) + + expect(observer.startedCount({path: ['slow']})).toBe(1) + expect(observer.completedCount({path: ['slow']})).toBe(0) + expect(settlement.done).toBe(false) + + server.releaseSlow() + expect((await answered).status).toBe(200) + expect(await inFlight).toEqual({tag: 'held'}) + observer.dispose() + } finally { + await page.close() + } }) it('ignores an inbound response whose request id belongs to no observed call', async () => { const {page, observer, inject, server} = await openProbeServerPage() - const answered = observer.completed({path: ['slow'], timeout: 15_000}) - const settlement = {done: false} - void answered.then(() => { - settlement.done = true - }) - const inFlight = callProbe(page, ['slow'], {tag: 'correlated'}) - await server.slowEntered(0) - - const impostor = await encodeResponseMessage('impostor-id', MessageType.RESPONSE, { - status: 200, - headers: {}, - body: {json: {tag: 'impostor'}, meta: []}, - }) - if (typeof impostor !== 'string') throw new Error('the impostor frame encoded to binary') - inject(impostor) - await callProbe(page, ['fast'], undefined) - await observer.completed({path: ['fast'], timeout: 15_000}) - expect(settlement.done).toBe(false) - - server.releaseSlow() - expect((await answered).status).toBe(200) - expect(await inFlight).toEqual({tag: 'correlated'}) - observer.dispose() - await page.close() + try { + const answered = observer.completed({path: ['slow'], timeout: 15_000}) + const settlement = {done: false} + void answered.then(() => { + settlement.done = true + }) + const inFlight = callProbe(page, ['slow'], {tag: 'correlated'}) + await server.slowEntered(0) + + const impostor = await encodeResponseMessage('impostor-id', MessageType.RESPONSE, { + status: 200, + headers: {}, + body: {json: {tag: 'impostor'}, meta: []}, + }) + if (typeof impostor !== 'string') throw new Error('the impostor frame encoded to binary') + inject(impostor) + await callProbe(page, ['fast'], undefined) + await observer.completed({path: ['fast'], timeout: 15_000}) + expect(settlement.done).toBe(false) + + server.releaseSlow() + expect((await answered).status).toBe(200) + expect(await inFlight).toEqual({tag: 'correlated'}) + observer.dispose() + } finally { + await page.close() + } }) it('counts an in-flight call started after the mark and skips one that only completed after it', async () => { const {page, observer, server} = await openProbeServerPage() - const early = callProbe(page, ['slow'], {tag: 'early'}) - await server.slowEntered(0) - await callProbe(page, ['fast'], undefined) - await observer.completed({path: ['fast'], timeout: 15_000}) - - const mark = observer.mark() - const late = callProbe(page, ['slow'], {tag: 'late'}) - await server.slowEntered(1) - await callProbe(page, ['fast'], undefined) - await observer.completed({path: ['fast'], since: mark, timeout: 15_000}) - - expect(observer.startedCount({path: ['slow'], since: mark})).toBe(1) - expect(observer.completedCount({path: ['slow'], since: mark})).toBe(0) - - server.releaseSlow() - await early - await late - const barrier = observer.mark() - await callProbe(page, ['fast'], undefined) - await observer.completed({path: ['fast'], since: barrier, timeout: 15_000}) - expect(observer.startedCount({path: ['slow'], since: mark})).toBe(1) - expect(observer.completedCount({path: ['slow'], since: mark})).toBe(2) - observer.dispose() - await page.close() + try { + const early = callProbe(page, ['slow'], {tag: 'early'}) + await server.slowEntered(0) + await callProbe(page, ['fast'], undefined) + await observer.completed({path: ['fast'], timeout: 15_000}) + + const mark = observer.mark() + const late = callProbe(page, ['slow'], {tag: 'late'}) + await server.slowEntered(1) + await callProbe(page, ['fast'], undefined) + await observer.completed({path: ['fast'], since: mark, timeout: 15_000}) + + expect(observer.startedCount({path: ['slow'], since: mark})).toBe(1) + expect(observer.completedCount({path: ['slow'], since: mark})).toBe(0) + + server.releaseSlow() + await early + await late + const barrier = observer.mark() + await callProbe(page, ['fast'], undefined) + await observer.completed({path: ['fast'], since: barrier, timeout: 15_000}) + expect(observer.startedCount({path: ['slow'], since: mark})).toBe(1) + expect(observer.completedCount({path: ['slow'], since: mark})).toBe(2) + observer.dispose() + } finally { + await page.close() + } }) it('rejects a first-event wait for a call already answered over fetch instead of hanging', async () => { const {page, observer} = await openProbePage() - await page.evaluate( - (base) => - fetch(`${base}/rpc/meta/tools`, { - method: 'POST', - headers: {'content-type': 'application/json'}, - body: JSON.stringify({json: undefined, meta: []}), - }).then((response) => response.status), - suite.kit().base, - ) - await observer.completed({path: ['meta', 'tools'], timeout: 15_000}) - const failure = await observer - .firstEvent({path: ['meta', 'tools'], timeout: 2_000}) - .then(() => 'resolved') - .catch((error: unknown) => (error instanceof Error ? error.message : String(error))) - expect(failure).toContain('fetch transport') - observer.dispose() - await page.close() + try { + await page.evaluate( + (base) => + fetch(`${base}/rpc/meta/tools`, { + method: 'POST', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({json: undefined, meta: []}), + }).then((response) => response.status), + suite.kit().base, + ) + await observer.completed({path: ['meta', 'tools'], timeout: 15_000}) + const failure = await observer + .firstEvent({path: ['meta', 'tools'], timeout: 2_000}) + .then(() => 'resolved') + .catch((error: unknown) => (error instanceof Error ? error.message : String(error))) + expect(failure).toContain('fetch transport') + observer.dispose() + } finally { + await page.close() + } }) it('never matches an extension procedure against the core procedure of the same name', async () => { const {page, observer} = await openProbePage() - const core = observer.completed({path: ['page', 'queries'], timeout: 15_000}) - const settlement = {done: false} - void core.then(() => { - settlement.done = true - }) - await page - .evaluate(() => window.__CONCIV_WS_PROBE__.call(['ext', 'page-probe', 'page', 'queries'], undefined)) - .catch(() => undefined) - expect(observer.startedCount({path: ['ext', 'page-probe', 'page', 'queries']})).toBe(1) - expect(observer.startedCount({path: ['page', 'queries']})).toBe(0) - expect(settlement.done).toBe(false) - observer.dispose() - await page.close() + try { + const core = observer.completed({path: ['page', 'queries'], timeout: 15_000}) + const settlement = {done: false} + void core.then(() => { + settlement.done = true + }) + await page + .evaluate(() => window.__CONCIV_WS_PROBE__.call(['ext', 'page-probe', 'page', 'queries'], undefined)) + .catch(() => undefined) + expect(observer.startedCount({path: ['ext', 'page-probe', 'page', 'queries']})).toBe(1) + expect(observer.startedCount({path: ['page', 'queries']})).toBe(0) + expect(settlement.done).toBe(false) + observer.dispose() + } finally { + await page.close() + } }) it('reports a subscription as completed when its stream opens and surfaces the first iterator payload', async () => { const {page, observer} = await openProbePage() - const opened = observer.completed({path: ['page', 'queries'], timeout: 15_000}) - const firstQuery = observer.firstEvent({path: ['page', 'queries'], timeout: 15_000}) - await page.evaluate(() => window.__CONCIV_WS_PROBE__.subscribe(['page', 'queries'], undefined)) - const call = await opened - expect(call.streaming).toBe(true) - await suite - .kit() - .rpc.registry.call({name: 'page.text', input: {selector: '#probe'}}) - .catch(() => {}) - const event = await firstQuery - expect(JSON.stringify(event.data)).toContain('page.text') - observer.dispose() - await page.close() + try { + const opened = observer.completed({path: ['page', 'queries'], timeout: 15_000}) + const firstQuery = observer.firstEvent({path: ['page', 'queries'], timeout: 15_000}) + await page.evaluate(() => window.__CONCIV_WS_PROBE__.subscribe(['page', 'queries'], undefined)) + const call = await opened + expect(call.streaming).toBe(true) + await suite + .kit() + .rpc.registry.call({name: 'page.text', input: {selector: '#probe'}}) + .catch(() => {}) + const event = await firstQuery + expect(JSON.stringify(event.data)).toContain('page.text') + observer.dispose() + } finally { + await page.close() + } }) }) From 23ad96cc5317cd4bfd59c957ea671d8279a5f374 Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Mon, 10 Aug 2026 22:15:54 +0300 Subject: [PATCH 2/2] fix(embed): close the reload-simulation pages on their own failure paths too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two reload-simulation tests kept a bare-body page for `first` (closed mid-body as the reload trigger) and `second` (closed only as the last statement). Either leaks on an assertion failure before its close: page.close() is idempotent, so wrapping each phase in its own try/finally closes on failure without changing happy-path behavior — the mid-body first.close() stays in place as the reload trigger. Co-Authored-By: Claude Fable 5 --- packages/embed/test/embed.it.test.ts | 62 +++++++++++++++++----------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/packages/embed/test/embed.it.test.ts b/packages/embed/test/embed.it.test.ts index 4240c519f2..b7e325e3fa 100644 --- a/packages/embed/test/embed.it.test.ts +++ b/packages/embed/test/embed.it.test.ts @@ -173,36 +173,50 @@ describe('embed boots the conciv app against a real core', () => { it('a reload restores the panel open on the same view', async () => { const first = await openPage() - await openPanel(first) - const switched = waitForNavigationWriteCarrying(first, '/terminal') - await first.getByRole('tab', {name: 'Terminal'}).click() - await switched - expect(await currentHref(kit)).toMatch(/\/terminal\?.*open=true/) - await first.close() + try { + await openPanel(first) + const switched = waitForNavigationWriteCarrying(first, '/terminal') + await first.getByRole('tab', {name: 'Terminal'}).click() + await switched + expect(await currentHref(kit)).toMatch(/\/terminal\?.*open=true/) + await first.close() + } finally { + await first.close() + } const second = await openPage() - await expectLocator(second.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expectLocator(second.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { - timeout: 30_000, - }) - await second.close() + try { + await expectLocator(second.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expectLocator(second.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { + timeout: 30_000, + }) + } finally { + await second.close() + } }) it('a reload after closing the panel boots shut', async () => { const first = observedPage(await browser.newPage()) - const opened = waitForNavigationWrite(first) - await first.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(first) - await opened - expect(await currentHref(kit)).toContain('open=true') - const shut = waitForNavigationWrite(first) - await first.getByRole('button', {name: 'Minimize conciv chat'}).click() - await shut - expect(await currentHref(kit)).not.toContain('open=true') - await first.close() + try { + const opened = waitForNavigationWrite(first) + await first.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(first) + await opened + expect(await currentHref(kit)).toContain('open=true') + const shut = waitForNavigationWrite(first) + await first.getByRole('button', {name: 'Minimize conciv chat'}).click() + await shut + expect(await currentHref(kit)).not.toContain('open=true') + await first.close() + } finally { + await first.close() + } const second = await openPage() - await expectLocator(second.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) - expect(await second.getByRole('dialog', {name: 'conciv chat agent'}).count()).toBe(0) - await second.close() + try { + await expectLocator(second.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) + expect(await second.getByRole('dialog', {name: 'conciv chat agent'}).count()).toBe(0) + } finally { + await second.close() + } }) it('renders the fab instantly and opens the panel', async () => {