Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

109 KB
Raw Blame
import { createServer } from 'node:http';
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
import path from 'node:path';
import { homedir, tmpdir } from 'node:os';
import { expect, OrkasTestApp, test } from './fixtures/orkas';

test('resource cache survives restart while website data stays in its original profile', async ({}, testInfo) => {
  test.setTimeout(120_000);
  // macOS permits some temporary roots independently; use a home-directory
  // fixture to detect the real external-profile sandbox regression. Windows
  // runs the same cache/restart oracle against its unchanged native directories.
  const orkas = new OrkasTestApp(testInfo, { rootParent: homedir() });
  let hits = 0;
  const server = createServer((req, res) => {
    if (req.url === '/asset') {
      hits++;
      res.setHeader('Cache-Control', 'public, max-age=3600');
      res.end('resource'.repeat(20_000));
      return;
    }
    res.setHeader('Cache-Control', 'no-store');
    if (req.url === '/sw.js') {
      res.setHeader('Content-Type', 'text/javascript');
      res.end('self.addEventListener("install", () => self.skipWaiting());');
      return;
    }
    res.setHeader('Content-Type', 'text/html');
    res.end('<title>Cache continuity</title><h1>Ready</h1>');
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    await orkas.launch();
    const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
    const created = await orkas.invoke<any>('conversations.create', { title: 'Cache continuity' });
    const open = async () => {
      expect(await orkas.invoke<any>('webAssist.open', { conversationId: created.conversation.conversation_id, url: origin })).toMatchObject({ ok: true });
      await expect.poll(async () => (await orkas.invoke<any>('webAssist.state')).state.loading).toBe(false);
    };
    const run = (script: string) => orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, code) => {
      const views = BrowserWindow.getAllWindows()[0].contentView.children.filter(v => v instanceof WebContentsView);
      return (views.at(-1) as InstanceType<typeof WebContentsView>).webContents.executeJavaScript(code);
    }, script);
    const native = (clear = false) => orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, clearCache) => {
      const views = BrowserWindow.getAllWindows()[0].contentView.children.filter(v => v instanceof WebContentsView);
      const ses = (views.at(-1) as InstanceType<typeof WebContentsView>).webContents.session;
      if (clearCache) await ses.clearCache();
      return { bytes: await ses.getCacheSize(), storagePath: ses.storagePath };
    }, clear);
    const fetchAsset = () => run("fetch('/asset').then(r => r.text()).then(s => s.length)");
    const readStores = ` (async () => {
      const db = await new Promise((resolve, reject) => { const q = indexedDB.open('retained', 1); q.onsuccess = () => resolve(q.result); q.onerror = () => reject(q.error); });
      const indexed = await new Promise((resolve, reject) => { const q = db.transaction('values').objectStore('values').get('key'); q.onsuccess = () => resolve(q.result); q.onerror = () => reject(q.error); });
      db.close();
      return { local: localStorage.getItem('key'), cookie: document.cookie, indexed,
        cache: await (await caches.match('/saved')).text(), worker: !!(await navigator.serviceWorker.getRegistration()) };
    })()`;
    await open();
    expect(await fetchAsset()).toBe(160_000);
    expect(await fetchAsset()).toBe(160_000);
    expect(hits).toBe(1);
    await expect.poll(async () => (await native()).bytes).toBeGreaterThan(160_000);
    const profile = path.join(orkas.workspaceRoot, 'account-e2e/local/web-assist/profile');
    expect(realpathSync((await native()).storagePath!)).toBe(realpathSync(profile));
    expect(lstatSync(path.join(profile, 'Cache')).isSymbolicLink()).toBe(process.platform === 'darwin');
    await run(`(async () => {
      localStorage.setItem('key', 'local'); sessionStorage.setItem('key', 'session'); document.cookie = 'retained=cookie; Max-Age=3600; Path=/';
      const db = await new Promise((resolve, reject) => { const q = indexedDB.open('retained', 1); q.onupgradeneeded = () => q.result.createObjectStore('values'); q.onsuccess = () => resolve(q.result); q.onerror = () => reject(q.error); });
      await new Promise((resolve, reject) => { const t = db.transaction('values', 'readwrite'); t.objectStore('values').put('indexed', 'key'); t.oncomplete = resolve; t.onerror = () => reject(t.error); }); db.close();
      await (await caches.open('retained')).put('/saved', new Response('website-cache'));
      await navigator.serviceWorker.register('/sw.js'); await navigator.serviceWorker.ready;
    })()`);
    const expected = { local: 'local', cookie: 'retained=cookie', indexed: 'indexed', cache: 'website-cache', worker: true };
    expect(await run(readStores)).toEqual(expected);
    for (const dir of ['Local Storage', 'Session Storage', 'IndexedDB', 'Service Worker']) expect(lstatSync(path.join(profile, dir)).isSymbolicLink()).toBe(false);
    await orkas.relaunch();
    await open();
    expect(await fetchAsset()).toBe(160_000);
    expect(hits).toBe(1);
    expect(await run(readStores)).toEqual(expected);
    // HTTP eviction must never include the website's CacheStorage or logins.
    await run("sessionStorage.setItem('key', 'new-session')");
    await native(true);
    expect(await run(readStores)).toEqual(expected);
    expect(await run("sessionStorage.getItem('key')")).toBe('new-session');
    expect(await fetchAsset()).toBe(160_000);
    expect(hits).toBe(2);
  } finally {
    await orkas.dispose();
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('website login survives app restart and website logout stays logged out', async ({ orkas }) => {
  test.setTimeout(120_000);
  const partitionedRequests: boolean[] = [];
  const server = createServer((req, res) => {
    res.setHeader('Cache-Control', 'no-store');
    res.setHeader('Content-Type', 'text/html');
    if (req.url === '/login') res.setHeader('Set-Cookie', [
      'login=fixture; HttpOnly; SameSite=Lax; Path=/',
      'partitioned=isolated; Secure; HttpOnly; SameSite=None; Partitioned; Path=/',
    ]);
    if (req.url === '/logout') res.setHeader('Set-Cookie', 'login=; Max-Age=0; HttpOnly; SameSite=Lax; Path=/');
    const signedIn = (req.headers.cookie || '').split('; ').includes('login=fixture');
    if (req.url === '/account') partitionedRequests.push((req.headers.cookie || '').includes('partitioned=isolated'));
    res.end(`<title>Login fixture</title><h1>${signedIn ? 'Signed in' : 'Signed out'}</h1>`);
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Browser login' });
    const cid = created.conversation.conversation_id;
    const open = async (pathname: string) => {
      const result = await orkas.invoke<any>('webAssist.open', { conversationId: cid, url: origin + pathname });
      expect(result.ok).toBe(true);
      await expect.poll(async () => (await orkas.invoke<any>('webAssist.state')).state.loading).toBe(false);
    };
    const text = () => orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
      const views = BrowserWindow.getAllWindows()[0].contentView.children.filter(v => v instanceof WebContentsView);
      const view = views[views.length - 1] as InstanceType<typeof WebContentsView>;
      return view.webContents.executeJavaScript('document.querySelector("h1").textContent');
    });
    await open('/login');
    await open('/account');
    expect(await text()).toBe('Signed in');
    expect(partitionedRequests.at(-1)).toBe(true);
    await orkas.relaunch();
    await open('/account');
    expect(await text()).toBe('Signed in');
    // Electron cannot round-trip CHIPS scope: never restore it as an ordinary cookie.
    expect(partitionedRequests.at(-1)).toBe(false);
    await open('/logout');
    await orkas.relaunch();
    await open('/account');
    expect(await text()).toBe('Signed out');
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

for (const location of ['temporary', 'home'] as const) {
  test(`persistent website login remains usable after a full app restart (${location})`, async ({}, testInfo) => {
    test.setTimeout(90_000);
    const orkas = new OrkasTestApp(testInfo, { rootParent: location === 'home' ? homedir() : tmpdir() });
    let cacheRequests = 0;
    const server = createServer((req, res) => {
      if (req.url === '/cache-evidence') {
        cacheRequests++;
        res.writeHead(200, { 'Cache-Control': 'public, max-age=3600', 'Content-Type': 'text/plain' });
        res.end('cache-evidence'.repeat(1024));
        return;
      }
      res.setHeader('Cache-Control', 'no-store');
      res.setHeader('Content-Type', 'text/html');
      if (req.url === '/login') res.setHeader('Set-Cookie', 'persistent-login=fixture; Max-Age=3600; HttpOnly; SameSite=Lax; Path=/');
      const signedIn = (req.headers.cookie || '').split('; ').includes('persistent-login=fixture');
      res.end(`<title>Persistent login fixture</title><h1>${signedIn ? 'Signed in' : 'Signed out'}</h1>`);
    });
    await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
    try {
      await orkas.launch();
      const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
      const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Persistent browser login' });
      const cid = created.conversation.conversation_id;
      const open = async (pathname: string) => {
        const result = await orkas.invoke<any>('webAssist.open', { conversationId: cid, url: origin + pathname });
        expect(result.ok).toBe(true);
        await expect.poll(async () => (await orkas.invoke<any>('webAssist.state')).state.loading).toBe(false);
      };
      const text = () => orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
        const views = BrowserWindow.getAllWindows()[0].contentView.children.filter(v => v instanceof WebContentsView);
        const view = views[views.length - 1] as InstanceType<typeof WebContentsView>;
        return view.webContents.executeJavaScript('document.querySelector("h1").textContent');
      });
      // Native cache failures must be tied to this session, not merely tolerated
      // because the separate encrypted login checkpoint restored successfully.
      const nativeStderr: string[] = [];
      const captureNativeStderr = () => orkas.electronApp!.process().stderr?.on('data', chunk => nativeStderr.push(String(chunk)));
      captureNativeStderr();
      const profile = path.join(orkas.workspaceRoot, 'account-e2e', 'local', 'web-assist', 'profile');
      const sessionEvidence = () => orkas.electronApp!.evaluate(async ({ app, session }, args) => {
        const require = (process as any).mainModule.require.bind((process as any).mainModule);
        const fs = require('node:fs');
        const ses = session.fromPath(args.profile, { cache: true });
        await require(args.sessionModule).flushWebAssistSessions();
        let cache: { size: number } | { error: string };
        try { cache = { size: await ses.getCacheSize() }; }
        catch (error) {
          if ((error as Error).message !== 'net::ERR_FAILED') throw error;
          cache = { error: (error as Error).message };
        }
        return {
          cache, sessionData: app.getPath('sessionData'), storagePath: ses.storagePath,
          sandboxDisabled: app.commandLine.hasSwitch('no-sandbox'),
          cacheDisabled: app.commandLine.hasSwitch('disable-http-cache'),
          nativeCookies: ['Cookies', 'Network/Cookies'].some(name => fs.existsSync(require('node:path').join(args.profile, name))),
          checkpoint: fs.readFileSync(require('node:path').join(args.profile, '..', 'session-cookies.enc'), 'utf8'),
        };
      }, { profile, sessionModule: path.resolve(__dirname, '../../src/main/features/web_assist_session.ts') });
      await open('/login');
      await open('/account');
      expect(await text()).toBe('Signed in');
      if (location === 'home') {
        await orkas.electronApp!.evaluate(async ({ session }, args) => {
          const ses = session.fromPath(args.profile, { cache: true });
          for (let attempt = 0; attempt < 2; attempt++) {
            const response = await ses.fetch(args.url);
            if (!response.ok) throw new Error(`Cache fixture HTTP ${response.status}`);
            await response.text();
          }
        }, { profile, url: origin + '/cache-evidence' });
      }
      const before = location === 'home' ? await sessionEvidence() : undefined;
      if (before) {
        expect(before.storagePath).toBe(profile);
        expect(before.sandboxDisabled).toBe(false);
        expect(before.cacheDisabled).toBe(false);
        expect(path.relative(before.sessionData, profile).startsWith('..')).toBe(true);
        expect(before.checkpoint.length).toBeGreaterThan(0);
        expect(before.checkpoint).not.toContain('persistent-login');
        expect(before.checkpoint).not.toContain('fixture');
        if ('error' in before.cache) {
          expect(process.platform).toBe('darwin');
          expect(before.nativeCookies).toBe(false);
          expect(cacheRequests).toBe(2);
          await expect.poll(() => nativeStderr.join('')).toContain(`path: ${profile}/Cache/Cache_Data`);
          expect(nativeStderr.join('')).toContain(`Failed to create directory: ${profile}/Shared Dictionary/cache`);
          expect(nativeStderr.join('')).toContain('Unable to create cache');
        } else {
          expect(before.cache.size).toBeGreaterThan(0);
          expect(cacheRequests).toBe(1);
          expect(nativeStderr.join('')).not.toContain('Unable to create cache');
        }
      }
      await orkas.relaunch();
      captureNativeStderr();
      await open('/account');
      expect(await text()).toBe('Signed in');
      if (before) {
        const after = await sessionEvidence();
        expect(after.sessionData).toBe(before.sessionData);
        expect(after.storagePath).toBe(before.storagePath);
        expect(after.sandboxDisabled).toBe(false);
        expect(after.cacheDisabled).toBe(false);
        expect(after.checkpoint).not.toContain('persistent-login');
        if ('error' in before.cache) {
          expect(after.cache).toEqual({ error: 'net::ERR_FAILED' });
          expect(after.nativeCookies).toBe(false);
        }
        await testInfo.attach('browser-session-cache-evidence', {
          body: JSON.stringify({ before: { ...before, checkpoint: '[encrypted]' }, after: { ...after, checkpoint: '[encrypted]' }, cacheRequests, nativeStderr }),
          contentType: 'application/json',
        });
      }
    } finally {
      await orkas.dispose();
      server.closeAllConnections();
      await new Promise<void>(resolve => server.close(() => resolve()));
    }
  });
}

test('task browser routes pages, resources and popup login through its launch proxy and bypasses local services', async ({ orkas }) => {
  const proxied: string[] = [];
  let directLoads = 0;
  let leakedAuthorization = false;
  const proxy = createServer((req, res) => {
    if (req.headers['proxy-authorization'] !== `Basic ${Buffer.from('fixture:proxy-password').toString('base64')}`) {
      res.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="browser-fixture"' });
      res.end();
      return;
    }
    const pathname = new URL(req.url!).pathname;
    proxied.push(pathname);
    res.setHeader('Cache-Control', 'no-store');
    if (pathname === '/asset.js') {
      res.setHeader('Content-Type', 'text/javascript');
      res.end('document.title = "Proxy page ready";');
    } else {
      res.setHeader('Content-Type', 'text/html');
      res.end(pathname === '/start'
        ? '<title>Loading</title><script src="/asset.js"></script><iframe src="/frame"></iframe>'
        : `<title>Proxy ${pathname}</title><h1>Loaded via proxy</h1>`);
    }
  });
  const direct = createServer((req, res) => {
    directLoads++;
    leakedAuthorization ||= !!req.headers['proxy-authorization'] || !!req.headers.authorization;
    res.end('<title>Local service ready</title>');
  });
  await Promise.all([proxy, direct].map(server => new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))));
  try {
    const proxyPort = (proxy.address() as { port: number }).port;
    const directUrl = `http://127.0.0.1:${(direct.address() as { port: number }).port}/bypass`;
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Browser proxy' });
    const cid = created.conversation.conversation_id;
    await orkas.page!.evaluate(async id => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', id);
    }, cid);
    const opened = await orkas.electronApp!.evaluate(async ({ BrowserWindow }, args) => {
      process.env.HTTP_PROXY = `http://fixture:[email protected]:${args.proxyPort}`;
      process.env.HTTPS_PROXY = process.env.HTTP_PROXY;
      process.env.NO_PROXY = 'localhost,127.0.0.1,::1,internal.test:8443';
      const web = (process as any).mainModule.require(args.modulePath);
      const sender = BrowserWindow.getAllWindows()[0].webContents;
      web.bindWebAssistConversation('account-e2e', args.cid, sender);
      return web.openWebAssist('account-e2e', sender, { conversationId: args.cid, url: 'http://browser-proxy.invalid/start' });
    }, { cid, proxyPort, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(opened.ok).toBe(true);
    const parentId = await orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => {
      const parent = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      return parent.webContents.id;
    });
    const title = () => orkas.electronApp!.evaluate(({ webContents }, id) => webContents.fromId(id)?.getTitle(), parentId);
    await expect.poll(title).toBe('Proxy page ready');
    await expect.poll(() => proxied.includes('/frame')).toBe(true);
    const routes = await orkas.electronApp!.evaluate(async ({ webContents }, id) => {
      const ses = webContents.fromId(id)!.session;
      return Promise.all(['https://accounts.google.com/', 'http://sub.internal.test:8443/', 'http://sub.internal.test:8080/'].map(url => ses.resolveProxy(url)));
    }, parentId);
    expect(routes).toEqual([`PROXY 127.0.0.1:${proxyPort}`, 'DIRECT', `PROXY 127.0.0.1:${proxyPort}`]);
    for (const [pathname, features] of [['/tab', ''], ['/popup', 'width=480,height=600']]) {
      await orkas.electronApp!.evaluate(async ({ webContents }, args) => {
        await webContents.fromId(args.parentId)!.executeJavaScript(`window.open(${JSON.stringify(args.pathname)}, '_blank', ${JSON.stringify(args.features)}); void 0`, true);
      }, { parentId, pathname, features });
      await expect.poll(() => proxied.includes(pathname)).toBe(true);
      await expect.poll(async () => orkas.electronApp!.evaluate(({ webContents }, expected) => (
        webContents.getAllWebContents().some(page => page.getTitle() === `Proxy ${expected}`)
      ), pathname)).toBe(true);
    }
    expect(proxied).toEqual(expect.arrayContaining(['/start', '/asset.js', '/frame', '/tab', '/popup']));
    await orkas.invoke('webAssist.navigateTo', { tabId: opened.state.active_tab_id, url: directUrl });
    await expect.poll(title).toBe('Local service ready');
    expect(directLoads).toBeGreaterThan(0);
    expect(leakedAuthorization).toBe(false);
    expect(proxied).not.toContain('/bypass');
    proxy.closeAllConnections();
    await new Promise<void>(resolve => proxy.close(() => resolve()));
    await orkas.invoke('webAssist.navigateTo', { tabId: opened.state.active_tab_id, url: 'http://browser-proxy.invalid/unavailable' });
    await expect.poll(async () => (await orkas.invoke<{ state: { tabs: Array<{ tab_id: string; error_code?: string }> } }>('webAssist.state', {})).state.tabs.find(tab => tab.tab_id === opened.state.active_tab_id)?.error_code).toBe('page_load_failed');
    expect(proxied).not.toContain('/unavailable');
  } finally {
    await orkas.invoke('webAssist.close', {});
    await orkas.electronApp!.evaluate(() => {
      delete process.env.HTTP_PROXY;
      delete process.env.HTTPS_PROXY;
    });
    for (const server of [proxy, direct]) {
      server.closeAllConnections();
      if (server.listening) await new Promise<void>(resolve => server.close(() => resolve()));
    }
  }
});

