diff --git a/packages/embed/tests/e2e/chat-send-parts.it.test.ts b/packages/embed/tests/e2e/chat-send-parts.it.test.ts deleted file mode 100644 index 16b08ead4f..0000000000 --- a/packages/embed/tests/e2e/chat-send-parts.it.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import {expect, test} from '@playwright/test' -import type {Grab} from '@conciv/grab' -import {GRAB_FILE_NAME, GRAB_MIME, grabToPayload} from '@conciv/grab/grab-attachment' -import {watchChatWire} from '@conciv/extension-testkit/chat-wire' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' - -const ASSISTANT_TEXT = 'Parts received' -const GRAB_TEXT = '

Payroll Deposit

at src/routes/index.tsx:12:9' -const MESSAGE_TEXT = 'what is wrong with this element' - -const GRAB: Grab = { - text: GRAB_TEXT, - snippet: '

Payroll Deposit

', - preview: {kind: 'dom', html: '

Payroll Deposit clone

', width: 200, height: 40}, - source: {componentName: 'Hero', filePath: 'src/routes/index.tsx', lineNumber: 12}, - rect: {x: 0, y: 0, width: 200, height: 40}, -} - -const GRAB_JSON = JSON.stringify(grabToPayload(GRAB)) - -const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) - -test.describe('a send that carries an attachment', () => { - test('reaches the chat transport as content parts the wire watcher reports without throwing', async ({page}) => { - test.setTimeout(120_000) - const wire = watchChatWire(page) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - - const addAttachment = page.getByRole('button', {name: 'Add an attachment'}) - await expect(addAttachment).toBeEnabled({timeout: 30_000}) - const opened = page.waitForEvent('filechooser', {timeout: 30_000}) - await addAttachment.click() - const chooser = await opened - await chooser.setFiles({name: GRAB_FILE_NAME, mimeType: GRAB_MIME, buffer: Buffer.from(GRAB_JSON)}) - await expect(page.getByRole('button', {name: 'Open grabbed element'})).toBeVisible({timeout: 30_000}) - - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(MESSAGE_TEXT) - const sent = wire.nextTurn() - await page.getByRole('button', {name: 'Send message'}).click() - - const frame = await sent - expect(frame.content).toEqual([ - {type: 'text', text: MESSAGE_TEXT}, - {type: 'document', source: {type: 'data', mimeType: GRAB_MIME, value: Buffer.from(GRAB_JSON).toString('base64')}}, - ]) - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - }) -}) diff --git a/packages/embed/tests/e2e/code-highlight-bundle.it.test.ts b/packages/embed/tests/e2e/code-highlight-bundle.it.test.ts deleted file mode 100644 index 90491bcaf6..0000000000 --- a/packages/embed/tests/e2e/code-highlight-bundle.it.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import {expect, test} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel, sendMessage} from './helpers/panel.js' - -const ASSISTANT_REPLY = [ - 'Here is the fix:', - '', - '```ts', - 'const greeting: string = "hello from the highlighter"', - '```', -].join('\n') - -const MESSAGE_TEXT = 'show me the fix' - -const suite = setupWidgetSuite({text: ASSISTANT_REPLY}) - -test.describe('code fences highlight through the worker on the built bundle', () => { - test('renders a shiki-highlighted code block for the fenced reply', async ({page}) => { - test.setTimeout(120_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await sendMessage(page, MESSAGE_TEXT, 'Here is the fix:') - - const highlighted = page.locator('pre.shiki span[style*="color"]').first() - await expect(highlighted).toBeVisible({timeout: 30_000}) - }) -}) diff --git a/packages/embed/tests/e2e/composer-rich-input.it.test.ts b/packages/embed/tests/e2e/composer-rich-input.it.test.ts deleted file mode 100644 index 69e942ab65..0000000000 --- a/packages/embed/tests/e2e/composer-rich-input.it.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import recorderServer from '@conciv/extension-recorder' -import {watchChatWire} from '@conciv/extension-testkit/chat-wire' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanelOnNewSession} from './helpers/panel.js' -import {untilPanelDraft} from './helpers/drafts.js' - -const ASSISTANT_TEXT = 'Rich input reply' - -const suite = setupWidgetSuite({ - text: ASSISTANT_TEXT, - extensions: [recorderServer], - commands: [ - {name: 'compact', description: 'Compact the conversation'}, - {name: 'config', description: 'Open configuration'}, - ], -}) - -const composer = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) -const panel = (page: Page) => page.getByRole('dialog', {name: 'conciv chat agent'}) - -const waitForDraftWrite = (sessionId: string, fragment: string) => - untilPanelDraft(suite.kit(), sessionId, (draft) => draft.text.includes(fragment)) - -async function openComposer(page: Page): Promise { - const sessionId = await openPanelOnNewSession(page, suite) - const input = composer(page) - await input.click() - await expect(input).toHaveText('') - return sessionId -} - -async function pickSuggestion(page: Page, listName: string, optionName: string): Promise { - const listbox = page.getByRole('listbox', {name: listName}) - const option = listbox.getByRole('option', {name: optionName}) - await expect(option).toBeVisible({timeout: 10_000}) - await expect(option).toHaveAttribute('id', /.+/, {timeout: 10_000}) - const optionId = await option.getAttribute('id') - if (!optionId) throw new Error(`option "${optionName}" in "${listName}" rendered without an id`) - await expect(composer(page)).toHaveAttribute('aria-activedescendant', optionId, {timeout: 10_000}) - await page.keyboard.press('Enter') - await expect(listbox).toBeHidden({timeout: 10_000}) -} - -test.describe('the rich composer input in the live widget shadow DOM', () => { - test('types multiline text with slash and mention chips and submits the exact directive string', async ({ - page: fixturePage, - }) => { - test.setTimeout(180_000) - const page = fixturePage - const wire = watchChatWire(page) - 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 = wire.nextTurn().then((turn) => turn.content) - await page.getByRole('button', {name: 'Send message'}).click() - expect(await sent).toBe(expected) - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expect(input).toHaveText('') - }) - - test('backspace removes a selected command chip in two steps, never a partial directive', async ({page}) => { - test.setTimeout(120_000) - await openComposer(page) - const input = composer(page) - - await input.pressSequentially('/compact') - await pickSuggestion(page, 'Commands', '/compact') - await expect(input).toHaveText('/compact ') - - await page.keyboard.press('Backspace') - await expect(input).toHaveText('/compact') - - await page.keyboard.press('Backspace') - await expect(input).toHaveText('') - }) - - test('forward delete removes the chip ahead of the caret in one step', async ({page}) => { - test.setTimeout(120_000) - await openComposer(page) - const input = composer(page) - - await input.pressSequentially('/compact') - await pickSuggestion(page, 'Commands', '/compact') - await expect(input).toHaveText('/compact ') - - await page.keyboard.press('Home') - await input.pressSequentially('x') - await expect(input).toHaveText('x/compact ') - await page.keyboard.press('Delete') - await expect(input).toHaveText('x ') - }) - - test('Escape closes the typeahead first, cancels the run next, and closes the panel last', async ({page}) => { - test.setTimeout(180_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 expect(stop).toBeVisible({timeout: 30_000}) - - await input.click() - await input.pressSequentially('/config') - const listbox = page.getByRole('listbox', {name: 'Commands'}) - await expect(listbox.getByRole('option', {name: '/config'})).toBeVisible({timeout: 10_000}) - - await page.keyboard.press('Escape') - await expect(listbox).toBeHidden({timeout: 10_000}) - await expect(input).toHaveText('/config') - await expect(stop).toBeVisible() - await expect(panel(page)).toBeVisible() - - await page.keyboard.press('Escape') - await expect(stop).toBeHidden({timeout: 30_000}) - await expect(panel(page)).toBeVisible() - } finally { - suite.kit().harness.script.release() - } - - await page.keyboard.press('Escape') - await expect(panel(page)).toBeHidden({timeout: 30_000}) - }) - - test('a failed send restores the full draft into the composer', async ({page}) => { - test.setTimeout(90_000) - 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() - - await expect(page.getByRole('alert', {name: 'the run collapsed'})).toBeVisible({timeout: 30_000}) - await expect(input).toHaveText('bring me back') - }) - - test('a reload restores the draft as plain directive text with the caret at the end', async ({page}) => { - test.setTimeout(180_000) - const sessionId = await openComposer(page) - const input = composer(page) - - await input.pressSequentially('ship ') - await input.pressSequentially('/config') - await pickSuggestion(page, 'Commands', '/config') - await waitForDraftWrite(sessionId, 'ship /config ') - - await page.reload({waitUntil: 'domcontentloaded'}) - const restored = composer(page) - await expect(restored).toHaveText('ship /config ', {timeout: 30_000}) - - await page.keyboard.type('!') - await expect(restored).toHaveText('ship /config !') - }) - - test('a reload restores the caret where the draft left it, not at the end', async ({page}) => { - test.setTimeout(90_000) - const sessionId = await openComposer(page) - const input = composer(page) - - await input.pressSequentially('hello world') - await waitForDraftWrite(sessionId, 'hello world') - await expect(input).toBeFocused() - for (let step = 0; step < 6; step += 1) await page.keyboard.press('ArrowLeft') - await input.pressSequentially('X') - await expect(input).toHaveText('helloX world') - await waitForDraftWrite(sessionId, 'helloX world') - - await page.reload({waitUntil: 'domcontentloaded'}) - const restored = composer(page) - await expect(restored).toHaveText('helloX world', {timeout: 30_000}) - await expect(restored).toBeFocused() - - await page.keyboard.type('Y') - await expect(restored).toHaveText('helloXY world') - }) - - test('Enter during IME composition never submits; Enter after the commit sends the composed text', async ({ - page: fixturePage, - }) => { - test.setTimeout(90_000) - const page = fixturePage - const wire = watchChatWire(page) - 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 expect(input).toHaveText(/hello/) - - await cdp.send('Input.insertText', {text: 'ん'}) - await expect(input).toHaveText('helloん') - const sent = wire.nextTurn().then((turn) => turn.content) - await page.keyboard.press('Enter') - expect(await sent).toBe('helloん') - - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expect(page.getByText('helloん', {exact: true})).toBeVisible() - }) - - test('the send button submits the visible draft including pending composition text', async ({page: fixturePage}) => { - test.setTimeout(90_000) - const page = fixturePage - const wire = watchChatWire(page) - 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 expect(input).toHaveText('committed draftか') - const sent = wire.nextTurn().then((turn) => turn.content) - await page.getByRole('button', {name: 'Send message'}).click() - expect(await sent).toBe('committed draftか') - - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expect(page.getByText('committed draftか', {exact: true})).toBeVisible() - }) -}) diff --git a/packages/embed/tests/e2e/composer-trigger-menu.it.test.ts b/packages/embed/tests/e2e/composer-trigger-menu.it.test.ts deleted file mode 100644 index c3f0fd562c..0000000000 --- a/packages/embed/tests/e2e/composer-trigger-menu.it.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import {expect, test, type Locator, type Page} from '@playwright/test' -import recorderServer from '@conciv/extension-recorder' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' - -const LONG_LIST_SIZE = 60 - -const longCommands = Array.from({length: LONG_LIST_SIZE}, (_unused, position) => ({ - name: `task-${String(position).padStart(2, '0')}`, - description: `Run the number ${position} maintenance routine for the active session`, -})) - -const suite = setupWidgetSuite({ - text: 'Trigger menu reply', - extensions: [recorderServer], - commands: [ - {name: 'compact', description: 'Compact the conversation'}, - {name: 'config', description: 'Open configuration'}, - {name: 'mcp__probe__connect', description: 'Connect the probe server'}, - {name: 'plugins:codeowners', description: 'List the code owners'}, - ...longCommands, - ], -}) - -const composer = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) -const commandMenu = (page: Page) => page.getByRole('listbox', {name: 'Commands'}) -const toolMenu = (page: Page) => page.getByRole('listbox', {name: 'Tools'}) - -async function openComposer(page: Page): Promise { - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - const input = composer(page) - await input.click() - await expect(input).toHaveText('') -} - -async function expectActiveOption(page: Page, option: Locator): Promise { - await expect(option).toBeVisible({timeout: 10_000}) - await expect(option).toHaveAttribute('id', /.+/, {timeout: 10_000}) - const optionId = await option.getAttribute('id') - if (!optionId) throw new Error('the highlighted option rendered without an id') - await expect(composer(page)).toHaveAttribute('aria-activedescendant', optionId, {timeout: 10_000}) -} - -test.describe('the composer trigger menu inside the live widget panel', () => { - test('groups commands by source with a visible header and a description per command', async ({page}) => { - test.setTimeout(90_000) - await openComposer(page) - await composer(page).pressSequentially('/co') - - const menu = commandMenu(page) - await expect(menu.getByRole('option', {name: '/compact'})).toBeVisible({timeout: 10_000}) - await expect(menu.getByRole('group', {name: 'Commands'})).toBeVisible() - await expect(menu.getByRole('group', {name: 'MCP'})).toBeVisible() - await expect(menu.getByRole('group', {name: 'Plugins'})).toBeVisible() - await expect(menu.getByRole('option', {name: '/compact'})).toHaveAccessibleDescription('Compact the conversation') - await expect(menu.getByRole('option', {name: '/mcp__probe__connect'})).toHaveAccessibleDescription( - 'Connect the probe server', - ) - await expect(menu.getByText('Compact the conversation')).toBeVisible() - }) - - test('moves the highlight with the arrow keys and commits the highlighted command with Enter', async ({page}) => { - test.setTimeout(240_000) - 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 expect(menu).toBeHidden({timeout: 10_000}) - await expect(input).toHaveText('/config ') - }) - - test('keeps the highlighted option inside the panel viewport while arrowing down a long list', async ({page}) => { - test.setTimeout(120_000) - 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 expect(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 expect(target).toBeInViewport() - await expect(first).not.toBeInViewport() - - await page.keyboard.press('Enter') - await expect(composer(page)).toHaveText('/task-30 ') - }) - - test('groups tools in the mention menu and commits the highlighted tool with Enter', async ({page}) => { - test.setTimeout(180_000) - 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 expect(menu.getByRole('group', {name: 'recorder'})).toBeVisible() - await expect(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 expect(menu).toBeHidden({timeout: 10_000}) - await expect(input).toHaveText('@recording_stop ') - }) - - test('never hands the keyboard to the menu: Tab closes it and the next keystroke still edits the composer', async ({ - page, - }) => { - test.setTimeout(120_000) - 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 expect(menu).toBeHidden({timeout: 10_000}) - await expect(input).toBeFocused() - - await input.pressSequentially('x') - await expect(input).toHaveText('/cox') - }) -}) diff --git a/packages/embed/tests/e2e/connection-pool.it.test.ts b/packages/embed/tests/e2e/connection-pool.it.test.ts deleted file mode 100644 index 423fd1cbe5..0000000000 --- a/packages/embed/tests/e2e/connection-pool.it.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import {expect, test, type BrowserContext, type Page} from '@playwright/test' -import {httpRpcRequestUrls, rpcCallCursor, type RpcCallCursor} from '@conciv/extension-testkit/rpc-counts' -import {watchChatWire, type ChatWireWatch} from '@conciv/extension-testkit/chat-wire' -import {watchPushWire, type PushWireWatch} from '@conciv/extension-testkit/push-wire' -import {setupProxiedEmbedSuite} from './helpers/proxied-suite.js' - -const ASSISTANT_TEXT = 'Hello from conciv' -const SHARED_CONTEXT_TAB_COUNT = 6 -const MOUNT_TIMEOUT_MS = 20_000 - -const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT}) - -type Tab = {page: Page; calls: RpcCallCursor; wire: ChatWireWatch; push: PushWireWatch; httpRpcUrls: string[]} - -async function openTab(context: BrowserContext): Promise { - const page = await context.newPage() - const {urls} = httpRpcRequestUrls(page) - const calls = rpcCallCursor(page) - const wire = watchChatWire(page) - const push = watchPushWire(page) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - return {page, calls, wire, push, httpRpcUrls: urls} -} - -async function openPanel(page: Page): Promise { - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toBeVisible({ - timeout: MOUNT_TIMEOUT_MS, - }) -} - -async function sendTurn(page: Page, text: string, expectedReplies: number): Promise { - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(text) - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(expectedReplies, {timeout: MOUNT_TIMEOUT_MS}) -} - -test.describe('six widget tabs sharing one browserContext connection pool (the per-test context fixture, not newPage, because the shared-context http connection limit is exactly what this gate measures)', () => { - test('holds one push socket per tab with rpc over http, and the sixth tab still chats', async ({context}) => { - test.setTimeout(180_000) - const tabs: Tab[] = [] - for (let index = 0; index < SHARED_CONTEXT_TAB_COUNT; index += 1) tabs.push(await openTab(context)) - - const lastTab = tabs[SHARED_CONTEXT_TAB_COUNT - 1] - if (!lastTab) throw new Error('expected six tabs') - for (const tab of tabs) await expect.poll(() => tab.push.liveSockets(), {timeout: MOUNT_TIMEOUT_MS}).toBe(1) - for (const tab of tabs.slice(0, SHARED_CONTEXT_TAB_COUNT - 1)) expect(tab.wire.liveSockets()).toBe(0) - - await openPanel(lastTab.page) - await sendTurn(lastTab.page, 'hi there', 1) - - for (const tab of tabs) expect(tab.calls.socketsSince()).toBe(0) - for (const tab of tabs) expect(tab.httpRpcUrls.length).toBeGreaterThan(0) - for (const tab of tabs) expect(tab.push.liveSockets()).toBe(1) - for (const tab of tabs) expect(tab.push.opened()).toBe(1) - expect(lastTab.wire.liveSockets()).toBe(1) - }) - - test('settles the chatting tab on exactly one live chat socket beside its push socket', async ({context}) => { - test.setTimeout(180_000) - const tab = await openTab(context) - - await openPanel(tab.page) - await sendTurn(tab.page, 'hi there', 1) - - expect(tab.wire.liveSockets()).toBe(1) - expect(tab.push.liveSockets()).toBe(1) - expect(tab.push.opened()).toBe(1) - }) -}) diff --git a/packages/embed/tests/e2e/create-conciv.it.test.ts b/packages/embed/tests/e2e/create-conciv.it.test.ts deleted file mode 100644 index 5146ea9a26..0000000000 --- a/packages/embed/tests/e2e/create-conciv.it.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import {expect, test, type Page, type WebSocket as PageWebSocket} from '@playwright/test' -import {watchChatWire} from '@conciv/extension-testkit/chat-wire' -import {CHAT_WS_PATH} from '@conciv/protocol/chat-types' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {handleHostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {mountHandle, remountHandle, unmountHandle} from './helpers/handle.js' -import {chatBox, openChatPanel, sendChatMessage} from './helpers/chat.js' - -const ASSISTANT_TEXT = 'Hello from conciv' - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeEach(async () => { - kit = await bootEmbedKit({text: ASSISTANT_TEXT}) - host = await serveHost(() => handleHostPage()) -}) - -test.afterEach(async () => { - await host.close() - await kit.cleanup() -}) - -async function openPage(page: Page): Promise { - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - return page -} - -const fab = (page: Page) => page.getByRole('button', {name: 'Open conciv chat'}) - -const SOCKET_CLOSE_TIMEOUT_MS = 5_000 - -function closedWithin(socket: PageWebSocket, timeoutMs: number): Promise { - return new Promise((resolve) => { - const timer = setTimeout(() => resolve(false), timeoutMs) - socket.on('close', () => { - clearTimeout(timer) - resolve(true) - }) - }) -} - -function trackChatSockets(page: Page): {last: () => PageWebSocket | undefined} { - const seen: PageWebSocket[] = [] - page.on('websocket', (socket) => { - if (socket.url().includes(CHAT_WS_PATH)) seen.push(socket) - }) - return {last: () => seen.at(-1)} -} - -test.describe('createConciv lifecycle', () => { - test('mounts, unmounts, and remounts the widget', async ({page}) => { - test.setTimeout(120_000) - await openPage(page) - await mountHandle(page, kit.base) - await expect(fab(page)).toBeVisible({timeout: 30_000}) - await unmountHandle(page) - await expect(fab(page)).toHaveCount(0, {timeout: 30_000}) - await remountHandle(page) - await expect(fab(page)).toBeVisible({timeout: 30_000}) - }) - - test('threads the mounted api base to extension surfaces when the host page has no conciv-api-base meta', async ({ - page, - }) => { - await openPage(page) - await mountHandle(page, kit.base) - const probe = page.getByRole('status', {name: 'host api base probe'}) - await expect(probe).toHaveText(kit.base, {timeout: 30_000}) - }) - - test('a second mount on an already-mounted handle is a no-op', async ({page}) => { - await openPage(page) - 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 expect(fab(page)).toHaveCount(1, {timeout: 30_000}) - expect(await fab(page).count()).toBe(1) - }) - - test('unmount during mount leaves nothing behind', async ({page}) => { - await openPage(page) - 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 expect(fab(page)).toHaveCount(0, {timeout: 30_000}) - expect(await page.evaluate(() => document.querySelector('[data-conciv-root]') === null)).toBe(true) - }) - - test('restores the host __TSR_ROUTER__ global on unmount', async ({page}) => { - await openPage(page) - await page.evaluate(() => { - Reflect.set(window, '__TSR_ROUTER__', {hostSentinel: true}) - }) - await mountHandle(page, kit.base) - await expect(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) - }) - - test('unmounts cleanly with an open panel and a completed turn', async ({page}) => { - test.setTimeout(120_000) - await openPage(page) - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - await mountHandle(page, kit.base) - await fab(page).click() - await expect(chatBox(page)).toBeVisible({timeout: 30_000}) - await chatBox(page).fill('hello') - await chatBox(page).press('Enter') - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await unmountHandle(page) - await expect(fab(page)).toHaveCount(0, {timeout: 30_000}) - expect(pageErrors).toEqual([]) - }) - - test('closes the tab chat websocket on unmount and dials a fresh one on remount', async ({page}) => { - test.setTimeout(180_000) - const wire = watchChatWire(page) - const sockets = trackChatSockets(page) - await openPage(page) - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - await mountHandle(page, kit.base) - await openChatPanel(page) - await sendChatMessage(page, 'before the unmount') - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - - const socket = sockets.last() - if (!socket) throw new Error('the first turn opened no chat websocket') - const closed = closedWithin(socket, SOCKET_CLOSE_TIMEOUT_MS) - await unmountHandle(page) - await expect(fab(page)).toHaveCount(0, {timeout: 30_000}) - expect(await closed).toBe(true) - - await remountHandle(page) - await expect(chatBox(page)).toBeVisible({timeout: 30_000}) - const remounted = wire.nextTurn() - await sendChatMessage(page, 'after the remount') - expect((await remounted).transport).toBe('websocket') - expect(pageErrors).toEqual([]) - }) -}) diff --git a/packages/embed/tests/e2e/dead-engine-boot.it.test.ts b/packages/embed/tests/e2e/dead-engine-boot.it.test.ts deleted file mode 100644 index 9f529b1b1d..0000000000 --- a/packages/embed/tests/e2e/dead-engine-boot.it.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import {expect, test} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage, reserveDeadPort} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {proxyTo, type ProxyCore} from '../helpers/proxy.js' - -const ASSISTANT_TEXT = 'Recovered from a dead boot' -const MOUNT_TIMEOUT_MS = 30_000 - -let kit: EmbedKit - -test.beforeAll(async () => { - kit = await bootEmbedKit({text: ASSISTANT_TEXT}) -}) - -test.afterAll(async () => { - await kit.cleanup() -}) - -test.describe('the router error screen surfaces a dead engine at boot and Retry recovers it', () => { - test('FAB click against a connection-refused base shows our error screen, then Retry recovers once the engine is reachable', async ({ - page, - }) => { - test.setTimeout(90_000) - const dead = await reserveDeadPort() - const host = await serveHost(() => hostPage({apiBase: dead.base, widget: '{"quickTerminal":false}'})) - let proxy: ProxyCore | null = null - try { - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - - const errorScreen = page.getByRole('alert').filter({hasText: /couldn.t reach the engine/}) - await expect(errorScreen).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - - proxy = await proxyTo(kit.base, {port: dead.port}) - - await errorScreen.getByRole('button', {name: 'Retry'}).click() - - const composer = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await expect(composer).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - await composer.fill('hi there') - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - } finally { - await host.close() - if (proxy) await proxy.close() - } - }) -}) diff --git a/packages/embed/tests/e2e/draft-selection.it.test.ts b/packages/embed/tests/e2e/draft-selection.it.test.ts deleted file mode 100644 index 202eb949e8..0000000000 --- a/packages/embed/tests/e2e/draft-selection.it.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {expect, test} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanelOnNewSession} from './helpers/panel.js' -import {untilPanelDraft} from './helpers/drafts.js' - -const suite = setupWidgetSuite() - -test.describe('draft persistence carries the caret offsets', () => { - test('persists the draft text with the caret position after the debounce', async ({page}) => { - test.setTimeout(90_000) - const sessionId = await openPanelOnNewSession(page, suite) - - 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') - await input.pressSequentially('say ') - await untilPanelDraft(suite.kit(), sessionId, (draft) => draft.text === 'say hello!') - - expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({ - text: 'say hello!', - selectionStart: 4, - selectionEnd: 4, - }) - }) -}) diff --git a/packages/embed/tests/e2e/draft-send-remount.it.test.ts b/packages/embed/tests/e2e/draft-send-remount.it.test.ts deleted file mode 100644 index d4c31fcfc9..0000000000 --- a/packages/embed/tests/e2e/draft-send-remount.it.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import {expect, test} from '@playwright/test' -import {until} from '@conciv/harness-testkit/until' -import {setupWidgetSuite, type WidgetSuite} from './helpers/suite.js' -import {openPanelOnNewSession} from './helpers/panel.js' - -const ASSISTANT_TEXT = 'Reply to the message sent before the reload' -const USER_TEXT = 'a message sent right before the reload' -const PENDING_DRAFT_WRITE_MS = 350 -const RESURRECTION_WINDOW_MS = 2_000 - -const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) - -function sentTextReappearsAsDraft(widget: WidgetSuite, sessionId: string): Promise { - return until(async () => (await widget.kit().rpc.drafts.get({sessionId}))?.text === USER_TEXT, { - hangGuardMs: RESURRECTION_WINDOW_MS, - intervalMs: 25, - }).then( - () => true, - () => false, - ) -} - -test.describe('a sent message never comes back as a draft', () => { - test('leaves the composer empty when the panel reloads right after the send', async ({page}) => { - test.setTimeout(240_000) - const sessionId = await openPanelOnNewSession(page, suite) - - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.fill(USER_TEXT) - await page.waitForTimeout(PENDING_DRAFT_WRITE_MS) - - await page.getByRole('button', {name: 'Send message'}).click() - const reappeared = await sentTextReappearsAsDraft(suite, sessionId) - await page.reload({waitUntil: 'domcontentloaded'}) - - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - - await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toHaveText('', {timeout: 30_000}) - await expect(page.getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - expect(reappeared).toBe(false) - }) -}) diff --git a/packages/embed/tests/e2e/draft-write-churn.it.test.ts b/packages/embed/tests/e2e/draft-write-churn.it.test.ts deleted file mode 100644 index f6349c5f75..0000000000 --- a/packages/embed/tests/e2e/draft-write-churn.it.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import {expect, test} from '@playwright/test' -import {rpcCallCursor} from '@conciv/extension-testkit/rpc-counts' -import {setupWidgetSuite, type WidgetSuite} from './helpers/suite.js' -import {openPanelOnNewSession} from './helpers/panel.js' - -const ASSISTANT_TEXT = 'Reply that no test waits for' -const TYPED_TEXT = 'the only draft this pane ever stores' -const DRAFT_WRITE_TIMEOUT_MS = 15_000 - -const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) - -async function storedDraftText(widget: WidgetSuite, sessionId: string): Promise { - const row = await widget.kit().rpc.drafts.get({sessionId}) - return row?.text ?? null -} - -test.describe('an empty composer stores nothing', () => { - test('writes the first draft only once the user types, never on mount', async ({page}) => { - test.setTimeout(120_000) - const drafts = rpcCallCursor(page) - const sessionId = await openPanelOnNewSession(page, suite) - - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(TYPED_TEXT) - await expect.poll(() => storedDraftText(suite, sessionId), {timeout: DRAFT_WRITE_TIMEOUT_MS}).toBe(TYPED_TEXT) - - expect(drafts.startedSince(['drafts', 'set'])).toBe(1) - }) -}) diff --git a/packages/embed/tests/e2e/element-capture.it.test.ts b/packages/embed/tests/e2e/element-capture.it.test.ts deleted file mode 100644 index 1db13b6fca..0000000000 --- a/packages/embed/tests/e2e/element-capture.it.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import type {SessionCaptures} from '@conciv/protocol/element-capture-types' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {openPagePlaneHost} from './helpers/page-plane-host.js' -import {openPanel} from './helpers/panel.js' - -const PASSWORD = 'hunter2-must-never-leave-the-page' - -const HOST_BODY = ` - -
- -

original prose

- -
-` - -let kit: EmbedKit -let host: {base: string; close: () => Promise} -let sessionId: string - -test.beforeAll(async () => { - kit = await bootEmbedKit() - sessionId = await kit.session() - host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: HOST_BODY})) -}) - -test.afterAll(async () => { - await host.close() - await kit.cleanup() -}) - -const openHostPage = (page: Page): Promise => openPagePlaneHost(page, host.base) - -function rowIdentities(stored: SessionCaptures): string[] { - return stored.captures.map((row) => `${row.toolCallId}:${row.kind}:${JSON.stringify(row.capture)}`).toSorted() -} - -async function sendAndSettle(page: Page, message: string): Promise { - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(message) - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) -} - -test.describe('a page tool run through the widget stores a frozen picture of the element it touched', () => { - test('keeps the pre-edit element after the page flips its theme and deletes the node', async ({page}) => { - test.setTimeout(90_000) - await openHostPage(page) - await kit.callTool('page_settext', {selector: '#prose', text: 'rewritten by the agent'}, sessionId) - - await page.evaluate(() => { - document.querySelector('#panel')?.classList.replace('theme-light', 'theme-dark') - document.querySelector('#prose')?.remove() - }) - - const stored: SessionCaptures = await kit.rpc.captures.list({sessionId}) - const edit = stored.captures.filter((row) => row.capture.descriptor.selectorPath.includes('prose')) - expect(edit.map((row) => row.kind).toSorted()).toEqual(['after', 'before']) - const before = edit.find((row) => row.kind === 'before') - const after = edit.find((row) => row.kind === 'after') - expect(before?.capture.descriptor.accessibleName).toBe('original prose') - expect(after?.capture.descriptor.accessibleName).toBe('rewritten by the agent') - expect(JSON.stringify(before?.capture.node)).toContain('theme-light') - expect(JSON.stringify(before?.capture.node)).not.toContain('theme-dark') - expect(JSON.stringify(before?.capture.node)).toContain('data-rr-target') - expect(JSON.stringify(after?.capture.node)).toContain('theme-light') - expect(JSON.stringify(after?.capture.node)).not.toContain('theme-dark') - const cssBundleId = before?.capture.cssBundleId - expect(cssBundleId === undefined ? '' : stored.cssBundles[cssBundleId]).toContain('.panel .cta') - }) - - test('never lets a password value reach the stored capture or the tool result', async ({page}) => { - test.setTimeout(90_000) - await openHostPage(page) - const result = await kit.callTool('page_fill', {selector: '#secret', value: 'typed by the agent'}, sessionId) - const stored: SessionCaptures = await kit.rpc.captures.list({sessionId}) - const secretCaptures = stored.captures.filter((row) => row.capture.descriptor.selectorPath.includes('secret')) - expect(secretCaptures.map((row) => row.kind).toSorted()).toEqual(['after']) - for (const row of secretCaptures) expect(JSON.stringify(row.capture)).not.toContain(PASSWORD) - expect(JSON.stringify(result)).not.toContain(PASSWORD) - expect(JSON.stringify(stored)).not.toContain(PASSWORD) - }) - - test('hands the harness a result with no capture in it', async ({page}) => { - test.setTimeout(90_000) - await openHostPage(page) - const result = await kit.callTool('page_click', {selector: '#cta'}, sessionId) - expect(JSON.stringify(result)).not.toContain('cssBundleId') - expect(JSON.stringify(result)).not.toContain('selectorPath') - expect(JSON.stringify(result)).not.toContain('data-rr-target') - }) - - test('takes no capture for a read verb', async ({page}) => { - test.setTimeout(90_000) - await openHostPage(page) - const before: SessionCaptures = await kit.rpc.captures.list({sessionId}) - await kit.callTool('page_text', {selector: '#cta'}, sessionId) - const after: SessionCaptures = await kit.rpc.captures.list({sessionId}) - expect(rowIdentities(after)).toEqual(rowIdentities(before)) - }) - - test('renders a page verb run through real code mode as one aggregated session card fed by the capture pipeline', async ({ - page, - }) => { - test.setTimeout(180_000) - await openHostPage(page) - await openPanel(page) - kit.harness.script.scriptToolCall('execute_typescript', { - typescriptCode: "await external_page_settext({selector: '#prose', text: 'rendered through the pipeline'})", - }) - await sendAndSettle(page, 'rewrite the prose through code mode') - const sessionCard = page.getByRole('button', {name: /Edited the page/}) - await expect(sessionCard).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('button', {name: /Set the text/})).toHaveCount(0) - await sessionCard.click() - const dialog = page.getByRole('dialog', {name: 'conciv chat agent'}) - const stepTarget = dialog.getByText('rendered through the pipeline', {exact: true}) - await expect(stepTarget).toBeVisible({timeout: 30_000}) - await dialog.getByRole('button', {name: 'Script'}).click() - await expect(dialog.getByText(/external_page_settext/).first()).toBeVisible({timeout: 30_000}) - }) -}) diff --git a/packages/embed/tests/e2e/embed.it.test.ts b/packages/embed/tests/e2e/embed.it.test.ts index f1cd7150a1..2b34af9132 100644 --- a/packages/embed/tests/e2e/embed.it.test.ts +++ b/packages/embed/tests/e2e/embed.it.test.ts @@ -1,296 +1,3225 @@ -import {expect, test, type Locator, type Page} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' +import { + expect, + test, + type Locator, + type Page, + type BrowserContext, + type WebSocket as PageWebSocket, +} from '@playwright/test' +import { + bootEmbedKit, + type EmbedKit, + hostPage, + openPanel, + sendMessage, + setupWidgetSuite, + openPanelOnNewSession, + untilPanelDraft, + setupProxiedEmbedSuite, + handleHostPage, + mountHandle, + remountHandle, + unmountHandle, + chatBox, + openChatPanel, + sendChatMessage, + reserveDeadPort, + proxyTo, + type ProxyCore, + type WidgetSuite, + openPagePlaneHost, + sendHeldTurn, + captureNativePosts, + installNativeStub, + type NativeBridge, + switchToSessionByTitle, + openHostWithHandle, + rebindHandle, + chatLog, +} from '../helpers.js' import {serveHost} from '@conciv/extension-testkit/serve-host' import {currentHref} from '@conciv/extension-testkit/navigation-state' import {until} from '@conciv/harness-testkit/until' -import {openPanel, sendMessage} from './helpers/panel.js' - -const ASSISTANT_TEXT = 'Hello from conciv' -const HARNESS_MODELS = [ - {id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5'}, - {id: 'claude-opus-4-1', name: 'Claude Opus 4.1'}, -] -const PHONE_VIEWPORT = {width: 393, height: 800} -const SHEET_INTERIOR_CLIP = {x: 40, y: 150, width: 313, height: 120} -const HOST_HEADING = 'Deployment checklist' -const LONG_HOST_BODY = `

Host site

${Array.from( - {length: 60}, - (_unused, index) => `

Host paragraph ${index} that the reader is scrolled through.

`, -).join('')}

${HOST_HEADING}

${Array.from( - {length: 60}, - (_unused, index) => `

Host paragraph ${index + 60} below the heading.

`, -).join('')}` - -let kit: EmbedKit -let host: {base: string; close: () => Promise} -let longHost: {base: string; close: () => Promise} - -test.beforeEach(async () => { - kit = await bootEmbedKit({text: ASSISTANT_TEXT, models: HARNESS_MODELS}) - host = await serveHost((url) => - hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', backdrop: url.searchParams.get('backdrop')}), - ) - longHost = await serveHost(() => - hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: LONG_HOST_BODY}), - ) -}) - -test.afterEach(async () => { - await host.close() - await longHost.close() - await kit.cleanup() -}) - -async function openPage(page: Page): Promise { - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - return page -} - -function latestTrace(page: Page): Locator { - return page.getByRole('list', {name: 'Execution trace'}).last() -} - -async function sendAndSettleWithTraceOpen(page: Page, message: string): Promise { - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(message) - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) - await expect(page.getByRole('button', {name: /Hide trace$/}).last()).toBeVisible({timeout: 30_000}) -} - -test.describe('embed boots the conciv app against a real core', () => { - test('fab close is a shutter: reopening restores the same view without touching history', async ({page}) => { - test.setTimeout(240_000) - await openPage(page) +import type {Grab} from '@conciv/grab' +import { + GRAB_FILE_NAME, + GRAB_MIME, + grabToPayload, + parseGrabPayload, + type GrabPayload, +} from '@conciv/grab/grab-attachment' +import {watchChatWire, type ChatWireWatch} from '@conciv/extension-testkit/chat-wire' +import recorderServer, {type RecorderRouter} from '@conciv/extension-recorder' +import {httpRpcRequestUrls, rpcCallCursor, type RpcCallCursor} from '@conciv/extension-testkit/rpc-counts' +import {watchPushWire, type PushWireWatch} from '@conciv/extension-testkit/push-wire' +import {CHAT_WS_PATH, HarnessSessionId} from '@conciv/protocol/chat-types' +import type {SessionCaptures} from '@conciv/protocol/element-capture-types' +import {holdRpcCalls, failRpcCalls, gateRpcCalls, type RpcGate} from '@conciv/extension-testkit/rpc-fault' +import {fileURLToPath} from 'node:url' +import {bootCoreKit, type CoreKit} from '@conciv/extension-testkit/core-kit' +import type {PageToNativeMessage} from '@conciv/extension-ios/bridge' +import {Buffer} from 'node:buffer' +import type {DraftRow} from '@conciv/contract' +import {watchRpcWire} from '@conciv/extension-testkit/rpc-wire' +import {z} from 'zod' +import {completeConnectHandshake} from '@conciv/extension-testkit/connect-handshake' +import {makeExtRpcClient} from '@conciv/extension' + +test.describe('embed boot', () => { + const ASSISTANT_TEXT = 'Hello from conciv' + const HARNESS_MODELS = [ + {id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5'}, + {id: 'claude-opus-4-1', name: 'Claude Opus 4.1'}, + ] + const PHONE_VIEWPORT = {width: 393, height: 800} + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit({text: ASSISTANT_TEXT, models: HARNESS_MODELS}) + host = await serveHost((url) => + hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', backdrop: url.searchParams.get('backdrop')}), + ) + }) + + test.afterEach(async () => { + await host.close() + await kit.cleanup() + }) + + async function openPage(page: Page): Promise { + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + return page + } + + function latestTrace(page: Page): Locator { + return page.getByRole('list', {name: 'Execution trace'}).last() + } + + async function sendAndSettleWithTraceOpen(page: Page, message: string): Promise { + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(message) + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) + await expect(page.getByRole('button', {name: /Hide trace$/}).last()).toBeVisible({timeout: 30_000}) + } + + test.describe('embed boots the conciv app against a real core', () => { + test('fab close is a shutter: reopening restores the same view without touching history', async ({page}) => { + test.setTimeout(240_000) + await openPage(page) + await openPanel(page) + await page.getByRole('tab', {name: 'Terminal'}).click() + await expect(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { + timeout: 30_000, + }) + await until( + async () => { + const href = await currentHref(kit) + return href.includes('/terminal') && href.includes('open=true') + }, + {hangGuardMs: 30_000, intervalMs: 100}, + ) + await page.getByRole('button', {name: 'Minimize conciv chat'}).click() + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + await until(async () => !(await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expect(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { + timeout: 30_000, + }) + await until(async () => (await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) + const persisted = await kit.rpc.navigation.get() + expect(persisted?.entries.filter((entry) => entry.href.includes('/panel/'))).toHaveLength(1) + }) + + test('a reload restores the panel open on the same view', async ({page, context}) => { + test.setTimeout(180_000) + const first = await openPage(page) + await openPanel(first) + await first.getByRole('tab', {name: 'Terminal'}).click() + await until(async () => (await currentHref(kit)).includes('/terminal'), {hangGuardMs: 30_000, intervalMs: 100}) + expect(await currentHref(kit)).toMatch(/\/terminal\?.*open=true/) + await first.close() + const second = await openPage(await context.newPage()) + await expect(second.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expect(second.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { + timeout: 30_000, + }) + }) + + test('a reload after closing the panel boots shut', async ({page, context}) => { + test.setTimeout(180_000) + const first = await openPage(page) + await openPanel(first) + await until(async () => (await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) + expect(await currentHref(kit)).toContain('open=true') + await first.getByRole('button', {name: 'Minimize conciv chat'}).click() + await until(async () => !(await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) + expect(await currentHref(kit)).not.toContain('open=true') + await first.close() + const second = await openPage(await context.newPage()) + await expect(second.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) + expect(await second.getByRole('dialog', {name: 'conciv chat agent'}).count()).toBe(0) + }) + + test('renders the fab instantly and opens the panel', async ({page}) => { + test.setTimeout(120_000) + await openPage(page) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) + await openPanel(page) + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible() + }) + + test('sends a message and renders the assistant reply from the fake harness', async ({page}) => { + test.setTimeout(120_000) + await openPage(page) + await openPanel(page) + await sendMessage(page, 'hi there', ASSISTANT_TEXT) + }) + + test('shows Stop instead of Send while a run is streaming; typing stays enabled', async ({page}) => { + test.setTimeout(180_000) + await openPage(page) + 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 expect(page.getByRole('button', {name: 'Stop generating'})).toBeVisible({timeout: 30_000}) + await input.fill('still typing while it runs') + await expect(input).toHaveText('still typing while it runs') + kit.harness.script.release() + await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) + }) + + test('Escape closes the panel back to the fab', async ({page}) => { + test.setTimeout(120_000) + await openPage(page) + await openPanel(page) + await page.getByRole('textbox', {name: 'Message the conciv agent'}).press('Escape') + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible() + }) + + test('renders the conciv_ui blocking card from the tool part and answers via uiReply', async ({page}) => { + test.setTimeout(180_000) + await openPage(page) + 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 expect(page.getByText('Proceed with the change?', {exact: true})).toBeVisible({timeout: 30_000}) + await page.getByRole('button', {name: 'Approve'}).click() + await expect(page.getByRole('status').getByText('yes')).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('button', {name: 'Approve'})).toBeHidden({timeout: 30_000}) + }) + + test('renders catalog and code-mode parts without blanking the transcript', async ({page}) => { + test.setTimeout(120_000) + await openPage(page) + 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 expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + const announced = await page.getByRole('alert').allTextContents() + expect(announced.every((text) => text.trim() === '')).toBe(true) + }) + + test('renders the new tool cards for results that do not match their payload schema', async ({page}) => { + test.setTimeout(240_000) + await openPage(page) + 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 sendAndSettleWithTraceOpen(page, 'run some code') + await expect(latestTrace(page).getByText('return 1').first()).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('button', {name: /exec return 1/})).toBeDisabled() + await sendAndSettleWithTraceOpen(page, 'now check the catalog') + await expect(latestTrace(page).getByText('Capability catalog')).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('button', {name: /Show trace$/})).toHaveCount(1) + await expect(input).toHaveText('') + const announced = await page.getByRole('alert').allTextContents() + expect(announced.every((text) => text.trim() === '')).toBe(true) + }) + }) + + test.describe('embed at a phone viewport', () => { + test.use({viewport: PHONE_VIEWPORT}) + + test('opens as a full-screen sheet with the launcher hidden and the composer reachable', async ({page}) => { + test.setTimeout(240_000) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await expect(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 expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) + }) + + test.describe('a narrower phone width', () => { + test.use({viewport: {width: 320, height: 800}}) + + test('keeps the single trailing button and the model menu reachable inside the sheet on a narrow phone while a run streams', async ({ + page, + }) => { + test.setTimeout(180_000) + 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'}) + const moreActions = page.getByRole('button', {name: 'More composer actions'}) + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill('a question that keeps running') + await send.click() + await expect(stop).toBeVisible({timeout: 30_000}) + await expect(send).toBeHidden() + await expect(moreActions).toBeInViewport({ratio: 1, timeout: 5_000}) + await expect(stop).toBeInViewport({ratio: 1, timeout: 5_000}) + await moreActions.click() + await expect(page.getByRole('menuitem', {name: /^Model: /}).first()).toBeVisible({timeout: 30_000}) + await page.keyboard.press('Escape') + kit.harness.script.release() + await expect(stop).toBeHidden({timeout: 30_000}) + await expect(send).toBeVisible() + await expect(send).toBeInViewport({ratio: 1, timeout: 5_000}) + }) + }) + }) + + test.describe('embed settings', () => { + test('modal disabled renders no fab', async ({page}) => { + const disabledHost = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"modal": false}'})) + 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 disabledHost.close() + }) + }) +}) + +test.describe('chat send parts', () => { + const ASSISTANT_TEXT = 'Parts received' + const GRAB_TEXT = '

Payroll Deposit

at src/routes/index.tsx:12:9' + const MESSAGE_TEXT = 'what is wrong with this element' + + const GRAB: Grab = { + text: GRAB_TEXT, + snippet: '

Payroll Deposit

', + preview: {kind: 'dom', html: '

Payroll Deposit clone

', width: 200, height: 40}, + source: {componentName: 'Hero', filePath: 'src/routes/index.tsx', lineNumber: 12}, + rect: {x: 0, y: 0, width: 200, height: 40}, + } + + const GRAB_JSON = JSON.stringify(grabToPayload(GRAB)) + + const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) + + test.describe('a send that carries an attachment', () => { + test('reaches the chat transport as content parts the wire watcher reports without throwing', async ({page}) => { + test.setTimeout(120_000) + const wire = watchChatWire(page) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + + const addAttachment = page.getByRole('button', {name: 'Add an attachment'}) + await expect(addAttachment).toBeEnabled({timeout: 30_000}) + const opened = page.waitForEvent('filechooser', {timeout: 30_000}) + await addAttachment.click() + const chooser = await opened + await chooser.setFiles({name: GRAB_FILE_NAME, mimeType: GRAB_MIME, buffer: Buffer.from(GRAB_JSON)}) + await expect(page.getByRole('button', {name: 'Open grabbed element'})).toBeVisible({timeout: 30_000}) + + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(MESSAGE_TEXT) + const sent = wire.nextTurn() + await page.getByRole('button', {name: 'Send message'}).click() + + const frame = await sent + expect(frame.content).toEqual([ + {type: 'text', text: MESSAGE_TEXT}, + { + type: 'document', + source: {type: 'data', mimeType: GRAB_MIME, value: Buffer.from(GRAB_JSON).toString('base64')}, + }, + ]) + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + }) + }) +}) + +test.describe('composer rich input', () => { + const ASSISTANT_TEXT = 'Rich input reply' + + const suite = setupWidgetSuite({ + text: ASSISTANT_TEXT, + extensions: [recorderServer], + commands: [ + {name: 'compact', description: 'Compact the conversation'}, + {name: 'config', description: 'Open configuration'}, + ], + }) + + const composer = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) + const panel = (page: Page) => page.getByRole('dialog', {name: 'conciv chat agent'}) + + const waitForDraftWrite = (sessionId: string, fragment: string) => + untilPanelDraft(suite.kit(), sessionId, (draft) => draft.text.includes(fragment)) + + async function openComposer(page: Page): Promise { + const sessionId = await openPanelOnNewSession(page, suite) + const input = composer(page) + await input.click() + await expect(input).toHaveText('') + return sessionId + } + + async function pickSuggestion(page: Page, listName: string, optionName: string): Promise { + const listbox = page.getByRole('listbox', {name: listName}) + const option = listbox.getByRole('option', {name: optionName}) + await expect(option).toBeVisible({timeout: 10_000}) + await expect(option).toHaveAttribute('id', /.+/, {timeout: 10_000}) + const optionId = await option.getAttribute('id') + if (!optionId) throw new Error(`option "${optionName}" in "${listName}" rendered without an id`) + await expect(composer(page)).toHaveAttribute('aria-activedescendant', optionId, {timeout: 10_000}) + await page.keyboard.press('Enter') + await expect(listbox).toBeHidden({timeout: 10_000}) + } + + test.describe('the rich composer input in the live widget shadow DOM', () => { + test('types multiline text with slash and mention chips and submits the exact directive string', async ({ + page: fixturePage, + }) => { + test.setTimeout(180_000) + const page = fixturePage + const wire = watchChatWire(page) + 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 = wire.nextTurn().then((turn) => turn.content) + await page.getByRole('button', {name: 'Send message'}).click() + expect(await sent).toBe(expected) + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expect(input).toHaveText('') + }) + + test('backspace removes a selected command chip in two steps, never a partial directive', async ({page}) => { + test.setTimeout(120_000) + await openComposer(page) + const input = composer(page) + + await input.pressSequentially('/compact') + await pickSuggestion(page, 'Commands', '/compact') + await expect(input).toHaveText('/compact ') + + await page.keyboard.press('Backspace') + await expect(input).toHaveText('/compact') + + await page.keyboard.press('Backspace') + await expect(input).toHaveText('') + }) + + test('forward delete removes the chip ahead of the caret in one step', async ({page}) => { + test.setTimeout(120_000) + await openComposer(page) + const input = composer(page) + + await input.pressSequentially('/compact') + await pickSuggestion(page, 'Commands', '/compact') + await expect(input).toHaveText('/compact ') + + await page.keyboard.press('Home') + await input.pressSequentially('x') + await expect(input).toHaveText('x/compact ') + await page.keyboard.press('Delete') + await expect(input).toHaveText('x ') + }) + + test('Escape closes the typeahead first, cancels the run next, and closes the panel last', async ({page}) => { + test.setTimeout(180_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 expect(stop).toBeVisible({timeout: 30_000}) + + await input.click() + await input.pressSequentially('/config') + const listbox = page.getByRole('listbox', {name: 'Commands'}) + await expect(listbox.getByRole('option', {name: '/config'})).toBeVisible({timeout: 10_000}) + + await page.keyboard.press('Escape') + await expect(listbox).toBeHidden({timeout: 10_000}) + await expect(input).toHaveText('/config') + await expect(stop).toBeVisible() + await expect(panel(page)).toBeVisible() + + await page.keyboard.press('Escape') + await expect(stop).toBeHidden({timeout: 30_000}) + await expect(panel(page)).toBeVisible() + } finally { + suite.kit().harness.script.release() + } + + await page.keyboard.press('Escape') + await expect(panel(page)).toBeHidden({timeout: 30_000}) + }) + + test('a failed send restores the full draft into the composer', async ({page}) => { + test.setTimeout(90_000) + 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() + + await expect(page.getByRole('alert', {name: 'the run collapsed'})).toBeVisible({timeout: 30_000}) + await expect(input).toHaveText('bring me back') + }) + + test('a reload restores the draft as plain directive text with the caret at the end', async ({page}) => { + test.setTimeout(180_000) + const sessionId = await openComposer(page) + const input = composer(page) + + await input.pressSequentially('ship ') + await input.pressSequentially('/config') + await pickSuggestion(page, 'Commands', '/config') + await waitForDraftWrite(sessionId, 'ship /config ') + + await page.reload({waitUntil: 'domcontentloaded'}) + const restored = composer(page) + await expect(restored).toHaveText('ship /config ', {timeout: 30_000}) + + await page.keyboard.type('!') + await expect(restored).toHaveText('ship /config !') + }) + + test('a reload restores the caret where the draft left it, not at the end', async ({page}) => { + test.setTimeout(90_000) + const sessionId = await openComposer(page) + const input = composer(page) + + await input.pressSequentially('hello world') + await waitForDraftWrite(sessionId, 'hello world') + await expect(input).toBeFocused() + for (let step = 0; step < 6; step += 1) await page.keyboard.press('ArrowLeft') + await input.pressSequentially('X') + await expect(input).toHaveText('helloX world') + await waitForDraftWrite(sessionId, 'helloX world') + + await page.reload({waitUntil: 'domcontentloaded'}) + const restored = composer(page) + await expect(restored).toHaveText('helloX world', {timeout: 30_000}) + await expect(restored).toBeFocused() + + await page.keyboard.type('Y') + await expect(restored).toHaveText('helloXY world') + }) + + test('Enter during IME composition never submits; Enter after the commit sends the composed text', async ({ + page: fixturePage, + }) => { + test.setTimeout(90_000) + const page = fixturePage + const wire = watchChatWire(page) + 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 expect(input).toHaveText(/hello/) + + await cdp.send('Input.insertText', {text: 'ん'}) + await expect(input).toHaveText('helloん') + const sent = wire.nextTurn().then((turn) => turn.content) + await page.keyboard.press('Enter') + expect(await sent).toBe('helloん') + + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expect(page.getByText('helloん', {exact: true})).toBeVisible() + }) + + test('the send button submits the visible draft including pending composition text', async ({ + page: fixturePage, + }) => { + test.setTimeout(90_000) + const page = fixturePage + const wire = watchChatWire(page) + 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 expect(input).toHaveText('committed draftか') + const sent = wire.nextTurn().then((turn) => turn.content) + await page.getByRole('button', {name: 'Send message'}).click() + expect(await sent).toBe('committed draftか') + + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expect(page.getByText('committed draftか', {exact: true})).toBeVisible() + }) + }) +}) + +test.describe('composer trigger menu', () => { + const LONG_LIST_SIZE = 60 + + const longCommands = Array.from({length: LONG_LIST_SIZE}, (_unused, position) => ({ + name: `task-${String(position).padStart(2, '0')}`, + description: `Run the number ${position} maintenance routine for the active session`, + })) + + const suite = setupWidgetSuite({ + text: 'Trigger menu reply', + extensions: [recorderServer], + commands: [ + {name: 'compact', description: 'Compact the conversation'}, + {name: 'config', description: 'Open configuration'}, + {name: 'mcp__probe__connect', description: 'Connect the probe server'}, + {name: 'plugins:codeowners', description: 'List the code owners'}, + ...longCommands, + ], + }) + + const composer = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) + const commandMenu = (page: Page) => page.getByRole('listbox', {name: 'Commands'}) + const toolMenu = (page: Page) => page.getByRole('listbox', {name: 'Tools'}) + + async function openComposer(page: Page): Promise { + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) await openPanel(page) - await page.getByRole('tab', {name: 'Terminal'}).click() - await expect(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { - timeout: 30_000, - }) - await until( - async () => { - const href = await currentHref(kit) - return href.includes('/terminal') && href.includes('open=true') - }, - {hangGuardMs: 30_000, intervalMs: 100}, + const input = composer(page) + await input.click() + await expect(input).toHaveText('') + } + + async function expectActiveOption(page: Page, option: Locator): Promise { + await expect(option).toBeVisible({timeout: 10_000}) + await expect(option).toHaveAttribute('id', /.+/, {timeout: 10_000}) + const optionId = await option.getAttribute('id') + if (!optionId) throw new Error('the highlighted option rendered without an id') + await expect(composer(page)).toHaveAttribute('aria-activedescendant', optionId, {timeout: 10_000}) + } + + test.describe('the composer trigger menu inside the live widget panel', () => { + test('groups commands by source with a visible header and a description per command', async ({page}) => { + test.setTimeout(90_000) + await openComposer(page) + await composer(page).pressSequentially('/co') + + const menu = commandMenu(page) + await expect(menu.getByRole('option', {name: '/compact'})).toBeVisible({timeout: 10_000}) + await expect(menu.getByRole('group', {name: 'Commands'})).toBeVisible() + await expect(menu.getByRole('group', {name: 'MCP'})).toBeVisible() + await expect(menu.getByRole('group', {name: 'Plugins'})).toBeVisible() + await expect(menu.getByRole('option', {name: '/compact'})).toHaveAccessibleDescription('Compact the conversation') + await expect(menu.getByRole('option', {name: '/mcp__probe__connect'})).toHaveAccessibleDescription( + 'Connect the probe server', + ) + await expect(menu.getByText('Compact the conversation')).toBeVisible() + }) + + test('moves the highlight with the arrow keys and commits the highlighted command with Enter', async ({page}) => { + test.setTimeout(240_000) + 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 expect(menu).toBeHidden({timeout: 10_000}) + await expect(input).toHaveText('/config ') + }) + + test('keeps the highlighted option inside the panel viewport while arrowing down a long list', async ({page}) => { + test.setTimeout(120_000) + 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 expect(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 expect(target).toBeInViewport() + await expect(first).not.toBeInViewport() + + await page.keyboard.press('Enter') + await expect(composer(page)).toHaveText('/task-30 ') + }) + + test('groups tools in the mention menu and commits the highlighted tool with Enter', async ({page}) => { + test.setTimeout(180_000) + 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 expect(menu.getByRole('group', {name: 'recorder'})).toBeVisible() + await expect(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 expect(menu).toBeHidden({timeout: 10_000}) + await expect(input).toHaveText('@recording_stop ') + }) + + test('never hands the keyboard to the menu: Tab closes it and the next keystroke still edits the composer', async ({ + page, + }) => { + test.setTimeout(120_000) + 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 expect(menu).toBeHidden({timeout: 10_000}) + await expect(input).toBeFocused() + + await input.pressSequentially('x') + await expect(input).toHaveText('/cox') + }) + }) +}) + +test.describe('connection pool', () => { + const ASSISTANT_TEXT = 'Hello from conciv' + const SHARED_CONTEXT_TAB_COUNT = 6 + const MOUNT_TIMEOUT_MS = 20_000 + + const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT}) + + type Tab = {page: Page; calls: RpcCallCursor; wire: ChatWireWatch; push: PushWireWatch; httpRpcUrls: string[]} + + async function openTab(context: BrowserContext): Promise { + const page = await context.newPage() + const {urls} = httpRpcRequestUrls(page) + const calls = rpcCallCursor(page) + const wire = watchChatWire(page) + const push = watchPushWire(page) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + return {page, calls, wire, push, httpRpcUrls: urls} + } + + async function openPanel(page: Page): Promise { + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toBeVisible({ + timeout: MOUNT_TIMEOUT_MS, + }) + } + + async function sendTurn(page: Page, text: string, expectedReplies: number): Promise { + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(text) + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(expectedReplies, {timeout: MOUNT_TIMEOUT_MS}) + } + + test.describe('six widget tabs sharing one browserContext connection pool (the per-test context fixture, not newPage, because the shared-context http connection limit is exactly what this gate measures)', () => { + test('holds one push socket per tab with rpc over http, and the sixth tab still chats', async ({context}) => { + test.setTimeout(180_000) + const tabs: Tab[] = [] + for (let index = 0; index < SHARED_CONTEXT_TAB_COUNT; index += 1) tabs.push(await openTab(context)) + + const lastTab = tabs[SHARED_CONTEXT_TAB_COUNT - 1] + if (!lastTab) throw new Error('expected six tabs') + for (const tab of tabs) await expect.poll(() => tab.push.liveSockets(), {timeout: MOUNT_TIMEOUT_MS}).toBe(1) + for (const tab of tabs.slice(0, SHARED_CONTEXT_TAB_COUNT - 1)) expect(tab.wire.liveSockets()).toBe(0) + + await openPanel(lastTab.page) + await sendTurn(lastTab.page, 'hi there', 1) + + for (const tab of tabs) expect(tab.calls.socketsSince()).toBe(0) + for (const tab of tabs) expect(tab.httpRpcUrls.length).toBeGreaterThan(0) + for (const tab of tabs) expect(tab.push.liveSockets()).toBe(1) + for (const tab of tabs) expect(tab.push.opened()).toBe(1) + expect(lastTab.wire.liveSockets()).toBe(1) + }) + + test('settles the chatting tab on exactly one live chat socket beside its push socket', async ({context}) => { + test.setTimeout(180_000) + const tab = await openTab(context) + + await openPanel(tab.page) + await sendTurn(tab.page, 'hi there', 1) + + expect(tab.wire.liveSockets()).toBe(1) + expect(tab.push.liveSockets()).toBe(1) + expect(tab.push.opened()).toBe(1) + }) + }) +}) + +test.describe('create conciv', () => { + const ASSISTANT_TEXT = 'Hello from conciv' + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit({text: ASSISTANT_TEXT}) + host = await serveHost(() => handleHostPage()) + }) + + test.afterEach(async () => { + await host.close() + await kit.cleanup() + }) + + async function openPage(page: Page): Promise { + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + return page + } + + const fab = (page: Page) => page.getByRole('button', {name: 'Open conciv chat'}) + + const SOCKET_CLOSE_TIMEOUT_MS = 5_000 + + function closedWithin(socket: PageWebSocket, timeoutMs: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => resolve(false), timeoutMs) + socket.on('close', () => { + clearTimeout(timer) + resolve(true) + }) + }) + } + + function trackChatSockets(page: Page): {last: () => PageWebSocket | undefined} { + const seen: PageWebSocket[] = [] + page.on('websocket', (socket) => { + if (socket.url().includes(CHAT_WS_PATH)) seen.push(socket) + }) + return {last: () => seen.at(-1)} + } + + test.describe('createConciv lifecycle', () => { + test('mounts, unmounts, and remounts the widget', async ({page}) => { + test.setTimeout(120_000) + await openPage(page) + await mountHandle(page, kit.base) + await expect(fab(page)).toBeVisible({timeout: 30_000}) + await unmountHandle(page) + await expect(fab(page)).toHaveCount(0, {timeout: 30_000}) + await remountHandle(page) + await expect(fab(page)).toBeVisible({timeout: 30_000}) + }) + + test('threads the mounted api base to extension surfaces when the host page has no conciv-api-base meta', async ({ + page, + }) => { + await openPage(page) + await mountHandle(page, kit.base) + const probe = page.getByRole('status', {name: 'host api base probe'}) + await expect(probe).toHaveText(kit.base, {timeout: 30_000}) + }) + + test('a second mount on an already-mounted handle is a no-op', async ({page}) => { + await openPage(page) + 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 expect(fab(page)).toHaveCount(1, {timeout: 30_000}) + expect(await fab(page).count()).toBe(1) + }) + + test('unmount during mount leaves nothing behind', async ({page}) => { + await openPage(page) + 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 expect(fab(page)).toHaveCount(0, {timeout: 30_000}) + expect(await page.evaluate(() => document.querySelector('[data-conciv-root]') === null)).toBe(true) + }) + + test('restores the host __TSR_ROUTER__ global on unmount', async ({page}) => { + await openPage(page) + await page.evaluate(() => { + Reflect.set(window, '__TSR_ROUTER__', {hostSentinel: true}) + }) + await mountHandle(page, kit.base) + await expect(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) + }) + + test('unmounts cleanly with an open panel and a completed turn', async ({page}) => { + test.setTimeout(120_000) + await openPage(page) + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + await mountHandle(page, kit.base) + await fab(page).click() + await expect(chatBox(page)).toBeVisible({timeout: 30_000}) + await chatBox(page).fill('hello') + await chatBox(page).press('Enter') + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await unmountHandle(page) + await expect(fab(page)).toHaveCount(0, {timeout: 30_000}) + expect(pageErrors).toEqual([]) + }) + + test('closes the tab chat websocket on unmount and dials a fresh one on remount', async ({page}) => { + test.setTimeout(180_000) + const wire = watchChatWire(page) + const sockets = trackChatSockets(page) + await openPage(page) + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + await mountHandle(page, kit.base) + await openChatPanel(page) + await sendChatMessage(page, 'before the unmount') + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + + const socket = sockets.last() + if (!socket) throw new Error('the first turn opened no chat websocket') + const closed = closedWithin(socket, SOCKET_CLOSE_TIMEOUT_MS) + await unmountHandle(page) + await expect(fab(page)).toHaveCount(0, {timeout: 30_000}) + expect(await closed).toBe(true) + + await remountHandle(page) + await expect(chatBox(page)).toBeVisible({timeout: 30_000}) + const remounted = wire.nextTurn() + await sendChatMessage(page, 'after the remount') + expect((await remounted).transport).toBe('websocket') + expect(pageErrors).toEqual([]) + }) + }) +}) + +test.describe('dead engine boot', () => { + const ASSISTANT_TEXT = 'Recovered from a dead boot' + const MOUNT_TIMEOUT_MS = 30_000 + + let kit: EmbedKit + + test.beforeAll(async () => { + kit = await bootEmbedKit({text: ASSISTANT_TEXT}) + }) + + test.afterAll(async () => { + await kit.cleanup() + }) + + test.describe('the router error screen surfaces a dead engine at boot and Retry recovers it', () => { + test('FAB click against a connection-refused base shows our error screen, then Retry recovers once the engine is reachable', async ({ + page, + }) => { + test.setTimeout(90_000) + const dead = await reserveDeadPort() + const host = await serveHost(() => hostPage({apiBase: dead.base, widget: '{"quickTerminal":false}'})) + let proxy: ProxyCore | null = null + try { + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + + const errorScreen = page.getByRole('alert').filter({hasText: /couldn.t reach the engine/}) + await expect(errorScreen).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + + proxy = await proxyTo(kit.base, {port: dead.port}) + + await errorScreen.getByRole('button', {name: 'Retry'}).click() + + const composer = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await expect(composer).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + await composer.fill('hi there') + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + } finally { + await host.close() + if (proxy) await proxy.close() + } + }) + }) +}) + +test.describe('draft selection', () => { + const suite = setupWidgetSuite() + + test.describe('draft persistence carries the caret offsets', () => { + test('persists the draft text with the caret position after the debounce', async ({page}) => { + test.setTimeout(90_000) + const sessionId = await openPanelOnNewSession(page, suite) + + 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') + await input.pressSequentially('say ') + await untilPanelDraft(suite.kit(), sessionId, (draft) => draft.text === 'say hello!') + + expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({ + text: 'say hello!', + selectionStart: 4, + selectionEnd: 4, + }) + }) + }) +}) + +test.describe('draft send remount', () => { + const ASSISTANT_TEXT = 'Reply to the message sent before the reload' + const USER_TEXT = 'a message sent right before the reload' + const PENDING_DRAFT_WRITE_MS = 350 + const RESURRECTION_WINDOW_MS = 2_000 + + const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) + + function sentTextReappearsAsDraft(widget: WidgetSuite, sessionId: string): Promise { + return until(async () => (await widget.kit().rpc.drafts.get({sessionId}))?.text === USER_TEXT, { + hangGuardMs: RESURRECTION_WINDOW_MS, + intervalMs: 25, + }).then( + () => true, + () => false, + ) + } + + test.describe('a sent message never comes back as a draft', () => { + test('leaves the composer empty when the panel reloads right after the send', async ({page}) => { + test.setTimeout(240_000) + const sessionId = await openPanelOnNewSession(page, suite) + + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.fill(USER_TEXT) + await page.waitForTimeout(PENDING_DRAFT_WRITE_MS) + + await page.getByRole('button', {name: 'Send message'}).click() + const reappeared = await sentTextReappearsAsDraft(suite, sessionId) + await page.reload({waitUntil: 'domcontentloaded'}) + + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + + await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toHaveText('', {timeout: 30_000}) + await expect(page.getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + expect(reappeared).toBe(false) + }) + }) +}) + +test.describe('draft write churn', () => { + const ASSISTANT_TEXT = 'Reply that no test waits for' + const TYPED_TEXT = 'the only draft this pane ever stores' + const DRAFT_WRITE_TIMEOUT_MS = 15_000 + + const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) + + async function storedDraftText(widget: WidgetSuite, sessionId: string): Promise { + const row = await widget.kit().rpc.drafts.get({sessionId}) + return row?.text ?? null + } + + test.describe('an empty composer stores nothing', () => { + test('writes the first draft only once the user types, never on mount', async ({page}) => { + test.setTimeout(120_000) + const drafts = rpcCallCursor(page) + const sessionId = await openPanelOnNewSession(page, suite) + + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(TYPED_TEXT) + await expect.poll(() => storedDraftText(suite, sessionId), {timeout: DRAFT_WRITE_TIMEOUT_MS}).toBe(TYPED_TEXT) + + expect(drafts.startedSince(['drafts', 'set'])).toBe(1) + }) + }) +}) + +test.describe('element capture', () => { + const PASSWORD = 'hunter2-must-never-leave-the-page' + + const HOST_BODY = ` + +
+ +

original prose

+ +
+` + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + let sessionId: string + + test.beforeAll(async () => { + kit = await bootEmbedKit() + sessionId = await kit.session() + host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: HOST_BODY})) + }) + + test.afterAll(async () => { + await host.close() + await kit.cleanup() + }) + + const openHostPage = (page: Page): Promise => openPagePlaneHost(page, host.base) + + function rowIdentities(stored: SessionCaptures): string[] { + return stored.captures.map((row) => `${row.toolCallId}:${row.kind}:${JSON.stringify(row.capture)}`).toSorted() + } + + async function sendAndSettle(page: Page, message: string): Promise { + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(message) + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) + } + + test.describe('a page tool run through the widget stores a frozen picture of the element it touched', () => { + test('never lets a password value reach the stored capture or the tool result', async ({page}) => { + test.setTimeout(90_000) + await openHostPage(page) + const result = await kit.callTool('page_fill', {selector: '#secret', value: 'typed by the agent'}, sessionId) + const stored: SessionCaptures = await kit.rpc.captures.list({sessionId}) + const secretCaptures = stored.captures.filter((row) => row.capture.descriptor.selectorPath.includes('secret')) + expect(secretCaptures.map((row) => row.kind).toSorted()).toEqual(['after']) + for (const row of secretCaptures) expect(JSON.stringify(row.capture)).not.toContain(PASSWORD) + expect(JSON.stringify(result)).not.toContain(PASSWORD) + expect(JSON.stringify(stored)).not.toContain(PASSWORD) + }) + + test('hands the harness a result with no capture in it', async ({page}) => { + test.setTimeout(90_000) + await openHostPage(page) + const result = await kit.callTool('page_click', {selector: '#cta'}, sessionId) + expect(JSON.stringify(result)).not.toContain('cssBundleId') + expect(JSON.stringify(result)).not.toContain('selectorPath') + expect(JSON.stringify(result)).not.toContain('data-rr-target') + }) + + test('takes no capture for a read verb', async ({page}) => { + test.setTimeout(90_000) + await openHostPage(page) + const before: SessionCaptures = await kit.rpc.captures.list({sessionId}) + await kit.callTool('page_text', {selector: '#cta'}, sessionId) + const after: SessionCaptures = await kit.rpc.captures.list({sessionId}) + expect(rowIdentities(after)).toEqual(rowIdentities(before)) + }) + + test('renders a page verb run through real code mode as one aggregated session card fed by the capture pipeline', async ({ + page, + }) => { + test.setTimeout(180_000) + await openHostPage(page) + await openPanel(page) + kit.harness.script.scriptToolCall('execute_typescript', { + typescriptCode: "await external_page_settext({selector: '#prose', text: 'rendered through the pipeline'})", + }) + await sendAndSettle(page, 'rewrite the prose through code mode') + const sessionCard = page.getByRole('button', {name: /Edited the page/}) + await expect(sessionCard).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('button', {name: /Set the text/})).toHaveCount(0) + await sessionCard.click() + const dialog = page.getByRole('dialog', {name: 'conciv chat agent'}) + const stepTarget = dialog.getByText('rendered through the pipeline', {exact: true}) + await expect(stepTarget).toBeVisible({timeout: 30_000}) + await dialog.getByRole('button', {name: 'Script'}).click() + await expect(dialog.getByText(/external_page_settext/).first()).toBeVisible({timeout: 30_000}) + }) + }) +}) + +test.describe('fab working', () => { + const suite = setupWidgetSuite() + + const IMMEDIATE_MS = 2_000 + + function openLauncher(page: Page) { + return page.getByRole('button', {name: 'Open conciv chat'}) + } + + function panelLauncher(page: Page) { + return page.getByRole('button', {name: 'Minimize conciv chat'}) + } + + function stopButton(page: Page) { + return page.getByRole('button', {name: 'Stop generating'}) + } + + test('the sending tab marks the open panel launcher busy while its run is still streaming', async ({page}) => { + await sendHeldTurn(page, suite) + + await expect(panelLauncher(page)).toHaveAttribute('aria-busy', 'true', {timeout: IMMEDIATE_MS}) + }) + + test('minimizing the panel mid-run leaves the closed launcher wearing the busy state', async ({page}) => { + await sendHeldTurn(page, suite) + + await panelLauncher(page).click() + + await expect(openLauncher(page)).toHaveAttribute('aria-busy', 'true', {timeout: IMMEDIATE_MS}) + }) + + test('switching to a new session mid-run hands the busy state over to the session list', async ({page}) => { + await sendHeldTurn(page, suite) + + await page.getByRole('button', {name: 'More composer actions'}).click() + await page.getByRole('menuitem', {name: 'Start a new session'}).click() + + await expect(stopButton(page)).toHaveCount(0, {timeout: IMMEDIATE_MS}) + await expect(panelLauncher(page)).toHaveAttribute('aria-busy', 'false') + + await page.getByRole('button', {name: 'Session options'}).click() + await page.getByRole('button', {name: /^Session: /}).click() + await expect(page.getByRole('option', {name: /running/})).toBeVisible({timeout: 30_000}) + }) +}) + +test.describe('forced drop', () => { + const ASSISTANT_TEXT = 'Reply across the drop' + const FIRST_TEXT = 'first turn before the drop' + const SECOND_TEXT = 'second turn after the drop' + const MOUNT_TIMEOUT_MS = 20_000 + + const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT}) + + async function sendTurn(page: Page, text: string): Promise { + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(text) + await page.getByRole('button', {name: 'Send message'}).click() + } + + test.describe('chat survives a forced websocket drop', () => { + test('reopens the chat socket and completes the next turn after the core drops every connection', async ({ + page, + }) => { + test.setTimeout(120_000) + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + const wire = watchChatWire(page) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toBeVisible({ + timeout: MOUNT_TIMEOUT_MS, + }) + + const first = wire.nextTurn() + await sendTurn(page, FIRST_TEXT) + expect((await first).transport).toBe('websocket') + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: MOUNT_TIMEOUT_MS}) + + const mark = wire.socketMark() + const second = wire.nextTurn() + suite.core().dropConnections() + + await sendTurn(page, SECOND_TEXT) + expect((await second).transport).toBe('websocket') + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: MOUNT_TIMEOUT_MS}) + + expect(wire.socketsOpenedSince(mark)).toBeGreaterThan(0) + expect(pageErrors).toEqual([]) + }) + }) +}) + +test.describe('host hotkey isolation', () => { + const HOST_SEARCH_HOTKEY = ` + + + +` + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit() + host = await serveHost(() => + hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: HOST_SEARCH_HOTKEY}), + ) + }) + + test.afterEach(async () => { + await host.close() + await kit.cleanup() + }) + + const suite: WidgetSuite = {kit: () => kit, host: () => host} + + const composer = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) + const hostSearch = (page: Page) => page.getByRole('status', {name: 'host search'}) + + test.describe('host-page keyboard hotkeys and the widget composer', () => { + test('a slash typed into the composer never reaches the host search hotkey', async ({page}) => { + test.setTimeout(120_000) + await openPanelOnNewSession(page, suite) + const input = composer(page) + await input.click() + await expect(input).toHaveText('') + + await input.pressSequentially('run tests in lib/utils') + await expect(input).toHaveText(/utils/, {timeout: 30_000}) + + await expect(hostSearch(page)).toHaveText('host search idle') + await expect(input).toHaveText('run tests in lib/utils') + }) + + test('a slash pressed with focus on the host page still fires the host search hotkey', async ({page}) => { + test.setTimeout(120_000) + await openPanelOnNewSession(page, suite) + + await page.getByRole('button', {name: 'Host focus target'}).click() + await page.keyboard.press('/') + + await expect(hostSearch(page)).toHaveText('host search open', {timeout: 30_000}) + }) + }) +}) + +test.describe('idle fetch heartbeat', () => { + const ASSISTANT_TEXT = 'Idle heartbeat reply' + const SETTLE_MS = 3_000 + const UNREACHABLE_TIMEOUT_MS = 45_000 + const RECOVERY_TIMEOUT_MS = 20_000 + const HEARTBEAT_WINDOW_MS = 32_000 + + const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT}) + + test.describe('an idle widget notices the engine going unreachable through the rpc heartbeat', () => { + test('the open panel heartbeat surfaces the unreachable notice with no user interaction, and clears it on recovery', async ({ + page, + }) => { + test.setTimeout(120_000) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openChatPanel(page) + await page.waitForTimeout(SETTLE_MS) + + const hold = await holdRpcCalls(page) + hold.hold() + const cursor = rpcCallCursor(page) + + const notice = page.getByText('conciv lost connection to the engine.') + await expect(notice).toBeVisible({timeout: UNREACHABLE_TIMEOUT_MS}) + expect(cursor.startedSince(['meta', 'engine'])).toBeGreaterThanOrEqual(1) + + hold.release() + + await expect(notice).not.toBeVisible({timeout: RECOVERY_TIMEOUT_MS}) + }) + + test('closing the panel stops the heartbeat from polling the engine', async ({page}) => { + test.setTimeout(60_000) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openChatPanel(page) + await page.waitForTimeout(SETTLE_MS) + await page.getByRole('button', {name: 'Close chat'}).click() + + const cursor = rpcCallCursor(page) + await page.waitForTimeout(HEARTBEAT_WINDOW_MS) + + expect(cursor.startedSince(['meta', 'engine'])).toBe(0) + }) + }) +}) + +test.describe('mid session outage', () => { + const ASSISTANT_TEXT = 'Recovered mid-session' + const MOUNT_TIMEOUT_MS = 30_000 + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeAll(async () => { + kit = await bootEmbedKit({text: ASSISTANT_TEXT}) + host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}'})) + }) + + test.afterAll(async () => { + await host.close() + await kit.cleanup() + }) + + test.describe('a mid-session outage raises the standing notice and disables sending, release auto-clears both', () => { + test('holding all rpc traffic surfaces the notice and a disabled send control, releasing it clears both', async ({ + page, + }) => { + test.setTimeout(90_000) + const hold = await holdRpcCalls(page) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openChatPanel(page) + + const composer = chatBox(page) + await composer.fill('a message queued during the outage') + + hold.hold() + + const notice = page.getByText('conciv lost connection to the engine.') + await expect(notice).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + const disabledSend = page.getByRole('button', {name: 'conciv lost connection to the engine'}) + await expect(disabledSend).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + await expect(disabledSend).toBeDisabled() + + hold.release() + + await expect(notice).not.toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + await expect(page.getByRole('button', {name: 'Send message'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + }) + }) +}) + +test.describe('model selector', () => { + const HARNESS_MODELS = [ + {id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5'}, + {id: 'claude-opus-4-1', name: 'Claude Opus 4.1'}, + ] + + const suite = setupWidgetSuite({text: 'Hello from conciv', models: HARNESS_MODELS}) + + test.describe('model selector error path', () => { + test.use({viewport: {width: 900, height: 760}}) + + test('offers a retry when meta.models fails and recovers on retry', async ({page}) => { + test.setTimeout(180_000) + const models = await failRpcCalls(page, {path: ['meta', 'models']}) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + + const moreActions = page.getByRole('button', {name: 'More composer actions'}) + await moreActions.click() + const retry = page.getByRole('menuitem', {name: /Retry loading models/}) + await expect(retry).toBeVisible({timeout: 30_000}) + await expect(page.getByText('Couldn’t load models').first()).toBeVisible({timeout: 30_000}) + + models.repair() + await retry.click() + await moreActions.click() + await expect(page.getByRole('menuitem', {name: /^Model: Claude Sonnet 4\.5/})).toBeVisible({timeout: 30_000}) + await page.keyboard.press('Escape') + }) + }) +}) + +test.describe('mount ready', () => { + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeAll(async () => { + kit = await bootEmbedKit({text: 'ready contract'}) + host = await serveHost(() => handleHostPage()) + }) + + test.afterAll(async () => { + await host.close() + await kit.cleanup() + }) + + async function openPage(page: Page): Promise { + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + return page + } + + test.describe('mount() readiness contract', () => { + test('an open dispatched right after mount() resolves opens the panel, never dropped', async ({page}) => { + await openPage(page) + await page.evaluate(async (base) => { + const el = document.createElement('div') + document.body.appendChild(el) + const handle = window.ConcivHandle.makeHandle(base) + await handle.mount(el) + window.dispatchEvent( + new CustomEvent('conciv-dispatch-event', { + detail: {type: 'panel:open', payload: undefined, pluginId: 'panel'}, + }), + ) + }, kit.base) + await expect(chatBox(page)).toBeVisible({timeout: 10_000}) + }) + }) +}) + +test.describe('native live region', () => { + const nativeDistDir = fileURLToPath(new URL('../../dist/', import.meta.url)) + + type NativeMethod = keyof NonNullable + type PanelToggled = Extract + + let kit: CoreKit + + test.beforeAll(async () => { + kit = await bootCoreKit({id: 'fake-native-region', text: 'Hello from conciv', nativePageDir: nativeDistDir}) + }) + + test.afterAll(async () => { + await kit.cleanup() + }) + + type Mascot = {page: Page; toggles: PanelToggled[]; notify: (toggle: PanelToggled) => void} + + function isToggle(message: PageToNativeMessage): message is PanelToggled { + return message.type === 'host.panelToggled' + } + + async function openMascotNative(page: Page): Promise { + const mascot: Mascot = {page, toggles: [], notify: () => {}} + const bridge = await captureNativePosts(page) + bridge.notify = (message) => { + if (!isToggle(message)) return + mascot.toggles.push(message) + mascot.notify(message) + } + await installNativeStub(page) + await page.goto(`${kit.base}/native?launcher=mascot`, {waitUntil: 'domcontentloaded'}) + await page.waitForFunction(() => typeof window.__concivNative === 'object') + return mascot + } + + function callNative(page: Page, method: NativeMethod, arg: Record): Promise { + return page.evaluate((call) => window.__concivNative?.[call.method]?.(call.arg), {method, arg}) + } + + const composerBox = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) + + async function openFromHost(page: Page): Promise { + await callNative(page, 'open', {v: 1, seq: 1}) + await expect(composerBox(page)).toBeVisible({timeout: 30_000}) + } + + test.describe('native live region reporting', () => { + test.use({viewport: {width: 1280, height: 900}}) + + test('never reports closed mascot-region state once the panel is open', async ({page: fixturePage}) => { + const mascot = await openMascotNative(fixturePage) + 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) + }) + + test('reports open, not a closed mascot rect, once a session is opened from the host', async ({ + page: fixturePage, + }) => { + const mascot = await openMascotNative(fixturePage) + 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) + }) + }) +}) + +test.describe('native widget', () => { + type NativeMethod = keyof NonNullable + + const nativeDistDir = fileURLToPath(new URL('../../dist/', import.meta.url)) + + const IMAGE_DATA_URL = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP4z8AARwzEcQCukw/x0F8jngAAAABJRU5ErkJggg==' + + const NEUTRAL_GRAB = { + text: 'Payroll Deposit', + preview: {kind: 'image', dataUrl: IMAGE_DATA_URL, width: 361, height: 72}, + rect: {x: 16, y: 232, width: 361, height: 72}, + source: {componentName: 'PaymentCardCell', filePath: '', lineNumber: null}, + subtree: { + class: 'PaymentCardCell', + a11yId: 'PaymentsScreen/payrollRow', + text: 'Payroll Deposit', + rect: {x: 16, y: 232, width: 361, height: 72}, + children: [ + { + class: 'UILabel', + a11yId: null, + text: 'Payroll Deposit', + rect: {x: 28, y: 240, width: 180, height: 20}, + children: [], + }, + ], + }, + } + + function grabPayloadOf(draft: DraftRow): GrabPayload | null { + const attachment = draft.attachments.find((candidate) => candidate.contentType === GRAB_MIME) + if (!attachment) return null + return parseGrabPayload(Buffer.from(attachment.data, 'base64').toString('utf8')) + } + + let kit: CoreKit + let sessionId: string + + test.beforeAll(async () => { + kit = await bootCoreKit({id: 'fake-native', text: 'Hello from conciv', nativePageDir: nativeDistDir}) + sessionId = (await kit.rpc.sessions.create()).sessionId + }) + + test.afterAll(async () => { + await kit.cleanup() + }) + + type Native = { + page: Page + bridge: NativeBridge + rebinds: {apiBase?: string}[] + onRebind: () => void + } + + async function openNative(page: Page): Promise { + const bridge = await captureNativePosts(page) + const native: Native = {page, bridge, rebinds: [], onRebind: () => {}} + await page.exposeFunction('concivNativeRebind', (detail: {apiBase?: string}) => { + native.rebinds.push(detail) + native.onRebind() + }) + await installNativeStub(page) + await page.addInitScript(() => { + window.addEventListener('conciv:rebind', (event) => void window.concivNativeRebind(event.detail)) + }) + await page.goto(`${kit.base}/native`, {waitUntil: 'domcontentloaded'}) + await page.waitForFunction(() => typeof window.__concivNative === 'object') + return native + } + + const countType = (messages: PageToNativeMessage[], type: PageToNativeMessage['type']): number => + messages.filter((message) => message.type === type).length + + const findByType = ( + messages: PageToNativeMessage[], + type: Type, + ): Extract | undefined => + messages.find((message): message is Extract => message.type === type) + + function callNative(page: Page, method: NativeMethod, arg: Record): Promise { + return page.evaluate((call) => window.__concivNative?.[call.method]?.(call.arg), {method, arg}) + } + + const composerBox = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) + const panel = (page: Page) => page.getByRole('dialog', {name: 'conciv chat agent'}) + const grabPreview = (page: Page) => panel(page).locator('img') + + async function pickElement(page: Page): Promise { + const inline = page.getByRole('button', {name: 'Select an element from the page'}) + if (await inline.isVisible()) { + await inline.click() + return + } + await page.getByRole('button', {name: 'More composer actions'}).click() + await page.getByRole('menuitem', {name: 'Select an element from the page'}).click() + } + + test.describe('native widget bridge', () => { + test('opens the panel on native open and is idempotent, and closes on native close', async ({ + page: fixturePage, + }) => { + const wire = watchRpcWire(fixturePage) + const {page} = await openNative(fixturePage) + await wire.sessionsBootTraffic() + await callNative(page, 'open', {v: 1, seq: 1}) + await callNative(page, 'open', {v: 1, seq: 2}) + await expect(composerBox(page)).toHaveCount(1, {timeout: 30_000}) + await expect(composerBox(page)).toBeVisible() + await callNative(page, 'close', {v: 1, seq: 3}) + await expect(composerBox(page)).toBeHidden({timeout: 30_000}) + }) + + test('drives the native grab provider: pick posts a requestId and a matching image grabResult stages the preview', async ({ + page: fixturePage, + }) => { + test.setTimeout(120_000) + const wire = watchRpcWire(fixturePage) + const {page, bridge} = await openNative(fixturePage) + await wire.sessionsBootTraffic() + const picked = Promise.withResolvers() + bridge.notify = (message) => { + if (message.type === 'grab.pick') picked.resolve(message) + } + await callNative(page, 'open', {v: 1, seq: 1}) + await expect(composerBox(page)).toBeVisible({timeout: 30_000}) + + await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) + await pickElement(page) + 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 expect(panel(page).getByText('PaymentCardCell')).toBeVisible({timeout: 30_000}) + await expect(grabPreview(page)).toHaveAttribute('src', IMAGE_DATA_URL) + await untilPanelDraft(kit, sessionId, (draft) => { + const payload = grabPayloadOf(draft) + return payload !== null && payload.text.includes('[view]') && payload.text.includes('PaymentCardCell') + }) + }) + + test('ignores a grabResult whose requestId does not match the pending pick', async ({page: fixturePage}) => { + const {page, bridge} = await openNative(fixturePage) + const picked = Promise.withResolvers() + bridge.notify = (message) => { + if (message.type === 'grab.pick') picked.resolve(message) + } + await callNative(page, 'open', {v: 1, seq: 1}) + await expect(composerBox(page)).toBeVisible({timeout: 30_000}) + await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) + await pickElement(page) + 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) + }) + + test('surfaces a visible error when native reports an incompatible bridge version', async ({page: fixturePage}) => { + const {page} = await openNative(fixturePage) + await callNative(page, 'bridgeIncompatible', {v: 1, seq: 1, nativeMinV: 2, nativeMaxV: 3}) + await expect(page.getByText('Update the conciv widget', {exact: false})).toBeVisible({timeout: 30_000}) + }) + + test('dispatches conciv:rebind when a handshake reports a different same-core base', async ({ + page: fixturePage, + }) => { + const native = await openNative(fixturePage) + 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'}]) + }) + }) +}) + +test.describe('page dispatch boot', () => { + const HOST_BODY = ` +
page-bus-ok
+

Embed page

+ + +` + + const SnapshotSchema = z.object({ + nodes: z.array(z.looseObject({ref: z.string(), role: z.string(), name: z.string().optional()})), + }) + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeAll(async () => { + kit = await bootEmbedKit() + host = await serveHost(() => handleHostPage(HOST_BODY)) + }) + + test.afterAll(async () => { + await host.close() + await kit.cleanup() + }) + + async function buttonRef(): Promise { + const snapshot = SnapshotSchema.parse(await kit.rpc.registry.call({name: 'page_snapshot', input: {}})) + const node = snapshot.nodes.find((entry) => entry.role === 'button' && entry.name === 'Press target') + if (!node) throw new Error('the snapshot did not list the press button') + return node.ref + } + + test.describe('the page-tool dispatcher serves registry page tools under bootConnect', () => { + let page: Page + + test.beforeAll(async ({browser}) => { + page = await browser.newPage() + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await page.evaluate(() => { + const el = document.createElement('div') + document.body.appendChild(el) + window.concivTestHandle = window.ConcivHandle.makeConnectHandle() + void window.concivTestHandle.mount(el) + }) + await completeConnectHandshake(page, kit.base, await kit.session()) + }) + + test.afterAll(async () => { + await page.close() + }) + + test('a plain read round-trips server -> browser -> result', async () => { + await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#probe'}})).resolves.toMatchObject({ + text: 'page-bus-ok', + }) + }) + + test('a mutating tool acts on the page, journals by declared meta, and fires the browser mirror', async () => { + await expect(kit.rpc.registry.call({name: 'page_click', input: {selector: '#press-btn'}})).resolves.toMatchObject( + { + ok: true, + }, + ) + await expect( + kit.rpc.registry.call({name: 'page_text', input: {selector: '#clicked-flag'}}), + ).resolves.toMatchObject({text: 'clicked'}) + const changes = await kit.rpc.page.changes(undefined) + expect(changes.map((entry) => entry.verb)).toContain('page_click') + await expect(page.locator('[data-conciv-cursor]')).toHaveCount(1, {timeout: 10_000}) + }) + + test('a ref-consuming tool resolves its target through the shared refs machinery', async () => { + const ref = await buttonRef() + await expect(kit.rpc.registry.call({name: 'page_attr', input: {ref, attribute: 'id'}})).resolves.toMatchObject({ + value: 'press-btn', + }) + }) + + test('a missing target rejects with the transport invalid-args mapping, not a success shape', async () => { + await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#not-here'}})).rejects.toMatchObject({ + code: 'INVALID_ARGS', + }) + }) + + test.describe('the page_effect verb drives host-registered effects', () => { + test('lists the highlight effect the widget registers', async () => { + await expect(kit.rpc.registry.call({name: 'page_effect', input: {action: 'list'}})).resolves.toMatchObject({ + effects: [{name: 'highlight', enabled: false}], + }) + }) + + test('enable shows the highlight inspector on the page, disable reverts, toggle flips', async () => { + await expect( + kit.rpc.registry.call({name: 'page_effect', input: {action: 'enable', effect: 'highlight'}}), + ).resolves.toMatchObject({effect: 'highlight', enabled: true}) + await expect(page.locator('[data-conciv-capture]')).toHaveCount(1, {timeout: 10_000}) + + await expect( + kit.rpc.registry.call({name: 'page_effect', input: {action: 'disable', effect: 'highlight'}}), + ).resolves.toMatchObject({effect: 'highlight', enabled: false}) + await expect(page.locator('[data-conciv-capture]')).toHaveCount(0, {timeout: 10_000}) + + await expect( + kit.rpc.registry.call({name: 'page_effect', input: {action: 'toggle', effect: 'highlight'}}), + ).resolves.toMatchObject({effect: 'highlight', enabled: true}) + await expect(page.locator('[data-conciv-capture]')).toHaveCount(1, {timeout: 10_000}) + + await expect( + kit.rpc.registry.call({name: 'page_effect', input: {action: 'toggle', effect: 'highlight'}}), + ).resolves.toMatchObject({effect: 'highlight', enabled: false}) + await expect(page.locator('[data-conciv-capture]')).toHaveCount(0, {timeout: 10_000}) + }) + + test('an unknown effect name rejects with the declared error', async () => { + await expect( + kit.rpc.registry.call({name: 'page_effect', input: {action: 'enable', effect: 'confetti'}}), + ).rejects.toMatchObject({code: 'UNKNOWN_EFFECT'}) + }) + }) + }) +}) + +test.describe('page dispatch parity', () => { + const HOST_BODY = ` +
page-bus-ok
+

Embed page

+ + +` + + const SnapshotSchema = z.object({ + nodes: z.array(z.looseObject({ref: z.string(), role: z.string(), name: z.string().optional()})), + }) + + const ChangesSchema = z.array(z.object({verb: z.string()}).loose()) + + type BootedPath = {kit: EmbedKit; page: Page} + + async function buttonRef(kit: EmbedKit): Promise { + const snapshot = SnapshotSchema.parse(await kit.rpc.registry.call({name: 'page_snapshot', input: {}})) + const node = snapshot.nodes.find((entry) => entry.role === 'button' && entry.name === 'Press target') + if (!node) throw new Error('the snapshot did not list the press button') + return node.ref + } + + function verbGroupBattery(boot: () => BootedPath): void { + test('read: page_text reports the live DOM', async () => { + const {kit} = boot() + await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#probe'}})).resolves.toMatchObject({ + text: 'page-bus-ok', + }) + }) + + test('read: page_attr resolves a snapshot ref through the shared refs machinery', async () => { + const {kit} = boot() + const ref = await buttonRef(kit) + await expect(kit.rpc.registry.call({name: 'page_attr', input: {ref, attribute: 'id'}})).resolves.toMatchObject({ + value: 'press-btn', + }) + }) + + test('react: page_locate fails structurally on a page without a React tree', async () => { + const {kit} = boot() + await expect(kit.rpc.registry.call({name: 'page_locate', input: {selector: '#title'}})).rejects.toMatchObject({ + code: 'HANDLER_ERROR', + message: expect.stringContaining('no React fiber'), + }) + }) + + test('act: page_click acts on the page, journals, and fires the browser mirror', async () => { + const {kit, page} = boot() + await expect(kit.rpc.registry.call({name: 'page_click', input: {selector: '#press-btn'}})).resolves.toMatchObject( + { + ok: true, + }, + ) + await expect( + kit.rpc.registry.call({name: 'page_text', input: {selector: '#clicked-flag'}}), + ).resolves.toMatchObject({text: 'clicked'}) + const changes = ChangesSchema.parse(await kit.rpc.page.changes(undefined)) + expect(changes.map((entry) => entry.verb)).toContain('page_click') + await expect(page.locator('[data-conciv-cursor]')).toHaveCount(1, {timeout: 10_000}) + }) + + test('edit-live: page_settext rewrites the DOM and journals by declared meta', async () => { + const {kit} = boot() + await expect( + kit.rpc.registry.call({name: 'page_settext', input: {selector: '#title', text: 'Rewritten title'}}), + ).resolves.toMatchObject({ok: true}) + await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#title'}})).resolves.toMatchObject({ + text: 'Rewritten title', + }) + const changes = ChangesSchema.parse(await kit.rpc.page.changes(undefined)) + expect(changes.map((entry) => entry.verb)).toContain('page_settext') + }) + } + + test.describe('bootNormal: the widget embed serves every verb group through the dispatcher', () => { + let kit: EmbedKit + let host: {base: string; close: () => Promise} + let page: Page + + test.beforeAll(async ({browser}) => { + kit = await bootEmbedKit() + host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: HOST_BODY})) + page = await browser.newPage() + await openPagePlaneHost(page, host.base) + }) + + test.afterAll(async () => { + await page.close() + await host.close() + await kit.cleanup() + }) + + test.afterEach(async () => { + await kit.rpc.page.clearChanges(undefined) + }) + + verbGroupBattery(() => ({kit, page})) + }) + + test.describe('bootConnect: the connect handle serves the same verb groups through the dispatcher', () => { + let kit: EmbedKit + let host: {base: string; close: () => Promise} + let page: Page + + test.beforeAll(async ({browser}) => { + kit = await bootEmbedKit() + host = await serveHost(() => handleHostPage(HOST_BODY)) + page = await browser.newPage() + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await page.evaluate(() => { + const el = document.createElement('div') + document.body.appendChild(el) + window.concivTestHandle = window.ConcivHandle.makeConnectHandle() + void window.concivTestHandle.mount(el) + }) + await completeConnectHandshake(page, kit.base, await kit.session()) + }) + + test.afterAll(async () => { + await page.close() + await host.close() + await kit.cleanup() + }) + + test.afterEach(async () => { + await kit.rpc.page.clearChanges(undefined) + }) + + verbGroupBattery(() => ({kit, page})) + }) +}) + +test.describe('page plane', () => { + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeAll(async () => { + kit = await bootEmbedKit() + host = await serveHost(() => + hostPage({ + apiBase: kit.base, + widget: '{"quickTerminal":false}', + body: '
page-bus-ok

Embed page

', + }), + ) + }) + + test.afterAll(async () => { + await host.close() + await kit.cleanup() + }) + + const openHostPage = (page: Page): Promise => openPagePlaneHost(page, host.base) + + test.describe('startPagePlane executes registry page tools in the browser', () => { + test('round-trips page_text through the push socket to the DOM dispatcher', async ({page}) => { + test.setTimeout(90_000) + await openHostPage(page) + expect(await kit.rpc.registry.call({name: 'page_text', input: {selector: '#probe'}})).toMatchObject({ + text: 'page-bus-ok', + }) + }) + + test('a verb whose target does not exist rejects with a declared code, not a success-shaped string', async ({ + page, + }) => { + test.setTimeout(90_000) + await openHostPage(page) + 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', + }) + }) + + test('the snapshot tool sees host page structure', async ({page}) => { + test.setTimeout(90_000) + await openHostPage(page) + expect(JSON.stringify(await kit.rpc.registry.call({name: 'page_snapshot', input: {}}))).toContain('Embed page') + }) + }) +}) + +test.describe('panel focus', () => { + const suite = setupWidgetSuite() + + const COMPOSER_NAME = 'Message the conciv agent' + const SESSIONS_LIST = ['sessions', 'list'] as const + + function composer(page: Page) { + return page.getByRole('textbox', {name: COMPOSER_NAME}) + } + + function sessionOptionsButton(page: Page) { + return page.getByRole('button', {name: 'Session options'}) + } + + async function ensurePanelClosed(page: Page): Promise { + const minimize = page.getByRole('button', {name: 'Minimize conciv chat'}) + const opener = page.getByRole('button', {name: 'Open conciv chat'}) + await expect(minimize.or(opener)).toBeVisible({timeout: 30_000}) + if (await minimize.isVisible()) await minimize.click() + await expect(opener).toBeVisible({timeout: 30_000}) + } + + type HostedPanel = {host: Awaited>; page: Page; hostButton: Locator} + + const dedicatedHosts: Array<{close: () => Promise}> = [] + + test.afterEach(async () => { + for (const dedicatedHost of dedicatedHosts.splice(0)) await dedicatedHost.close() + }) + + async function openPanelOverFocusedHostButton(page: Page): Promise { + const host = await serveHost(() => + hostPage({ + apiBase: suite.kit().base, + widget: '{"quickTerminal":false}', + body: '', + }), + ) + dedicatedHosts.push(host) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await ensurePanelClosed(page) + const hostButton = page.getByRole('button', {name: 'Host action'}) + await hostButton.click() + await expect(hostButton).toBeFocused() + await page.evaluate(() => + window.dispatchEvent( + new CustomEvent('conciv-dispatch-event', { + detail: {type: 'panel:open', payload: undefined, pluginId: 'panel'}, + }), + ), + ) + await expect(composer(page)).toBeVisible({timeout: 30_000}) + return {host, page, hostButton} + } + + test.describe('panel open focuses the composer', () => { + test('focuses the composer input when the panel opens', async ({page}) => { + test.setTimeout(90_000) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await expect(composer(page)).toBeFocused({timeout: 10_000}) + await page.keyboard.type('typed without clicking') + await expect(composer(page)).toHaveText('typed without clicking') + }) + + test('paints the shell while the session list is still loading, then focuses the composer', async ({page}) => { + test.setTimeout(90_000) + const host = await serveHost(() => + hostPage({apiBase: suite.kit().base, widget: '{"quickTerminal":false,"transport":"fetch"}'}), + ) + dedicatedHosts.push(host) + const sessionListGate = await gateRpcCalls(page, {path: SESSIONS_LIST}) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + try { + await sessionListGate.awaitCaptured(1) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 15_000}) + expect(sessionListGate.pending()).toBeGreaterThan(0) + } finally { + await sessionListGate.dispose() + } + await openPanel(page) + await expect(sessionOptionsButton(page)).toBeVisible({timeout: 30_000}) + await expect(composer(page)).toBeFocused({timeout: 30_000}) + await page.keyboard.type('typed after the session list resolved') + await expect(composer(page)).toHaveText('typed after the session list resolved') + }) + }) + + test.describe('panel close restores focus: host element captured at open wins, FAB is the fallback', () => { + test('closing via the FAB restores the host element that was focused before a programmatic open', async ({ + page, + }) => { + test.setTimeout(120_000) + const {hostButton} = await openPanelOverFocusedHostButton(page) + await page.getByRole('button', {name: 'Minimize conciv chat'}).click() + await expect(hostButton).toBeFocused({timeout: 10_000}) + }) + + test('closing via the panel header restores the host element that was focused before the open', async ({page}) => { + test.setTimeout(120_000) + const {hostButton} = await openPanelOverFocusedHostButton(page) + await page.getByRole('button', {name: 'Close chat'}).click() + await expect(hostButton).toBeFocused({timeout: 10_000}) + }) + + test('collapsing the panel by dragging its resize handle shut restores the host element', async ({page}) => { + test.setTimeout(180_000) + const {hostButton} = await openPanelOverFocusedHostButton(page) + + 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 expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) + await expect(hostButton).toBeFocused({timeout: 10_000}) + }) + + test('closing via the FAB falls back to FAB focus when no host element was captured at open time', async ({ + page, + }) => { + test.setTimeout(120_000) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await ensurePanelClosed(page) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expect(composer(page)).toBeVisible({timeout: 30_000}) + await page.getByRole('button', {name: 'Minimize conciv chat'}).click() + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) + }) + + test('closing a boot-restored open panel falls back to FAB focus', async ({page}) => { + test.setTimeout(180_000) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await until(async () => (await currentHref(suite.kit())).includes('open=true'), { + hangGuardMs: 30_000, + intervalMs: 100, + }) + expect(await currentHref(suite.kit())).toContain('open=true') + + await page.reload({waitUntil: 'domcontentloaded'}) + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await page.getByRole('button', {name: 'Close chat'}).click() + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) + }) + + test('closing the phone sheet falls back to FAB focus once the launcher remounts', async ({page}) => { + test.setTimeout(180_000) + await page.setViewportSize({width: 390, height: 780}) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await ensurePanelClosed(page) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expect(composer(page)).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeHidden({timeout: 30_000}) + await page.getByRole('button', {name: 'Close chat'}).click() + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) + }) + }) + + test.describe('Escape dismisses the topmost open layer only', () => { + test('pressing Escape while the Session options menu is open closes only the menu, not the panel', async ({ + page, + }) => { + test.setTimeout(90_000) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + + await sessionOptionsButton(page).click() + await expect(page.getByRole('dialog', {name: 'Session options'})).toBeVisible({timeout: 10_000}) + + await page.keyboard.press('Escape') + + await expect(page.getByRole('dialog', {name: 'Session options'})).toBeHidden({timeout: 10_000}) + await expect(composer(page)).toBeVisible({timeout: 10_000}) + await expect(sessionOptionsButton(page)).toBeFocused({timeout: 10_000}) + }) + }) + + test.describe('panel restore-on-load never steals focus from the host page', () => { + test('reloading with a restored open panel leaves an autofocused host input focused', async ({page}) => { + test.setTimeout(180_000) + const host = await serveHost(() => + hostPage({ + apiBase: suite.kit().base, + widget: '{"quickTerminal":false}', + body: '', + }), + ) + dedicatedHosts.push(host) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await until(async () => (await currentHref(suite.kit())).includes('open=true'), { + hangGuardMs: 30_000, + intervalMs: 100, + }) + expect(await currentHref(suite.kit())).toContain('open=true') + + await page.reload({waitUntil: 'domcontentloaded'}) + const hostInput = page.getByRole('textbox', {name: 'Host search'}) + await expect(hostInput).toBeFocused({timeout: 10_000}) + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expect(hostInput).toBeFocused({timeout: 10_000}) + }) + }) +}) + +test.describe('panel session switch', () => { + const RECENT_ID = HarnessSessionId.parse('43548fd1-0000-4220-acf0-014b10b5815f') + const OLDER_ID = HarnessSessionId.parse('43548fd1-0000-4220-acf0-014b10b5815e') + const RECENT_TITLE = 'the session opened at boot' + const OLDER_TITLE = 'the session switched to' + const FIRST_DRAFT = 'draft of the session opened first' + const SECOND_DRAFT = 'draft of the session switched to' + + const suite = setupWidgetSuite({ + history: [ + {id: RECENT_ID, derivedTitle: RECENT_TITLE, updatedAt: Date.now(), messageCount: 3}, + {id: OLDER_ID, derivedTitle: OLDER_TITLE, updatedAt: Date.now() - 60_000, messageCount: 2}, + ], + }) + + test.describe('composer drafts after a session switch', () => { + test('persists each draft against the session the panel is on when it is typed', async ({page}) => { + test.setTimeout(180_000) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await switchToSessionByTitle(page, RECENT_TITLE) + + const opened = await suite.kit().rpc.sessions.resolve({id: RECENT_ID}) + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.click() + await input.pressSequentially(FIRST_DRAFT) + await untilPanelDraft(suite.kit(), opened.sessionId, (draft) => draft.text === FIRST_DRAFT) + + const sessionOptions = page.getByRole('button', {name: 'Session options'}) + await sessionOptions.click() + await page.getByRole('button', {name: /^Session: /}).click() + await page.getByRole('option', {name: new RegExp(OLDER_TITLE)}).click() + const pill = page.getByRole('button', {name: `Session: ${OLDER_TITLE}`}) + if (!(await pill.isVisible())) await sessionOptions.click() + await expect(pill).toBeVisible({timeout: 30_000}) + await page.keyboard.press('Escape') + await expect(pill).toBeHidden({timeout: 30_000}) + + const switched = await suite.kit().rpc.sessions.resolve({id: OLDER_ID}) + expect(switched.sessionId).not.toBe(opened.sessionId) + + await input.click() + await input.pressSequentially(SECOND_DRAFT) + await untilPanelDraft(suite.kit(), switched.sessionId, (draft) => draft.text === SECOND_DRAFT) + + expect(await suite.kit().rpc.drafts.get({sessionId: opened.sessionId})).toMatchObject({text: FIRST_DRAFT}) + expect(await suite.kit().rpc.drafts.get({sessionId: switched.sessionId})).toMatchObject({text: SECOND_DRAFT}) + }) + }) +}) + +test.describe('rebind', () => { + const ASSISTANT_TEXT = 'Rebound reply' + const USER_TEXT = 'first message before the drift' + const SECOND_USER_TEXT = 'second message after the drift' + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit({text: ASSISTANT_TEXT}) + host = await serveHost(() => handleHostPage()) + }) + + test.afterEach(async () => { + await host.close() + await kit.cleanup() + }) + + async function openPanelTabs(page: Page): Promise { + const opener = page.getByRole('button', {name: 'Open conciv chat'}) + await expect(opener).toBeVisible({timeout: 30_000}) + await opener.click() + await expect(page.getByRole('tab', {name: 'Mount probe'})).toBeVisible({timeout: 30_000}) + } + + async function panelSession(): Promise { + const state = await kit.rpc.navigation.get(undefined) + const entry = state?.entries.find((row) => row.href.startsWith('/panel/')) + if (!entry) return null + return (entry.href.split('/')[2] ?? '').split('?')[0] ?? null + } + + test.describe('handle.rebind survives same-core port drift', () => { + let proxyA: ProxyCore + let proxyB: ProxyCore + + test.beforeEach(async () => { + proxyA = await proxyTo(kit.base) + proxyB = await proxyTo(kit.base) + }) + + test.afterEach(async () => { + await proxyB.close() + }) + + test('re-points rpc and SSE to the new port, keeps the panel open, the session, and delivers the next turn', async ({ + page, + }) => { + test.setTimeout(480_000) + 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 expect(apiBaseProbe).toHaveText(proxyA.base, {timeout: 30_000}) + + await until(async () => (await panelSession()) !== null, {hangGuardMs: 30_000, intervalMs: 100}) + const sessionBefore = await panelSession() + expect(sessionBefore).not.toBeNull() + + await sendChatMessage(page, USER_TEXT) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + + const beforeB = proxyB.trafficCount() + await rebindHandle(page, proxyB.base) + await proxyA.close() + + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expect(chatBox(page)).toBeVisible({timeout: 30_000}) + + await expect(apiBaseProbe).toHaveText(proxyB.base, {timeout: 30_000}) + + await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + + await sendChatMessage(page, SECOND_USER_TEXT) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) + await expect(chatLog(page).getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expect(chatLog(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([]) + }) + }) + + test.describe('handle.rebind remounts extension surfaces on the new core', () => { + let proxyC: ProxyCore + let proxyD: ProxyCore + + test.beforeEach(async () => { + proxyC = await proxyTo(kit.base) + proxyD = await proxyTo(kit.base) + }) + + test.afterEach(async () => { + await proxyD.close() + }) + + test('rebuilds the global surface and the open extension view against the new base', async ({page}) => { + test.setTimeout(240_000) + const pageErrors = await openHostWithHandle(page, host.base, 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 expect(surfaceProbe).toHaveText(proxyC.base, {timeout: 30_000}) + + const probeTab = page.getByRole('tab', {name: 'Mount probe'}) + await probeTab.click() + await expect(viewProbe).toHaveText(proxyC.base, {timeout: 30_000}) + + const beforeD = proxyD.trafficCount() + await rebindHandle(page, proxyD.base) + await proxyC.close() + + await expect(surfaceProbe).toHaveText(proxyD.base, {timeout: 15_000}) + await expect(viewProbe).toHaveText(proxyD.base, {timeout: 15_000}) + await expect(probeTab).toHaveAttribute('aria-selected', 'true', {timeout: 15_000}) + expect(proxyD.trafficCount()).toBeGreaterThan(beforeD) + expect(pageErrors).toEqual([]) + }) + }) + + test.describe('handle.rebind quiesces the old connection before tearing consumers down', () => { + let proxyE: ProxyCore + let proxyF: ProxyCore + + test.beforeEach(async () => { + proxyE = await proxyTo(kit.base) + proxyF = await proxyTo(kit.base) + }) + + test.afterEach(async () => { + await proxyE.close() + await proxyF.close() + }) + + test('writes nothing more to the old core once rebind is called', async ({page}) => { + test.setTimeout(180_000) + const wire = watchChatWire(page) + const framesSentPerSocket: number[] = [] + page.on('websocket', (socket) => { + if (!socket.url().includes(CHAT_WS_PATH)) 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 mountHandle(page, proxyE.base) + await openChatPanel(page) + + const apiBaseProbe = page.getByRole('status', {name: 'host api base probe'}) + await expect(apiBaseProbe).toHaveText(proxyE.base, {timeout: 30_000}) + + await rebindHandle(page, proxyF.base) + await expect(apiBaseProbe).toHaveText(proxyF.base, {timeout: 30_000}) + + const settledOnOldSocket = framesSentPerSocket[0] ?? 0 + const sentOnNewCore = wire.nextTurn() + await sendChatMessage(page, SECOND_USER_TEXT) + await sentOnNewCore + + expect(framesSentPerSocket[0]).toBe(settledOnOldSocket) + }) + }) + + test.describe('handle.rebind to the base the widget is already on re-runs the transport probe', () => { + let blockedCore: ProxyCore + + test.beforeEach(async () => { + blockedCore = await proxyTo(kit.base, {blockUpgrades: true}) + }) + + test.afterEach(async () => { + await blockedCore.close() + }) + + test('rides the websocket after the blocked upgrade path opens up again', async ({page}) => { + test.setTimeout(180_000) + const wire = watchChatWire(page) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + + await mountHandle(page, blockedCore.base) + await openChatPanel(page) + const blocked = wire.nextTurn() + await sendChatMessage(page, 'while upgrades are blocked') + expect((await blocked).transport).toBe('fetch') + + blockedCore.setUpgradesBlocked(false) + await rebindHandle(page, blockedCore.base) + await expect(chatBox(page)).toBeVisible({timeout: 30_000}) + const reprobed = wire.nextTurn() + await sendChatMessage(page, 'after the upgrade path opens') + expect((await reprobed).transport).toBe('websocket') + }) + }) +}) + +test.describe('recording attachment', () => { + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeAll(async () => { + kit = await bootEmbedKit({text: 'Recording received', extensions: [recorderServer]}) + host = await serveHost(() => + hostPage({ + apiBase: kit.base, + widget: '{"quickTerminal":false}', + body: '', + }), ) - await page.getByRole('button', {name: 'Minimize conciv chat'}).click() - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - await until(async () => !(await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expect(page.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { - timeout: 30_000, - }) - await until(async () => (await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) - const persisted = await kit.rpc.navigation.get() - expect(persisted?.entries.filter((entry) => entry.href.includes('/panel/'))).toHaveLength(1) - }) - - test('a reload restores the panel open on the same view', async ({page, context}) => { - test.setTimeout(180_000) - const first = await openPage(page) - await openPanel(first) - await first.getByRole('tab', {name: 'Terminal'}).click() - await until(async () => (await currentHref(kit)).includes('/terminal'), {hangGuardMs: 30_000, intervalMs: 100}) - expect(await currentHref(kit)).toMatch(/\/terminal\?.*open=true/) - await first.close() - const second = await openPage(await context.newPage()) - await expect(second.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expect(second.getByRole('tab', {name: 'Terminal'})).toHaveAttribute('aria-selected', 'true', { - timeout: 30_000, - }) - }) - - test('a reload after closing the panel boots shut', async ({page, context}) => { - test.setTimeout(180_000) - const first = await openPage(page) - await openPanel(first) - await until(async () => (await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) - expect(await currentHref(kit)).toContain('open=true') - await first.getByRole('button', {name: 'Minimize conciv chat'}).click() - await until(async () => !(await currentHref(kit)).includes('open=true'), {hangGuardMs: 30_000, intervalMs: 100}) - expect(await currentHref(kit)).not.toContain('open=true') - await first.close() - const second = await openPage(await context.newPage()) - await expect(second.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) - expect(await second.getByRole('dialog', {name: 'conciv chat agent'}).count()).toBe(0) - }) - - test('renders the fab instantly and opens the panel', async ({page}) => { - test.setTimeout(120_000) - await openPage(page) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) - await openPanel(page) - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible() }) - test('opening and closing the panel keeps the host page where the reader scrolled it', async ({page}) => { - test.setTimeout(180_000) - 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() + test.afterAll(async () => { + await host.close() + await kit.cleanup() + }) + + const ClickEventSchema = z.object({ + type: z.literal(3), + data: z.looseObject({source: z.literal(2), type: z.literal(2)}), + }) - await page.mouse.wheel(0, unscrolled - 200) - await expect(heading).toBeInViewport({timeout: 30_000}) - const readerPosition = await headingTop() - expect(readerPosition).toBeLessThan(unscrolled - 1000) + const AppendedEventsSchema = z.object({events: z.array(z.unknown())}) - await openPanel(page) - expect(await headingTop()).toBe(readerPosition) + test.describe('recording attachment end to end in the real widget', () => { + test('composes the card chip, sends log text to the model, renders the durable transcript card', async ({page}) => { + test.setTimeout(480_000) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + + await openPanel(page) + const recorderRpc = makeExtRpcClient(kit.base, 'recorder') + const client: {id?: string} = {} + const clicksAppendedSince = async (cursor: number): Promise => { + if (!client.id) throw new Error('no recorder client connected') + const appended = AppendedEventsSchema.parse(await recorderRpc.events({cursor, clientId: client.id})) + return appended.events.filter((event) => ClickEventSchema.safeParse(event).success).length + } + + await page.getByRole('tab', {name: 'Recorder'}).click() + await until( + async () => { + const {clients} = await recorderRpc.clients() + if (clients.length > 1) throw new Error(`expected one recorder client for this page, saw ${clients.length}`) + client.id = clients[0]?.id + return client.id !== undefined + }, + {hangGuardMs: 30_000, intervalMs: 100}, + ) + if (!client.id) throw new Error('no recorder client connected') + const captureBaseline = (await recorderRpc.window({clientId: client.id})).cursor + + await page.getByRole('button', {name: 'Embed fixture'}).click() + await page.getByRole('button', {name: 'Embed fixture'}).click() + await until(async () => (await clicksAppendedSince(captureBaseline)) >= 2, { + hangGuardMs: 30_000, + intervalMs: 100, + }) + + 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.getByRole('textbox', {name: 'Message the conciv agent'}).press('Escape') - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - expect(await headingTop()).toBe(readerPosition) + 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 expect(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 persisted = {messages: ''} + await until( + async () => { + persisted.messages = JSON.stringify((await kit.rpc.chat.hydrate({sessionId: chatSession})).messages) + return persisted.messages.includes('[click]') + }, + {hangGuardMs: 30_000, intervalMs: 200}, + ) + expect(persisted.messages).toContain('"modelOnly":true') + + 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 expect(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 expect(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 expect(composerAfterModal).toHaveText('still alive after replay') + }) }) +}) - test('sends a message and renders the assistant reply from the fake harness', async ({page}) => { - test.setTimeout(120_000) - await openPage(page) - await openPanel(page) - await sendMessage(page, 'hi there', ASSISTANT_TEXT) +test.describe('reload continuity', () => { + const ASSISTANT_TEXT = 'Continuity reply' + + const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) + + test.describe('reload continuity through the db-backed navigation row', () => { + test('restores the open panel route, the transcript, and the draft after a reload', async ({page}) => { + test.setTimeout(240_000) + const sessionId = await openPanelOnNewSession(page, suite) + + const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) + await input.fill('remember me') + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + + await input.fill('an unsent draft survives') + await input.press('End') + await untilPanelDraft(suite.kit(), sessionId, (draft) => draft.text === 'an unsent draft survives') + + expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({text: 'an unsent draft survives'}) + + await page.reload({waitUntil: 'domcontentloaded'}) + + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toHaveText( + 'an unsent draft survives', + { + timeout: 30_000, + }, + ) + }) + }) +}) + +test.describe('remount', () => { + const ASSISTANT_TEXT = 'Remounted reply' + const USER_TEXT = 'first message before the remount' + const SECOND_USER_TEXT = 'second message after the remount' + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeAll(async () => { + host = await serveHost(() => handleHostPage()) }) - test('shows Stop instead of Send while a run is streaming; typing stays enabled', async ({page}) => { - test.setTimeout(180_000) - await openPage(page) - 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 expect(page.getByRole('button', {name: 'Stop generating'})).toBeVisible({timeout: 30_000}) - await input.fill('still typing while it runs') - await expect(input).toHaveText('still typing while it runs') - kit.harness.script.release() - await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) + test.afterAll(async () => { + await host.close() }) - test('Escape closes the panel back to the fab', async ({page}) => { - test.setTimeout(120_000) - await openPage(page) - await openPanel(page) - await page.getByRole('textbox', {name: 'Message the conciv agent'}).press('Escape') - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible() + test.beforeEach(async () => { + kit = await bootEmbedKit({text: ASSISTANT_TEXT}) }) - test('renders the conciv_ui blocking card from the tool part and answers via uiReply', async ({page}) => { - test.setTimeout(180_000) - await openPage(page) - await openPanel(page) - kit.harness.script.scriptToolCall('execute_typescript', { - typescriptCode: "return await external_conciv_ui({kind: 'confirm', question: 'Proceed with the change?'})", + test.afterEach(async () => { + await kit.cleanup() + }) + + test.describe('handle unmount and remount keeps delivering turns', () => { + test('renders the second assistant reply after a full unmount and remount', async ({page}) => { + test.setTimeout(240_000) + const pageErrors = await openHostWithHandle(page, host.base, kit.base) + await openChatPanel(page) + + await sendChatMessage(page, USER_TEXT) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + + await unmountHandle(page) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toHaveCount(0, {timeout: 30_000}) + + await remountHandle(page) + await expect(chatBox(page)).toBeVisible({timeout: 30_000}) + await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + + await sendChatMessage(page, SECOND_USER_TEXT) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) + await expect(chatLog(page).getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + + expect(pageErrors).toEqual([]) + }) + + test('renders the second assistant reply after a fresh handle replaces the unmounted one', async ({page}) => { + test.setTimeout(240_000) + const pageErrors = await openHostWithHandle(page, host.base, kit.base) + await openChatPanel(page) + + await sendChatMessage(page, USER_TEXT) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + + await unmountHandle(page) + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toHaveCount(0, {timeout: 30_000}) + + await mountHandle(page, kit.base) + await expect(chatBox(page)).toBeVisible({timeout: 30_000}) + await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) + + await sendChatMessage(page, SECOND_USER_TEXT) + await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) + await expect(chatLog(page).getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) + + expect(pageErrors).toEqual([]) }) - 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 expect(page.getByText('Proceed with the change?', {exact: true})).toBeVisible({timeout: 30_000}) - await page.getByRole('button', {name: 'Approve'}).click() - await expect(page.getByRole('status').getByText('yes')).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('button', {name: 'Approve'})).toBeHidden({timeout: 30_000}) }) +}) - test('renders catalog and code-mode parts without blanking the transcript', async ({page}) => { - test.setTimeout(120_000) - await openPage(page) - 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 expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - const announced = await page.getByRole('alert').allTextContents() - expect(announced.every((text) => text.trim() === '')).toBe(true) +test.describe('selection containment', () => { + const ASSISTANT_REPLY = 'The widget reply stays selectable inside the chat thread for quoting.' + + const HOST_TEXT = 'Host page article text that must never join a chat selection.' + + const HOST_STYLES: Record = { + 'a host page with default selection styles': '', + 'a host page that forces its article text selectable': 'main p{user-select:text}', + 'a host page that forces its article text selectable with !important': 'main p{user-select:text !important}', + } + + const hostBody = (url: URL) => ` + +
+

${HOST_TEXT}

+

${HOST_TEXT}

+

${HOST_TEXT}

+
+` + + type Point = {x: number; y: number} + + type SelectionEnds = {startInWidget: boolean; endInWidget: boolean; text: string} + + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit({text: ASSISTANT_REPLY}) + host = await serveHost((url) => + hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: hostBody(url)}), + ) + }) + + test.afterEach(async () => { + await host.close() + await kit.cleanup() }) - test('renders the new tool cards for results that do not match their payload schema', async ({page}) => { - test.setTimeout(240_000) - await openPage(page) + async function openWithReply(page: Page, hostStyle = ''): Promise { + await page.setViewportSize({width: 1400, height: 900}) + await page.goto(`${host.base}/?${new URLSearchParams({host: hostStyle})}`, {waitUntil: 'domcontentloaded'}) 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 sendAndSettleWithTraceOpen(page, 'run some code') - await expect(latestTrace(page).getByText('return 1').first()).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('button', {name: /exec return 1/})).toBeDisabled() - await sendAndSettleWithTraceOpen(page, 'now check the catalog') - await expect(latestTrace(page).getByText('Capability catalog')).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('button', {name: /Show trace$/})).toHaveCount(1) - await expect(input).toHaveText('') - const announced = await page.getByRole('alert').allTextContents() - expect(announced.every((text) => text.trim() === '')).toBe(true) + await sendMessage(page, 'say something selectable', ASSISTANT_REPLY) + } + + async function textStart(page: Page, text: string): Promise { + const box = await page.getByText(text).first().boundingBox() + expect(box).not.toBeNull() + return {x: (box?.x ?? 0) + 60, y: (box?.y ?? 0) + (box?.height ?? 0) / 2} + } + + async function drag(page: Page, from: Point, to: Point): Promise { + await page.mouse.move(from.x, from.y) + await page.mouse.down() + await page.mouse.move(to.x, to.y, {steps: 12}) + await page.mouse.up() + } + + function selectionEnds(page: Page): Promise { + return page.evaluate(() => { + const root = document.querySelector('[data-conciv-root]')?.shadowRoot + const selection = document.getSelection() + const range = root ? selection?.getComposedRanges({shadowRoots: [root]})[0] : undefined + return { + startInWidget: range?.startContainer.getRootNode() === root, + endInWidget: range?.endContainer.getRootNode() === root, + text: selection?.toString() ?? '', + } + }) + } + + test.describe('text selection and the host page', () => { + const outwardDrags: {name: string; target: (page: Page) => Promise; selects: RegExp}[] = [ + { + name: 'up past the top of the panel', + target: async (page) => ({...(await textStart(page, ASSISTANT_REPLY)), y: 2}), + selects: /^\s*CONCIV[\s\S]*say something selectable[\s\S]*The widge$/, + }, + {name: 'sideways over host page text', target: (page) => textStart(page, HOST_TEXT), selects: /^The widge$/}, + { + name: 'down past the bottom of the panel', + target: async (page) => ({...(await textStart(page, ASSISTANT_REPLY)), y: 895}), + selects: /^t reply stays selectable inside the chat thread for quoting\.\s*$/, + }, + ] + + for (const hostStyle of Object.keys(HOST_STYLES)) { + for (const outward of outwardDrags) { + test(`on ${hostStyle}, a selection dragged from the chat reply ${outward.name} stays inside the widget`, async ({ + page, + }) => { + test.setTimeout(120_000) + await openWithReply(page, hostStyle) + + await drag(page, await textStart(page, ASSISTANT_REPLY), await outward.target(page)) + + const ends = await selectionEnds(page) + expect(ends.text).toMatch(outward.selects) + expect(ends).toMatchObject({startInWidget: true, endInWidget: true}) + }) + } + } + + test('a selection started on the host page and dragged over the panel still selects host text', async ({page}) => { + test.setTimeout(120_000) + await openWithReply(page) + + await drag(page, await textStart(page, HOST_TEXT), await textStart(page, ASSISTANT_REPLY)) + + const ends = await selectionEnds(page) + expect(ends.text).toContain('page article text') + expect(ends.startInWidget).toBe(false) + }) }) }) -test.describe('embed at a phone viewport', () => { - test.use({viewport: PHONE_VIEWPORT}) +test.describe('session canonicalize', () => { + const RAW_HARNESS_ID = HarnessSessionId.parse('43548fd1-0000-4220-acf0-014b10b5815f') + const EXTERNAL_TITLE = 'a session started outside conciv' + const NEWER_HARNESS_ID = HarnessSessionId.parse('9f2c77aa-1111-4a10-b3d1-77c0a2e9b004') + const NEWER_TITLE = 'the newest session outside conciv' + + const suite = setupWidgetSuite({ + history: [ + {id: NEWER_HARNESS_ID, derivedTitle: NEWER_TITLE, updatedAt: Date.now(), messageCount: 1}, + {id: RAW_HARNESS_ID, derivedTitle: EXTERNAL_TITLE, updatedAt: Date.now() - 60_000, messageCount: 3}, + ], + }) + + test.describe('switching to a harness session conciv has never adopted', () => { + test('lands the panel on the canonical conciv session route, not the raw harness id', async ({page}) => { + test.setTimeout(180_000) + + const metas = await suite.kit().rpc.sessions.list() + expect(metas.map((meta) => String(meta.id)).filter((id) => !id.startsWith('conciv_'))).toEqual([]) + const external = metas.find((meta) => meta.title === EXTERNAL_TITLE) + if (!external) throw new Error('the harness-native session was not listed under its derived title') + const newer = metas.find((meta) => meta.title === NEWER_TITLE) + if (!newer) throw new Error('the newest harness-native session was not listed under its derived title') - test('paints an opaque sheet so the host page never shows through', async ({page}) => { - test.setTimeout(240_000) - const shootOver = async (backdrop: string): Promise => { - await page.goto(`${host.base}/?backdrop=${backdrop}`, {waitUntil: 'domcontentloaded'}) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) await openPanel(page) - const shot = await page.screenshot({animations: 'disabled', clip: SHEET_INTERIOR_CLIP}) - await page.getByRole('button', {name: 'Close chat'}).click() - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - return shot - } - 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) + + const sessionOptions = page.getByRole('button', {name: 'Session options'}) + await sessionOptions.click() + await page.getByRole('button', {name: /^Session: /}).click() + const search = page.getByPlaceholder('Search sessions…') + await expect(search).toBeVisible({timeout: 30_000}) + + await search.fill(String(RAW_HARNESS_ID)) + await expect(page.getByText('No sessions match')).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('option', {name: new RegExp(EXTERNAL_TITLE)})).toHaveCount(0) + + await search.fill(String(external.id)) + const canonicalOption = page.getByRole('option', {name: new RegExp(EXTERNAL_TITLE)}) + await expect(canonicalOption).toBeVisible({timeout: 30_000}) + + await canonicalOption.click() + const pill = page.getByRole('button', {name: `Session: ${EXTERNAL_TITLE}`}) + if (!(await pill.isVisible())) await sessionOptions.click() + await expect(pill).toBeVisible({timeout: 30_000}) + + await until(async () => (await currentHref(suite.kit())).includes(String(external.id)), { + hangGuardMs: 30_000, + intervalMs: 100, + }) + const href = await currentHref(suite.kit()) + expect(href).not.toContain(RAW_HARNESS_ID) + expect(href).not.toContain(newer.id) + + const adopted = await suite.kit().rpc.sessions.resolve({id: RAW_HARNESS_ID}) + expect(adopted.sessionId).toBe(external.id) + }) }) +}) - test('opens as a full-screen sheet with the launcher hidden and the composer reachable', async ({page}) => { - test.setTimeout(240_000) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await expect(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 expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 30_000}) +test.describe('tool code body', () => { + const ASSISTANT_TEXT = 'Read the pipeline.' + const RESULT_MARKER = 'pipeline body renders on the built bundle' + + const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) + + async function sendAndOpenTrace(page: Page, message: string): Promise { + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(message) + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) + await expect(page.getByRole('button', {name: /Hide trace$/}).last()).toBeVisible({timeout: 30_000}) + } + + test.describe('tool result code bodies on the built bundle', () => { + test('renders the lines of a tool result code body', async ({page}) => { + test.setTimeout(180_000) + suite.kit().harness.script.scriptTurn({ + toolCalls: [{name: 'Read', input: {filePath: 'pipeline.ts'}, result: RESULT_MARKER}], + text: ASSISTANT_TEXT, + }) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await sendAndOpenTrace(page, 'read the pipeline file') + + await expect(page.getByText(RESULT_MARKER).first()).toBeVisible({timeout: 30_000}) + }) + }) +}) + +test.describe('transport selection', () => { + const ASSISTANT_TEXT = 'Hello from conciv' + const MOUNT_TIMEOUT_MS = 30_000 + + let kit: EmbedKit + let openCore: ProxyCore + let blockedCore: ProxyCore + let openHost: {base: string; close: () => Promise} + let blockedHost: {base: string; close: () => Promise} + let pinnedFetchHost: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit({text: ASSISTANT_TEXT}) + openCore = await proxyTo(kit.base) + blockedCore = await proxyTo(kit.base, {blockUpgrades: true}) + openHost = await serveHost(() => hostPage({apiBase: openCore.base, widget: '{"quickTerminal":false}'})) + blockedHost = await serveHost(() => hostPage({apiBase: blockedCore.base, widget: '{"quickTerminal":false}'})) + pinnedFetchHost = await serveHost(() => + hostPage({apiBase: openCore.base, widget: '{"quickTerminal":false,"transport":"fetch"}'}), + ) + }) + + test.afterEach(async () => { + await openHost.close() + await blockedHost.close() + await pinnedFetchHost.close() + await openCore.close() + await blockedCore.close() + await kit.cleanup() }) - test.describe('a narrower phone width', () => { - test.use({viewport: {width: 320, height: 800}}) + type Tab = {page: Page; calls: RpcCallCursor; wire: ChatWireWatch; httpRpcUrls: string[]} - test('keeps the single trailing button and the model menu reachable inside the sheet on a narrow phone while a run streams', async ({ + async function openTab(page: Page, hostBase: string): Promise { + const {urls} = httpRpcRequestUrls(page) + const calls = rpcCallCursor(page) + const wire = watchChatWire(page) + await page.goto(hostBase, {waitUntil: 'domcontentloaded'}) + return {page, calls, wire, httpRpcUrls: urls} + } + + async function completeTurn(page: Page): Promise { + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill('hi there') + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) + } + + test.describe('the chat connection picks one delivery transport per tab at boot', () => { + test('rides the chat websocket when the boot probe succeeds, while rpc rides http', async ({page}) => { + test.setTimeout(120_000) + const tab = await openTab(page, openHost.base) + const sent = tab.wire.nextTurn() + await completeTurn(tab.page) + expect((await sent).transport).toBe('websocket') + expect(tab.calls.socketsSince()).toBe(0) + expect(tab.httpRpcUrls.length).toBeGreaterThan(0) + }) + + test('falls back to the chat event stream for the whole tab when the websocket upgrade is blocked', async ({ page, }) => { - test.setTimeout(180_000) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + test.setTimeout(120_000) + const tab = await openTab(page, blockedHost.base) + const sent = tab.wire.nextTurn() + await completeTurn(tab.page) + expect((await sent).transport).toBe('fetch') + expect(tab.httpRpcUrls.length).toBeGreaterThan(0) + }) + + test('honours the fetch escape hatch without ever opening a chat socket', async ({page}) => { + test.setTimeout(120_000) + const tab = await openTab(page, pinnedFetchHost.base) + const mark = tab.wire.socketMark() + const sent = tab.wire.nextTurn() + await completeTurn(tab.page) + expect((await sent).transport).toBe('fetch') + expect(tab.wire.socketsOpenedSince(mark)).toBe(0) + }) + }) +}) + +test.describe('unknown view restore', () => { + const suite = setupWidgetSuite({text: 'Unknown view reply', extensions: [recorderServer]}) + + test.describe('restoring a persisted panel route whose extension view is no longer mounted', () => { + test('lands on the chat view instead of an empty pane', async ({page}) => { + test.setTimeout(240_000) + await page.goto(suite.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'}) - const moreActions = page.getByRole('button', {name: 'More composer actions'}) - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill('a question that keeps running') - await send.click() - await expect(stop).toBeVisible({timeout: 30_000}) - await expect(send).toBeHidden() - await expect(moreActions).toBeInViewport({ratio: 1, timeout: 5_000}) - await expect(stop).toBeInViewport({ratio: 1, timeout: 5_000}) - await moreActions.click() - await expect(page.getByRole('menuitem', {name: /^Model: /}).first()).toBeVisible({timeout: 30_000}) - await page.keyboard.press('Escape') - kit.harness.script.release() - await expect(stop).toBeHidden({timeout: 30_000}) - await expect(send).toBeVisible() - await expect(send).toBeInViewport({ratio: 1, timeout: 5_000}) + + await page.getByRole('tab', {name: 'Recorder'}).click() + await expect(page.getByRole('tab', {name: 'Recorder'})).toHaveAttribute('aria-selected', 'true') + await until(async () => (await currentHref(suite.kit())).includes('/recorder'), { + hangGuardMs: 30_000, + intervalMs: 100, + }) + + await page.goto(`${suite.host().base}/?extensions=terminal`, {waitUntil: 'domcontentloaded'}) + + await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) + await expect(page.getByRole('tab', {name: 'Recorder'})).toHaveCount(0) + await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toBeVisible({timeout: 30_000}) + const statusBar = page.getByRole('toolbar', {name: 'Session status'}) + await expect(statusBar.getByRole('tab', {name: 'Chat', exact: true})).toHaveAttribute('aria-selected', 'true') + await until(async () => !(await currentHref(suite.kit())).includes('/recorder'), { + hangGuardMs: 30_000, + intervalMs: 100, + }) }) }) }) -test.describe('embed settings', () => { - test('modal disabled renders no fab', async ({page}) => { - const disabledHost = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"modal": false}'})) - 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 disabledHost.close() +test.describe('virtualize threshold cliff', () => { + const MARKDOWN_HEAVY_REPLY = [ + '## Findings', + '', + 'Here is a **detailed** breakdown with `inline code` and a fenced block:', + '', + '```ts', + 'function reconcileSnapshotToolCalls(snapshot: UIMessage[]): UIMessage[] {', + ' const prevToolCalls = new Map()', + ' for (const msg of snapshot) for (const part of msg.parts) {', + ' if (part.type === "tool-call") prevToolCalls.set(part.id, part)', + ' }', + ' return snapshot', + '}', + '```', + '', + '- first bullet point with some explanation', + '- second bullet point that is a bit longer to force line wrapping in the estimator', + '- third bullet point', + '', + '> a blockquote noting a caveat worth remembering', + ].join('\n') + + const VIRTUALIZE_THRESHOLD_MIRRORED_FROM_UI_KIT_CHAT = 15 + const BELOW_EXCHANGES = Math.floor((VIRTUALIZE_THRESHOLD_MIRRORED_FROM_UI_KIT_CHAT - 1) / 2) + const ABOVE_EXCHANGES = Math.ceil(VIRTUALIZE_THRESHOLD_MIRRORED_FROM_UI_KIT_CHAT / 2) + + const suite = setupWidgetSuite({text: MARKDOWN_HEAVY_REPLY}) + + async function seedExchanges(sessionId: string, exchanges: number): Promise { + const kit = suite.kit() + for (let index = 0; index < exchanges; index += 1) { + const turn = await kit.chat(`question number ${index} about the reconciliation logic`, sessionId) + await turn.done({hangGuardMs: 10_000}) + } + } + + async function measureSwitch(page: import('@playwright/test').Page, exchanges: number): Promise<{rowCount: number}> { + const {sessionId} = await suite.kit().rpc.sessions.create() + const title = `cliff ${exchanges} ${sessionId.slice(-8)}` + await suite.kit().rpc.sessions.rename({sessionId, title}) + await seedExchanges(sessionId, exchanges) + + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await switchToSessionByTitle(page, title) + await expect(page.getByText(`question number ${exchanges - 1}`).first()).toBeVisible({timeout: 30_000}) + + const rowCount = await page.locator('[data-message-id]').count() + return {rowCount} + } + + test.describe('virtualize threshold cliff', () => { + test('a transcript just below the virtualize threshold mounts every turn; crossing it bounds the DOM again', async ({ + page, + }) => { + test.setTimeout(240_000) + const below = await measureSwitch(page, BELOW_EXCHANGES) + console.log(`BELOW THRESHOLD (${BELOW_EXCHANGES * 2} turns, flat mode) rendered row count`, below.rowCount) + + const at = await measureSwitch(page, ABOVE_EXCHANGES) + console.log(`AT THRESHOLD (${ABOVE_EXCHANGES * 2} turns, virtual mode) rendered row count`, at.rowCount) + + expect(below.rowCount, 'below the threshold every turn is mounted unvirtualized').toBe(BELOW_EXCHANGES * 2) + expect( + at.rowCount, + 'at/above the threshold the virtualizer bounds the mounted rows to a window smaller than the transcript', + ).toBeLessThan(ABOVE_EXCHANGES * 2) + }) + }) +}) + +test.describe('warm session resolve', () => { + const suite = setupWidgetSuite() + + const COMPOSER_NAME = 'Message the conciv agent' + const LAUNCHER_NAME = 'Open conciv chat' + const SESSIONS_LIST = ['sessions', 'list'] as const + const SESSIONS_RESOLVE = ['sessions', 'resolve'] as const + + const dedicatedHosts: Array<{close: () => Promise}> = [] + + test.afterEach(async () => { + for (const dedicatedHost of dedicatedHosts.splice(0)) await dedicatedHost.close() + }) + + function composer(page: Page) { + return page.getByRole('textbox', {name: COMPOSER_NAME}) + } + + function launcher(page: Page) { + return page.getByRole('button', {name: LAUNCHER_NAME}) + } + + type StalledSessionRpcs = {list: RpcGate; resolve: RpcGate} + + async function stallSessionRpcs(page: Page): Promise { + const list = await gateRpcCalls(page, {path: SESSIONS_LIST}) + const resolve = await gateRpcCalls(page, {path: SESSIONS_RESOLVE}) + return {list, resolve} + } + + test.describe('first panel open does not re-run session resolution at click time', () => { + test('clicking the launcher after boot has settled still reveals the composer with sessions RPCs stalled', async ({ + page, + }) => { + test.setTimeout(30_000) + await suite.kit().rpc.sessions.create() + const host = await serveHost(() => + hostPage({apiBase: suite.kit().base, widget: '{"quickTerminal":false,"transport":"fetch"}'}), + ) + dedicatedHosts.push(host) + const wire = watchRpcWire(page) + await page.goto(host.base, {waitUntil: 'domcontentloaded'}) + await expect(launcher(page)).toBeVisible({timeout: 15_000}) + await wire.sessionsBootTraffic() + + const stalled = await stallSessionRpcs(page) + try { + await launcher(page).click() + + await expect(composer(page)).toBeVisible({timeout: 5_000}) + expect(stalled.resolve.pending()).toBe(0) + } finally { + await stalled.list.dispose() + await stalled.resolve.dispose() + } + }) }) }) diff --git a/packages/embed/tests/e2e/fab-drag-snap.it.test.ts b/packages/embed/tests/e2e/fab-drag-snap.it.test.ts deleted file mode 100644 index 0f6a9945fc..0000000000 --- a/packages/embed/tests/e2e/fab-drag-snap.it.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' - -const suite = setupWidgetSuite() - -type Frame = {x: number; y: number; width: number; height: number} - -const launcher = (page: Page) => page.getByRole('button', {name: 'Open conciv chat'}) - -async function armFrameSampler(page: Page): Promise { - await page.evaluate(() => { - const shadowHosts = [...document.querySelectorAll('*')] - const element = - document.querySelector('[data-conciv-fab]') ?? - shadowHosts.map((host) => host.shadowRoot?.querySelector('[data-conciv-fab]')).find(Boolean) - if (!(element instanceof HTMLElement)) throw new Error('launcher not found') - globalThis.__fabFrames = new Promise((resolve) => { - const frames: Array<{x: number; y: number; width: number; height: number}> = [] - const tick = () => { - const rect = element.getBoundingClientRect() - frames.push({x: rect.x, y: rect.y, width: rect.width, height: rect.height}) - if (frames.length < 72) { - requestAnimationFrame(tick) - return - } - resolve(frames) - } - window.addEventListener('pointerup', () => requestAnimationFrame(tick), {once: true, capture: true}) - }) - }) -} - -async function collectFrames(page: Page): Promise { - return page.evaluate(() => globalThis.__fabFrames) -} - -async function dragLauncherTo(page: Page, target: {x: number; y: number}): Promise { - const box = await launcher(page).boundingBox() - if (!box) throw new Error('launcher has no box') - const startX = box.x + box.width / 2 - const startY = box.y + box.height / 2 - await page.mouse.move(startX, startY) - await page.mouse.down() - await page.mouse.move(target.x, target.y, {steps: 12}) -} - -function outsideViewport(frames: Frame[], viewport: {width: number; height: number}): Frame[] { - return frames.filter( - (frame) => - frame.x < -0.5 || - frame.y < -0.5 || - frame.x + frame.width > viewport.width + 0.5 || - frame.y + frame.height > viewport.height + 0.5, - ) -} - -function largestRetreat(frames: Frame[]): number { - const last = frames[frames.length - 1] - if (!last) return 0 - const distances = frames.map((frame) => Math.hypot(frame.x - last.x, frame.y - last.y)) - return distances.reduce((worst, distance, index) => Math.max(worst, distance - (distances[index - 1] ?? distance)), 0) -} - -test('a launcher dropped past the viewport edge settles inward without ever leaving the viewport', async ({page}) => { - const viewport = page.viewportSize() - if (!viewport) throw new Error('no viewport') - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await expect(launcher(page)).toBeVisible() - - await dragLauncherTo(page, {x: viewport.width - 2, y: 2}) - await armFrameSampler(page) - await page.mouse.up() - - await expect(launcher(page)).not.toHaveClass(/cursor-grabbing/) - const frames = await collectFrames(page) - - expect(outsideViewport(frames, viewport)).toEqual([]) - expect(largestRetreat(frames)).toBeLessThanOrEqual(1) -}) diff --git a/packages/embed/tests/e2e/fab-mascot.it.test.ts b/packages/embed/tests/e2e/fab-mascot.it.test.ts deleted file mode 100644 index 85c7ec5a38..0000000000 --- a/packages/embed/tests/e2e/fab-mascot.it.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {sendHeldTurn} from './helpers/chat.js' -import {setupWidgetSuite} from './helpers/suite.js' - -const suite = setupWidgetSuite() - -const IMMEDIATE_MS = 2_000 - -const stage = (page: Page) => page.locator('[data-conciv-fab] .conciv-fab-rig[aria-hidden="true"]') - -const glowingEyes = (page: Page) => - page.locator('[data-conciv-fab] .conciv-fab-busy ~ .conciv-fab-rig .conciv-rig-eyes') - -const restingEyes = (page: Page) => page.locator('[data-conciv-fab] .conciv-fab-rig .conciv-rig-eyes') - -const emitter = (page: Page) => - page.locator('[data-conciv-fab] .conciv-fab-rig [data-scope="mascot"][data-part="effect"] > span') - -test('the launcher hosts the mascot stage as decorative content', async ({page}) => { - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible() - await expect(stage(page)).toBeVisible() - await expect(restingEyes(page)).toBeAttached() -}) - -test('an idle launcher never matches the busy eye-glow selector', async ({page}) => { - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - - await expect(stage(page)).toBeVisible() - await expect(glowingEyes(page)).toHaveCount(0) -}) - -test('a streaming run puts the busy overlay ahead of the stage so the eye-glow selector matches', async ({page}) => { - await sendHeldTurn(page, suite) - - await expect(glowingEyes(page)).toBeAttached({timeout: IMMEDIATE_MS}) -}) - -test('the emitter keeps running while the panel is open during a run', async ({page}) => { - await sendHeldTurn(page, suite) - - await expect(emitter(page)).toHaveCount(1) -}) diff --git a/packages/embed/tests/e2e/fab-working.it.test.ts b/packages/embed/tests/e2e/fab-working.it.test.ts deleted file mode 100644 index b3d7bbb921..0000000000 --- a/packages/embed/tests/e2e/fab-working.it.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' -import {sendHeldTurn} from './helpers/chat.js' - -const suite = setupWidgetSuite() - -const IMMEDIATE_MS = 2_000 - -function openLauncher(page: Page) { - return page.getByRole('button', {name: 'Open conciv chat'}) -} - -function panelLauncher(page: Page) { - return page.getByRole('button', {name: 'Minimize conciv chat'}) -} - -function stopButton(page: Page) { - return page.getByRole('button', {name: 'Stop generating'}) -} - -test('the sending tab marks the open panel launcher busy while its run is still streaming', async ({page}) => { - await sendHeldTurn(page, suite) - - await expect(panelLauncher(page)).toHaveAttribute('aria-busy', 'true', {timeout: IMMEDIATE_MS}) -}) - -test('minimizing the panel mid-run leaves the closed launcher wearing the busy state', async ({page}) => { - await sendHeldTurn(page, suite) - - await panelLauncher(page).click() - - await expect(openLauncher(page)).toHaveAttribute('aria-busy', 'true', {timeout: IMMEDIATE_MS}) -}) - -test('switching to a new session mid-run hands the busy state over to the session list', async ({page}) => { - await sendHeldTurn(page, suite) - - await page.getByRole('button', {name: 'More composer actions'}).click() - await page.getByRole('menuitem', {name: 'Start a new session'}).click() - - await expect(stopButton(page)).toHaveCount(0, {timeout: IMMEDIATE_MS}) - await expect(panelLauncher(page)).toHaveAttribute('aria-busy', 'false') - - await page.getByRole('button', {name: 'Session options'}).click() - await page.getByRole('button', {name: /^Session: /}).click() - await expect(page.getByRole('option', {name: /running/})).toBeVisible({timeout: 30_000}) -}) diff --git a/packages/embed/tests/e2e/forced-drop.it.test.ts b/packages/embed/tests/e2e/forced-drop.it.test.ts deleted file mode 100644 index 9bb5b4138e..0000000000 --- a/packages/embed/tests/e2e/forced-drop.it.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {watchChatWire} from '@conciv/extension-testkit/chat-wire' -import {setupProxiedEmbedSuite} from './helpers/proxied-suite.js' - -const ASSISTANT_TEXT = 'Reply across the drop' -const FIRST_TEXT = 'first turn before the drop' -const SECOND_TEXT = 'second turn after the drop' -const MOUNT_TIMEOUT_MS = 20_000 - -const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT}) - -async function sendTurn(page: Page, text: string): Promise { - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(text) - await page.getByRole('button', {name: 'Send message'}).click() -} - -test.describe('chat survives a forced websocket drop', () => { - test('reopens the chat socket and completes the next turn after the core drops every connection', async ({page}) => { - test.setTimeout(120_000) - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - const wire = watchChatWire(page) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toBeVisible({ - timeout: MOUNT_TIMEOUT_MS, - }) - - const first = wire.nextTurn() - await sendTurn(page, FIRST_TEXT) - expect((await first).transport).toBe('websocket') - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: MOUNT_TIMEOUT_MS}) - - const mark = wire.socketMark() - const second = wire.nextTurn() - suite.core().dropConnections() - - await sendTurn(page, SECOND_TEXT) - expect((await second).transport).toBe('websocket') - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: MOUNT_TIMEOUT_MS}) - - expect(wire.socketsOpenedSince(mark)).toBeGreaterThan(0) - expect(pageErrors).toEqual([]) - }) -}) diff --git a/packages/embed/tests/e2e/helpers/chat.ts b/packages/embed/tests/e2e/helpers/chat.ts deleted file mode 100644 index 7980e2facd..0000000000 --- a/packages/embed/tests/e2e/helpers/chat.ts +++ /dev/null @@ -1,31 +0,0 @@ -import {expect, type Page} from '@playwright/test' -import type {WidgetSuite} from './suite.js' - -const PANEL_TIMEOUT_MS = 30_000 - -export function chatLog(page: Page) { - return page.getByRole('log') -} - -export function chatBox(page: Page) { - return page.getByRole('textbox', {name: 'Message the conciv agent'}) -} - -export async function openChatPanel(page: Page): Promise { - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: PANEL_TIMEOUT_MS}) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expect(chatBox(page)).toBeVisible({timeout: PANEL_TIMEOUT_MS}) -} - -export async function sendChatMessage(page: Page, text: string): Promise { - await chatBox(page).fill(text) - await page.getByRole('button', {name: 'Send message'}).click() -} - -export async function sendHeldTurn(page: Page, suite: WidgetSuite): Promise { - suite.kit().harness.script.hold() - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openChatPanel(page) - await sendChatMessage(page, 'hold this turn open') - await expect(page.getByRole('button', {name: 'Stop generating'})).toBeVisible() -} diff --git a/packages/embed/tests/e2e/helpers/drafts.ts b/packages/embed/tests/e2e/helpers/drafts.ts deleted file mode 100644 index 75c4b8f070..0000000000 --- a/packages/embed/tests/e2e/helpers/drafts.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type {DraftRow} from '@conciv/contract' -import {until} from '@conciv/harness-testkit/until' -import type {EmbedKit} from '../../helpers/boot.js' - -export function untilPanelDraft( - kit: EmbedKit, - sessionId: string, - matches: (draft: DraftRow) => boolean, -): Promise { - return until( - async () => { - const draft = await kit.rpc.drafts.get({sessionId}) - return draft !== null && matches(draft) - }, - {hangGuardMs: 30_000, intervalMs: 100}, - ) -} diff --git a/packages/embed/tests/e2e/helpers/handle.ts b/packages/embed/tests/e2e/helpers/handle.ts deleted file mode 100644 index 539029854b..0000000000 --- a/packages/embed/tests/e2e/helpers/handle.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type {Page} from '@playwright/test' - -export async function mountHandle(page: Page, apiBase: string): Promise { - await page.evaluate((base) => { - const el = document.createElement('div') - document.body.appendChild(el) - window.concivTestElement = el - window.concivTestHandle = window.ConcivHandle.makeHandle(base) - void window.concivTestHandle.mount(el) - }, apiBase) -} - -export async function openHostWithHandle(page: Page, hostBase: string, apiBase: string): Promise { - const pageErrors: string[] = [] - page.on('pageerror', (error) => pageErrors.push(String(error))) - await page.goto(hostBase, {waitUntil: 'domcontentloaded'}) - await mountHandle(page, apiBase) - return pageErrors -} - -export async function remountHandle(page: Page): Promise { - await page.evaluate(() => void window.concivTestHandle.mount(window.concivTestElement)) -} - -export async function unmountHandle(page: Page): Promise { - await page.evaluate(() => window.concivTestHandle.unmount()) -} - -export async function rebindHandle(page: Page, apiBase: string): Promise { - await page.evaluate((base) => window.concivTestHandle.rebind(base), apiBase) -} diff --git a/packages/embed/tests/e2e/helpers/native-bridge.ts b/packages/embed/tests/e2e/helpers/native-bridge.ts deleted file mode 100644 index 4cc4f469a4..0000000000 --- a/packages/embed/tests/e2e/helpers/native-bridge.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type {Page} from '@playwright/test' -import {PageToNativeSchema, type PageToNativeMessage} from '@conciv/extension-ios/bridge' - -export type NativeBridge = { - posted: PageToNativeMessage[] - notify: (message: PageToNativeMessage) => void -} - -export async function captureNativePosts(page: Page): Promise { - const bridge: NativeBridge = {posted: [], notify: () => {}} - await page.exposeFunction('concivNativePost', (message: unknown) => { - const parsed = PageToNativeSchema.safeParse(message) - if (!parsed.success) return - bridge.posted.push(parsed.data) - bridge.notify(parsed.data) - }) - return bridge -} - -export async function installNativeStub(page: Page): Promise { - await page.addInitScript(() => { - window.webkit = { - messageHandlers: {concivBridge: {postMessage: (message) => void window.concivNativePost(message)}}, - } - }) -} diff --git a/packages/embed/tests/e2e/helpers/page-plane-host.ts b/packages/embed/tests/e2e/helpers/page-plane-host.ts deleted file mode 100644 index 45daceff48..0000000000 --- a/packages/embed/tests/e2e/helpers/page-plane-host.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type {Page} from '@playwright/test' -import {awaitPagePlaneSubscribed} from '@conciv/extension-testkit/page-plane' - -const PAGE_DRIVER_TIMEOUT_MS = 30_000 - -export async function openPagePlaneHost(page: Page, base: string): Promise { - await awaitPagePlaneSubscribed(page, async () => { - await page.goto(base, {waitUntil: 'domcontentloaded'}) - await page.waitForFunction(() => '__CONCIV_PAGE_DRIVER__' in window, undefined, {timeout: PAGE_DRIVER_TIMEOUT_MS}) - }) - return page -} diff --git a/packages/embed/tests/e2e/helpers/panel.ts b/packages/embed/tests/e2e/helpers/panel.ts deleted file mode 100644 index 55f38c82b5..0000000000 --- a/packages/embed/tests/e2e/helpers/panel.ts +++ /dev/null @@ -1,42 +0,0 @@ -import {expect, type Page} from '@playwright/test' -import type {WidgetSuite} from './suite.js' - -const escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - -export async function openPanel(page: Page): Promise { - const composer = page.getByRole('textbox', {name: 'Message the conciv agent'}) - const opener = page.getByRole('button', {name: 'Open conciv chat'}) - await expect(composer.or(opener)).toBeVisible({timeout: 30_000}) - if (!(await composer.isVisible())) await opener.click() - await expect(composer).toBeVisible({timeout: 30_000}) -} - -export async function switchToSessionByTitle(page: Page, title: string): Promise { - const sessionOptions = page.getByRole('button', {name: 'Session options'}) - await sessionOptions.click() - await page.getByRole('button', {name: /^Session: /}).click() - const option = page.getByRole('option', {name: new RegExp(escapeRegex(title))}) - await expect(option).toBeVisible({timeout: 30_000}) - await option.click() - const pill = page.getByRole('button', {name: `Session: ${title}`}) - if (!(await pill.isVisible())) await sessionOptions.click() - await expect(pill).toBeVisible({timeout: 30_000}) - await page.keyboard.press('Escape') - await expect(pill).toBeHidden({timeout: 30_000}) -} - -export async function openPanelOnNewSession(page: Page, suite: WidgetSuite): Promise { - const {sessionId} = await suite.kit().rpc.sessions.create() - const title = `session under test ${sessionId.slice(-12)}` - await suite.kit().rpc.sessions.rename({sessionId, title}) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await switchToSessionByTitle(page, title) - return sessionId -} - -export async function sendMessage(page: Page, text: string, reply: string): Promise { - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(text) - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByText(reply).first()).toBeVisible({timeout: 30_000}) -} diff --git a/packages/embed/tests/e2e/helpers/proxied-suite.ts b/packages/embed/tests/e2e/helpers/proxied-suite.ts deleted file mode 100644 index 68a2843888..0000000000 --- a/packages/embed/tests/e2e/helpers/proxied-suite.ts +++ /dev/null @@ -1,41 +0,0 @@ -import {test} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../../helpers/boot.js' -import {hostPage} from '../../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {proxyTo, type ProxyCore} from '../../helpers/proxy.js' - -export type ProxiedEmbedSuite = { - kit: () => EmbedKit - core: () => ProxyCore - host: () => {base: string; close: () => Promise} -} - -export function setupProxiedEmbedSuite( - opts: { - text?: string - widget?: string - proxy?: {blockUpgrades?: boolean; port?: number} - } = {}, -): ProxiedEmbedSuite { - let kit: EmbedKit - let core: ProxyCore - let host: {base: string; close: () => Promise} - - test.beforeEach(async () => { - kit = await bootEmbedKit({text: opts.text}) - core = await proxyTo(kit.base, opts.proxy) - host = await serveHost(() => hostPage({apiBase: core.base, widget: opts.widget ?? '{"quickTerminal":false}'})) - }) - - test.afterEach(async () => { - await host.close() - await core.close() - await kit.cleanup() - }) - - return { - kit: () => kit, - core: () => core, - host: () => host, - } -} diff --git a/packages/embed/tests/e2e/helpers/suite.ts b/packages/embed/tests/e2e/helpers/suite.ts deleted file mode 100644 index 3f26da9f7f..0000000000 --- a/packages/embed/tests/e2e/helpers/suite.ts +++ /dev/null @@ -1,27 +0,0 @@ -import {test} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../../helpers/boot.js' -import {hostPage} from '../../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' - -export type WidgetSuite = { - kit: () => EmbedKit - host: () => {base: string; close: () => Promise} -} - -export function setupWidgetSuite(options: Parameters[0] = {}): WidgetSuite { - let kit: EmbedKit - let host: {base: string; close: () => Promise} - - test.beforeEach(async () => { - kit = await bootEmbedKit(options) - host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}'})) - }) - - test.afterEach(async () => { - kit.harness.script.release() - await host.close() - await kit.cleanup() - }) - - return {kit: () => kit, host: () => host} -} diff --git a/packages/embed/tests/e2e/host-hotkey-isolation.it.test.ts b/packages/embed/tests/e2e/host-hotkey-isolation.it.test.ts deleted file mode 100644 index 9f6ad9e5ba..0000000000 --- a/packages/embed/tests/e2e/host-hotkey-isolation.it.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' -import {openPanelOnNewSession} from './helpers/panel.js' -import type {WidgetSuite} from './helpers/suite.js' - -const HOST_SEARCH_HOTKEY = ` - - - -` - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeEach(async () => { - kit = await bootEmbedKit() - host = await serveHost(() => - hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: HOST_SEARCH_HOTKEY}), - ) -}) - -test.afterEach(async () => { - await host.close() - await kit.cleanup() -}) - -const suite: WidgetSuite = {kit: () => kit, host: () => host} - -const composer = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) -const hostSearch = (page: Page) => page.getByRole('status', {name: 'host search'}) - -test.describe('host-page keyboard hotkeys and the widget composer', () => { - test('a slash typed into the composer never reaches the host search hotkey', async ({page}) => { - test.setTimeout(120_000) - await openPanelOnNewSession(page, suite) - const input = composer(page) - await input.click() - await expect(input).toHaveText('') - - await input.pressSequentially('run tests in lib/utils') - await expect(input).toHaveText(/utils/, {timeout: 30_000}) - - await expect(hostSearch(page)).toHaveText('host search idle') - await expect(input).toHaveText('run tests in lib/utils') - }) - - test('a slash pressed with focus on the host page still fires the host search hotkey', async ({page}) => { - test.setTimeout(120_000) - await openPanelOnNewSession(page, suite) - - await page.getByRole('button', {name: 'Host focus target'}).click() - await page.keyboard.press('/') - - await expect(hostSearch(page)).toHaveText('host search open', {timeout: 30_000}) - }) -}) diff --git a/packages/embed/tests/e2e/idle-fetch-heartbeat.it.test.ts b/packages/embed/tests/e2e/idle-fetch-heartbeat.it.test.ts deleted file mode 100644 index 0ea1fdd513..0000000000 --- a/packages/embed/tests/e2e/idle-fetch-heartbeat.it.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import {expect, test} from '@playwright/test' -import {holdRpcCalls} from '@conciv/extension-testkit/rpc-fault' -import {rpcCallCursor} from '@conciv/extension-testkit/rpc-counts' -import {openChatPanel} from './helpers/chat.js' -import {setupProxiedEmbedSuite} from './helpers/proxied-suite.js' - -const ASSISTANT_TEXT = 'Idle heartbeat reply' -const SETTLE_MS = 3_000 -const UNREACHABLE_TIMEOUT_MS = 45_000 -const RECOVERY_TIMEOUT_MS = 20_000 -const HEARTBEAT_WINDOW_MS = 32_000 - -const suite = setupProxiedEmbedSuite({text: ASSISTANT_TEXT}) - -test.describe('an idle widget notices the engine going unreachable through the rpc heartbeat', () => { - test('the open panel heartbeat surfaces the unreachable notice with no user interaction, and clears it on recovery', async ({ - page, - }) => { - test.setTimeout(120_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openChatPanel(page) - await page.waitForTimeout(SETTLE_MS) - - const hold = await holdRpcCalls(page) - hold.hold() - const cursor = rpcCallCursor(page) - - const notice = page.getByText('conciv lost connection to the engine.') - await expect(notice).toBeVisible({timeout: UNREACHABLE_TIMEOUT_MS}) - expect(cursor.startedSince(['meta', 'engine'])).toBeGreaterThanOrEqual(1) - - hold.release() - - await expect(notice).not.toBeVisible({timeout: RECOVERY_TIMEOUT_MS}) - }) - - test('closing the panel stops the heartbeat from polling the engine', async ({page}) => { - test.setTimeout(60_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openChatPanel(page) - await page.waitForTimeout(SETTLE_MS) - await page.getByRole('button', {name: 'Close chat'}).click() - - const cursor = rpcCallCursor(page) - await page.waitForTimeout(HEARTBEAT_WINDOW_MS) - - expect(cursor.startedSince(['meta', 'engine'])).toBe(0) - }) -}) diff --git a/packages/embed/tests/e2e/landing-cost.it.test.ts b/packages/embed/tests/e2e/landing-cost.it.test.ts deleted file mode 100644 index ba551c4395..0000000000 --- a/packages/embed/tests/e2e/landing-cost.it.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import {expect, test} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' - -const STEPS = 30 -const PACE_MS = 300 -const FRAME_BUDGET_P95_MS = 20 - -const suite = setupWidgetSuite({}) - -function sourceLine(index: number): string { - const body = [ - `export async function resolveStep${index}(input: PipelineInput, options: StepOptions = {}): Promise {`, - ` const resolved = await lookupTable.get(input.steps[${index}]?.identifier ?? fallbackIdentifier)`, - ` if (!resolved) throw new StepResolutionError('step ${index} could not be resolved', {cause: input})`, - ` return {identifier: resolved.identifier, value: resolved.value * ${index + 1}, retries: options.retries ?? 0}`, - '}', - '', - ] - return body[index % body.length] ?? '' -} - -function readResult(fileIndex: number, lines: number): string { - return Array.from({length: lines}, (_, index) => { - const number = String(index + 1).padStart(6, ' ') - return `${number}\t${sourceLine(index + fileIndex)}` - }).join('\n') -} - -function readSteps(): Array<{name: string; input: Record; result: string}> { - return Array.from({length: STEPS}, (_, index) => ({ - name: 'Read', - input: {file_path: `packages/pipeline/src/resolve-step-${index}.ts`}, - result: readResult(index, 40 + ((index * 7) % 120)), - })) -} - -test.describe('per landing main thread cost on the built bundle', () => { - test('thirty realistic read results stay inside the frame budget', async ({page}) => { - test.setTimeout(180_000) - const script = suite.kit().harness.script - script.scriptTurn({toolCalls: readSteps(), text: 'Every file is read.'}) - script.holdResults() - - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill('read every pipeline file') - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByText('resolve-step-0.ts').first()).toBeVisible({timeout: 30_000}) - - await page.evaluate((steps) => { - const roots = [...document.querySelectorAll('*')] - .map((element) => element.shadowRoot) - .filter((root): root is ShadowRoot => root !== null) - const list = roots - .map((root) => root.querySelector('[aria-label="Execution trace"]')) - .find((node): node is Element => node !== null) - if (!list) throw new Error('no trace list in any shadow root') - const state: {gaps: number[]; done: boolean} = {gaps: [], done: false} - let previous = performance.now() - const tick = (now: number) => { - state.gaps.push(now - previous) - previous = now - if (!state.done) requestAnimationFrame(tick) - } - requestAnimationFrame(tick) - const observer = new MutationObserver(() => { - if (list.querySelectorAll(':scope > li').length < steps) return - observer.disconnect() - state.done = true - }) - observer.observe(list, {childList: true}) - Reflect.set(window, 'landingRig', state) - }, STEPS) - - script.releaseResults({everyMs: PACE_MS}) - await page.waitForFunction(() => Reflect.get(window, 'landingRig')?.done === true, undefined, {timeout: 90_000}) - - await page.waitForTimeout(2000) - const report = await page.evaluate(() => { - const state = Reflect.get(window, 'landingRig') as {gaps: number[]} - const sorted = [...state.gaps].toSorted((left, right) => left - right) - const at = (fraction: number) => Math.round((sorted[Math.floor(fraction * (sorted.length - 1))] ?? 0) * 10) / 10 - const roots = [...document.querySelectorAll('*')] - .map((element) => element.shadowRoot) - .filter((root): root is ShadowRoot => root !== null) - const containers = roots.flatMap((root) => [...root.querySelectorAll('diffs-container')]) - const inner = containers.flatMap((node) => (node.shadowRoot ? [node.shadowRoot] : [])) - return { - containers: containers.length, - codeChars: inner.reduce((sum, root) => sum + (root.textContent ?? '').length, 0), - frames: sorted.length, - p50: at(0.5), - p90: at(0.9), - p95: at(0.95), - max: at(1), - over33: state.gaps.filter((gap) => gap > 33).length, - over100: state.gaps.filter((gap) => gap > 100).length, - worst: sorted.slice(-8).map(Math.round), - } - }) - console.log('[embed-landing]', JSON.stringify(report)) - - expect(report.containers).toBeGreaterThanOrEqual(STEPS) - expect(report.codeChars).toBeGreaterThan(0) - expect(report.frames).toBeGreaterThan(STEPS) - expect(report.p95).toBeLessThanOrEqual(FRAME_BUDGET_P95_MS) - }) -}) diff --git a/packages/embed/tests/e2e/mid-session-outage.it.test.ts b/packages/embed/tests/e2e/mid-session-outage.it.test.ts deleted file mode 100644 index 0f3ed524fe..0000000000 --- a/packages/embed/tests/e2e/mid-session-outage.it.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import {expect, test} from '@playwright/test' -import {holdRpcCalls} from '@conciv/extension-testkit/rpc-fault' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {chatBox, openChatPanel} from './helpers/chat.js' - -const ASSISTANT_TEXT = 'Recovered mid-session' -const MOUNT_TIMEOUT_MS = 30_000 - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeAll(async () => { - kit = await bootEmbedKit({text: ASSISTANT_TEXT}) - host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}'})) -}) - -test.afterAll(async () => { - await host.close() - await kit.cleanup() -}) - -test.describe('a mid-session outage raises the standing notice and disables sending, release auto-clears both', () => { - test('holding all rpc traffic surfaces the notice and a disabled send control, releasing it clears both', async ({ - page, - }) => { - test.setTimeout(90_000) - const hold = await holdRpcCalls(page) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openChatPanel(page) - - const composer = chatBox(page) - await composer.fill('a message queued during the outage') - - hold.hold() - - const notice = page.getByText('conciv lost connection to the engine.') - await expect(notice).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - const disabledSend = page.getByRole('button', {name: 'conciv lost connection to the engine'}) - await expect(disabledSend).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - await expect(disabledSend).toBeDisabled() - - hold.release() - - await expect(notice).not.toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - await expect(page.getByRole('button', {name: 'Send message'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - }) -}) diff --git a/packages/embed/tests/e2e/model-selector.it.test.ts b/packages/embed/tests/e2e/model-selector.it.test.ts deleted file mode 100644 index 376d3dc6fc..0000000000 --- a/packages/embed/tests/e2e/model-selector.it.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import {expect, test} from '@playwright/test' -import {failRpcCalls} from '@conciv/extension-testkit/rpc-fault' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' - -const HARNESS_MODELS = [ - {id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5'}, - {id: 'claude-opus-4-1', name: 'Claude Opus 4.1'}, -] - -const suite = setupWidgetSuite({text: 'Hello from conciv', models: HARNESS_MODELS}) - -test.describe('model selector error path', () => { - test.use({viewport: {width: 900, height: 760}}) - - test('offers a retry when meta.models fails and recovers on retry', async ({page}) => { - test.setTimeout(180_000) - const models = await failRpcCalls(page, {path: ['meta', 'models']}) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - - const moreActions = page.getByRole('button', {name: 'More composer actions'}) - await moreActions.click() - const retry = page.getByRole('menuitem', {name: /Retry loading models/}) - await expect(retry).toBeVisible({timeout: 30_000}) - await expect(page.getByText('Couldn’t load models').first()).toBeVisible({timeout: 30_000}) - - models.repair() - await retry.click() - await moreActions.click() - await expect(page.getByRole('menuitem', {name: /^Model: Claude Sonnet 4\.5/})).toBeVisible({timeout: 30_000}) - await page.keyboard.press('Escape') - }) -}) diff --git a/packages/embed/tests/e2e/mount-ready.it.test.ts b/packages/embed/tests/e2e/mount-ready.it.test.ts deleted file mode 100644 index a8b6088875..0000000000 --- a/packages/embed/tests/e2e/mount-ready.it.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {handleHostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {chatBox} from './helpers/chat.js' - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeAll(async () => { - kit = await bootEmbedKit({text: 'ready contract'}) - host = await serveHost(() => handleHostPage()) -}) - -test.afterAll(async () => { - await host.close() - await kit.cleanup() -}) - -async function openPage(page: Page): Promise { - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - return page -} - -test.describe('mount() readiness contract', () => { - test('an open dispatched right after mount() resolves opens the panel, never dropped', async ({page}) => { - await openPage(page) - await page.evaluate(async (base) => { - const el = document.createElement('div') - document.body.appendChild(el) - const handle = window.ConcivHandle.makeHandle(base) - await handle.mount(el) - window.dispatchEvent( - new CustomEvent('conciv-dispatch-event', { - detail: {type: 'panel:open', payload: undefined, pluginId: 'panel'}, - }), - ) - }, kit.base) - await expect(chatBox(page)).toBeVisible({timeout: 10_000}) - }) -}) diff --git a/packages/embed/tests/e2e/native-live-region.it.test.ts b/packages/embed/tests/e2e/native-live-region.it.test.ts deleted file mode 100644 index 44a4f15c67..0000000000 --- a/packages/embed/tests/e2e/native-live-region.it.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import {fileURLToPath} from 'node:url' -import {expect, test, type Page} from '@playwright/test' -import {bootCoreKit, type CoreKit} from '@conciv/extension-testkit/core-kit' -import type {PageToNativeMessage} from '@conciv/extension-ios/bridge' -import {captureNativePosts, installNativeStub} from './helpers/native-bridge.js' - -const nativeDistDir = fileURLToPath(new URL('../../dist/', import.meta.url)) - -type NativeMethod = keyof NonNullable -type PanelToggled = Extract -type Rect = NonNullable - -let kit: CoreKit - -test.beforeAll(async () => { - kit = await bootCoreKit({id: 'fake-native-region', text: 'Hello from conciv', nativePageDir: nativeDistDir}) -}) - -test.afterAll(async () => { - await kit.cleanup() -}) - -type Mascot = {page: Page; toggles: PanelToggled[]; notify: (toggle: PanelToggled) => void} - -function isToggle(message: PageToNativeMessage): message is PanelToggled { - return message.type === 'host.panelToggled' -} - -async function openMascotNative(page: Page): Promise { - const mascot: Mascot = {page, toggles: [], notify: () => {}} - const bridge = await captureNativePosts(page) - bridge.notify = (message) => { - if (!isToggle(message)) return - mascot.toggles.push(message) - mascot.notify(message) - } - await installNativeStub(page) - await page.goto(`${kit.base}/native?launcher=mascot`, {waitUntil: 'domcontentloaded'}) - await page.waitForFunction(() => typeof window.__concivNative === 'object') - return mascot -} - -function callNative(page: Page, method: NativeMethod, arg: Record): Promise { - return page.evaluate((call) => window.__concivNative?.[call.method]?.(call.arg), {method, arg}) -} - -const composerBox = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) - -const closedRects = (all: PanelToggled[]): Rect[] => - all.flatMap((toggle) => (toggle.open === false && toggle.mascotRect ? [toggle.mascotRect] : [])) - -async function openFromHost(page: Page): Promise { - await callNative(page, 'open', {v: 1, seq: 1}) - await expect(composerBox(page)).toBeVisible({timeout: 30_000}) -} - -test.describe('native live region reporting', () => { - test.use({viewport: {width: 1280, height: 900}}) - - test('reports the mascot rect on a fresh closed mount so tap-to-open stays live', async ({page: fixturePage}) => { - const mascot = await openMascotNative(fixturePage) - 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) - }) - - test('re-reports the mascot rect when the launcher moves and settles on a stable value', async ({ - page: fixturePage, - }) => { - const mascot = await openMascotNative(fixturePage) - 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) - }) - - test('never reports closed mascot-region state once the panel is open', async ({page: fixturePage}) => { - const mascot = await openMascotNative(fixturePage) - 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) - }) - - test('reports open, not a closed mascot rect, once a session is opened from the host', async ({ - page: fixturePage, - }) => { - const mascot = await openMascotNative(fixturePage) - 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) - }) -}) diff --git a/packages/embed/tests/e2e/native-widget.it.test.ts b/packages/embed/tests/e2e/native-widget.it.test.ts deleted file mode 100644 index 2e00248da5..0000000000 --- a/packages/embed/tests/e2e/native-widget.it.test.ts +++ /dev/null @@ -1,207 +0,0 @@ -import {Buffer} from 'node:buffer' -import {fileURLToPath} from 'node:url' -import {expect, test, type Page} from '@playwright/test' -import type {DraftRow} from '@conciv/contract' -import {bootCoreKit, type CoreKit} from '@conciv/extension-testkit/core-kit' -import type {PageToNativeMessage} from '@conciv/extension-ios/bridge' -import {GRAB_MIME, parseGrabPayload, type GrabPayload} from '@conciv/grab/grab-attachment' -import {watchRpcWire} from '@conciv/extension-testkit/rpc-wire' -import {captureNativePosts, installNativeStub, type NativeBridge} from './helpers/native-bridge.js' -import {untilPanelDraft} from './helpers/drafts.js' - -type NativeMethod = keyof NonNullable - -const nativeDistDir = fileURLToPath(new URL('../../dist/', import.meta.url)) - -const IMAGE_DATA_URL = - 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP4z8AARwzEcQCukw/x0F8jngAAAABJRU5ErkJggg==' - -const NEUTRAL_GRAB = { - text: 'Payroll Deposit', - preview: {kind: 'image', dataUrl: IMAGE_DATA_URL, width: 361, height: 72}, - rect: {x: 16, y: 232, width: 361, height: 72}, - source: {componentName: 'PaymentCardCell', filePath: '', lineNumber: null}, - subtree: { - class: 'PaymentCardCell', - a11yId: 'PaymentsScreen/payrollRow', - text: 'Payroll Deposit', - rect: {x: 16, y: 232, width: 361, height: 72}, - children: [ - { - class: 'UILabel', - a11yId: null, - text: 'Payroll Deposit', - rect: {x: 28, y: 240, width: 180, height: 20}, - children: [], - }, - ], - }, -} - -function grabPayloadOf(draft: DraftRow): GrabPayload | null { - const attachment = draft.attachments.find((candidate) => candidate.contentType === GRAB_MIME) - if (!attachment) return null - return parseGrabPayload(Buffer.from(attachment.data, 'base64').toString('utf8')) -} - -let kit: CoreKit -let sessionId: string - -test.beforeAll(async () => { - kit = await bootCoreKit({id: 'fake-native', text: 'Hello from conciv', nativePageDir: nativeDistDir}) - sessionId = (await kit.rpc.sessions.create()).sessionId -}) - -test.afterAll(async () => { - await kit.cleanup() -}) - -type Native = { - page: Page - bridge: NativeBridge - rebinds: {apiBase?: string}[] - onRebind: () => void -} - -async function openNative(page: Page): Promise { - const bridge = await captureNativePosts(page) - const native: Native = {page, bridge, rebinds: [], onRebind: () => {}} - await page.exposeFunction('concivNativeRebind', (detail: {apiBase?: string}) => { - native.rebinds.push(detail) - native.onRebind() - }) - await installNativeStub(page) - await page.addInitScript(() => { - window.addEventListener('conciv:rebind', (event) => void window.concivNativeRebind(event.detail)) - }) - await page.goto(`${kit.base}/native`, {waitUntil: 'domcontentloaded'}) - await page.waitForFunction(() => typeof window.__concivNative === 'object') - return native -} - -const countType = (messages: PageToNativeMessage[], type: PageToNativeMessage['type']): number => - messages.filter((message) => message.type === type).length - -const findByType = ( - messages: PageToNativeMessage[], - type: Type, -): Extract | undefined => - messages.find((message): message is Extract => message.type === type) - -function callNative(page: Page, method: NativeMethod, arg: Record): Promise { - return page.evaluate((call) => window.__concivNative?.[call.method]?.(call.arg), {method, arg}) -} - -const composerBox = (page: Page) => page.getByRole('textbox', {name: 'Message the conciv agent'}) -const panel = (page: Page) => page.getByRole('dialog', {name: 'conciv chat agent'}) -const grabPreview = (page: Page) => panel(page).locator('img') - -async function pickElement(page: Page): Promise { - const inline = page.getByRole('button', {name: 'Select an element from the page'}) - if (await inline.isVisible()) { - await inline.click() - return - } - await page.getByRole('button', {name: 'More composer actions'}).click() - await page.getByRole('menuitem', {name: 'Select an element from the page'}).click() -} - -test.describe('native widget bridge', () => { - test('installs the native bridge, re-posts readiness, and settles after the first acked call and handshake', async ({ - page: fixturePage, - }) => { - const {page, bridge} = await openNative(fixturePage) - 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')) - }) - - test('opens the panel on native open and is idempotent, and closes on native close', async ({page: fixturePage}) => { - const wire = watchRpcWire(fixturePage) - const {page} = await openNative(fixturePage) - await wire.sessionsBootTraffic() - await callNative(page, 'open', {v: 1, seq: 1}) - await callNative(page, 'open', {v: 1, seq: 2}) - await expect(composerBox(page)).toHaveCount(1, {timeout: 30_000}) - await expect(composerBox(page)).toBeVisible() - await callNative(page, 'close', {v: 1, seq: 3}) - await expect(composerBox(page)).toBeHidden({timeout: 30_000}) - }) - - test('drives the native grab provider: pick posts a requestId and a matching image grabResult stages the preview', async ({ - page: fixturePage, - }) => { - test.setTimeout(120_000) - const wire = watchRpcWire(fixturePage) - const {page, bridge} = await openNative(fixturePage) - await wire.sessionsBootTraffic() - const picked = Promise.withResolvers() - bridge.notify = (message) => { - if (message.type === 'grab.pick') picked.resolve(message) - } - await callNative(page, 'open', {v: 1, seq: 1}) - await expect(composerBox(page)).toBeVisible({timeout: 30_000}) - - await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) - await pickElement(page) - 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 expect(panel(page).getByText('PaymentCardCell')).toBeVisible({timeout: 30_000}) - await expect(grabPreview(page)).toHaveAttribute('src', IMAGE_DATA_URL) - await untilPanelDraft(kit, sessionId, (draft) => { - const payload = grabPayloadOf(draft) - return payload !== null && payload.text.includes('[view]') && payload.text.includes('PaymentCardCell') - }) - }) - - test('ignores a grabResult whose requestId does not match the pending pick', async ({page: fixturePage}) => { - const {page, bridge} = await openNative(fixturePage) - const picked = Promise.withResolvers() - bridge.notify = (message) => { - if (message.type === 'grab.pick') picked.resolve(message) - } - await callNative(page, 'open', {v: 1, seq: 1}) - await expect(composerBox(page)).toBeVisible({timeout: 30_000}) - await callNative(page, 'grabCapability', {v: 1, seq: 2, grabbable: true}) - await pickElement(page) - 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) - }) - - test('surfaces a visible error when native reports an incompatible bridge version', async ({page: fixturePage}) => { - const {page} = await openNative(fixturePage) - await callNative(page, 'bridgeIncompatible', {v: 1, seq: 1, nativeMinV: 2, nativeMaxV: 3}) - await expect(page.getByText('Update the conciv widget', {exact: false})).toBeVisible({timeout: 30_000}) - }) - - test('dispatches conciv:rebind when a handshake reports a different same-core base', async ({page: fixturePage}) => { - const native = await openNative(fixturePage) - 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'}]) - }) -}) diff --git a/packages/embed/tests/e2e/page-dispatch-boot.it.test.ts b/packages/embed/tests/e2e/page-dispatch-boot.it.test.ts deleted file mode 100644 index c7cffeb90b..0000000000 --- a/packages/embed/tests/e2e/page-dispatch-boot.it.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {z} from 'zod' -import {completeConnectHandshake} from '@conciv/extension-testkit/connect-handshake' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {handleHostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' - -const HOST_BODY = ` -
page-bus-ok
-

Embed page

- - -` - -const SnapshotSchema = z.object({ - nodes: z.array(z.looseObject({ref: z.string(), role: z.string(), name: z.string().optional()})), -}) - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeAll(async () => { - kit = await bootEmbedKit() - host = await serveHost(() => handleHostPage(HOST_BODY)) -}) - -test.afterAll(async () => { - await host.close() - await kit.cleanup() -}) - -async function buttonRef(): Promise { - const snapshot = SnapshotSchema.parse(await kit.rpc.registry.call({name: 'page_snapshot', input: {}})) - const node = snapshot.nodes.find((entry) => entry.role === 'button' && entry.name === 'Press target') - if (!node) throw new Error('the snapshot did not list the press button') - return node.ref -} - -test.describe('the page-tool dispatcher serves registry page tools under bootConnect', () => { - let page: Page - - test.beforeAll(async ({browser}) => { - page = await browser.newPage() - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await page.evaluate(() => { - const el = document.createElement('div') - document.body.appendChild(el) - window.concivTestHandle = window.ConcivHandle.makeConnectHandle() - void window.concivTestHandle.mount(el) - }) - await completeConnectHandshake(page, kit.base, await kit.session()) - }) - - test.afterAll(async () => { - await page.close() - }) - - test('a plain read round-trips server -> browser -> result', async () => { - await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#probe'}})).resolves.toMatchObject({ - text: 'page-bus-ok', - }) - }) - - test('a mutating tool acts on the page, journals by declared meta, and fires the browser mirror', async () => { - await expect(kit.rpc.registry.call({name: 'page_click', input: {selector: '#press-btn'}})).resolves.toMatchObject({ - ok: true, - }) - await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#clicked-flag'}})).resolves.toMatchObject( - {text: 'clicked'}, - ) - const changes = await kit.rpc.page.changes(undefined) - expect(changes.map((entry) => entry.verb)).toContain('page_click') - await expect(page.locator('[data-conciv-cursor]')).toHaveCount(1, {timeout: 10_000}) - }) - - test('a ref-consuming tool resolves its target through the shared refs machinery', async () => { - const ref = await buttonRef() - await expect(kit.rpc.registry.call({name: 'page_attr', input: {ref, attribute: 'id'}})).resolves.toMatchObject({ - value: 'press-btn', - }) - }) - - test('a missing target rejects with the transport invalid-args mapping, not a success shape', async () => { - await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#not-here'}})).rejects.toMatchObject({ - code: 'INVALID_ARGS', - }) - }) - - test.describe('the page_effect verb drives host-registered effects', () => { - test('lists the highlight effect the widget registers', async () => { - await expect(kit.rpc.registry.call({name: 'page_effect', input: {action: 'list'}})).resolves.toMatchObject({ - effects: [{name: 'highlight', enabled: false}], - }) - }) - - test('enable shows the highlight inspector on the page, disable reverts, toggle flips', async () => { - await expect( - kit.rpc.registry.call({name: 'page_effect', input: {action: 'enable', effect: 'highlight'}}), - ).resolves.toMatchObject({effect: 'highlight', enabled: true}) - await expect(page.locator('[data-conciv-capture]')).toHaveCount(1, {timeout: 10_000}) - - await expect( - kit.rpc.registry.call({name: 'page_effect', input: {action: 'disable', effect: 'highlight'}}), - ).resolves.toMatchObject({effect: 'highlight', enabled: false}) - await expect(page.locator('[data-conciv-capture]')).toHaveCount(0, {timeout: 10_000}) - - await expect( - kit.rpc.registry.call({name: 'page_effect', input: {action: 'toggle', effect: 'highlight'}}), - ).resolves.toMatchObject({effect: 'highlight', enabled: true}) - await expect(page.locator('[data-conciv-capture]')).toHaveCount(1, {timeout: 10_000}) - - await expect( - kit.rpc.registry.call({name: 'page_effect', input: {action: 'toggle', effect: 'highlight'}}), - ).resolves.toMatchObject({effect: 'highlight', enabled: false}) - await expect(page.locator('[data-conciv-capture]')).toHaveCount(0, {timeout: 10_000}) - }) - - test('an unknown effect name rejects with the declared error', async () => { - await expect( - kit.rpc.registry.call({name: 'page_effect', input: {action: 'enable', effect: 'confetti'}}), - ).rejects.toMatchObject({code: 'UNKNOWN_EFFECT'}) - }) - }) -}) diff --git a/packages/embed/tests/e2e/page-dispatch-parity.it.test.ts b/packages/embed/tests/e2e/page-dispatch-parity.it.test.ts deleted file mode 100644 index 98b159d93c..0000000000 --- a/packages/embed/tests/e2e/page-dispatch-parity.it.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {z} from 'zod' -import {completeConnectHandshake} from '@conciv/extension-testkit/connect-handshake' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {handleHostPage, hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {openPagePlaneHost} from './helpers/page-plane-host.js' - -const HOST_BODY = ` -
page-bus-ok
-

Embed page

- - -` - -const SnapshotSchema = z.object({ - nodes: z.array(z.looseObject({ref: z.string(), role: z.string(), name: z.string().optional()})), -}) - -const ChangesSchema = z.array(z.object({verb: z.string()}).loose()) - -type BootedPath = {kit: EmbedKit; page: Page} - -async function buttonRef(kit: EmbedKit): Promise { - const snapshot = SnapshotSchema.parse(await kit.rpc.registry.call({name: 'page_snapshot', input: {}})) - const node = snapshot.nodes.find((entry) => entry.role === 'button' && entry.name === 'Press target') - if (!node) throw new Error('the snapshot did not list the press button') - return node.ref -} - -function verbGroupBattery(boot: () => BootedPath): void { - test('read: page_text reports the live DOM', async () => { - const {kit} = boot() - await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#probe'}})).resolves.toMatchObject({ - text: 'page-bus-ok', - }) - }) - - test('read: page_attr resolves a snapshot ref through the shared refs machinery', async () => { - const {kit} = boot() - const ref = await buttonRef(kit) - await expect(kit.rpc.registry.call({name: 'page_attr', input: {ref, attribute: 'id'}})).resolves.toMatchObject({ - value: 'press-btn', - }) - }) - - test('react: page_locate fails structurally on a page without a React tree', async () => { - const {kit} = boot() - await expect(kit.rpc.registry.call({name: 'page_locate', input: {selector: '#title'}})).rejects.toMatchObject({ - code: 'HANDLER_ERROR', - message: expect.stringContaining('no React fiber'), - }) - }) - - test('act: page_click acts on the page, journals, and fires the browser mirror', async () => { - const {kit, page} = boot() - await expect(kit.rpc.registry.call({name: 'page_click', input: {selector: '#press-btn'}})).resolves.toMatchObject({ - ok: true, - }) - await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#clicked-flag'}})).resolves.toMatchObject( - {text: 'clicked'}, - ) - const changes = ChangesSchema.parse(await kit.rpc.page.changes(undefined)) - expect(changes.map((entry) => entry.verb)).toContain('page_click') - await expect(page.locator('[data-conciv-cursor]')).toHaveCount(1, {timeout: 10_000}) - }) - - test('edit-live: page_settext rewrites the DOM and journals by declared meta', async () => { - const {kit} = boot() - await expect( - kit.rpc.registry.call({name: 'page_settext', input: {selector: '#title', text: 'Rewritten title'}}), - ).resolves.toMatchObject({ok: true}) - await expect(kit.rpc.registry.call({name: 'page_text', input: {selector: '#title'}})).resolves.toMatchObject({ - text: 'Rewritten title', - }) - const changes = ChangesSchema.parse(await kit.rpc.page.changes(undefined)) - expect(changes.map((entry) => entry.verb)).toContain('page_settext') - }) -} - -test.describe('bootNormal: the widget embed serves every verb group through the dispatcher', () => { - let kit: EmbedKit - let host: {base: string; close: () => Promise} - let page: Page - - test.beforeAll(async ({browser}) => { - kit = await bootEmbedKit() - host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: HOST_BODY})) - page = await browser.newPage() - await openPagePlaneHost(page, host.base) - }) - - test.afterAll(async () => { - await page.close() - await host.close() - await kit.cleanup() - }) - - test.afterEach(async () => { - await kit.rpc.page.clearChanges(undefined) - }) - - verbGroupBattery(() => ({kit, page})) -}) - -test.describe('bootConnect: the connect handle serves the same verb groups through the dispatcher', () => { - let kit: EmbedKit - let host: {base: string; close: () => Promise} - let page: Page - - test.beforeAll(async ({browser}) => { - kit = await bootEmbedKit() - host = await serveHost(() => handleHostPage(HOST_BODY)) - page = await browser.newPage() - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await page.evaluate(() => { - const el = document.createElement('div') - document.body.appendChild(el) - window.concivTestHandle = window.ConcivHandle.makeConnectHandle() - void window.concivTestHandle.mount(el) - }) - await completeConnectHandshake(page, kit.base, await kit.session()) - }) - - test.afterAll(async () => { - await page.close() - await host.close() - await kit.cleanup() - }) - - test.afterEach(async () => { - await kit.rpc.page.clearChanges(undefined) - }) - - verbGroupBattery(() => ({kit, page})) -}) diff --git a/packages/embed/tests/e2e/page-plane.it.test.ts b/packages/embed/tests/e2e/page-plane.it.test.ts deleted file mode 100644 index f05965df26..0000000000 --- a/packages/embed/tests/e2e/page-plane.it.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {openPagePlaneHost} from './helpers/page-plane-host.js' - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeAll(async () => { - kit = await bootEmbedKit() - host = await serveHost(() => - hostPage({ - apiBase: kit.base, - widget: '{"quickTerminal":false}', - body: '
page-bus-ok

Embed page

', - }), - ) -}) - -test.afterAll(async () => { - await host.close() - await kit.cleanup() -}) - -const openHostPage = (page: Page): Promise => openPagePlaneHost(page, host.base) - -test.describe('startPagePlane executes registry page tools in the browser', () => { - test('round-trips page_text through the push socket to the DOM dispatcher', async ({page}) => { - test.setTimeout(90_000) - await openHostPage(page) - expect(await kit.rpc.registry.call({name: 'page_text', input: {selector: '#probe'}})).toMatchObject({ - text: 'page-bus-ok', - }) - }) - - test('a verb whose target does not exist rejects with a declared code, not a success-shaped string', async ({ - page, - }) => { - test.setTimeout(90_000) - await openHostPage(page) - 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', - }) - }) - - test('the snapshot tool sees host page structure', async ({page}) => { - test.setTimeout(90_000) - await openHostPage(page) - expect(JSON.stringify(await kit.rpc.registry.call({name: 'page_snapshot', input: {}}))).toContain('Embed page') - }) -}) diff --git a/packages/embed/tests/e2e/panel-focus.it.test.ts b/packages/embed/tests/e2e/panel-focus.it.test.ts deleted file mode 100644 index 66f9198d1c..0000000000 --- a/packages/embed/tests/e2e/panel-focus.it.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -import {expect, test, type Locator, type Page} from '@playwright/test' -import {gateRpcCalls} from '@conciv/extension-testkit/rpc-fault' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' -import {currentHref} from '@conciv/extension-testkit/navigation-state' -import {until} from '@conciv/harness-testkit/until' -import {hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' - -const suite = setupWidgetSuite() - -const COMPOSER_NAME = 'Message the conciv agent' -const SESSIONS_LIST = ['sessions', 'list'] as const - -function composer(page: Page) { - return page.getByRole('textbox', {name: COMPOSER_NAME}) -} - -function sessionOptionsButton(page: Page) { - return page.getByRole('button', {name: 'Session options'}) -} - -async function ensurePanelClosed(page: Page): Promise { - const minimize = page.getByRole('button', {name: 'Minimize conciv chat'}) - const opener = page.getByRole('button', {name: 'Open conciv chat'}) - await expect(minimize.or(opener)).toBeVisible({timeout: 30_000}) - if (await minimize.isVisible()) await minimize.click() - await expect(opener).toBeVisible({timeout: 30_000}) -} - -type HostedPanel = {host: Awaited>; page: Page; hostButton: Locator} - -const dedicatedHosts: Array<{close: () => Promise}> = [] - -test.afterEach(async () => { - for (const dedicatedHost of dedicatedHosts.splice(0)) await dedicatedHost.close() -}) - -async function openPanelOverFocusedHostButton(page: Page): Promise { - const host = await serveHost(() => - hostPage({ - apiBase: suite.kit().base, - widget: '{"quickTerminal":false}', - body: '', - }), - ) - dedicatedHosts.push(host) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await ensurePanelClosed(page) - const hostButton = page.getByRole('button', {name: 'Host action'}) - await hostButton.click() - await expect(hostButton).toBeFocused() - await page.evaluate(() => - window.dispatchEvent( - new CustomEvent('conciv-dispatch-event', { - detail: {type: 'panel:open', payload: undefined, pluginId: 'panel'}, - }), - ), - ) - await expect(composer(page)).toBeVisible({timeout: 30_000}) - return {host, page, hostButton} -} - -test.describe('panel open focuses the composer', () => { - test('focuses the composer input when the panel opens', async ({page}) => { - test.setTimeout(90_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await expect(composer(page)).toBeFocused({timeout: 10_000}) - await page.keyboard.type('typed without clicking') - await expect(composer(page)).toHaveText('typed without clicking') - }) - - test('paints the shell while the session list is still loading, then focuses the composer', async ({page}) => { - test.setTimeout(90_000) - const host = await serveHost(() => - hostPage({apiBase: suite.kit().base, widget: '{"quickTerminal":false,"transport":"fetch"}'}), - ) - dedicatedHosts.push(host) - const sessionListGate = await gateRpcCalls(page, {path: SESSIONS_LIST}) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - try { - await sessionListGate.awaitCaptured(1) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: 15_000}) - expect(sessionListGate.pending()).toBeGreaterThan(0) - } finally { - await sessionListGate.dispose() - } - await openPanel(page) - await expect(sessionOptionsButton(page)).toBeVisible({timeout: 30_000}) - await expect(composer(page)).toBeFocused({timeout: 30_000}) - await page.keyboard.type('typed after the session list resolved') - await expect(composer(page)).toHaveText('typed after the session list resolved') - }) -}) - -test.describe('panel close restores focus: host element captured at open wins, FAB is the fallback', () => { - test('closing via the FAB restores the host element that was focused before a programmatic open', async ({page}) => { - test.setTimeout(120_000) - const {hostButton} = await openPanelOverFocusedHostButton(page) - await page.getByRole('button', {name: 'Minimize conciv chat'}).click() - await expect(hostButton).toBeFocused({timeout: 10_000}) - }) - - test('closing via the panel header restores the host element that was focused before the open', async ({page}) => { - test.setTimeout(120_000) - const {hostButton} = await openPanelOverFocusedHostButton(page) - await page.getByRole('button', {name: 'Close chat'}).click() - await expect(hostButton).toBeFocused({timeout: 10_000}) - }) - - test('collapsing the panel by dragging its resize handle shut restores the host element', async ({page}) => { - test.setTimeout(180_000) - const {hostButton} = await openPanelOverFocusedHostButton(page) - - 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 expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeHidden({timeout: 30_000}) - await expect(hostButton).toBeFocused({timeout: 10_000}) - }) - - test('closing via the FAB falls back to FAB focus when no host element was captured at open time', async ({page}) => { - test.setTimeout(120_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await ensurePanelClosed(page) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expect(composer(page)).toBeVisible({timeout: 30_000}) - await page.getByRole('button', {name: 'Minimize conciv chat'}).click() - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) - }) - - test('closing a boot-restored open panel falls back to FAB focus', async ({page}) => { - test.setTimeout(180_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await until(async () => (await currentHref(suite.kit())).includes('open=true'), { - hangGuardMs: 30_000, - intervalMs: 100, - }) - expect(await currentHref(suite.kit())).toContain('open=true') - - await page.reload({waitUntil: 'domcontentloaded'}) - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await page.getByRole('button', {name: 'Close chat'}).click() - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) - }) - - test('closing the phone sheet falls back to FAB focus once the launcher remounts', async ({page}) => { - test.setTimeout(180_000) - await page.setViewportSize({width: 390, height: 780}) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await ensurePanelClosed(page) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await expect(composer(page)).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeHidden({timeout: 30_000}) - await page.getByRole('button', {name: 'Close chat'}).click() - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeFocused({timeout: 10_000}) - }) -}) - -test.describe('Escape dismisses the topmost open layer only', () => { - test('pressing Escape while the Session options menu is open closes only the menu, not the panel', async ({page}) => { - test.setTimeout(90_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - - await sessionOptionsButton(page).click() - await expect(page.getByRole('dialog', {name: 'Session options'})).toBeVisible({timeout: 10_000}) - - await page.keyboard.press('Escape') - - await expect(page.getByRole('dialog', {name: 'Session options'})).toBeHidden({timeout: 10_000}) - await expect(composer(page)).toBeVisible({timeout: 10_000}) - await expect(sessionOptionsButton(page)).toBeFocused({timeout: 10_000}) - }) -}) - -test.describe('panel restore-on-load never steals focus from the host page', () => { - test('reloading with a restored open panel leaves an autofocused host input focused', async ({page}) => { - test.setTimeout(180_000) - const host = await serveHost(() => - hostPage({ - apiBase: suite.kit().base, - widget: '{"quickTerminal":false}', - body: '', - }), - ) - dedicatedHosts.push(host) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await until(async () => (await currentHref(suite.kit())).includes('open=true'), { - hangGuardMs: 30_000, - intervalMs: 100, - }) - expect(await currentHref(suite.kit())).toContain('open=true') - - await page.reload({waitUntil: 'domcontentloaded'}) - const hostInput = page.getByRole('textbox', {name: 'Host search'}) - await expect(hostInput).toBeFocused({timeout: 10_000}) - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expect(hostInput).toBeFocused({timeout: 10_000}) - }) -}) diff --git a/packages/embed/tests/e2e/panel-session-switch.it.test.ts b/packages/embed/tests/e2e/panel-session-switch.it.test.ts deleted file mode 100644 index 295a0679b0..0000000000 --- a/packages/embed/tests/e2e/panel-session-switch.it.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import {expect, test} from '@playwright/test' -import {HarnessSessionId} from '@conciv/protocol/chat-types' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel, switchToSessionByTitle} from './helpers/panel.js' -import {untilPanelDraft} from './helpers/drafts.js' - -const RECENT_ID = HarnessSessionId.parse('43548fd1-0000-4220-acf0-014b10b5815f') -const OLDER_ID = HarnessSessionId.parse('43548fd1-0000-4220-acf0-014b10b5815e') -const RECENT_TITLE = 'the session opened at boot' -const OLDER_TITLE = 'the session switched to' -const FIRST_DRAFT = 'draft of the session opened first' -const SECOND_DRAFT = 'draft of the session switched to' - -const suite = setupWidgetSuite({ - history: [ - {id: RECENT_ID, derivedTitle: RECENT_TITLE, updatedAt: Date.now(), messageCount: 3}, - {id: OLDER_ID, derivedTitle: OLDER_TITLE, updatedAt: Date.now() - 60_000, messageCount: 2}, - ], -}) - -test.describe('composer drafts after a session switch', () => { - test('persists each draft against the session the panel is on when it is typed', async ({page}) => { - test.setTimeout(180_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await switchToSessionByTitle(page, RECENT_TITLE) - - const opened = await suite.kit().rpc.sessions.resolve({id: RECENT_ID}) - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.click() - await input.pressSequentially(FIRST_DRAFT) - await untilPanelDraft(suite.kit(), opened.sessionId, (draft) => draft.text === FIRST_DRAFT) - - const sessionOptions = page.getByRole('button', {name: 'Session options'}) - await sessionOptions.click() - await page.getByRole('button', {name: /^Session: /}).click() - await page.getByRole('option', {name: new RegExp(OLDER_TITLE)}).click() - const pill = page.getByRole('button', {name: `Session: ${OLDER_TITLE}`}) - if (!(await pill.isVisible())) await sessionOptions.click() - await expect(pill).toBeVisible({timeout: 30_000}) - await page.keyboard.press('Escape') - await expect(pill).toBeHidden({timeout: 30_000}) - - const switched = await suite.kit().rpc.sessions.resolve({id: OLDER_ID}) - expect(switched.sessionId).not.toBe(opened.sessionId) - - await input.click() - await input.pressSequentially(SECOND_DRAFT) - await untilPanelDraft(suite.kit(), switched.sessionId, (draft) => draft.text === SECOND_DRAFT) - - expect(await suite.kit().rpc.drafts.get({sessionId: opened.sessionId})).toMatchObject({text: FIRST_DRAFT}) - expect(await suite.kit().rpc.drafts.get({sessionId: switched.sessionId})).toMatchObject({text: SECOND_DRAFT}) - }) -}) diff --git a/packages/embed/tests/e2e/rebind.it.test.ts b/packages/embed/tests/e2e/rebind.it.test.ts deleted file mode 100644 index 5355050c09..0000000000 --- a/packages/embed/tests/e2e/rebind.it.test.ts +++ /dev/null @@ -1,214 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {handleHostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {watchChatWire} from '@conciv/extension-testkit/chat-wire' -import {until} from '@conciv/harness-testkit/until' -import {CHAT_WS_PATH} from '@conciv/protocol/chat-types' -import {proxyTo, type ProxyCore} from '../helpers/proxy.js' -import {mountHandle, openHostWithHandle, rebindHandle} from './helpers/handle.js' -import {chatBox, chatLog, openChatPanel, sendChatMessage} from './helpers/chat.js' - -const ASSISTANT_TEXT = 'Rebound reply' -const USER_TEXT = 'first message before the drift' -const SECOND_USER_TEXT = 'second message after the drift' - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeEach(async () => { - kit = await bootEmbedKit({text: ASSISTANT_TEXT}) - host = await serveHost(() => handleHostPage()) -}) - -test.afterEach(async () => { - await host.close() - await kit.cleanup() -}) - -async function openPanelTabs(page: Page): Promise { - const opener = page.getByRole('button', {name: 'Open conciv chat'}) - await expect(opener).toBeVisible({timeout: 30_000}) - await opener.click() - await expect(page.getByRole('tab', {name: 'Mount probe'})).toBeVisible({timeout: 30_000}) -} - -async function panelSession(): Promise { - const state = await kit.rpc.navigation.get(undefined) - const entry = state?.entries.find((row) => row.href.startsWith('/panel/')) - if (!entry) return null - return (entry.href.split('/')[2] ?? '').split('?')[0] ?? null -} - -test.describe('handle.rebind survives same-core port drift', () => { - let proxyA: ProxyCore - let proxyB: ProxyCore - - test.beforeEach(async () => { - proxyA = await proxyTo(kit.base) - proxyB = await proxyTo(kit.base) - }) - - test.afterEach(async () => { - await proxyB.close() - }) - - test('re-points rpc and SSE to the new port, keeps the panel open, the session, and delivers the next turn', async ({ - page, - }) => { - test.setTimeout(480_000) - 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 expect(apiBaseProbe).toHaveText(proxyA.base, {timeout: 30_000}) - - await until(async () => (await panelSession()) !== null, {hangGuardMs: 30_000, intervalMs: 100}) - const sessionBefore = await panelSession() - expect(sessionBefore).not.toBeNull() - - await sendChatMessage(page, USER_TEXT) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - - const beforeB = proxyB.trafficCount() - await rebindHandle(page, proxyB.base) - await proxyA.close() - - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expect(chatBox(page)).toBeVisible({timeout: 30_000}) - - await expect(apiBaseProbe).toHaveText(proxyB.base, {timeout: 30_000}) - - await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - - await sendChatMessage(page, SECOND_USER_TEXT) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) - await expect(chatLog(page).getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expect(chatLog(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([]) - }) -}) - -test.describe('handle.rebind remounts extension surfaces on the new core', () => { - let proxyC: ProxyCore - let proxyD: ProxyCore - - test.beforeEach(async () => { - proxyC = await proxyTo(kit.base) - proxyD = await proxyTo(kit.base) - }) - - test.afterEach(async () => { - await proxyD.close() - }) - - test('rebuilds the global surface and the open extension view against the new base', async ({page}) => { - test.setTimeout(240_000) - const pageErrors = await openHostWithHandle(page, host.base, 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 expect(surfaceProbe).toHaveText(proxyC.base, {timeout: 30_000}) - - const probeTab = page.getByRole('tab', {name: 'Mount probe'}) - await probeTab.click() - await expect(viewProbe).toHaveText(proxyC.base, {timeout: 30_000}) - - const beforeD = proxyD.trafficCount() - await rebindHandle(page, proxyD.base) - await proxyC.close() - - await expect(surfaceProbe).toHaveText(proxyD.base, {timeout: 15_000}) - await expect(viewProbe).toHaveText(proxyD.base, {timeout: 15_000}) - await expect(probeTab).toHaveAttribute('aria-selected', 'true', {timeout: 15_000}) - expect(proxyD.trafficCount()).toBeGreaterThan(beforeD) - expect(pageErrors).toEqual([]) - }) -}) - -test.describe('handle.rebind quiesces the old connection before tearing consumers down', () => { - let proxyE: ProxyCore - let proxyF: ProxyCore - - test.beforeEach(async () => { - proxyE = await proxyTo(kit.base) - proxyF = await proxyTo(kit.base) - }) - - test.afterEach(async () => { - await proxyE.close() - await proxyF.close() - }) - - test('writes nothing more to the old core once rebind is called', async ({page}) => { - test.setTimeout(180_000) - const wire = watchChatWire(page) - const framesSentPerSocket: number[] = [] - page.on('websocket', (socket) => { - if (!socket.url().includes(CHAT_WS_PATH)) 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 mountHandle(page, proxyE.base) - await openChatPanel(page) - - const apiBaseProbe = page.getByRole('status', {name: 'host api base probe'}) - await expect(apiBaseProbe).toHaveText(proxyE.base, {timeout: 30_000}) - - await rebindHandle(page, proxyF.base) - await expect(apiBaseProbe).toHaveText(proxyF.base, {timeout: 30_000}) - - const settledOnOldSocket = framesSentPerSocket[0] ?? 0 - const sentOnNewCore = wire.nextTurn() - await sendChatMessage(page, SECOND_USER_TEXT) - await sentOnNewCore - - expect(framesSentPerSocket[0]).toBe(settledOnOldSocket) - }) -}) - -test.describe('handle.rebind to the base the widget is already on re-runs the transport probe', () => { - let blockedCore: ProxyCore - - test.beforeEach(async () => { - blockedCore = await proxyTo(kit.base, {blockUpgrades: true}) - }) - - test.afterEach(async () => { - await blockedCore.close() - }) - - test('rides the websocket after the blocked upgrade path opens up again', async ({page}) => { - test.setTimeout(180_000) - const wire = watchChatWire(page) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - - await mountHandle(page, blockedCore.base) - await openChatPanel(page) - const blocked = wire.nextTurn() - await sendChatMessage(page, 'while upgrades are blocked') - expect((await blocked).transport).toBe('fetch') - - blockedCore.setUpgradesBlocked(false) - await rebindHandle(page, blockedCore.base) - await expect(chatBox(page)).toBeVisible({timeout: 30_000}) - const reprobed = wire.nextTurn() - await sendChatMessage(page, 'after the upgrade path opens') - expect((await reprobed).transport).toBe('websocket') - }) -}) diff --git a/packages/embed/tests/e2e/recording-attachment.it.test.ts b/packages/embed/tests/e2e/recording-attachment.it.test.ts deleted file mode 100644 index e8ccc02150..0000000000 --- a/packages/embed/tests/e2e/recording-attachment.it.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import {expect, test} from '@playwright/test' -import {z} from 'zod' -import {makeExtRpcClient} from '@conciv/extension' -import {until} from '@conciv/harness-testkit/until' -import recorderServer, {type RecorderRouter} from '@conciv/extension-recorder' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {openPanel} from './helpers/panel.js' - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeAll(async () => { - kit = await bootEmbedKit({text: 'Recording received', extensions: [recorderServer]}) - host = await serveHost(() => - hostPage({ - apiBase: kit.base, - widget: '{"quickTerminal":false}', - body: '', - }), - ) -}) - -test.afterAll(async () => { - await host.close() - await kit.cleanup() -}) - -const ClickEventSchema = z.object({ - type: z.literal(3), - data: z.looseObject({source: z.literal(2), type: z.literal(2)}), -}) - -const AppendedEventsSchema = z.object({events: z.array(z.unknown())}) - -test.describe('recording attachment end to end in the real widget', () => { - test('composes the card chip, sends log text to the model, renders the durable transcript card', async ({page}) => { - test.setTimeout(480_000) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - - await openPanel(page) - const recorderRpc = makeExtRpcClient(kit.base, 'recorder') - const client: {id?: string} = {} - const clicksAppendedSince = async (cursor: number): Promise => { - if (!client.id) throw new Error('no recorder client connected') - const appended = AppendedEventsSchema.parse(await recorderRpc.events({cursor, clientId: client.id})) - return appended.events.filter((event) => ClickEventSchema.safeParse(event).success).length - } - - await page.getByRole('tab', {name: 'Recorder'}).click() - await until( - async () => { - const {clients} = await recorderRpc.clients() - if (clients.length > 1) throw new Error(`expected one recorder client for this page, saw ${clients.length}`) - client.id = clients[0]?.id - return client.id !== undefined - }, - {hangGuardMs: 30_000, intervalMs: 100}, - ) - if (!client.id) throw new Error('no recorder client connected') - const captureBaseline = (await recorderRpc.window({clientId: client.id})).cursor - - await page.getByRole('button', {name: 'Embed fixture'}).click() - await page.getByRole('button', {name: 'Embed fixture'}).click() - await until(async () => (await clicksAppendedSince(captureBaseline)) >= 2, { - hangGuardMs: 30_000, - intervalMs: 100, - }) - - 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) - - 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 expect(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 persisted = {messages: ''} - await until( - async () => { - persisted.messages = JSON.stringify((await kit.rpc.chat.hydrate({sessionId: chatSession})).messages) - return persisted.messages.includes('[click]') - }, - {hangGuardMs: 30_000, intervalMs: 200}, - ) - expect(persisted.messages).toContain('"modelOnly":true') - - 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 expect(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 expect(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 expect(composerAfterModal).toHaveText('still alive after replay') - }) -}) diff --git a/packages/embed/tests/e2e/reload-continuity.it.test.ts b/packages/embed/tests/e2e/reload-continuity.it.test.ts deleted file mode 100644 index 683446f031..0000000000 --- a/packages/embed/tests/e2e/reload-continuity.it.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import {expect, test} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanelOnNewSession} from './helpers/panel.js' -import {untilPanelDraft} from './helpers/drafts.js' - -const ASSISTANT_TEXT = 'Continuity reply' - -const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) - -test.describe('reload continuity through the db-backed navigation row', () => { - test('restores the open panel route, the transcript, and the draft after a reload', async ({page}) => { - test.setTimeout(240_000) - const sessionId = await openPanelOnNewSession(page, suite) - - const input = page.getByRole('textbox', {name: 'Message the conciv agent'}) - await input.fill('remember me') - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - - await input.fill('an unsent draft survives') - await input.press('End') - await untilPanelDraft(suite.kit(), sessionId, (draft) => draft.text === 'an unsent draft survives') - - expect(await suite.kit().rpc.drafts.get({sessionId})).toMatchObject({text: 'an unsent draft survives'}) - - await page.reload({waitUntil: 'domcontentloaded'}) - - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toHaveText('an unsent draft survives', { - timeout: 30_000, - }) - }) -}) diff --git a/packages/embed/tests/e2e/remount.it.test.ts b/packages/embed/tests/e2e/remount.it.test.ts deleted file mode 100644 index b43bf8fbd9..0000000000 --- a/packages/embed/tests/e2e/remount.it.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import {expect, test} from '@playwright/test' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {handleHostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {mountHandle, openHostWithHandle, remountHandle, unmountHandle} from './helpers/handle.js' -import {chatBox, chatLog, openChatPanel, sendChatMessage} from './helpers/chat.js' - -const ASSISTANT_TEXT = 'Remounted reply' -const USER_TEXT = 'first message before the remount' -const SECOND_USER_TEXT = 'second message after the remount' - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeAll(async () => { - host = await serveHost(() => handleHostPage()) -}) - -test.afterAll(async () => { - await host.close() -}) - -test.beforeEach(async () => { - kit = await bootEmbedKit({text: ASSISTANT_TEXT}) -}) - -test.afterEach(async () => { - await kit.cleanup() -}) - -test.describe('handle unmount and remount keeps delivering turns', () => { - test('renders the second assistant reply after a full unmount and remount', async ({page}) => { - test.setTimeout(240_000) - const pageErrors = await openHostWithHandle(page, host.base, kit.base) - await openChatPanel(page) - - await sendChatMessage(page, USER_TEXT) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - - await unmountHandle(page) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toHaveCount(0, {timeout: 30_000}) - - await remountHandle(page) - await expect(chatBox(page)).toBeVisible({timeout: 30_000}) - await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - - await sendChatMessage(page, SECOND_USER_TEXT) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) - await expect(chatLog(page).getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - - expect(pageErrors).toEqual([]) - }) - - test('renders the second assistant reply after a fresh handle replaces the unmounted one', async ({page}) => { - test.setTimeout(240_000) - const pageErrors = await openHostWithHandle(page, host.base, kit.base) - await openChatPanel(page) - - await sendChatMessage(page, USER_TEXT) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - - await unmountHandle(page) - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toHaveCount(0, {timeout: 30_000}) - - await mountHandle(page, kit.base) - await expect(chatBox(page)).toBeVisible({timeout: 30_000}) - await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(1, {timeout: 30_000}) - - await sendChatMessage(page, SECOND_USER_TEXT) - await expect(page.getByText(ASSISTANT_TEXT)).toHaveCount(2, {timeout: 30_000}) - await expect(chatLog(page).getByText(SECOND_USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - await expect(chatLog(page).getByText(USER_TEXT)).toHaveCount(1, {timeout: 30_000}) - - expect(pageErrors).toEqual([]) - }) -}) diff --git a/packages/embed/tests/e2e/selection-containment.it.test.ts b/packages/embed/tests/e2e/selection-containment.it.test.ts deleted file mode 100644 index 6c0a99f0fb..0000000000 --- a/packages/embed/tests/e2e/selection-containment.it.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' -import {openPanel, sendMessage} from './helpers/panel.js' - -const ASSISTANT_REPLY = 'The widget reply stays selectable inside the chat thread for quoting.' - -const HOST_TEXT = 'Host page article text that must never join a chat selection.' - -const HOST_STYLES: Record = { - 'a host page with default selection styles': '', - 'a host page that forces its article text selectable': 'main p{user-select:text}', - 'a host page that forces its article text selectable with !important': 'main p{user-select:text !important}', -} - -const hostBody = (url: URL) => ` - -
-

${HOST_TEXT}

-

${HOST_TEXT}

-

${HOST_TEXT}

-
-` - -type Point = {x: number; y: number} - -type SelectionEnds = {startInWidget: boolean; endInWidget: boolean; text: string} - -let kit: EmbedKit -let host: {base: string; close: () => Promise} - -test.beforeEach(async () => { - kit = await bootEmbedKit({text: ASSISTANT_REPLY}) - host = await serveHost((url) => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}', body: hostBody(url)})) -}) - -test.afterEach(async () => { - await host.close() - await kit.cleanup() -}) - -async function openWithReply(page: Page, hostStyle = ''): Promise { - await page.setViewportSize({width: 1400, height: 900}) - await page.goto(`${host.base}/?${new URLSearchParams({host: hostStyle})}`, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await sendMessage(page, 'say something selectable', ASSISTANT_REPLY) -} - -async function textStart(page: Page, text: string): Promise { - const box = await page.getByText(text).first().boundingBox() - expect(box).not.toBeNull() - return {x: (box?.x ?? 0) + 60, y: (box?.y ?? 0) + (box?.height ?? 0) / 2} -} - -async function drag(page: Page, from: Point, to: Point): Promise { - await page.mouse.move(from.x, from.y) - await page.mouse.down() - await page.mouse.move(to.x, to.y, {steps: 12}) - await page.mouse.up() -} - -function selectionEnds(page: Page): Promise { - return page.evaluate(() => { - const root = document.querySelector('[data-conciv-root]')?.shadowRoot - const selection = document.getSelection() - const range = root ? selection?.getComposedRanges({shadowRoots: [root]})[0] : undefined - return { - startInWidget: range?.startContainer.getRootNode() === root, - endInWidget: range?.endContainer.getRootNode() === root, - text: selection?.toString() ?? '', - } - }) -} - -test.describe('text selection and the host page', () => { - const outwardDrags: {name: string; target: (page: Page) => Promise; selects: RegExp}[] = [ - { - name: 'up past the top of the panel', - target: async (page) => ({...(await textStart(page, ASSISTANT_REPLY)), y: 2}), - selects: /^\s*CONCIV[\s\S]*say something selectable[\s\S]*The widge$/, - }, - {name: 'sideways over host page text', target: (page) => textStart(page, HOST_TEXT), selects: /^The widge$/}, - { - name: 'down past the bottom of the panel', - target: async (page) => ({...(await textStart(page, ASSISTANT_REPLY)), y: 895}), - selects: /^t reply stays selectable inside the chat thread for quoting\.\s*$/, - }, - ] - - for (const hostStyle of Object.keys(HOST_STYLES)) { - for (const outward of outwardDrags) { - test(`on ${hostStyle}, a selection dragged from the chat reply ${outward.name} stays inside the widget`, async ({ - page, - }) => { - test.setTimeout(120_000) - await openWithReply(page, hostStyle) - - await drag(page, await textStart(page, ASSISTANT_REPLY), await outward.target(page)) - - const ends = await selectionEnds(page) - expect(ends.text).toMatch(outward.selects) - expect(ends).toMatchObject({startInWidget: true, endInWidget: true}) - }) - } - } - - test('a selection started on the host page and dragged over the panel still selects host text', async ({page}) => { - test.setTimeout(120_000) - await openWithReply(page) - - await drag(page, await textStart(page, HOST_TEXT), await textStart(page, ASSISTANT_REPLY)) - - const ends = await selectionEnds(page) - expect(ends.text).toContain('page article text') - expect(ends.startInWidget).toBe(false) - }) -}) diff --git a/packages/embed/tests/e2e/session-canonicalize.it.test.ts b/packages/embed/tests/e2e/session-canonicalize.it.test.ts deleted file mode 100644 index 23622c2001..0000000000 --- a/packages/embed/tests/e2e/session-canonicalize.it.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import {expect, test} from '@playwright/test' -import {currentHref} from '@conciv/extension-testkit/navigation-state' -import {until} from '@conciv/harness-testkit/until' -import {HarnessSessionId} from '@conciv/protocol/chat-types' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' - -const RAW_HARNESS_ID = HarnessSessionId.parse('43548fd1-0000-4220-acf0-014b10b5815f') -const EXTERNAL_TITLE = 'a session started outside conciv' -const NEWER_HARNESS_ID = HarnessSessionId.parse('9f2c77aa-1111-4a10-b3d1-77c0a2e9b004') -const NEWER_TITLE = 'the newest session outside conciv' - -const suite = setupWidgetSuite({ - history: [ - {id: NEWER_HARNESS_ID, derivedTitle: NEWER_TITLE, updatedAt: Date.now(), messageCount: 1}, - {id: RAW_HARNESS_ID, derivedTitle: EXTERNAL_TITLE, updatedAt: Date.now() - 60_000, messageCount: 3}, - ], -}) - -test.describe('switching to a harness session conciv has never adopted', () => { - test('lands the panel on the canonical conciv session route, not the raw harness id', async ({page}) => { - test.setTimeout(180_000) - - const metas = await suite.kit().rpc.sessions.list() - expect(metas.map((meta) => String(meta.id)).filter((id) => !id.startsWith('conciv_'))).toEqual([]) - const external = metas.find((meta) => meta.title === EXTERNAL_TITLE) - if (!external) throw new Error('the harness-native session was not listed under its derived title') - const newer = metas.find((meta) => meta.title === NEWER_TITLE) - if (!newer) throw new Error('the newest harness-native session was not listed under its derived title') - - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - - const sessionOptions = page.getByRole('button', {name: 'Session options'}) - await sessionOptions.click() - await page.getByRole('button', {name: /^Session: /}).click() - const search = page.getByPlaceholder('Search sessions…') - await expect(search).toBeVisible({timeout: 30_000}) - - await search.fill(String(RAW_HARNESS_ID)) - await expect(page.getByText('No sessions match')).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('option', {name: new RegExp(EXTERNAL_TITLE)})).toHaveCount(0) - - await search.fill(String(external.id)) - const canonicalOption = page.getByRole('option', {name: new RegExp(EXTERNAL_TITLE)}) - await expect(canonicalOption).toBeVisible({timeout: 30_000}) - - await canonicalOption.click() - const pill = page.getByRole('button', {name: `Session: ${EXTERNAL_TITLE}`}) - if (!(await pill.isVisible())) await sessionOptions.click() - await expect(pill).toBeVisible({timeout: 30_000}) - - await until(async () => (await currentHref(suite.kit())).includes(String(external.id)), { - hangGuardMs: 30_000, - intervalMs: 100, - }) - const href = await currentHref(suite.kit()) - expect(href).not.toContain(RAW_HARNESS_ID) - expect(href).not.toContain(newer.id) - - const adopted = await suite.kit().rpc.sessions.resolve({id: RAW_HARNESS_ID}) - expect(adopted.sessionId).toBe(external.id) - }) -}) diff --git a/packages/embed/tests/e2e/tool-code-body.it.test.ts b/packages/embed/tests/e2e/tool-code-body.it.test.ts deleted file mode 100644 index fc044843d5..0000000000 --- a/packages/embed/tests/e2e/tool-code-body.it.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' - -const ASSISTANT_TEXT = 'Read the pipeline.' -const RESULT_MARKER = 'pipeline body renders on the built bundle' - -const suite = setupWidgetSuite({text: ASSISTANT_TEXT}) - -async function sendAndOpenTrace(page: Page, message: string): Promise { - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(message) - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByRole('button', {name: 'Stop generating'})).toBeHidden({timeout: 30_000}) - await expect(page.getByRole('button', {name: /Hide trace$/}).last()).toBeVisible({timeout: 30_000}) -} - -test.describe('tool result code bodies on the built bundle', () => { - test('renders the lines of a tool result code body', async ({page}) => { - test.setTimeout(180_000) - suite.kit().harness.script.scriptTurn({ - toolCalls: [{name: 'Read', input: {filePath: 'pipeline.ts'}, result: RESULT_MARKER}], - text: ASSISTANT_TEXT, - }) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await sendAndOpenTrace(page, 'read the pipeline file') - - await expect(page.getByText(RESULT_MARKER).first()).toBeVisible({timeout: 30_000}) - }) -}) diff --git a/packages/embed/tests/e2e/transport-selection.it.test.ts b/packages/embed/tests/e2e/transport-selection.it.test.ts deleted file mode 100644 index 6f25e6ebb3..0000000000 --- a/packages/embed/tests/e2e/transport-selection.it.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {httpRpcRequestUrls, rpcCallCursor, type RpcCallCursor} from '@conciv/extension-testkit/rpc-counts' -import {watchChatWire, type ChatWireWatch} from '@conciv/extension-testkit/chat-wire' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' -import {proxyTo, type ProxyCore} from '../helpers/proxy.js' - -const ASSISTANT_TEXT = 'Hello from conciv' -const MOUNT_TIMEOUT_MS = 30_000 - -let kit: EmbedKit -let openCore: ProxyCore -let blockedCore: ProxyCore -let openHost: {base: string; close: () => Promise} -let blockedHost: {base: string; close: () => Promise} -let pinnedFetchHost: {base: string; close: () => Promise} - -test.beforeEach(async () => { - kit = await bootEmbedKit({text: ASSISTANT_TEXT}) - openCore = await proxyTo(kit.base) - blockedCore = await proxyTo(kit.base, {blockUpgrades: true}) - openHost = await serveHost(() => hostPage({apiBase: openCore.base, widget: '{"quickTerminal":false}'})) - blockedHost = await serveHost(() => hostPage({apiBase: blockedCore.base, widget: '{"quickTerminal":false}'})) - pinnedFetchHost = await serveHost(() => - hostPage({apiBase: openCore.base, widget: '{"quickTerminal":false,"transport":"fetch"}'}), - ) -}) - -test.afterEach(async () => { - await openHost.close() - await blockedHost.close() - await pinnedFetchHost.close() - await openCore.close() - await blockedCore.close() - await kit.cleanup() -}) - -type Tab = {page: Page; calls: RpcCallCursor; wire: ChatWireWatch; httpRpcUrls: string[]} - -async function openTab(page: Page, hostBase: string): Promise { - const {urls} = httpRpcRequestUrls(page) - const calls = rpcCallCursor(page) - const wire = watchChatWire(page) - await page.goto(hostBase, {waitUntil: 'domcontentloaded'}) - return {page, calls, wire, httpRpcUrls: urls} -} - -async function completeTurn(page: Page): Promise { - await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) - await page.getByRole('button', {name: 'Open conciv chat'}).click() - await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill('hi there') - await page.getByRole('button', {name: 'Send message'}).click() - await expect(page.getByText(ASSISTANT_TEXT).first()).toBeVisible({timeout: MOUNT_TIMEOUT_MS}) -} - -test.describe('the chat connection picks one delivery transport per tab at boot', () => { - test('rides the chat websocket when the boot probe succeeds, while rpc rides http', async ({page}) => { - test.setTimeout(120_000) - const tab = await openTab(page, openHost.base) - const sent = tab.wire.nextTurn() - await completeTurn(tab.page) - expect((await sent).transport).toBe('websocket') - expect(tab.calls.socketsSince()).toBe(0) - expect(tab.httpRpcUrls.length).toBeGreaterThan(0) - }) - - test('falls back to the chat event stream for the whole tab when the websocket upgrade is blocked', async ({ - page, - }) => { - test.setTimeout(120_000) - const tab = await openTab(page, blockedHost.base) - const sent = tab.wire.nextTurn() - await completeTurn(tab.page) - expect((await sent).transport).toBe('fetch') - expect(tab.httpRpcUrls.length).toBeGreaterThan(0) - }) - - test('honours the fetch escape hatch without ever opening a chat socket', async ({page}) => { - test.setTimeout(120_000) - const tab = await openTab(page, pinnedFetchHost.base) - const mark = tab.wire.socketMark() - const sent = tab.wire.nextTurn() - await completeTurn(tab.page) - expect((await sent).transport).toBe('fetch') - expect(tab.wire.socketsOpenedSince(mark)).toBe(0) - }) -}) diff --git a/packages/embed/tests/e2e/unknown-view-restore.it.test.ts b/packages/embed/tests/e2e/unknown-view-restore.it.test.ts deleted file mode 100644 index ef73e0490b..0000000000 --- a/packages/embed/tests/e2e/unknown-view-restore.it.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import {expect, test} from '@playwright/test' -import recorderServer from '@conciv/extension-recorder' -import {currentHref} from '@conciv/extension-testkit/navigation-state' -import {until} from '@conciv/harness-testkit/until' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel} from './helpers/panel.js' - -const suite = setupWidgetSuite({text: 'Unknown view reply', extensions: [recorderServer]}) - -test.describe('restoring a persisted panel route whose extension view is no longer mounted', () => { - test('lands on the chat view instead of an empty pane', async ({page}) => { - test.setTimeout(240_000) - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - - await page.getByRole('tab', {name: 'Recorder'}).click() - await expect(page.getByRole('tab', {name: 'Recorder'})).toHaveAttribute('aria-selected', 'true') - await until(async () => (await currentHref(suite.kit())).includes('/recorder'), { - hangGuardMs: 30_000, - intervalMs: 100, - }) - - await page.goto(`${suite.host().base}/?extensions=terminal`, {waitUntil: 'domcontentloaded'}) - - await expect(page.getByRole('dialog', {name: 'conciv chat agent'})).toBeVisible({timeout: 30_000}) - await expect(page.getByRole('tab', {name: 'Recorder'})).toHaveCount(0) - await expect(page.getByRole('textbox', {name: 'Message the conciv agent'})).toBeVisible({timeout: 30_000}) - const statusBar = page.getByRole('toolbar', {name: 'Session status'}) - await expect(statusBar.getByRole('tab', {name: 'Chat', exact: true})).toHaveAttribute('aria-selected', 'true') - await until(async () => !(await currentHref(suite.kit())).includes('/recorder'), { - hangGuardMs: 30_000, - intervalMs: 100, - }) - }) -}) diff --git a/packages/embed/tests/e2e/virtualize-threshold-cliff.it.test.ts b/packages/embed/tests/e2e/virtualize-threshold-cliff.it.test.ts deleted file mode 100644 index e9aa28902f..0000000000 --- a/packages/embed/tests/e2e/virtualize-threshold-cliff.it.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import {expect, test} from '@playwright/test' -import {setupWidgetSuite} from './helpers/suite.js' -import {openPanel, switchToSessionByTitle} from './helpers/panel.js' - -const MARKDOWN_HEAVY_REPLY = [ - '## Findings', - '', - 'Here is a **detailed** breakdown with `inline code` and a fenced block:', - '', - '```ts', - 'function reconcileSnapshotToolCalls(snapshot: UIMessage[]): UIMessage[] {', - ' const prevToolCalls = new Map()', - ' for (const msg of snapshot) for (const part of msg.parts) {', - ' if (part.type === "tool-call") prevToolCalls.set(part.id, part)', - ' }', - ' return snapshot', - '}', - '```', - '', - '- first bullet point with some explanation', - '- second bullet point that is a bit longer to force line wrapping in the estimator', - '- third bullet point', - '', - '> a blockquote noting a caveat worth remembering', -].join('\n') - -const VIRTUALIZE_THRESHOLD_MIRRORED_FROM_UI_KIT_CHAT = 15 -const BELOW_EXCHANGES = Math.floor((VIRTUALIZE_THRESHOLD_MIRRORED_FROM_UI_KIT_CHAT - 1) / 2) -const ABOVE_EXCHANGES = Math.ceil(VIRTUALIZE_THRESHOLD_MIRRORED_FROM_UI_KIT_CHAT / 2) - -const suite = setupWidgetSuite({text: MARKDOWN_HEAVY_REPLY}) - -async function seedExchanges(sessionId: string, exchanges: number): Promise { - const kit = suite.kit() - for (let index = 0; index < exchanges; index += 1) { - const turn = await kit.chat(`question number ${index} about the reconciliation logic`, sessionId) - await turn.done({hangGuardMs: 10_000}) - } -} - -async function measureSwitch(page: import('@playwright/test').Page, exchanges: number): Promise<{rowCount: number}> { - const {sessionId} = await suite.kit().rpc.sessions.create() - const title = `cliff ${exchanges} ${sessionId.slice(-8)}` - await suite.kit().rpc.sessions.rename({sessionId, title}) - await seedExchanges(sessionId, exchanges) - - await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) - await openPanel(page) - await switchToSessionByTitle(page, title) - await expect(page.getByText(`question number ${exchanges - 1}`).first()).toBeVisible({timeout: 30_000}) - - const rowCount = await page.locator('[data-message-id]').count() - return {rowCount} -} - -test.describe('virtualize threshold cliff', () => { - test('a transcript just below the virtualize threshold mounts every turn; crossing it bounds the DOM again', async ({ - page, - }) => { - test.setTimeout(240_000) - const below = await measureSwitch(page, BELOW_EXCHANGES) - console.log(`BELOW THRESHOLD (${BELOW_EXCHANGES * 2} turns, flat mode) rendered row count`, below.rowCount) - - const at = await measureSwitch(page, ABOVE_EXCHANGES) - console.log(`AT THRESHOLD (${ABOVE_EXCHANGES * 2} turns, virtual mode) rendered row count`, at.rowCount) - - expect(below.rowCount, 'below the threshold every turn is mounted unvirtualized').toBe(BELOW_EXCHANGES * 2) - expect( - at.rowCount, - 'at/above the threshold the virtualizer bounds the mounted rows to a window smaller than the transcript', - ).toBeLessThan(ABOVE_EXCHANGES * 2) - }) -}) diff --git a/packages/embed/tests/e2e/warm-session-resolve.it.test.ts b/packages/embed/tests/e2e/warm-session-resolve.it.test.ts deleted file mode 100644 index caa85b3211..0000000000 --- a/packages/embed/tests/e2e/warm-session-resolve.it.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import {expect, test, type Page} from '@playwright/test' -import {gateRpcCalls, type RpcGate} from '@conciv/extension-testkit/rpc-fault' -import {watchRpcWire} from '@conciv/extension-testkit/rpc-wire' -import {setupWidgetSuite} from './helpers/suite.js' -import {hostPage} from '../helpers/host.js' -import {serveHost} from '@conciv/extension-testkit/serve-host' - -const suite = setupWidgetSuite() - -const COMPOSER_NAME = 'Message the conciv agent' -const LAUNCHER_NAME = 'Open conciv chat' -const SESSIONS_LIST = ['sessions', 'list'] as const -const SESSIONS_RESOLVE = ['sessions', 'resolve'] as const - -const dedicatedHosts: Array<{close: () => Promise}> = [] - -test.afterEach(async () => { - for (const dedicatedHost of dedicatedHosts.splice(0)) await dedicatedHost.close() -}) - -function composer(page: Page) { - return page.getByRole('textbox', {name: COMPOSER_NAME}) -} - -function launcher(page: Page) { - return page.getByRole('button', {name: LAUNCHER_NAME}) -} - -type StalledSessionRpcs = {list: RpcGate; resolve: RpcGate} - -async function stallSessionRpcs(page: Page): Promise { - const list = await gateRpcCalls(page, {path: SESSIONS_LIST}) - const resolve = await gateRpcCalls(page, {path: SESSIONS_RESOLVE}) - return {list, resolve} -} - -test.describe('first panel open does not re-run session resolution at click time', () => { - test('clicking the launcher after boot has settled still reveals the composer with sessions RPCs stalled', async ({ - page, - }) => { - test.setTimeout(30_000) - await suite.kit().rpc.sessions.create() - const host = await serveHost(() => - hostPage({apiBase: suite.kit().base, widget: '{"quickTerminal":false,"transport":"fetch"}'}), - ) - dedicatedHosts.push(host) - const wire = watchRpcWire(page) - await page.goto(host.base, {waitUntil: 'domcontentloaded'}) - await expect(launcher(page)).toBeVisible({timeout: 15_000}) - await wire.sessionsBootTraffic() - - const stalled = await stallSessionRpcs(page) - try { - await launcher(page).click() - - await expect(composer(page)).toBeVisible({timeout: 5_000}) - expect(stalled.resolve.pending()).toBe(0) - } finally { - await stalled.list.dispose() - await stalled.resolve.dispose() - } - }) -}) diff --git a/packages/embed/tests/globals.d.ts b/packages/embed/tests/globals.d.ts index 54bbd7dccc..1c70a92243 100644 --- a/packages/embed/tests/globals.d.ts +++ b/packages/embed/tests/globals.d.ts @@ -11,5 +11,4 @@ declare global { concivNativePost: (message: unknown) => Promise concivNativeRebind: (detail: unknown) => Promise } - var __fabFrames: Promise> } diff --git a/packages/embed/tests/helpers.ts b/packages/embed/tests/helpers.ts new file mode 100644 index 0000000000..758101f369 --- /dev/null +++ b/packages/embed/tests/helpers.ts @@ -0,0 +1,401 @@ +import type {AnyExtension} from '@conciv/extension' +import type {HarnessCommand, HarnessModel, HarnessSessionMeta} from '@conciv/protocol/harness-types' +import {bootCoreKit, type CoreKit} from '@conciv/extension-testkit/core-kit' +import fs from 'node:fs' +import path from 'node:path' +import {fileURLToPath} from 'node:url' +import {createServer, type Server, request as httpRequest, type IncomingMessage} from 'node:http' +import {listenLocal} from '@conciv/extension-testkit/listen-local' +import type {Duplex} from 'node:stream' +import {test, expect, type Page} from '@playwright/test' +import {serveHost} from '@conciv/extension-testkit/serve-host' +import type {DraftRow} from '@conciv/contract' +import {until} from '@conciv/harness-testkit/until' +import {PageToNativeSchema, type PageToNativeMessage} from '@conciv/extension-ios/bridge' +import {awaitPagePlaneSubscribed} from '@conciv/extension-testkit/page-plane' + +export type EmbedKit = CoreKit + +export async function bootEmbedKit( + opts: { + text?: string + extensions?: AnyExtension[] + models?: HarnessModel[] + commands?: HarnessCommand[] + history?: HarnessSessionMeta[] + } = {}, +): Promise { + const kit = await bootCoreKit({ + id: 'fake-embed', + text: opts.text, + extensions: opts.extensions, + models: opts.models, + commands: opts.commands, + history: opts.history, + }) + return { + ...kit, + cleanup: async () => { + try { + await kit.cleanup() + } catch (error) { + console.error('[embed-testkit] kit cleanup failed:', error) + } + }, + } +} + +const dirname = path.dirname(fileURLToPath(import.meta.url)) + +export const embedBundle = fs.readFileSync(path.join(dirname, '../dist/conciv-widget.global.js'), 'utf8') + +const HOST_BACKDROPS: Record = { + 'light-stripes': 'repeating-linear-gradient(45deg, #ffffff 0 14px, #ff0000 14px 28px)', + 'dark-stripes': 'repeating-linear-gradient(45deg, #000000 0 14px, #0000ff 14px 28px)', +} + +function backdropStyle(backdrop: string | null | undefined): string { + const stripes = backdrop === null || backdrop === undefined ? undefined : HOST_BACKDROPS[backdrop] + if (stripes === undefined) return '' + return `` +} + +export function hostPage(opts: {apiBase: string; widget?: string; body?: string; backdrop?: string | null}): string { + return ` + + + + ${backdropStyle(opts.backdrop)} + + ${opts.body ?? '
page-bus-ok
'} + + ` +} + +export function handleHostPage(body?: string): string { + const handleBundle = fs.readFileSync(path.join(dirname, 'dist/conciv-handle.global.js'), 'utf8') + return ` + + + ${body ?? '
page-bus-ok
'} + + ` +} + +export async function reserveDeadPort(): Promise<{base: string; port: number}> { + const probe: Server = createServer() + const {port} = await listenLocal(probe) + await new Promise((resolve) => probe.close(() => resolve())) + return {base: `http://127.0.0.1:${port}`, port} +} + +export type ProxyCore = { + base: string + port: number + requestCount: () => number + wsConnectionCount: () => number + trafficCount: () => number + dropConnections: () => void + setUpgradesBlocked: (blocked: boolean) => void + close: () => Promise +} + +function handshakeResponse(upstream: IncomingMessage): string { + const statusLine = `HTTP/1.1 ${upstream.statusCode ?? 101} ${upstream.statusMessage ?? 'Switching Protocols'}` + const headers = upstream.rawHeaders.reduce((lines, value, index) => { + if (index % 2 === 1) return lines + return [...lines, `${value}: ${upstream.rawHeaders[index + 1] ?? ''}`] + }, []) + return [statusLine, ...headers, '', ''].join('\r\n') +} + +export async function proxyTo( + targetBase: string, + opts: {blockUpgrades?: boolean; port?: number} = {}, +): Promise { + const target = new URL(targetBase) + let count = 0 + let upgrades = 0 + let upgradesBlocked = opts.blockUpgrades === true + const piped = new Set() + const server: Server = createServer((req, res) => { + count += 1 + const proxyReq = httpRequest( + { + hostname: target.hostname, + port: target.port, + path: req.url, + method: req.method, + headers: {...req.headers, host: target.host}, + }, + (proxyRes) => { + res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers) + proxyRes.pipe(res) + }, + ) + proxyReq.on('error', () => { + if (!res.headersSent) res.writeHead(502) + res.end() + }) + req.pipe(proxyReq) + }) + server.on('upgrade', (req, clientSocket: Duplex, head: Buffer) => { + upgrades += 1 + if (upgradesBlocked) { + clientSocket.destroy() + return + } + piped.add(clientSocket) + clientSocket.on('close', () => piped.delete(clientSocket)) + const proxyReq = httpRequest({ + hostname: target.hostname, + port: target.port, + path: req.url, + method: req.method, + headers: {...req.headers, host: target.host}, + }) + proxyReq.on('upgrade', (upstreamRes, upstreamSocket: Duplex, upstreamHead: Buffer) => { + piped.add(upstreamSocket) + upstreamSocket.on('close', () => piped.delete(upstreamSocket)) + clientSocket.write(handshakeResponse(upstreamRes)) + if (upstreamHead.length > 0) clientSocket.write(upstreamHead) + if (head.length > 0) upstreamSocket.write(head) + upstreamSocket.on('error', () => clientSocket.destroy()) + clientSocket.on('error', () => upstreamSocket.destroy()) + upstreamSocket.pipe(clientSocket) + clientSocket.pipe(upstreamSocket) + }) + proxyReq.on('error', () => clientSocket.destroy()) + proxyReq.end() + }) + const {base, port, close} = await listenLocal(server, opts.port ?? 0) + return { + base, + port, + requestCount: () => count, + wsConnectionCount: () => upgrades, + trafficCount: () => count + upgrades, + dropConnections: () => { + for (const socket of piped) socket.destroy() + piped.clear() + }, + setUpgradesBlocked: (blocked) => { + upgradesBlocked = blocked + }, + close: async () => { + try { + for (const socket of piped) socket.destroy() + piped.clear() + await close() + } catch (error) { + console.error('[embed-testkit] proxy close failed:', error) + } + }, + } +} + +export type WidgetSuite = { + kit: () => EmbedKit + host: () => {base: string; close: () => Promise} +} + +export function setupWidgetSuite(options: Parameters[0] = {}): WidgetSuite { + let kit: EmbedKit + let host: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit(options) + host = await serveHost(() => hostPage({apiBase: kit.base, widget: '{"quickTerminal":false}'})) + }) + + test.afterEach(async () => { + kit.harness.script.release() + await host.close() + await kit.cleanup() + }) + + return {kit: () => kit, host: () => host} +} + +export type ProxiedEmbedSuite = { + kit: () => EmbedKit + core: () => ProxyCore + host: () => {base: string; close: () => Promise} +} + +export function setupProxiedEmbedSuite( + opts: { + text?: string + widget?: string + proxy?: {blockUpgrades?: boolean; port?: number} + } = {}, +): ProxiedEmbedSuite { + let kit: EmbedKit + let core: ProxyCore + let host: {base: string; close: () => Promise} + + test.beforeEach(async () => { + kit = await bootEmbedKit({text: opts.text}) + core = await proxyTo(kit.base, opts.proxy) + host = await serveHost(() => hostPage({apiBase: core.base, widget: opts.widget ?? '{"quickTerminal":false}'})) + }) + + test.afterEach(async () => { + await host.close() + await core.close() + await kit.cleanup() + }) + + return { + kit: () => kit, + core: () => core, + host: () => host, + } +} + +const PANEL_TIMEOUT_MS = 30_000 + +export function chatLog(page: Page) { + return page.getByRole('log') +} + +export function chatBox(page: Page) { + return page.getByRole('textbox', {name: 'Message the conciv agent'}) +} + +export async function openChatPanel(page: Page): Promise { + await expect(page.getByRole('button', {name: 'Open conciv chat'})).toBeVisible({timeout: PANEL_TIMEOUT_MS}) + await page.getByRole('button', {name: 'Open conciv chat'}).click() + await expect(chatBox(page)).toBeVisible({timeout: PANEL_TIMEOUT_MS}) +} + +export async function sendChatMessage(page: Page, text: string): Promise { + await chatBox(page).fill(text) + await page.getByRole('button', {name: 'Send message'}).click() +} + +export async function sendHeldTurn(page: Page, suite: WidgetSuite): Promise { + suite.kit().harness.script.hold() + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openChatPanel(page) + await sendChatMessage(page, 'hold this turn open') + await expect(page.getByRole('button', {name: 'Stop generating'})).toBeVisible() +} + +export function untilPanelDraft( + kit: EmbedKit, + sessionId: string, + matches: (draft: DraftRow) => boolean, +): Promise { + return until( + async () => { + const draft = await kit.rpc.drafts.get({sessionId}) + return draft !== null && matches(draft) + }, + {hangGuardMs: 30_000, intervalMs: 100}, + ) +} + +export async function mountHandle(page: Page, apiBase: string): Promise { + await page.evaluate((base) => { + const el = document.createElement('div') + document.body.appendChild(el) + window.concivTestElement = el + window.concivTestHandle = window.ConcivHandle.makeHandle(base) + void window.concivTestHandle.mount(el) + }, apiBase) +} + +export async function openHostWithHandle(page: Page, hostBase: string, apiBase: string): Promise { + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + await page.goto(hostBase, {waitUntil: 'domcontentloaded'}) + await mountHandle(page, apiBase) + return pageErrors +} + +export async function remountHandle(page: Page): Promise { + await page.evaluate(() => void window.concivTestHandle.mount(window.concivTestElement)) +} + +export async function unmountHandle(page: Page): Promise { + await page.evaluate(() => window.concivTestHandle.unmount()) +} + +export async function rebindHandle(page: Page, apiBase: string): Promise { + await page.evaluate((base) => window.concivTestHandle.rebind(base), apiBase) +} + +export type NativeBridge = { + posted: PageToNativeMessage[] + notify: (message: PageToNativeMessage) => void +} + +export async function captureNativePosts(page: Page): Promise { + const bridge: NativeBridge = {posted: [], notify: () => {}} + await page.exposeFunction('concivNativePost', (message: unknown) => { + const parsed = PageToNativeSchema.safeParse(message) + if (!parsed.success) return + bridge.posted.push(parsed.data) + bridge.notify(parsed.data) + }) + return bridge +} + +export async function installNativeStub(page: Page): Promise { + await page.addInitScript(() => { + window.webkit = { + messageHandlers: {concivBridge: {postMessage: (message) => void window.concivNativePost(message)}}, + } + }) +} + +const PAGE_DRIVER_TIMEOUT_MS = 30_000 + +export async function openPagePlaneHost(page: Page, base: string): Promise { + await awaitPagePlaneSubscribed(page, async () => { + await page.goto(base, {waitUntil: 'domcontentloaded'}) + await page.waitForFunction(() => '__CONCIV_PAGE_DRIVER__' in window, undefined, {timeout: PAGE_DRIVER_TIMEOUT_MS}) + }) + return page +} + +const escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +export async function openPanel(page: Page): Promise { + const composer = page.getByRole('textbox', {name: 'Message the conciv agent'}) + const opener = page.getByRole('button', {name: 'Open conciv chat'}) + await expect(composer.or(opener)).toBeVisible({timeout: 30_000}) + if (!(await composer.isVisible())) await opener.click() + await expect(composer).toBeVisible({timeout: 30_000}) +} + +export async function switchToSessionByTitle(page: Page, title: string): Promise { + const sessionOptions = page.getByRole('button', {name: 'Session options'}) + await sessionOptions.click() + await page.getByRole('button', {name: /^Session: /}).click() + const option = page.getByRole('option', {name: new RegExp(escapeRegex(title))}) + await expect(option).toBeVisible({timeout: 30_000}) + await option.click() + const pill = page.getByRole('button', {name: `Session: ${title}`}) + if (!(await pill.isVisible())) await sessionOptions.click() + await expect(pill).toBeVisible({timeout: 30_000}) + await page.keyboard.press('Escape') + await expect(pill).toBeHidden({timeout: 30_000}) +} + +export async function openPanelOnNewSession(page: Page, suite: WidgetSuite): Promise { + const {sessionId} = await suite.kit().rpc.sessions.create() + const title = `session under test ${sessionId.slice(-12)}` + await suite.kit().rpc.sessions.rename({sessionId, title}) + await page.goto(suite.host().base, {waitUntil: 'domcontentloaded'}) + await openPanel(page) + await switchToSessionByTitle(page, title) + return sessionId +} + +export async function sendMessage(page: Page, text: string, reply: string): Promise { + await page.getByRole('textbox', {name: 'Message the conciv agent'}).fill(text) + await page.getByRole('button', {name: 'Send message'}).click() + await expect(page.getByText(reply).first()).toBeVisible({timeout: 30_000}) +} diff --git a/packages/embed/tests/helpers/boot.ts b/packages/embed/tests/helpers/boot.ts deleted file mode 100644 index 3c8d12da84..0000000000 --- a/packages/embed/tests/helpers/boot.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type {AnyExtension} from '@conciv/extension' -import type {HarnessCommand, HarnessModel, HarnessSessionMeta} from '@conciv/protocol/harness-types' -import {bootCoreKit, type CoreKit} from '@conciv/extension-testkit/core-kit' - -export type EmbedKit = CoreKit - -export async function bootEmbedKit( - opts: { - text?: string - extensions?: AnyExtension[] - models?: HarnessModel[] - commands?: HarnessCommand[] - history?: HarnessSessionMeta[] - } = {}, -): Promise { - const kit = await bootCoreKit({ - id: 'fake-embed', - text: opts.text, - extensions: opts.extensions, - models: opts.models, - commands: opts.commands, - history: opts.history, - }) - return { - ...kit, - cleanup: async () => { - try { - await kit.cleanup() - } catch (error) { - console.error('[embed-testkit] kit cleanup failed:', error) - } - }, - } -} diff --git a/packages/embed/tests/helpers/host.ts b/packages/embed/tests/helpers/host.ts deleted file mode 100644 index f9d912f647..0000000000 --- a/packages/embed/tests/helpers/host.ts +++ /dev/null @@ -1,49 +0,0 @@ -import fs from 'node:fs' -import path from 'node:path' -import {fileURLToPath} from 'node:url' -import {createServer, type Server} from 'node:http' -import {listenLocal} from '@conciv/extension-testkit/listen-local' - -const dirname = path.dirname(fileURLToPath(import.meta.url)) - -export const embedBundle = fs.readFileSync(path.join(dirname, '../../dist/conciv-widget.global.js'), 'utf8') - -const HOST_BACKDROPS: Record = { - 'light-stripes': 'repeating-linear-gradient(45deg, #ffffff 0 14px, #ff0000 14px 28px)', - 'dark-stripes': 'repeating-linear-gradient(45deg, #000000 0 14px, #0000ff 14px 28px)', -} - -function backdropStyle(backdrop: string | null | undefined): string { - const stripes = backdrop === null || backdrop === undefined ? undefined : HOST_BACKDROPS[backdrop] - if (stripes === undefined) return '' - return `` -} - -export function hostPage(opts: {apiBase: string; widget?: string; body?: string; backdrop?: string | null}): string { - return ` - - - - ${backdropStyle(opts.backdrop)} - - ${opts.body ?? '
page-bus-ok
'} - - ` -} - -export function handleHostPage(body?: string): string { - const handleBundle = fs.readFileSync(path.join(dirname, '../dist/conciv-handle.global.js'), 'utf8') - return ` - - - ${body ?? '
page-bus-ok
'} - - ` -} - -export async function reserveDeadPort(): Promise<{base: string; port: number}> { - const probe: Server = createServer() - const {port} = await listenLocal(probe) - await new Promise((resolve) => probe.close(() => resolve())) - return {base: `http://127.0.0.1:${port}`, port} -} diff --git a/packages/embed/tests/helpers/proxy.ts b/packages/embed/tests/helpers/proxy.ts deleted file mode 100644 index 7215727dbe..0000000000 --- a/packages/embed/tests/helpers/proxy.ts +++ /dev/null @@ -1,108 +0,0 @@ -import {createServer, request as httpRequest, type IncomingMessage, type Server} from 'node:http' -import type {Duplex} from 'node:stream' -import {listenLocal} from '@conciv/extension-testkit/listen-local' - -export type ProxyCore = { - base: string - port: number - requestCount: () => number - wsConnectionCount: () => number - trafficCount: () => number - dropConnections: () => void - setUpgradesBlocked: (blocked: boolean) => void - close: () => Promise -} - -function handshakeResponse(upstream: IncomingMessage): string { - const statusLine = `HTTP/1.1 ${upstream.statusCode ?? 101} ${upstream.statusMessage ?? 'Switching Protocols'}` - const headers = upstream.rawHeaders.reduce((lines, value, index) => { - if (index % 2 === 1) return lines - return [...lines, `${value}: ${upstream.rawHeaders[index + 1] ?? ''}`] - }, []) - return [statusLine, ...headers, '', ''].join('\r\n') -} - -export async function proxyTo( - targetBase: string, - opts: {blockUpgrades?: boolean; port?: number} = {}, -): Promise { - const target = new URL(targetBase) - let count = 0 - let upgrades = 0 - let upgradesBlocked = opts.blockUpgrades === true - const piped = new Set() - const server: Server = createServer((req, res) => { - count += 1 - const proxyReq = httpRequest( - { - hostname: target.hostname, - port: target.port, - path: req.url, - method: req.method, - headers: {...req.headers, host: target.host}, - }, - (proxyRes) => { - res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers) - proxyRes.pipe(res) - }, - ) - proxyReq.on('error', () => { - if (!res.headersSent) res.writeHead(502) - res.end() - }) - req.pipe(proxyReq) - }) - server.on('upgrade', (req, clientSocket: Duplex, head: Buffer) => { - upgrades += 1 - if (upgradesBlocked) { - clientSocket.destroy() - return - } - piped.add(clientSocket) - clientSocket.on('close', () => piped.delete(clientSocket)) - const proxyReq = httpRequest({ - hostname: target.hostname, - port: target.port, - path: req.url, - method: req.method, - headers: {...req.headers, host: target.host}, - }) - proxyReq.on('upgrade', (upstreamRes, upstreamSocket: Duplex, upstreamHead: Buffer) => { - piped.add(upstreamSocket) - upstreamSocket.on('close', () => piped.delete(upstreamSocket)) - clientSocket.write(handshakeResponse(upstreamRes)) - if (upstreamHead.length > 0) clientSocket.write(upstreamHead) - if (head.length > 0) upstreamSocket.write(head) - upstreamSocket.on('error', () => clientSocket.destroy()) - clientSocket.on('error', () => upstreamSocket.destroy()) - upstreamSocket.pipe(clientSocket) - clientSocket.pipe(upstreamSocket) - }) - proxyReq.on('error', () => clientSocket.destroy()) - proxyReq.end() - }) - const {base, port, close} = await listenLocal(server, opts.port ?? 0) - return { - base, - port, - requestCount: () => count, - wsConnectionCount: () => upgrades, - trafficCount: () => count + upgrades, - dropConnections: () => { - for (const socket of piped) socket.destroy() - piped.clear() - }, - setUpgradesBlocked: (blocked) => { - upgradesBlocked = blocked - }, - close: async () => { - try { - for (const socket of piped) socket.destroy() - piped.clear() - await close() - } catch (error) { - console.error('[embed-testkit] proxy close failed:', error) - } - }, - } -} diff --git a/packages/embed/tests/unit/embed.test.ts b/packages/embed/tests/unit/embed.test.ts new file mode 100644 index 0000000000..98292db08c --- /dev/null +++ b/packages/embed/tests/unit/embed.test.ts @@ -0,0 +1,115 @@ +import {readdirSync, readFileSync} from 'node:fs' +import {fileURLToPath} from 'node:url' +import {describe, expect, it} from 'vitest' +import {createConciv, mountConciv} from '../../src/mount.js' + +describe('mount externals', () => { + const distDir = fileURLToPath(new URL('../../dist/', import.meta.url)) + const chunkName = readdirSync(distDir).find((name) => /^mount-impl.*\.js$/.test(name)) ?? '' + const mount = chunkName ? readFileSync(distDir + chunkName, 'utf8') : '' + const entry = readFileSync(distDir + 'mount.js', 'utf8') + const globalBundle = readFileSync(distDir + 'conciv-widget.global.js', 'utf8') + + const externalized = (specifier: string) => new RegExp(`from\\s*["']${specifier.replace('/', '\\/')}`).test(mount) + + describe('embed mount build pins the onlineManager singleton topology (#350)', () => { + it('never externalizes @tanstack/query-core, so the mounted app shares one onlineManager with its own QueryClient', () => { + expect(externalized('@tanstack/query-core')).toBe(false) + }) + + it('never inlines @conciv/contract, so its reachability seam cannot capture a second query-core instance', () => { + expect(externalized('@conciv/contract')).toBe(true) + }) + }) + + describe('embed mount build shares one Ark environment instance with extensions', () => { + it('externalizes ui-kit-system so the root EnvironmentProvider and extension Combobox read the same context', () => { + expect(externalized('@conciv/ui-kit-system')).toBe(true) + }) + + it('externalizes ui-kit-chat so the model selector context is shared', () => { + expect(externalized('@conciv/ui-kit-chat')).toBe(true) + }) + + it('externalizes ui-kit-tap so extensions share one editor and Solid/Ark copy', () => { + expect(externalized('@conciv/ui-kit-tap')).toBe(true) + }) + + it('externalizes @ark-ui rather than bundling a second copy', () => { + expect(externalized('@ark-ui/')).toBe(true) + }) + + it('externalizes solid-js so extension clients share the reactive runtime', () => { + expect(externalized('solid-js')).toBe(true) + }) + + it('inlines the private conciv app, @conciv/page, and the packages whose cards it renders', () => { + expect(externalized('@conciv/app/router')).toBe(false) + expect(externalized('@conciv/page')).toBe(false) + expect(externalized('@conciv/tools')).toBe(false) + expect(externalized('@conciv/core')).toBe(false) + }) + + it('ships only the page declarations, never the dev-server ones the widget cannot call', () => { + expect(globalBundle).toContain('type a value into a form field') + expect(globalBundle).not.toContain('restart the dev server') + }) + + it('emits the app graph as a mount-impl chunk', () => { + expect(chunkName).not.toBe('') + }) + + it('keeps the mount entry free of static runtime imports (SSR-safe)', () => { + expect(/^import\s/m.test(entry)).toBe(false) + }) + }) +}) + +describe('mount node', () => { + describe('createConciv outside a browser', () => { + it('unmount before mount is a no-op', () => { + expect(() => createConciv().unmount()).not.toThrow() + }) + + it('mountConciv is safe to call without document', () => { + expect(() => mountConciv([])).not.toThrow() + }) + }) +}) + +describe('native bundle', () => { + const distDir = fileURLToPath(new URL('../../dist/', import.meta.url)) + const nativeBundle = readFileSync(distDir + 'conciv-widget-native.global.js', 'utf8') + const widgetBundle = readFileSync(distDir + 'conciv-widget.global.js', 'utf8') + + const importsExternally = (specifier: string) => + new RegExp(`from\\s*["']${specifier.replace('/', '\\/')}`).test(nativeBundle) + + const occurrences = (bundle: string, marker: string) => bundle.split(marker).length - 1 + + describe('embed native bundle', () => { + it('inlines the ios extension client so the WebView carries the native bridge', () => { + expect(nativeBundle.includes('concivBridge')).toBe(true) + expect(nativeBundle.includes('__concivNative')).toBe(true) + }) + + it('bundles the conciv app graph into the native entry', () => { + expect(nativeBundle.includes('conciv chat agent')).toBe(true) + }) + + it('leaves no runtime import external in the self-contained native bundle', () => { + expect(importsExternally('solid-js')).toBe(false) + expect(importsExternally('@ark-ui/')).toBe(false) + expect(importsExternally('@conciv/ui-kit-system')).toBe(false) + }) + + it('inlines the ios client without adding a second Solid runtime copy beyond the audited widget bundle', () => { + const nativeProxy = occurrences(nativeBundle, 'solid-proxy') + const nativeTrack = occurrences(nativeBundle, 'solid-track') + expect(nativeProxy).toBeGreaterThan(0) + expect(nativeTrack).toBeGreaterThan(0) + expect(nativeProxy).toBe(occurrences(widgetBundle, 'solid-proxy')) + expect(nativeTrack).toBe(occurrences(widgetBundle, 'solid-track')) + }) + }) +}) diff --git a/packages/embed/tests/unit/mount-externals.test.ts b/packages/embed/tests/unit/mount-externals.test.ts deleted file mode 100644 index 29db81b994..0000000000 --- a/packages/embed/tests/unit/mount-externals.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import {readdirSync, readFileSync} from 'node:fs' -import {fileURLToPath} from 'node:url' -import {describe, expect, it} from 'vitest' - -const distDir = fileURLToPath(new URL('../../dist/', import.meta.url)) -const chunkName = readdirSync(distDir).find((name) => /^mount-impl.*\.js$/.test(name)) ?? '' -const mount = chunkName ? readFileSync(distDir + chunkName, 'utf8') : '' -const entry = readFileSync(distDir + 'mount.js', 'utf8') -const globalBundle = readFileSync(distDir + 'conciv-widget.global.js', 'utf8') - -const externalized = (specifier: string) => new RegExp(`from\\s*["']${specifier.replace('/', '\\/')}`).test(mount) - -describe('embed mount build pins the onlineManager singleton topology (#350)', () => { - it('never externalizes @tanstack/query-core, so the mounted app shares one onlineManager with its own QueryClient', () => { - expect(externalized('@tanstack/query-core')).toBe(false) - }) - - it('never inlines @conciv/contract, so its reachability seam cannot capture a second query-core instance', () => { - expect(externalized('@conciv/contract')).toBe(true) - }) -}) - -describe('embed mount build shares one Ark environment instance with extensions', () => { - it('externalizes ui-kit-system so the root EnvironmentProvider and extension Combobox read the same context', () => { - expect(externalized('@conciv/ui-kit-system')).toBe(true) - }) - - it('externalizes ui-kit-chat so the model selector context is shared', () => { - expect(externalized('@conciv/ui-kit-chat')).toBe(true) - }) - - it('externalizes ui-kit-tap so extensions share one editor and Solid/Ark copy', () => { - expect(externalized('@conciv/ui-kit-tap')).toBe(true) - }) - - it('externalizes @ark-ui rather than bundling a second copy', () => { - expect(externalized('@ark-ui/')).toBe(true) - }) - - it('externalizes solid-js so extension clients share the reactive runtime', () => { - expect(externalized('solid-js')).toBe(true) - }) - - it('inlines the private conciv app, @conciv/page, and the packages whose cards it renders', () => { - expect(externalized('@conciv/app/router')).toBe(false) - expect(externalized('@conciv/page')).toBe(false) - expect(externalized('@conciv/tools')).toBe(false) - expect(externalized('@conciv/core')).toBe(false) - }) - - it('ships only the page declarations, never the dev-server ones the widget cannot call', () => { - expect(globalBundle).toContain('type a value into a form field') - expect(globalBundle).not.toContain('restart the dev server') - }) - - it('emits the app graph as a mount-impl chunk', () => { - expect(chunkName).not.toBe('') - }) - - it('keeps the mount entry free of static runtime imports (SSR-safe)', () => { - expect(/^import\s/m.test(entry)).toBe(false) - }) -}) diff --git a/packages/embed/tests/unit/mount-node.test.ts b/packages/embed/tests/unit/mount-node.test.ts deleted file mode 100644 index 8ca960f9b5..0000000000 --- a/packages/embed/tests/unit/mount-node.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import {describe, expect, it} from 'vitest' -import {createConciv, mountConciv} from '../../src/mount.js' - -describe('createConciv outside a browser', () => { - it('unmount before mount is a no-op', () => { - expect(() => createConciv().unmount()).not.toThrow() - }) - - it('mountConciv is safe to call without document', () => { - expect(() => mountConciv([])).not.toThrow() - }) -}) diff --git a/packages/embed/tests/unit/native-bundle.test.ts b/packages/embed/tests/unit/native-bundle.test.ts deleted file mode 100644 index 78c7315550..0000000000 --- a/packages/embed/tests/unit/native-bundle.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import {readFileSync} from 'node:fs' -import {fileURLToPath} from 'node:url' -import {describe, expect, it} from 'vitest' - -const distDir = fileURLToPath(new URL('../../dist/', import.meta.url)) -const nativeBundle = readFileSync(distDir + 'conciv-widget-native.global.js', 'utf8') -const widgetBundle = readFileSync(distDir + 'conciv-widget.global.js', 'utf8') - -const importsExternally = (specifier: string) => - new RegExp(`from\\s*["']${specifier.replace('/', '\\/')}`).test(nativeBundle) - -const occurrences = (bundle: string, marker: string) => bundle.split(marker).length - 1 - -describe('embed native bundle', () => { - it('inlines the ios extension client so the WebView carries the native bridge', () => { - expect(nativeBundle.includes('concivBridge')).toBe(true) - expect(nativeBundle.includes('__concivNative')).toBe(true) - }) - - it('bundles the conciv app graph into the native entry', () => { - expect(nativeBundle.includes('conciv chat agent')).toBe(true) - }) - - it('leaves no runtime import external in the self-contained native bundle', () => { - expect(importsExternally('solid-js')).toBe(false) - expect(importsExternally('@ark-ui/')).toBe(false) - expect(importsExternally('@conciv/ui-kit-system')).toBe(false) - }) - - it('inlines the ios client without adding a second Solid runtime copy beyond the audited widget bundle', () => { - const nativeProxy = occurrences(nativeBundle, 'solid-proxy') - const nativeTrack = occurrences(nativeBundle, 'solid-track') - expect(nativeProxy).toBeGreaterThan(0) - expect(nativeTrack).toBeGreaterThan(0) - expect(nativeProxy).toBe(occurrences(widgetBundle, 'solid-proxy')) - expect(nativeTrack).toBe(occurrences(widgetBundle, 'solid-track')) - }) -}) diff --git a/packages/embed/tests/unit/navigation-storage.test.ts b/packages/embed/tests/unit/navigation-storage.test.ts deleted file mode 100644 index de6e146f42..0000000000 --- a/packages/embed/tests/unit/navigation-storage.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import {describe, expect, it, vi} from 'vitest' -import type {NavigationWrite} from '@conciv/protocol/chat-types' -import {makeNavigationStorage} from '../../src/navigation-storage.js' - -type FakeNavigationRpc = { - navigation: { - get: () => Promise - set: (write: NavigationWrite) => Promise<{ok: true; applied: boolean}> - } -} - -function fakeRpc( - onSet: (base: string, write: NavigationWrite) => void, - currentBase: {value: string}, -): FakeNavigationRpc { - return { - navigation: { - get: async () => null, - set: async (write) => { - onSet(currentBase.value, write) - return {ok: true, applied: true} - }, - }, - } -} - -describe('makeNavigationStorage', () => { - it('never delivers a navigation write scheduled before dispose to the base that was active at delivery time', async () => { - vi.useFakeTimers() - try { - const currentBase = {value: 'https://old.example.test'} - const deliveries: Array<{base: string; write: NavigationWrite}> = [] - const rpc = fakeRpc((base, write) => deliveries.push({base, write}), currentBase) - const storage = makeNavigationStorage(rpc, () => {}) - - storage.setItem('conciv-navigation', JSON.stringify({entries: [{href: '/old'}], index: 0})) - - currentBase.value = 'https://new.example.test' - storage.dispose() - - await vi.advanceTimersByTimeAsync(1000) - - expect(deliveries).toEqual([]) - } finally { - vi.useRealTimers() - } - }) - - it('delivers a navigation write to the currently bound base when not disposed before the debounce fires', async () => { - vi.useFakeTimers() - try { - const currentBase = {value: 'https://old.example.test'} - const deliveries: Array<{base: string; write: NavigationWrite}> = [] - const rpc = fakeRpc((base, write) => deliveries.push({base, write}), currentBase) - const storage = makeNavigationStorage(rpc, () => {}) - - storage.setItem('conciv-navigation', JSON.stringify({entries: [{href: '/old'}], index: 0})) - await vi.advanceTimersByTimeAsync(1000) - - expect(deliveries).toHaveLength(1) - expect(deliveries[0]?.base).toBe('https://old.example.test') - storage.dispose() - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/packages/embed/tests/unit/proxy-upgrade.test.ts b/packages/embed/tests/unit/proxy-upgrade.test.ts deleted file mode 100644 index 19c74adb00..0000000000 --- a/packages/embed/tests/unit/proxy-upgrade.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import {afterAll, beforeAll, describe, expect, it} from 'vitest' -import {CHAT_WS_PATH} from '@conciv/protocol/chat-types' -import {bootEmbedKit, type EmbedKit} from '../helpers/boot.js' -import {proxyTo, type ProxyCore} from '../helpers/proxy.js' - -let kit: EmbedKit - -beforeAll(async () => { - kit = await bootEmbedKit() -}, 60_000) - -afterAll(async () => { - await kit.cleanup() -}) - -function openChatSocket(proxy: ProxyCore): {socket: WebSocket; opened: Promise; closed: Promise} { - const socket = new WebSocket(`${proxy.base.replace('http:', 'ws:')}${CHAT_WS_PATH}`) - const opened = new Promise((resolve, reject) => { - socket.addEventListener('open', () => resolve(), {once: true}) - socket.addEventListener('error', () => reject(new Error('the proxied chat socket never opened')), {once: true}) - }) - const closed = new Promise((resolve) => socket.addEventListener('close', (event) => resolve(event.code))) - return {socket, opened, closed} -} - -describe('the embed test proxy carries the chat websocket', () => { - it('pipes the upgrade to the target core so the socket opens through the proxy', async () => { - const proxy = await proxyTo(kit.base) - const {socket, opened} = openChatSocket(proxy) - await opened - expect(proxy.wsConnectionCount()).toBe(1) - expect(proxy.requestCount()).toBe(0) - socket.close() - await proxy.close() - }) - - it('counts http requests and socket upgrades separately on the same proxy', async () => { - const proxy = await proxyTo(kit.base) - const {socket, opened} = openChatSocket(proxy) - await opened - await fetch(`${proxy.base}/rpc/meta/tools`, { - method: 'POST', - headers: {'content-type': 'application/json'}, - body: JSON.stringify({json: undefined, meta: []}), - }) - expect(proxy.requestCount()).toBe(1) - expect(proxy.wsConnectionCount()).toBe(1) - socket.close() - await proxy.close() - }) - - it('closing the proxy drops the piped socket so a reconnect gate can force a drop', async () => { - const proxy = await proxyTo(kit.base) - const {opened, closed} = openChatSocket(proxy) - await opened - await proxy.close() - expect(await closed).toBeGreaterThan(0) - }) -}) diff --git a/packages/oxlint-plugin/src/banned-vocabulary.js b/packages/oxlint-plugin/src/banned-vocabulary.js index 4e228c4601..9386c8ba02 100644 --- a/packages/oxlint-plugin/src/banned-vocabulary.js +++ b/packages/oxlint-plugin/src/banned-vocabulary.js @@ -36,7 +36,7 @@ const NATIVE_AND_REACT_BRIDGE_PATHS = [ 'packages/publish/src/swift-mirror.ts', 'packages/page/src/', 'packages/embed/src/mount-impl.tsx', - 'packages/embed/tests/e2e/helpers/native-bridge.ts', + 'packages/embed/tests/helpers.ts', ] const PRE_REWRITE_BRIDGE_PATHS = [