test('task browser blocks requests when proxy setup fails instead of using a reachable direct route', async ({ orkas }) => {
  let received = 0;
  const server = createServer((_req, res) => { received++; res.end('<title>Unexpected direct request</title>'); });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/must-not-leak`;
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Proxy failure' });
    const opened = await orkas.electronApp!.evaluate(async ({ BrowserWindow, session }, args) => {
      const require = (process as any).mainModule.require.bind((process as any).mainModule);
      const paths = require(args.pathsModule);
      const dir = paths.userWebAssistProfileDir('account-e2e');
      // Fault injection must preserve the production prepare-before-session
      // boundary, otherwise this fixture races native cache initialization.
      await require(args.cacheModule).prepareWebAssistCache('account-e2e');
      require('node:fs').mkdirSync(dir, { recursive: true });
      const ses = session.fromPath(dir, { cache: true });
      // Fault injection: Chromium cannot apply the requested proxy. No request may escape on its old route.
      ses.setProxy = async () => { throw new Error('Fixture proxy setup failure'); };
      process.env.HTTP_PROXY = 'http://127.0.0.1:8080';
      const web = require(args.webModule);
      return web.openWebAssist('account-e2e', BrowserWindow.getAllWindows()[0].webContents, { conversationId: args.cid, url: args.url });
    }, {
      cid: created.conversation.conversation_id, url,
      pathsModule: path.resolve(__dirname, '../../src/main/paths.ts'),
      cacheModule: path.resolve(__dirname, '../../src/main/features/web_assist_cache.ts'),
      webModule: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
    });
    expect(opened.ok).toBe(true);
    await expect.poll(async () => (await orkas.invoke<{ state: { error_code?: string } }>('webAssist.state', {})).state.error_code).toBe('page_load_failed');
    expect(received).toBe(0);
  } finally {
    await orkas.invoke('webAssist.close', {});
    await orkas.electronApp!.evaluate(() => { delete process.env.HTTP_PROXY; });
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('idle task pages release native contents and lazily restore cookies, storage and identity', async ({ orkas }) => {
  let loads = 0;
  const server = createServer((req, res) => {
    if (req.url?.startsWith('/work')) loads++;
    res.setHeader('Cache-Control', 'no-store');
    res.setHeader('Content-Type', 'text/html');
    res.end('<title>Idle workspace</title><h1>Resume work</h1><input id="draft" aria-label="Draft">');
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/work?item=7`;
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Idle browser' });
    const cid = created.conversation.conversation_id;
    await orkas.page!.evaluate(async id => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', id);
    }, cid);
    const input = { cid, url, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') };
    const opened = await orkas.electronApp!.evaluate(async ({ BrowserWindow }, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      web.bindWebAssistConversation('account-e2e', args.cid, BrowserWindow.getAllWindows()[0].webContents);
      return web.openModelWebAssist('account-e2e', args.cid, { url: args.url });
    }, input);
    expect(opened.ok).toBe(true);
    const inventory = () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      const owner = BrowserWindow.getAllWindows()[0];
      return { ...web.listModelWebAssistTabs('account-e2e', args.cid), nativeCount: owner.contentView.children.filter(v => v instanceof WebContentsView).length };
    }, input);
    await expect.poll(async () => (await inventory()).tabs[0]?.loading).toBe(false);
    const nativeId = await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, args) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      await view.webContents.executeJavaScript("localStorage.setItem('fixture', 'retained'); document.cookie = 'fixture=retained; SameSite=Lax';");
      return view.webContents.id;
    }, input);
    const observe = () => orkas.electronApp!.evaluate(async (_electron, args) => {
      return (process as any).mainModule.require(args.modulePath).observeModelWebAssist('account-e2e', args.cid, args.tabId);
    }, { ...input, tabId: opened.active_tab_id });
    const before = await observe();
    expect(before.ok).toBe(true);
    // Switching to Attachments must not cause state events to wake the browser.
    await orkas.page!.evaluate(() => (window as any).ConversationInfo.openAndSetTab('attachments'));
    const reclaim = () => orkas.electronApp!.evaluate(async ({ BrowserWindow }, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      const owner = BrowserWindow.getAllWindows()[0];
      web.layoutWebAssist(owner.webContents, { visible: false });
      await web.reclaimIdleWebAssistPages(Date.now() + 600_000, owner.id);
    }, input);
    await reclaim();
    await expect.poll(async () => (await inventory()).nativeCount).toBe(0);
    expect((await inventory()).tabs).toMatchObject([{ tab_id: opened.active_tab_id, suspended: true }]);
    await inventory();
    expect(loads).toBe(1);
    const destroyed = await orkas.electronApp!.evaluate(({ webContents }, id) => !webContents.fromId(id), nativeId);
    expect(destroyed).toBe(true);
    // Actual model access recreates contents while leaving the user's chosen panel alone.
    await observe();
    await expect.poll(async () => (await inventory()).tabs[0]?.loading).toBe(false);
    const after = await observe();
    const hiddenLayout = await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
      const v = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      return { visible: v.getVisible(), width: await v.webContents.executeJavaScript('innerWidth') };
    });
    expect(hiddenLayout.visible).toBe(false);
    expect(hiddenLayout.width).toBeGreaterThan(0);
    expect(after).toMatchObject({ ok: true, tab_id: opened.active_tab_id });
    expect(after.text).toContain('Resume work');
    expect(after.page_id).not.toBe(before.page_id);
    expect(loads).toBe(2);
    const restored = await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      return { id: view.webContents.id, url: view.webContents.getURL(), values: await view.webContents.executeJavaScript("({ local: localStorage.getItem('fixture'), cookie: document.cookie })") };
    });
    expect(restored.id).not.toBe(nativeId);
    expect(restored.url).toBe(url);
    expect(restored.values).toEqual({ local: 'retained', cookie: 'fixture=retained' });
    // Script-driven form editing must also protect unsaved work, without keyboard events.
    await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      await view.webContents.executeJavaScript("document.querySelector('#draft').value = 'private unsaved draft'");
    });
    await reclaim();
    expect((await inventory()).nativeCount).toBe(1);
    expect(loads).toBe(2);
    await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      await view.webContents.executeJavaScript("document.querySelector('#draft').value = ''");
    });
    // Tab-scoped storage cannot be copied into recovery records; retain it instead.
    await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      await view.webContents.executeJavaScript("sessionStorage.setItem('transient', 'fixture')");
    });
    await reclaim();
    expect((await inventory()).nativeCount).toBe(1);
    await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      await view.webContents.executeJavaScript('sessionStorage.clear()');
    });
    await reclaim();
    await expect.poll(async () => (await inventory()).nativeCount).toBe(0);
    await orkas.page!.evaluate(() => (window as any).ConversationInfo.openAndSetTab('browser'));
    await expect.poll(async () => (await inventory()).nativeCount).toBe(1);
    await expect.poll(() => loads).toBe(3);
    await expect(orkas.page!.locator('.web-assist-tab.is-suspended')).toHaveCount(0);
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('task browser opens ordinary pages as tabs while preserving web navigation semantics', async ({ orkas }) => {
  const requests: Array<{ path: string; method: string; body: string; ua: string }> = [];
  const server = createServer((req, res) => {
    let body = '';
    req.on('data', chunk => { body += chunk; });
    req.on('end', () => {
      requests.push({ path: req.url!, method: req.method!, body, ua: req.headers['user-agent'] || '' });
      res.setHeader('Content-Type', 'text/html');
      if (req.url !== '/') {
        res.end('<title>Business page</title><h1>Account balance</h1>');
        return;
      }
      res.end(`<!doctype html><title>Shop console</title>
        <a id="ordinary" href="/balance" target="_blank">View balance</a>
        <form action="/statement" method="post" target="_blank"><input name="period" value="month"><button id="submit">Statement</button></form>
        <button id="named" onclick="window.child = window.open('', 'business-detail'); child.document.write('<title>Draft</title><h1>Draft</h1>');">Named page</button>
        <button id="no-popup" onclick="window.open('/no-popup', '_blank', 'popup=no,width=480,height=620')">No popup</button>`);
    });
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address() as { port: number };
    const url = `http://127.0.0.1:${address.port}/`;
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Browser navigation' });
    const cid = created.conversation.conversation_id;
    await orkas.page!.evaluate(async id => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', id);
    }, cid);
    const input = { cid, url, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') };
    const opened = await orkas.electronApp!.evaluate(async ({ BrowserWindow }, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      const owner = BrowserWindow.getAllWindows()[0];
      web.bindWebAssistConversation('account-e2e', args.cid, owner.webContents);
      return web.openModelWebAssist('account-e2e', args.cid, { url: args.url });
    }, input);
    expect(opened.ok).toBe(true);
    const inventory = () => orkas.electronApp!.evaluate(({ BrowserWindow }, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return { ...web.listModelWebAssistTabs('account-e2e', args.cid), windows: BrowserWindow.getAllWindows().length };
    }, input);
    const click = (selector: string, middle = false) => orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, args) => {
      const parent = BrowserWindow.getAllWindows().find(win => !win.getParentWindow())!.contentView.children
        .find(view => view instanceof WebContentsView && view.webContents.getURL() === args.url) as InstanceType<typeof WebContentsView>;
      if (args.middle) {
        // Native input requires a focused owner; the shared E2E window starts
        // hidden and unfocusable. DOM .click() above does not have that prerequisite.
        const owner = BrowserWindow.getAllWindows().find(win => !win.getParentWindow())!;
        owner.setFocusable(true);
        owner.show();
        owner.focus();
        parent.webContents.focus();
        const geometry = await parent.webContents.executeJavaScript(`(() => { const r = document.querySelector(${JSON.stringify(args.selector)}).getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2, width: innerWidth }; })()`);
        // Desktop emulation scales CSS coordinates into the narrow native view.
        // Sending the unscaled point clicks empty space instead of the anchor.
        const scale = parent.getBounds().width / geometry.width;
        const point = { x: Math.round(geometry.x * scale), y: Math.round(geometry.y * scale) };
        parent.webContents.sendInputEvent({ type: 'mouseDown', ...point, button: 'middle', clickCount: 1 });
        parent.webContents.sendInputEvent({ type: 'mouseUp', ...point, button: 'middle', clickCount: 1 });
      } else {
        await parent.webContents.executeJavaScript(`document.querySelector(${JSON.stringify(args.selector)}).click()`, true);
      }
    }, { url, selector, middle });
    await expect.poll(async () => (await inventory()).tabs[0]?.page_title).toBe('Shop console');
    await click('#ordinary');
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(2);
    const state = await inventory();
    expect(state.windows).toBe(1);
    const business = state.tabs.find((tab: any) => tab.tab_id !== opened.active_tab_id);
    await expect.poll(async () => (await inventory()).tabs.find((tab: any) => tab.tab_id === business.tab_id)?.display_url).toBe(url + 'balance');
    expect(state.active_tab_id).toBe(business.tab_id);
    // Renderer selection and actual native content must agree, not just the tool result.
    await expect(orkas.page!.locator('.web-assist-tab.is-active')).toContainText('Business page');
    const observed = await orkas.electronApp!.evaluate(async (_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return web.observeModelWebAssist('account-e2e', args.cid, args.tabId);
    }, { ...input, tabId: business.tab_id });
    expect(observed.text).toContain('Account balance');
    await click('#submit');
    await expect.poll(() => requests.find(request => request.path === '/statement')).toMatchObject({ method: 'POST', body: 'period=month' });
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(3);
    await click('#named');
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(4);
    await expect.poll(async () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => {
      const draft = BrowserWindow.getAllWindows()[0].contentView.children
        .find(view => view instanceof WebContentsView && view.webContents.getTitle() === 'Draft');
      return draft?.getVisible();
    })).toBe(true);
    await expect(orkas.page!.locator('.web-assist-external-btn')).toBeDisabled();
    const named = await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, args) => {
      const owner = BrowserWindow.getAllWindows()[0];
      const parent = owner.contentView.children.find(view => view instanceof WebContentsView && view.webContents.getURL() === args.url) as InstanceType<typeof WebContentsView>;
      return parent.webContents.executeJavaScript(`(() => { const same = window.open('', 'business-detail') === child; const connected = child.opener === window; const childUa = child.navigator.userAgent; child.location.href = '/named'; return { same, connected, ua: navigator.userAgent, childUa }; })()`, true);
    }, input);
    expect(named).toMatchObject({ same: true, connected: true });
    expect(named.ua).toMatch(/Chrome\//);
    expect(named.ua).toMatch(/Electron\//);
    expect(named.ua).toBe(requests.find(request => request.path === '/balance')!.ua);
    // UA is diagnostic evidence, not a fingerprint policy. The native default
    // is intentionally retained so its brand and missing client hints agree.
    console.log('[web-assist UA]', {
      page: named.ua, initialChild: named.childUa,
      firstRequest: requests.find(request => request.path === '/balance')!.ua,
    });
    await click('#no-popup');
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(5);
    expect((await inventory()).windows).toBe(1);
    // Switch to the opener and middle-click a real anchor. Background opening
    // must keep that selected page, while adding an independently usable tab.
    await orkas.invoke('webAssist.activateTab', { tabId: opened.active_tab_id });
    await expect(orkas.page!.locator('.web-assist-tab.is-active')).toContainText('Shop console');
    await click('#ordinary', true);
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(6);
    expect((await inventory()).active_tab_id).toBe(opened.active_tab_id);
    await expect(orkas.page!.locator('.web-assist-tab.is-active')).toContainText('Shop console');
    await orkas.invoke('webAssist.closeTab', { tabId: opened.active_tab_id });
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(5);
    expect((await inventory()).windows).toBe(1);
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('task completion only closes explicitly temporary native tabs and resumes an unmarked login', async ({ modelOrkas: orkas }) => {
  const server = createServer((_req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.end('<title>Lifecycle page</title><h1>Browser lifecycle</h1><input aria-label="Draft">');
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address() as { port: number };
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Tab lifecycle' });
    const cid = created.conversation.conversation_id;
    const page = orkas.page!;
    await page.evaluate(async taskId => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', taskId);
    }, cid);
    // Exercise the real native-view disposal/renderer push path with no live model.
    // Bus integration independently proves which production terminal invokes it.
    const input = {
      cid, url: `http://127.0.0.1:${address.port}/`,
      webPath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
      lifecyclePath: path.resolve(__dirname, '../../src/main/features/web_assist_lifecycle.ts'),
    };
    const initial = await orkas.electronApp!.evaluate(async ({ BrowserWindow }, args) => {
      const web = (process as any).mainModule.require(args.webPath);
      const lifecycle = (process as any).mainModule.require(args.lifecyclePath);
      const sender = BrowserWindow.getAllWindows()[0].webContents;
      web.bindWebAssistConversation('account-e2e', args.cid, sender);
      lifecycle.beginBrowserTaskRun('account-e2e', args.cid, 'e2e-first');
      await web.openWebAssist('account-e2e', sender, { conversationId: args.cid, url: args.url + 'user' });
      const temporary = await web.openModelWebAssist('account-e2e', args.cid, { url: args.url + 'temporary', retention: 'temporary' });
      const deliverable = await web.openModelWebAssist('account-e2e', args.cid, { url: args.url + 'deliverable', retention: 'deliverable' });
      const handoff = await web.openModelWebAssist('account-e2e', args.cid, { url: args.url + 'explicit-handoff', retention: 'handoff' });
      const takeover = await web.openModelWebAssist('account-e2e', args.cid, { url: args.url + 'takeover', retention: 'temporary' });
      const login = await web.openControlledWebAssist('account-e2e', args.cid, {
        scope: 'connector_setup', scopeId: 'fixture-shop', url: args.url + 'handoff',
      });
      return { temporary, deliverable, handoff, takeover, login, state: web.webAssistState(sender) };
    }, input);
    expect(initial.temporary).toMatchObject({ ok: true, tab: { retention: 'temporary' } });
    expect(initial.deliverable).toMatchObject({ ok: true, tab: { retention: 'deliverable' } });
    expect(initial.handoff).toMatchObject({ ok: true, tab: { retention: 'handoff' } });
    expect(initial.login.ok).toBe(true);
    await expect(page.locator('.web-assist-tab')).toHaveCount(6);
    const nativePaths = () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => (
      BrowserWindow.getAllWindows()[0].contentView.children
        .filter(view => view instanceof WebContentsView)
        .map(view => view.webContents.getURL())
        .map(url => url ? new URL(url).pathname : '').sort()
    ));
    await expect.poll(nativePaths).toEqual(['/deliverable', '/explicit-handoff', '/handoff', '/takeover', '/temporary', '/user']);
    await orkas.invoke('webAssist.activateTab', { tabId: initial.takeover.active_tab_id });
    const draft = () => orkas.electronApp!.evaluate(async ({ webContents }, url) => (
      webContents.getAllWebContents().find(contents => contents.getURL() === url)!
        .executeJavaScript('document.querySelector("input").value')
    ), input.url + 'takeover');
    // Native user input uses the production takeover lease, without an
    // assistant-input marker or a synthetic retention mutation.
    await orkas.electronApp!.evaluate(async ({ BrowserWindow, webContents }, url) => {
      const owner = BrowserWindow.getAllWindows()[0];
      owner.setFocusable(true); owner.show(); owner.focus();
      const contents = webContents.getAllWebContents().find(contents => contents.getURL() === url)!;
      contents.focus();
      await contents.executeJavaScript('document.querySelector("input").focus()');
      contents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
      contents.sendInputEvent({ type: 'char', keyCode: 'A' });
      contents.sendInputEvent({ type: 'keyUp', keyCode: 'A' });
    }, input.url + 'takeover');
    await expect.poll(draft).toBe('A');
    await expect.poll(async () => (await orkas.invoke<any>('webAssist.state')).state.tabs
      .find((tab: any) => tab.tab_id === initial.takeover.active_tab_id)?.retention).toBe('handoff');
    await orkas.electronApp!.evaluate((_electron, args) => {
      (process as any).mainModule.require(args.lifecyclePath).finishBrowserTaskRun('account-e2e', args.cid, 'e2e-first');
    }, input);
    await expect(page.locator('.web-assist-tab')).toHaveCount(5);
    await expect.poll(nativePaths).toEqual(['/deliverable', '/explicit-handoff', '/handoff', '/takeover', '/user']);
    expect(await draft()).toBe('A');
    const resumed = await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, args) => {
      const lifecycle = (process as any).mainModule.require(args.lifecyclePath);
      const web = (process as any).mainModule.require(args.webPath);
      // Stand in for the user's login navigation, without a retain call.
      const login = BrowserWindow.getAllWindows()[0].contentView.children
        .find(view => view instanceof WebContentsView && view.webContents.getURL() === args.url + 'handoff') as InstanceType<typeof WebContentsView>;
      await login.webContents.loadURL(args.url + 'applications');
      lifecycle.beginBrowserTaskRun('account-e2e', args.cid, 'e2e-second');
      const loaded = await web.waitForControlledWebAssist('account-e2e', args.cid, 'fixture-shop', { condition: 'loaded' });
      if (!loaded.ok) throw new Error(JSON.stringify(loaded));
      const observed = await web.observeControlledWebAssist('account-e2e', args.cid, 'fixture-shop');
      lifecycle.finishBrowserTaskRun('account-e2e', args.cid, 'e2e-second');
      return observed;
    }, input);
    expect(resumed, JSON.stringify(resumed)).toMatchObject({ ok: true, tab_id: initial.login.state.active_tab_id, display_url: input.url + 'applications' });
    await expect(page.locator('.web-assist-tab')).toHaveCount(5);
    await expect.poll(nativePaths).toEqual(['/applications', '/deliverable', '/explicit-handoff', '/takeover', '/user']);
    const closed = await orkas.electronApp!.evaluate((_electron, args) => {
      return (process as any).mainModule.require(args.webPath)
        .closeModelWebAssistTab('account-e2e', args.cid, args.tabId);
    }, { ...input, tabId: resumed.tab_id });
    expect(closed.ok).toBe(true);
    await expect(page.locator('.web-assist-tab')).toHaveCount(4);
    await expect.poll(nativePaths).toEqual(['/deliverable', '/explicit-handoff', '/takeover', '/user']);
    await orkas.invoke('webAssist.close', {});
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('model last-page closure hides only its task browser while user closure keeps the browser available', async ({}, testInfo) => {
  const orkas = new OrkasTestApp(testInfo, { softwareRendering: true });
  const server = createServer((_req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.end('<title>Close lifecycle</title><h1>Ready</h1>');
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    await orkas.launch();
    const page = orkas.page!;
    const a = (await orkas.invoke<any>('conversations.create', { title: 'Browser close owner' })).conversation.conversation_id;
    const b = (await orkas.invoke<any>('conversations.create', { title: 'Other browser task' })).conversation.conversation_id;
    await page.evaluate(async () => (window as any).loadConversations());
    const select = async (cid: string) => {
      await page.evaluate(id => (window as any).setView('conversation', id), cid);
      await orkas.invoke('webAssist.setContext', { conversationId: cid });
    };
    const input = {
      webPath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
      lifecyclePath: path.resolve(__dirname, '../../src/main/features/web_assist_lifecycle.ts'),
      url: `http://127.0.0.1:${(server.address() as { port: number }).port}/`,
    };
    const open = async (cid: string) => {
      const result = await orkas.electronApp!.evaluate(async ({ BrowserWindow }, args) => {
        const web = (process as any).mainModule.require(args.webPath);
        web.bindWebAssistConversation('account-e2e', args.cid, BrowserWindow.getAllWindows()[0].webContents);
        return web.openModelWebAssist('account-e2e', args.cid, { url: args.url });
      }, { ...input, cid });
      expect(result.ok).toBe(true);
      return String(result.active_tab_id);
    };
    const close = async (cid: string, tabId: string) => {
      const result = await orkas.electronApp!.evaluate((_electron, args) => (
        (process as any).mainModule.require(args.webPath).closeModelWebAssistTab('account-e2e', args.cid, args.tabId)
      ), { ...input, cid, tabId });
      expect(result.ok).toBe(true);
    };
    const details = page.locator('#conversation-info-panel');
    await select(a);
    const first = await open(a);
    const last = await open(a);
    await expect(details).toBeVisible();
    await expect(page.locator('.web-assist-tab')).toHaveCount(2);
    await close(a, first);
    await expect(page.locator('.web-assist-tab')).toHaveCount(1);
    await expect(details).toBeVisible();
    await page.locator('[data-act="expand"]').click();
    await expect(details).toHaveClass(/is-web-assist-expanded/);
    await close(a, last);
    await expect(details).toBeHidden();
    await expect(details).not.toHaveClass(/is-web-assist-expanded/);
    expect((await orkas.invoke<any>('webAssist.state')).state.tabs).toHaveLength(0);

    // Automatic dismissal permits later model work to reveal again in this turn.
    await open(a);
    await expect(details).toBeVisible();
    await page.locator('.web-assist-tab-close').click();
    await expect(details).toBeVisible();
    await expect(page.locator('.web-assist-tab')).toHaveCount(1);
    await expect(page.locator('.web-assist-empty')).toBeVisible();
    expect((await orkas.invoke<any>('webAssist.state')).state.tabs[0].created_by).toBe('user');
    await orkas.invoke('webAssist.close', {});
    await expect(page.locator('.web-assist-tab')).toHaveCount(0);
    await expect(details).toBeVisible();

    const temporary = await open(a);
    await orkas.electronApp!.evaluate((_electron, args) => {
      const lifecycle = (process as any).mainModule.require(args.lifecyclePath);
      const web = (process as any).mainModule.require(args.webPath);
      lifecycle.beginBrowserTaskRun('account-e2e', args.cid, 'e2e-auto-dismiss');
      const marked = web.retainModelWebAssistTab('account-e2e', args.cid, args.tabId, 'temporary');
      if (!marked.ok) throw new Error('temporary page setup failed');
      lifecycle.finishBrowserTaskRun('account-e2e', args.cid, 'e2e-auto-dismiss');
    }, { ...input, cid: a, tabId: temporary });
    await expect(details).toBeHidden();

    const background = await open(a);
    await expect(details).toBeVisible();
    await select(b);
    await open(b);
    await expect(details).toBeVisible();
    await close(a, background);
    await expect(details).toBeVisible();
    await expect(page.locator('.web-assist-tab')).toHaveCount(1);
    await select(a);
    await expect(details).toBeHidden();
    // A model close must not dismiss the Files tab the user chose instead.
    const checking = await open(a);
    await expect(details).toBeVisible();
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('files'));
    await close(a, checking);
    await expect(details).toBeVisible();
    await expect(details.locator('[data-info-tab="files"]')).toHaveClass(/is-active/);
  } finally {
    await orkas.dispose();
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('task browser caps its visible strip at thirty while keeping user and connector handoff pages', async ({ orkas }) => {
  const server = createServer((_req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.end('<title>Capacity fixture</title><h1>Ready</h1>');
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const { port } = server.address() as { port: number };
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Browser capacity' });
    const cid = created.conversation.conversation_id;
    await orkas.page!.evaluate(async taskId => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', taskId);
    }, cid);
    const result = await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, args) => {
      const web = (process as any).mainModule.require(args.webPath);
      const owner = BrowserWindow.getAllWindows()[0];
      web.bindWebAssistConversation('account-e2e', args.cid, owner.webContents);
      await web.openWebAssist('account-e2e', owner.webContents, { conversationId: args.cid, url: args.url + 'user' });
      const login = await web.openControlledWebAssist('account-e2e', args.cid, {
        scope: 'connector_setup', scopeId: 'fixture-shop', url: args.url + 'login',
      });
      await web.waitForControlledWebAssist('account-e2e', args.cid, 'fixture-shop', { condition: 'loaded' });
      const results: any[] = [];
      for (let index = 0; index < 29; index++) {
        const opened = await web.openModelWebAssist('account-e2e', args.cid, { url: args.url + index });
        if (!opened.ok) throw new Error(JSON.stringify(opened));
        const loaded = await web.waitForModelWebAssist('account-e2e', args.cid, { tabId: opened.active_tab_id, condition: 'loaded' });
        if (!loaded.ok) throw new Error(JSON.stringify(loaded));
        results.push(opened);
      }
      return {
        login, results, tabs: web.listModelWebAssistTabs('account-e2e', args.cid),
        paths: owner.contentView.children.filter(view => view instanceof WebContentsView)
          .map(view => new URL(view.webContents.getURL()).pathname).sort(),
      };
    }, { cid, url: `http://127.0.0.1:${port}/`, webPath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(result.login.ok).toBe(true);
    expect(result.tabs.tab_limit).toBe(30);
    expect(result.tabs.tabs).toHaveLength(30);
    expect(result.results[28].closed_tab_ids).toEqual([result.results[0].active_tab_id]);
    expect(result.paths).toEqual([...Array.from({ length: 28 }, (_, index) => `/${index + 1}`), '/login', '/user'].sort());
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(30);
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('task browser owns an authorization popup as a tab and preserves its opener', async ({ modelOrkas: orkas }) => {
  const authorizationCookies: string[] = [];
  const server = createServer((req, res) => {
    res.setHeader('Content-Type', 'text/html');
    if (req.url === '/authorize') {
      authorizationCookies.push(req.headers.cookie || '');
      res.end(`<!doctype html><title>Provider authorization</title>
        <h1>Provider authorization</h1>
        <button id="authorize">Authorize</button>
        <script>
          document.querySelector('#authorize').addEventListener('click', () => {
            window.opener.postMessage({ type: 'authorized' }, location.origin);
            window.close();
          });
        </script>`);
      return;
    }
    res.setHeader('Set-Cookie', 'provider-session=fixture; HttpOnly; SameSite=Lax; Path=/');
    res.end(`<!doctype html><title>Provider settings</title>
      <h1>Provider settings</h1>
      <button id="open-auth">Connect account</button>
      <p id="auth-result">Not connected</p>
      <script>
        document.querySelector('#open-auth').addEventListener('click', () => {
          const popup = window.open('', 'provider-oauth', 'width=480,height=620');
          if (popup) popup.location.href = '/authorize';
        });
        window.addEventListener('message', (event) => {
          if (event.origin === location.origin && event.data?.type === 'authorized') {
            document.querySelector('#auth-result').textContent = 'Connected';
          }
        });
      </script>`);
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address() as { port: number };
    const parentUrl = `http://127.0.0.1:${address.port}/`;
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>(
      'conversations.create',
      { title: 'Authorization popup' },
    );
    const cid = created.conversation.conversation_id;
    await orkas.page!.evaluate(async taskId => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', taskId);
    }, cid);
    const input = { cid, parentUrl, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') };
    const opened = await orkas.electronApp!.evaluate(async ({ BrowserWindow }, args) => {
      const owner = BrowserWindow.getAllWindows()[0];
      const web = (process as any).mainModule.require(args.modulePath);
      web.bindWebAssistConversation('account-e2e', args.cid, owner.webContents);
      return web.openWebAssist('account-e2e', owner.webContents, {
        conversationId: args.cid,
        url: args.parentUrl,
        label: 'Provider settings',
      });
    }, input);
    expect(opened).toMatchObject({ ok: true });
    await orkas.page!.evaluate(() => (window as any).ConversationInfo.openAndSetTab('browser'));
    await expect(orkas.page!.locator('.web-assist-shell')).toBeVisible();
    await expect.poll(async () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => {
      const owner = BrowserWindow.getAllWindows().find(win => !win.getParentWindow())!;
      const parent = owner.contentView.children.find(child => child instanceof WebContentsView);
      return parent?.webContents.getTitle();
    })).toBe('Provider settings');

    const inventory = () => orkas.electronApp!.evaluate(({ BrowserWindow }, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return { ...web.listModelWebAssistTabs('account-e2e', args.cid), windows: BrowserWindow.getAllWindows().length };
    }, input);
    const openAuthorization = () => orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, url) => {
      const owner = BrowserWindow.getAllWindows().find(win => !win.getParentWindow())!;
      const parent = owner.contentView.children.find(child => child instanceof WebContentsView
        && child.webContents.getURL() === url) as InstanceType<typeof WebContentsView>;
      await parent.webContents.executeJavaScript('document.querySelector("#open-auth").click()', true);
    }, parentUrl);
    await openAuthorization();
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(2);
    await expect(orkas.page!.locator('.web-assist-tab.is-active')).toContainText('Provider authorization');
    const popupState = await inventory();
    expect(popupState.windows).toBe(1);
    expect(popupState.tabs).toHaveLength(2);
    expect(popupState.tabs.find((tab: any) => tab.tab_id === popupState.active_tab_id)?.page_title).toBe('Provider authorization');
    expect(authorizationCookies).toEqual(['provider-session=fixture']);
    const nativePopup = await orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, url) => {
      const owner = BrowserWindow.getAllWindows().find(win => !win.getParentWindow())!;
      const views = owner.contentView.children.filter(child => child instanceof WebContentsView) as InstanceType<typeof WebContentsView>[];
      const parent = views.find(view => view.webContents.getURL() === url)!;
      const popup = views.find(view => view.webContents.getURL() === url + 'authorize')!;
      return {
        id: popup.webContents.id,
        sharedSession: popup.webContents.session === parent.webContents.session,
        opener: await popup.webContents.executeJavaScript('window.opener !== null && window.opener.location.href === ' + JSON.stringify(url)),
        visible: popup.getVisible(),
      };
    }, parentUrl);
    expect(nativePopup).toMatchObject({ sharedSession: true, opener: true, visible: true });

    await orkas.electronApp!.evaluate(async ({ webContents }, id) => {
      await webContents.fromId(id)!.executeJavaScript('document.querySelector("#authorize").click()', true);
    }, nativePopup.id);
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(1);
    await expect.poll(() => orkas.electronApp!.evaluate(({ webContents }, id) => !!webContents.fromId(id), nativePopup.id)).toBe(false);
    await expect.poll(async () => orkas.electronApp!.evaluate(async ({ BrowserWindow, WebContentsView }, url) => {
      const owner = BrowserWindow.getAllWindows().find(win => !win.getParentWindow())!;
      const parent = owner.contentView.children.find(child => child instanceof WebContentsView
        && child.webContents.getURL() === url) as InstanceType<typeof WebContentsView>;
      return parent.webContents.executeJavaScript('document.querySelector("#auth-result").textContent');
    }, parentUrl)).toBe('Connected');

    await openAuthorization();
    await expect(orkas.page!.locator('.web-assist-tab')).toHaveCount(2);
    await expect(orkas.page!.locator('.web-assist-tab.is-active')).toContainText('Provider authorization');
    expect(authorizationCookies).toEqual(['provider-session=fixture', 'provider-session=fixture']);
    await orkas.invoke('webAssist.close', {});
    await expect.poll(() => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => (
      BrowserWindow.getAllWindows()[0].contentView.children.filter(child => child instanceof WebContentsView).length
    ))).toBe(0);
    expect((await inventory()).tabs).toHaveLength(0);
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('a browser open finishing after a task switch cannot expand the new task', async ({ orkas }) => {
  const server = createServer((_req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.end('<title>Task A page</title><h1>Task A</h1>');
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const a = (await orkas.invoke<any>('conversations.create', { title: 'Browser owner' })).conversation.conversation_id;
    const b = (await orkas.invoke<any>('conversations.create', { title: 'Current task' })).conversation.conversation_id;
    const page = orkas.page!;
    const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/`;
    expect(await page.evaluate(async ({ a, b, url }) => {
      const app = window as any;
      await app.loadConversations();
      app.setView('conversation', a);
      const opening = app.WebAssist.openForModel({ url });
      // Switch synchronously, before the IPC response can be delivered.
      app.setView('conversation', b);
      return opening;
    }, { a, b, url })).toBe(true);
    const details = page.locator('#conversation-info-panel');
    await expect(details).toBeHidden();
    const args = { cid: a, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') };
    await orkas.electronApp!.evaluate((_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      web.bindHostStartedWebAssistConversation('account-e2e', input.cid);
    }, args);
    await expect.poll(async () => orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return (await web.observeModelWebAssist('account-e2e', input.cid)).ok;
    }, args)).toBe(true);
    await expect(details).toBeHidden();
    expect((await orkas.invoke<any>('webAssist.state')).state.tabs.every((tab: any) => tab.conversation_id === a)).toBe(true);
    // The owning task still reveals its browser when the user returns.
    await page.evaluate(cid => (window as any).setView('conversation', cid), a);
    await expect(details).toBeVisible();
    await expect(details.locator('[data-info-tab="browser"]')).toHaveClass(/is-active/);
    await expect(page.locator('.web-assist-tab-title')).toHaveText('Task A page');
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('background browser work is revealed on return and activity overlays preserve its page', async ({ orkas }, testInfo) => {
  const server = createServer((req, res) => {
    if (req.url === '/report.csv') {
      res.setHeader('Content-Type', 'text/csv');
      res.setHeader('Content-Disposition', 'attachment; filename="report.csv"');
      res.end('name,value\nfixture,1');
    } else {
      res.setHeader('Content-Type', 'text/html');
      res.end('<style>html { background: #dbeafe; }</style><title>Background work</title><h1>Task page</h1><input value="kept"><a href="/report.csv">Download report</a>');
    }
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const page = orkas.page!;
    const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
    const front = await orkas.invoke<any>('conversations.create', { title: 'Foreground task' });
    const back = await orkas.invoke<any>('conversations.create', { title: 'Background task' });
    const cid = back.conversation.conversation_id;
    await page.evaluate(async id => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', id);
      (window as any).ConversationInfo.close();
    }, front.conversation.conversation_id);
    const input = { cid, url: origin + '/work', modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') };
    const opened = await orkas.electronApp!.evaluate(async (_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      web.bindHostStartedWebAssistConversation('account-e2e', args.cid);
      return web.openModelWebAssist('account-e2e', args.cid, { url: args.url });
    }, input);
    expect(opened.ok).toBe(true);
    await expect.poll(async () => orkas.electronApp!.evaluate((_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return web.listModelWebAssistTabs('account-e2e', args.cid).tabs[0]?.loading;
    }, input)).toBe(false);
    const observed = await orkas.electronApp!.evaluate(async (_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return web.observeModelWebAssist('account-e2e', args.cid);
    }, input);
    expect(observed).toMatchObject({ ok: true, title: 'Background work' });
    const details = page.locator('#conversation-info-panel');
    await expect(details).toBeHidden();
    const native = () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      return { id: view.webContents.id, visible: view.getVisible() };
    });
    expect((await native()).visible).toBe(false);
    const nativeId = (await native()).id;
    await page.evaluate(id => (window as any).setView('conversation', id), cid);
    await expect(details).toBeVisible();
    await expect(details.locator('[data-info-tab="browser"]')).toHaveClass(/is-active/);
    await expect.poll(async () => (await native()).visible).toBe(true);
    const documentState = () => orkas.electronApp!.evaluate(async ({ webContents }, id) => (
      webContents.fromId(id)!.executeJavaScript('({ timeOrigin: performance.timeOrigin, draft: document.querySelector("input").value })')
    ), nativeId);
    const before = await documentState();
    const backdrop = page.locator('.web-assist-page-preview');
    const expectPageHidden = async () => {
      // Floating application controls conceal pixels only; no screenshot copy
      // or page replacement is mounted in the browser host.
      await expect(backdrop).toHaveCount(0);
      await expect(page.locator('.web-assist-native-host img')).toHaveCount(0);
    };
    const prompt = page.locator('.web-assist-download-prompt');
    await expect(prompt).toBeHidden();
    const activity = page.locator('.web-assist-activity-popover');
    const button = page.locator('[data-act="activity"]');
    const hostBox = await page.locator('.web-assist-native-host').boundingBox();
    await button.click();
    await expect(activity).toBeVisible();
    await expect(activity.locator('.web-assist-trail-row')).toHaveCount(1);
    await expect(activity.locator('.web-assist-trail-url').last()).toHaveText(origin + '/work');
    await expect(activity.locator('.web-assist-download-allow')).toHaveCount(0);
    await expect.poll(async () => (await native()).visible).toBe(false);
    expect(await page.locator('.web-assist-native-host').boundingBox()).toEqual(hostBox);
    await expectPageHidden();
    await page.screenshot({ path: testInfo.outputPath('browser-activity.png') });
    await page.keyboard.press('Escape');
    await expect(activity).toBeHidden();
    await expect(button).toBeFocused();
    await expect.poll(async () => (await native()).visible).toBe(true);
    await expect(backdrop).toHaveCount(0);
    expect((await native()).id).toBe(nativeId);
    expect(await documentState()).toEqual(before);
    await button.click();
    await expect(activity).toBeVisible();
    const downloaded = await orkas.electronApp!.evaluate(async ({ webContents }, id) => {
      const contents = webContents.fromId(id)!;
      const completed = new Promise<{ state: string; path: string }>(resolve => {
        contents.session.once('will-download', (_event, item) => {
          item.once('done', (_done, state) => resolve({ state, path: item.getSavePath() }));
        });
      });
      await contents.executeJavaScript('document.querySelector("a").click(); void 0', true);
      return completed;
    }, nativeId);
    expect(downloaded.state).toBe('completed');
    expect(readFileSync(downloaded.path, 'utf8')).toBe('name,value\nfixture,1');
    const saved = activity.locator('.web-assist-trail-row').filter({ has: page.locator('[data-download-action="view"]') });
    await expect(saved).toHaveCount(1);
    await expect(saved.locator('.web-assist-trail-url')).toHaveText('report.csv');
    await expect(saved.locator('.web-assist-activity-marker .is-download')).toHaveCount(1);
    await expect(activity.locator('.web-assist-trail-row')).toHaveCount(2);
    await page.screenshot({ path: testInfo.outputPath('browser-download-actions.png') });
    const navigated = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.navigateModelWebAssist('account-e2e', input.cid, {
        tabId: input.tabId, action: 'goto', url: input.url,
      });
    }, { cid, tabId: opened.active_tab_id, url: origin + '/updated',
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(navigated.ok).toBe(true);
    await expect(activity).toBeVisible();
    await expect(activity.locator('.web-assist-trail-url').first()).toHaveText(origin + '/updated');
    await expect(activity.locator('.web-assist-trail-row')).toHaveCount(3);
    const preview = await orkas.openPreview(() => saved.locator('[data-download-action="view"]').click());
    await expect(preview.locator('.delimited-preview td').filter({ hasText: /^fixture$/ })).toHaveCount(1);
    await expect(preview.locator('.delimited-preview td').filter({ hasText: /^1$/ })).toHaveCount(1);
    await orkas.closePreview(preview);
    // Observe the final OS handoff without opening Finder/Explorer in CI.
    await orkas.electronApp!.evaluate(({ shell }) => {
      (globalThis as any).__activityReveal = { original: shell.showItemInFolder, paths: [] };
      shell.showItemInFolder = file => { (globalThis as any).__activityReveal.paths.push(file); };
    });
    try {
      await saved.locator('[data-download-action="reveal"]').click();
      await expect.poll(() => orkas.electronApp!.evaluate(() => (globalThis as any).__activityReveal.paths)).toEqual([downloaded.path]);
    } finally {
      await orkas.electronApp!.evaluate(({ shell }) => {
        shell.showItemInFolder = (globalThis as any).__activityReveal.original;
        delete (globalThis as any).__activityReveal;
      });
    }
    await page.locator('.web-assist-address-input').click();
    await expect(activity).toBeHidden();
    await button.click();
    await page.evaluate(id => (window as any).setView('conversation', id), front.conversation.conversation_id);
    await expect(activity).toBeHidden();
    await page.evaluate(id => (window as any).setView('conversation', id), cid);
    await expect(activity).toBeHidden();
    await orkas.invoke('webAssist.close', {});
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('a background task clicks its hidden page natively and is refused before input when the page cannot render', async ({ orkas }) => {
  // Playwright's focus emulation keeps every page it attaches to painting, so
  // a page that never rendered cannot be reproduced here. That page and its
  // wake are covered by test/gui/web-assist-background-input-canary.ts.
  const clicks: string[] = [];
  let blocking = false;
  const server = createServer((req, res) => {
    if (req.url === '/blocking') {
      blocking = true;
      res.end();
      return;
    }
    if (req.method === 'POST') {
      clicks.push(req.url!);
      res.end('ok');
      return;
    }
    res.setHeader('Content-Type', 'text/html');
    res.end(`<!doctype html><title>Report</title><h1>Report</h1>
      <button id="continue" type="button">Continue</button><p id="state">idle</p>
      <script>
        document.querySelector('#continue').addEventListener('click', event => {
          document.querySelector('#state').textContent = event.isTrusted ? 'trusted' : 'synthetic';
          fetch(location.pathname + '/clicked', { method: 'POST' });
        });
      </script>`);
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const page = orkas.page!;
    const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
    const front = await orkas.invoke<any>('conversations.create', { title: 'Foreground task' });
    const back = await orkas.invoke<any>('conversations.create', { title: 'Background clicks' });
    await page.evaluate(async id => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', id);
      (window as any).ConversationInfo.close();
    }, front.conversation.conversation_id);
    const input = { cid: back.conversation.conversation_id, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') };
    const opened = await orkas.electronApp!.evaluate(async (_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      web.bindHostStartedWebAssistConversation('account-e2e', args.cid);
      return web.openModelWebAssist('account-e2e', args.cid, { url: args.url });
    }, { ...input, url: origin + '/first' });
    expect(opened.ok).toBe(true);
    const tab = { ...input, tabId: opened.active_tab_id as string };
    const loading = () => orkas.electronApp!.evaluate((_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return web.listModelWebAssistTabs('account-e2e', args.cid).tabs[0]?.loading;
    }, tab);
    await expect.poll(loading).toBe(false);
    const native = () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children.find(v => v instanceof WebContentsView) as InstanceType<typeof WebContentsView>;
      return { id: view.webContents.id, visible: view.getVisible() };
    });
    const nativeId = (await native()).id;
    // Read from the page itself, not through the host.
    const pageState = () => orkas.electronApp!.evaluate(async ({ webContents }, id) => (
      webContents.fromId(id)!.executeJavaScript(`new Promise(resolve => {
        const state = document.querySelector('#state').textContent;
        requestAnimationFrame(() => resolve({ rendering: true, state }));
        setTimeout(() => resolve({ rendering: false, state }), 500);
      })`)
    ), nativeId);
    const observe = () => orkas.electronApp!.evaluate(async (_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      const observed = await web.observeModelWebAssist('account-e2e', args.cid, args.tabId);
      return { pageId: observed.page_id as string, ref: observed.elements.find((element: { label: string }) => element.label === 'Continue')?.ref as string };
    }, tab);
    // The model's own path: the host dispatches Chromium input, not DOM click().
    const act = (target: { pageId: string; ref: string }) => orkas.electronApp!.evaluate(async (_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return web.actOnModelWebAssist('account-e2e', args.cid, {
        tabId: args.tabId, pageId: args.pageId, elementRef: args.ref, action: 'click',
      });
    }, { ...tab, ...target });

    expect(await act(await observe())).toMatchObject({ ok: true, outcome: 'acted', action: 'click' });
    await expect.poll(() => clicks).toEqual(['/first/clicked']);
    expect((await pageState()).state).toBe('trusted');
    // Still background work: nothing was revealed over the task the user is in.
    expect((await native()).visible).toBe(false);
    await expect(page.locator('#conversation-info-panel')).toBeHidden();
    expect(await act(await observe())).toMatchObject({ ok: true, outcome: 'acted' });
    await expect.poll(() => clicks).toEqual(['/first/clicked', '/first/clicked']);
    expect(await orkas.electronApp!.evaluate(async (_electron, args) => {
      const web = (process as any).mainModule.require(args.modulePath);
      return web.navigateModelWebAssist('account-e2e', args.cid, { tabId: args.tabId, action: 'goto', url: args.url });
    }, { ...tab, url: origin + '/second' })).toMatchObject({ ok: true });
    await expect.poll(loading).toBe(false);
    expect(await act(await observe())).toMatchObject({ ok: true, outcome: 'acted' });
    await expect.poll(() => clicks).toEqual(['/first/clicked', '/first/clicked', '/second/clicked']);

    // A page that cannot produce a frame, here because its main thread is
    // blocked, is refused before any input reaches it.
    const blocked = await observe();
    await orkas.electronApp!.evaluate(async ({ webContents }, id) => {
      await webContents.fromId(id)!.executeJavaScript("setTimeout(() => { navigator.sendBeacon('/blocking'); const end = Date.now() + 4000; while (Date.now() < end); }, 0); void 0");
    }, nativeId);
    // The beacon leaves as the loop starts, so the click cannot race ahead of it.
    await expect.poll(() => blocking).toBe(true);
    const refused = await act(blocked);
    expect(refused).toMatchObject({ ok: false, code: 'page_not_rendered' });
    expect(refused.error).toContain('the action was not sent');
    await expect.poll(async () => (await pageState()).rendering, { timeout: 15_000 }).toBe(true);
    // Nothing arrived late, and the same observation acts exactly once.
    expect(clicks).toHaveLength(3);
    expect(await act(blocked)).toMatchObject({ ok: true, outcome: 'acted' });
    await expect.poll(() => clicks).toHaveLength(4);
    expect((await native()).visible).toBe(false);
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});

test('full-screen task browser keeps keyboard focus out of covered controls and permits dialogs', async ({ modelOrkas: orkas }, testInfo) => {
  const created = await orkas.invoke<{ conversation: { conversation_id: string } }>(
    'conversations.create', { title: 'Browser focus boundary' },
  );
  const page = orkas.page!;
  await page.evaluate(async cid => {
    await (window as any).loadConversations();
    (window as any).setView('conversation', cid);
    (window as any).ConversationInfo.openAndSetTab('browser', cid);
  }, created.conversation.conversation_id);
  const details = page.locator('#conversation-info-panel');
  await expect(details.locator('.web-assist-shell')).toBeVisible();
  await details.locator('.web-assist-expand-btn').click();
  await expect(details).toHaveClass(/is-web-assist-expanded/);

  await details.locator('.web-assist-add-tab').focus();
  for (let i = 0; i < 3; i++) {
    await page.keyboard.press('Shift+Tab');
    expect(await page.evaluate(() => !!document.activeElement?.closest('#conversation-info-panel')))
      .toBe(true);
  }
  await page.locator('#chat-send-btn').focus();
  await expect(page.locator('#chat-send-btn')).not.toBeFocused();
  await page.locator('#sidebar-search-btn').focus();
  await expect(page.locator('#sidebar-search-btn')).not.toBeFocused();

  await page.evaluate(() => { void (window as any).uiConfirm('Focus check'); });
  const dialog = page.locator('.ui-dialog-overlay.open');
  await expect(dialog).toBeVisible();
  await expect(dialog.locator('[data-act="ok"]')).toBeFocused();
  await dialog.locator('[data-act="cancel"]').click();
  await expect(dialog).toHaveCount(0);
  await expect(details).toHaveClass(/is-web-assist-expanded/);

  await page.keyboard.press('Escape');
  await expect(details).not.toHaveClass(/is-web-assist-expanded/);
  await page.locator('#chat-send-btn').focus();
  await expect(page.locator('#chat-send-btn')).toBeFocused();
  await details.locator('.web-assist-expand-btn').click();
  await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('files'));
  await expect(details).not.toHaveClass(/is-web-assist-expanded/);
  await page.locator('#sidebar-search-btn').focus();
  await expect(page.locator('#sidebar-search-btn')).toBeFocused();
});

test('task-details browser supports tabs, address navigation, resizing, and view recovery', async ({ orkas }, testInfo) => {
  const server = createServer((_req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.end('<title>Setup console</title><h1>Application setup</h1><label>Application name<input></label><button type="button" onclick="window.purchaseClicks = (window.purchaseClicks || 0) + 1">Purchase now</button>');
  });
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address() as { port: number };
    const page = orkas.page!;
    const created = await orkas.invoke<{ conversation: { conversation_id: string } }>(
      'conversations.create',
      { title: 'Browser E2E' },
    );
    const cid = created.conversation.conversation_id;
    expect(cid).not.toBe('');
    await page.evaluate(async taskId => {
      await (window as any).loadConversations();
      (window as any).setView('conversation', taskId);
    }, cid);
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('files'));
    await page.setViewportSize({ width: 1800, height: 900 });
    await expect.poll(async () => (await page.locator('#conversation-info-panel').boundingBox())!.width).toBe(540);
    await page.setViewportSize({ width: 1500, height: 900 });
    await expect.poll(async () => (await page.locator('#conversation-info-panel').boundingBox())!.width).toBe(450);
    await page.setViewportSize({ width: 1280, height: 800 });
    await expect.poll(async () => (await page.locator('#conversation-info-panel').boundingBox())!.width).toBe(400);
    const opened = await orkas.electronApp!.evaluate(async ({ BrowserWindow }, input) => {
      const owner = BrowserWindow.getAllWindows()[0];
      const web = (process as any).mainModule.require(input.modulePath);
      web.bindWebAssistConversation('account-e2e', input.cid, owner.webContents);
      return web.openModelWebAssist('account-e2e', input.cid, {
        url: input.url, label: 'Browser E2E',
      });
    }, { cid, url: `http://127.0.0.1:${address.port}/`, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(opened.ok).toBe(true);
    await expect.poll(async () => {
      const result = await orkas.invoke<{ state: { page_title: string; loading: boolean } }>('webAssist.state', {});
      return { title: result.state.page_title, loading: result.state.loading };
    }).toEqual({ title: 'Setup console', loading: false });
    const openedTabId = (opened as { active_tab_id: string }).active_tab_id;
    const observed = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.observeModelWebAssist('account-e2e', input.cid, input.tabId);
    }, { cid, tabId: openedTabId, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(observed).toMatchObject({ ok: true, title: 'Setup console' });
    expect(observed.text).toContain('Application setup');
    const native = () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }) => {
      const views = BrowserWindow.getAllWindows()[0].contentView.children
        .filter(child => child instanceof WebContentsView);
      const visible = views.find(view => view.getVisible());
      const measured = visible || views[0];
      return measured ? { visible: !!visible, bounds: measured.getBounds(), id: measured.webContents.id } : null;
    });
    const details = page.locator('#conversation-info-panel');
    const browser = details.locator('.web-assist-shell');
    await expect(details).toBeVisible();
    await expect(details.locator('[data-info-tab="browser"]')).toHaveClass(/is-active/);
    await expect(browser).toBeVisible();
    await expect(browser.locator('.web-assist-status')).toHaveCSS('font-size', '12px');
    // Task-wide history stays beside Add Tab, independently of the page status.
    const statusLayout = () => browser.evaluate(el => {
      const box = el.getBoundingClientRect();
      const status = el.querySelector('.web-assist-status')!.getBoundingClientRect();
      const button = el.querySelector('.web-assist-activity-btn')!.getBoundingClientRect();
      const add = el.querySelector('.web-assist-add-tab')!.getBoundingClientRect();
      return { centerOffset: status.x + status.width / 2 - (box.x + box.width / 2),
        gap: button.x - add.right, sameRow: Math.abs(button.y - add.y),
        buttonInset: box.right - button.right };
    });
    // Allow only DOMRect floating-point noise, not visible spacing regressions.
    const geometryEpsilon = 0.0001;
    for (const width of [1500, 400]) {
      await page.setViewportSize({ width, height: 900 });
      await expect.poll(async () => Math.abs((await statusLayout()).centerOffset)).toBeLessThan(1);
      expect((await statusLayout()).gap + geometryEpsilon).toBeGreaterThanOrEqual(4);
      expect((await statusLayout()).sameRow).toBeLessThan(2);
      expect((await statusLayout()).buttonInset + geometryEpsilon).toBeGreaterThanOrEqual(7);
    }
    await page.setViewportSize({ width: 1280, height: 800 });
    await expect.poll(async () => (await native())?.visible).toBe(true);
    const pageBeforeSearch = (await native())!.id;
    await orkas.electronApp!.evaluate(async ({ webContents }, id) => {
      await webContents.fromId(id)!.executeJavaScript('document.querySelector("input").value = "Unsaved browser draft"');
    }, pageBeforeSearch);
    for (const fullScreen of [false, true]) {
      if (fullScreen) await browser.locator('.web-assist-expand-btn').click();
      // Use the sidebar entry and the real keyboard toggle, rather than a
      // synthetic modal: search has its own overlay shell and display state.
      if (fullScreen) {
        await browser.locator('.web-assist-address-input').focus();
        await page.keyboard.press('ControlOrMeta+k');
      } else await page.locator('#sidebar-search-btn').click();
      await expect(page.locator('#search-input')).toBeFocused();
      await expect.poll(async () => (await native())?.visible).toBe(false);
      await page.locator('#search-input').fill('Browser E2E');
      await page.screenshot({ path: testInfo.outputPath(fullScreen ? 'browser-search-fullscreen.png' : 'browser-search.png') });
      await page.locator('#search-close-btn').click();
      await expect(page.locator('#search-overlay')).toBeHidden();
      await expect.poll(async () => (await native())?.visible).toBe(true);
      expect((await native())?.id).toBe(pageBeforeSearch);

      await browser.locator('.web-assist-address-input').focus();
      await page.keyboard.press('ControlOrMeta+k');
      await expect.poll(async () => (await native())?.visible).toBe(false);
      await page.keyboard.press('ControlOrMeta+k');
      await expect(page.locator('#search-overlay')).toBeHidden();
      await expect.poll(async () => (await native())?.visible).toBe(true);
      await browser.locator('.web-assist-address-input').focus();
      await page.keyboard.press('ControlOrMeta+k');
      await expect(page.locator('#search-input')).toBeFocused();
      await expect.poll(async () => (await native())?.visible).toBe(false);
      await page.keyboard.press('Escape');
      await expect(page.locator('#search-overlay')).toBeHidden();
      await expect.poll(async () => (await native())?.visible).toBe(true);
      if (fullScreen) {
        await expect(details).toHaveClass(/is-web-assist-expanded/);
        await browser.locator('.web-assist-expand-btn').click();
      }
    }
    expect(await orkas.electronApp!.evaluate(async ({ webContents }, id) => {
      return webContents.fromId(id)!.executeJavaScript('document.querySelector("input").value');
    }, pageBeforeSearch)).toBe('Unsaved browser draft');
    // Use the actual close/tab controls: ongoing model operations must not
    // undo the user's view choice, and the native page remains usable hidden.
    await page.locator('#conversation-info-close').click();
    const hiddenObservation = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.observeModelWebAssist('account-e2e', input.cid, input.tabId);
    }, { cid, tabId: openedTabId, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(hiddenObservation.ok).toBe(true);
    await expect(details).toBeHidden();
    await expect.poll(async () => (await native())?.visible).toBe(false);
    await page.locator('#conversation-info-toggle').click();
    await details.locator('[data-info-tab="attachments"]').click();
    const field = hiddenObservation.elements.find((element: { label: string }) => element.label === 'Application name');
    const hiddenAction = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.actOnModelWebAssist('account-e2e', input.cid, {
        tabId: input.tabId, pageId: input.pageId, elementRef: input.ref,
        action: 'fill', text: 'Hidden-page draft',
      });
    }, { cid, tabId: openedTabId, pageId: hiddenObservation.page_id, ref: field.ref,
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(hiddenAction).toMatchObject({ ok: true, outcome: 'acted' });
    // Independent page oracle: a tool success envelope alone cannot prove
    // the draft was entered in the still-hidden native page.
    const draftValue = await orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }, url) => {
      const view = BrowserWindow.getAllWindows()[0].contentView.children
        .find(child => child instanceof WebContentsView && child.webContents.getURL() === url) as InstanceType<typeof WebContentsView>;
      return view.webContents.executeJavaScript('document.querySelector("input").value');
    }, `http://127.0.0.1:${address.port}/`);
    expect(draftValue).toBe('Hidden-page draft');
    const hiddenWait = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.waitForModelWebAssist('account-e2e', input.cid, {
        tabId: input.tabId, condition: 'text', text: 'Application setup', timeoutMs: 1000,
      });
    }, { cid, tabId: openedTabId, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    expect(hiddenWait).toMatchObject({ ok: true, condition: 'text' });
    await expect(details.locator('[data-info-tab="attachments"]')).toHaveClass(/is-active/);
    await expect(browser).toBeHidden();
    await expect.poll(async () => (await native())?.visible).toBe(false);
    // The conversation controller invokes this at the next request boundary.
    await page.evaluate(taskId => (window as any).WebAssist.beginTaskTurn(taskId), cid);
    // The retained page alone must not expand details in a non-browser turn.
    await page.locator('#conversation-info-close').click();
    await page.evaluate(taskId => {
      (window as any).setView('settings');
      (window as any).setView('conversation', taskId);
    }, cid);
    await orkas.invoke('webAssist.state', {});
    await expect(details).toBeHidden();
    await expect.poll(async () => (await native())?.visible).toBe(false);
    expect((await native())?.id).toBe(pageBeforeSearch);
    expect(await orkas.electronApp!.evaluate(async ({ webContents }, id) => (
      webContents.fromId(id)!.executeJavaScript('document.querySelector("input").value')
    ), pageBeforeSearch)).toBe('Hidden-page draft');
    await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.observeModelWebAssist('account-e2e', input.cid, input.tabId);
    }, { cid, tabId: openedTabId, modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts') });
    await expect(details.locator('[data-info-tab="browser"]')).toHaveClass(/is-active/);
    await expect.poll(async () => (await native())?.visible).toBe(true);
    const modelOpened = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.openModelWebAssist('account-e2e', input.cid, {
        url: input.url,
        label: 'Model-opened tab',
      });
    }, {
      cid,
      url: `http://127.0.0.1:${address.port}/model-opened`,
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
    });
    expect(modelOpened).toMatchObject({ ok: true });
    const modelTabId = String(modelOpened.active_tab_id || '');
    await expect(page.locator('.web-assist-tab')).toHaveCount(2);
    await expect.poll(async () => orkas.electronApp!.evaluate(({ BrowserWindow, WebContentsView }, expectedId) => {
      const views = BrowserWindow.getAllWindows()[0].contentView.children
        .filter(child => child instanceof WebContentsView);
      const selected = views.find(view => view.webContents.getURL().includes('/model-opened'));
      return {
        active: selected?.getVisible() === true,
        tabIdPresent: expectedId.length === 12,
      };
    }, modelTabId)).toEqual({ active: true, tabIdPresent: true });
    const closedModelTab = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.closeModelWebAssistTab('account-e2e', input.cid, input.tabId);
    }, {
      cid,
      tabId: modelTabId,
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
    });
    expect(closedModelTab).toMatchObject({ ok: true, closed: true });
    await expect(page.locator('.web-assist-tab')).toHaveCount(1);
    await expect.poll(async () => (await native())?.visible).toBe(true);
    const chat = await page.locator('#panel-conversation .chat-main-pane').boundingBox();
    const box = (await browser.boundingBox())!;
    expect(box.x).toBeGreaterThanOrEqual(chat!.x + chat!.width - 1);
    expect(chat!.width).toBeGreaterThan(250);
    expect((await native())!.bounds.x).toBeGreaterThanOrEqual(Math.floor(box.x));
    const handle = page.locator('#conversation-info-resize');
    await expect(handle).toHaveAttribute('aria-valuemin', '400');
    expect(Number(await handle.getAttribute('aria-valuemax'))).toBeGreaterThan(400);
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(400);
    const nativeWidth = (await native())!.bounds.width;
    const grip = (await handle.boundingBox())!;
    const pageBeforeResize = (await native())!.id;
    const resizeDocument = () => orkas.electronApp!.evaluate(({ webContents }, id) => (
      webContents.fromId(id)!.executeJavaScript('({ timeOrigin: performance.timeOrigin, draft: document.querySelector("input")?.value })')
    ), pageBeforeResize);
    const documentBeforeResize = await resizeDocument();
    await page.mouse.move(grip.x + grip.width / 2, grip.y + 100);
    await page.mouse.down();
    await page.mouse.move(grip.x + 85, grip.y + 100);
    // Assert while the pointer is still held, not only after release.
    await expect.poll(async () => (await native())?.bounds.width).toBe(nativeWidth);
    expect((await native())?.visible).toBe(true);
    expect((await native())?.id).toBe(pageBeforeResize);
    await page.mouse.move(grip.x - 40, grip.y + 100);
    await expect.poll(async () => (await native())?.bounds.width).toBeGreaterThan(nativeWidth);
    expect((await native())?.visible).toBe(true);
    await page.mouse.move(grip.x + 85, grip.y + 100);
    await page.mouse.up();
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(400);
    const resizedWidth = (await browser.boundingBox())!.width;
    await expect.poll(async () => (await native())?.visible).toBe(true);
    // Every application overlay suppresses the browser, including a surface
    // outside its rectangle. No geometry-specific browser exception remains.
    await page.evaluate(() => {
      const overlay = document.createElement('div');
      overlay.id = 'browser-occlusion-fixture';
      overlay.className = 'modal-overlay';
      overlay.style.cssText = 'position:fixed;inset:auto;left:0;top:0;width:1px;height:1px;display:block';
      document.body.appendChild(overlay);
      return new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
    });
    await expect.poll(async () => (await native())?.visible).toBe(false);
    await page.evaluate(() => {
      const overlay = document.getElementById('browser-occlusion-fixture')!;
      const rect = document.querySelector('.web-assist-native-host')!.getBoundingClientRect();
      overlay.style.left = `${rect.left + 10}px`;
      overlay.style.top = `${rect.top + 10}px`;
      overlay.style.width = '20px';
      overlay.style.height = '20px';
    });
    await expect.poll(async () => (await native())?.visible).toBe(false);
    await page.evaluate(() => document.getElementById('browser-occlusion-fixture')!.remove());
    await expect.poll(async () => (await native())?.visible).toBe(true);
    expect((await native())?.id).toBe(pageBeforeResize);
    expect(await resizeDocument()).toEqual(documentBeforeResize);
    // Full screen hands the window to the browser without touching the page:
    // same native contents and document, and the width chosen at the resize
    // handle is still there after leaving.
    const expand = browser.locator('[data-act="expand"]');
    const header = details.locator('.conversation-info-header');
    await expand.click();
    await expect(header).toBeHidden();
    await expect(page.locator('#conversation-info-resize')).toBeHidden();
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(1280);
    await expect.poll(async () => (await native())?.bounds.width).toBeGreaterThan(resizedWidth);
    expect((await native())?.visible).toBe(true);
    expect((await native())?.id).toBe(pageBeforeResize);
    expect(await resizeDocument()).toEqual(documentBeforeResize);
    await page.keyboard.press('Escape');
    await expect(header).toBeVisible();
    await expect(expand).toBeFocused();
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(400);
    await expect.poll(async () => (await native())?.bounds.width).toBeLessThan(resizedWidth + 1);
    expect((await native())?.visible).toBe(true);
    expect((await native())?.id).toBe(pageBeforeResize);
    expect(await resizeDocument()).toEqual(documentBeforeResize);
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('files'));
    await expect(browser).toBeHidden();
    await expect.poll(async () => (await native())?.visible).toBe(false);
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('browser'));
    await expect(browser).toBeVisible();
    // Leaving the Browser tab must never leave a full-screen drawer covering
    // the app: the collapse is wired into the tab change, not only Escape.
    await expand.click();
    await expect(header).toBeHidden();
    await expect(details).toHaveClass(/is-web-assist-expanded/);
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('files'));
    await expect(details).not.toHaveClass(/is-web-assist-expanded/);
    await expect(header).toBeVisible();
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('browser'));
    await expect(browser).toBeVisible();
    await expect(details).not.toHaveClass(/is-web-assist-expanded/);

    await page.locator('.web-assist-add-tab').click();
    await expect(page.locator('.web-assist-tab')).toHaveCount(2);
    await page.locator('.web-assist-address-input').fill(`http://127.0.0.1:${address.port}/second`);
    await page.locator('.web-assist-address-input').press('Enter');
    await expect.poll(async () => {
      const result = await orkas.invoke<{ state: { display_url: string; loading: boolean } }>('webAssist.state', {});
      return result.state.loading ? '' : result.state.display_url;
    }).toContain('/second');
    const activeState = await orkas.invoke<{ state: { active_tab_id: string } }>('webAssist.state', {});
    const modelObservation = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.observeModelWebAssist('account-e2e', input.cid, input.tabId);
    }, {
      cid,
      tabId: activeState.state.active_tab_id,
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
    });
    expect(modelObservation).toMatchObject({ ok: true, untrusted_content: true });
    const inputRef = (modelObservation.elements as Array<{ ref: string; label: string }>)
      .find(element => element.label === 'Application name')?.ref;
    expect(inputRef).toBeTruthy();
    const purchase = (modelObservation.elements as Array<{
      ref: string;
      label: string;
    }>).find(element => element.label === 'Purchase now');
    // Task actions are never flagged for the user (2026-10-03); observations
    // no longer carry the flag at all.
    expect(purchase).toBeTruthy();
    expect(purchase).not.toHaveProperty('requires_user_action');
    const permissionMode = await orkas.invoke<{ ok: boolean; mode: string }>(
      'permissions.setLocalExecMode',
      { mode: 'all_files_approval' },
    );
    expect(permissionMode).toMatchObject({ ok: true, mode: 'all_files_approval' });
    const modelAction = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.actOnModelWebAssist('account-e2e', input.cid, {
        tabId: input.tabId,
        pageId: input.pageId,
        elementRef: input.elementRef,
        action: 'fill',
        text: 'Orkas shared browser',
      });
    }, {
      cid,
      tabId: activeState.state.active_tab_id,
      pageId: modelObservation.page_id,
      elementRef: inputRef,
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
    });
    expect(modelAction).toMatchObject({ ok: true, outcome: 'acted' });

    // A successful fill invalidates its snapshot. A fresh reference clicks
    // once without a second approval, and replay is rejected.
    const approvedObservation = await orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.observeModelWebAssist('account-e2e', input.cid, input.tabId);
    }, {
      cid,
      tabId: activeState.state.active_tab_id,
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
    });
    const repeatPurchase = (approvedObservation.elements as Array<{ ref: string; label: string }>)
      .find(element => element.label === 'Purchase now');
    expect(repeatPurchase).toBeTruthy();
    const clickPurchase = () => orkas.electronApp!.evaluate(async (_electron, input) => {
      const web = (process as any).mainModule.require(input.modulePath);
      return web.actOnModelWebAssist('account-e2e', input.cid, {
        tabId: input.tabId,
        pageId: input.pageId,
        elementRef: input.elementRef,
        action: 'click',
      });
    }, {
      cid,
      tabId: activeState.state.active_tab_id,
      pageId: approvedObservation.page_id,
      elementRef: repeatPurchase!.ref,
      modulePath: path.resolve(__dirname, '../../src/main/features/web_assist.ts'),
    });
    expect(await clickPurchase()).toMatchObject({ ok: true, outcome: 'acted', action: 'click' });
    expect(await clickPurchase()).toMatchObject({ ok: false, code: 'stale_page' });
    await expect(page.locator('.bash-permission-dialog')).toHaveCount(0);
    expect(await orkas.electronApp!.evaluate(async ({ webContents }, url) => {
      return webContents.getAllWebContents().find(wc => wc.getURL() === url)!.executeJavaScript('window.purchaseClicks');
    }, `http://127.0.0.1:${address.port}/second`)).toBe(1);

    await page.locator('.web-assist-tab-close').last().click();
    await expect(page.locator('.web-assist-tab')).toHaveCount(1);

    await page.evaluate(() => (window as any).setView('connectors'));
    await expect(browser).toBeHidden();
    await expect.poll(async () => (await native())?.visible).toBe(false);
    await page.evaluate(cid => (window as any).setView('conversation', cid), cid);
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('browser'));
    await expect.poll(async () => (await native())?.visible).toBe(true);
    expect((await browser.boundingBox())!.width).toBe(resizedWidth);

    await page.evaluate(async taskId => {
      await (window as any).openAgentDetail('commander', {
        returnTarget: { view: 'conversation', id: taskId },
      });
    }, cid);
    await expect(page.locator('#panel-agents')).toHaveClass(/resource-detail-overlay/);
    await expect(page.locator('#agents-detail-view')).toBeVisible();
    await expect.poll(async () => (await native())?.visible).toBe(false);
    await page.locator('#agents-back-btn').click();
    await expect(page.locator('#panel-agents')).not.toHaveClass(/resource-detail-overlay/);
    await expect.poll(async () => (await native())?.visible).toBe(true);

    await page.evaluate(() => {
      const overlay = document.createElement('div');
      overlay.id = 'web-assist-e2e-overlay';
      overlay.className = 'modal-overlay open';
      document.body.appendChild(overlay);
    });
    await expect.poll(async () => (await native())?.visible).toBe(false);
    await page.evaluate(() => document.getElementById('web-assist-e2e-overlay')?.remove());
    await expect.poll(async () => (await native())?.visible).toBe(true);
    const state = await orkas.invoke<{ state: { conversation_id: string; assistant_controlled: boolean } }>('webAssist.state', {});
    expect(state.state).toMatchObject({ conversation_id: cid, assistant_controlled: true });
    // The host display can be narrower than the emulated viewport. Exercise
    // wide layout on Files so the native browser is never placed off screen.
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('files'));
    await page.setViewportSize({ width: 1800, height: 900 });
    expect(Number(await handle.getAttribute('aria-valuemax'))).toBeGreaterThan(540);
    await handle.press('ArrowLeft');
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(424);
    const wideGrip = (await handle.boundingBox())!;
    await page.mouse.move(wideGrip.x + wideGrip.width / 2, wideGrip.y + 100);
    await page.mouse.down();
    await page.mouse.move(0, wideGrip.y + 100);
    await expect.poll(async () => (await details.boundingBox())!.width).toBeGreaterThan(540);
    await expect.poll(async () => (await page.locator('#panel-conversation .chat-main-pane').boundingBox())!.width).toBeCloseTo(420, 0);
    await page.mouse.move(wideGrip.x + 300, wideGrip.y + 100);
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(400);
    await page.mouse.up();
    await handle.press('ArrowRight');
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(400);
    for (let step = 0; step < 10; step++) await handle.press('ArrowLeft');
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(640);
    await page.setViewportSize({ width: 1500, height: 900 });
    await expect.poll(async () => (await details.boundingBox())!.width).toBe(640);
    await page.setViewportSize({ width: 1280, height: 800 });
    await expect.poll(async () => (await details.boundingBox())!.width).toBeLessThan(640);
    expect((await details.boundingBox())!.width).toBeGreaterThan(400);
    await expect.poll(async () => (await page.locator('#panel-conversation .chat-main-pane').boundingBox())!.width).toBeCloseTo(420, 0);
    await page.evaluate(() => (window as any).ConversationInfo.openAndSetTab('browser'));
    await expect.poll(async () => (await native())?.visible).toBe(true);
    await page.screenshot({ path: testInfo.outputPath('conversation-browser-panel.png') });
  } finally {
    server.closeAllConnections();
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});