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.

69.0 KB
Raw Blame
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, writeFileSync } from 'node:fs';
import path from 'node:path';

import { expect, test, type OrkasTestApp } from './fixtures/orkas';


async function expectProjectFileReady(orkas: OrkasTestApp, projectId: string, fileName: string): Promise<void> {
  await expect.poll(async () => {
    const status = await orkas.invoke<{
      files: Array<{ path: string; status: string; error?: unknown }>;
    }>('projects.files.status', { projectId, skipReconcile: true });
    const file = status.files.find((item) => item.path === fileName);
    return { status: file?.status, error: file?.error || null };
  }, { timeout: 40_000 }).toEqual({ status: 'ready', error: null });
}

/** The unprojected `cloud/chats` dir of whichever account the run activated. */
function globalChatsDir(workspaceRoot: string): string {
  for (const entry of readdirSync(workspaceRoot, { withFileTypes: true })) {
    if (!entry.isDirectory()) continue;
    const candidate = path.join(workspaceRoot, entry.name, 'cloud', 'chats');
    if (existsSync(candidate)) return candidate;
  }
  throw new Error('global chats dir not found');
}

async function createProject(orkas: OrkasTestApp, name: string): Promise<void> {
  if (!orkas.page) throw new Error('Orkas renderer is unavailable');
  const page = orkas.page;
  const input = page.locator('#project-create-input');
  const row = page.locator('.project-row', {
    has: page.locator('.project-name', { hasText: name }),
  });
  const title = page.locator('#project-detail-title');
  const projectExists = async (): Promise<boolean> => {
    const result = await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list');
    return result.projects.some((project) => project.name === name);
  };
  // Project data can finish its initial refresh just after the shell becomes
  // ready. Retry the user action if that refresh replaces the inline editor,
  // but consult persisted state first so a delayed renderer update never turns
  // a successful attempt into a duplicate create.
  await expect(async () => {
    if (!await projectExists()) {
      if (!await input.isVisible()) await page.locator('#projects-add-btn').click();
      await input.fill(name);
      // Enter removes the inline editor synchronously after a successful create.
      // Send it through the page keyboard so Playwright does not keep waiting on
      // the locator action after its target has already been detached.
      await input.focus();
      await page.keyboard.press('Enter');
      await expect.poll(projectExists, { timeout: 3_000 }).toBe(true);
    }
    await expect(row).toHaveCount(1, { timeout: 3_000 });
    if (await title.textContent() !== name) {
      // Background project refresh can replace the row during the click.
      // Keep each attempt short so the outer result-based retry can reacquire it.
      await row.click({ timeout: 2_000 });
      await expect(title).toHaveText(name, { timeout: 3_000 });
    }
  }).toPass({ timeout: process.platform === 'win32' ? 30_000 : 20_000 });
  await expect(page.locator('#project-detail-title')).toHaveText(name);
  await expect(page.locator('.project-name', { hasText: name })).toHaveCount(1);
}

test.describe('projects', () => {
  test('selects and reveals a project opened outside the sidebar without pinning later scroll', async ({ orkas }, testInfo) => {
    const page = orkas.page!;
    let targetId = '';
    for (let index = 0; index < 24; index += 1) {
      const result = await orkas.invoke<{ project: { project_id: string } }>('projects.create', {
        name: `Navigation ${String(index).padStart(2, '0')} long project title`,
      });
      targetId = result.project.project_id;
    }
    await page.evaluate(() => (window as any).loadProjects(true));
    try {
      for (const [locale, width, height] of [['zh', 1440, 900], ['en', 900, 600]] as const) {
        await page.setViewportSize({ width, height });
        await page.evaluate((lang) => (window as any).setLang(lang), locale);
        await page.evaluate(() => {
          (window as any).setView('settings');
          const toggle = document.getElementById('projects-section-toggle')!;
          if (toggle.getAttribute('aria-expanded') === 'true') toggle.click();
          document.querySelector('.sidebar-conversation-nav')!.scrollTop = 0;
        });
        await expect(page.locator('#panel-settings')).toHaveClass(/\bactive\b/);
        await page.evaluate(pid => (window as any).setView('project', pid), targetId);
        const row = page.locator(`.project-row[data-pid="${targetId}"]`);
        await expect(row).toHaveClass(/\bactive\b/);
        await expect(page.locator('.project-row.active')).toHaveCount(1);
        await expect(page.locator('#project-detail-title')).toHaveText('Navigation 23 long project title');
        await expect.poll(async () => row.evaluate(el => {
          const bounds = el.getBoundingClientRect();
          const scroll = document.querySelector('.sidebar-conversation-nav')!.getBoundingClientRect();
          return bounds.top >= scroll.top && bounds.bottom <= scroll.bottom;
        })).toBe(true);
        await page.screenshot({ path: testInfo.outputPath(`project-navigation-${locale}.png`) });
        await page.evaluate(() => {
          document.querySelector('.sidebar-conversation-nav')!.scrollTop = 0;
          (window as any).renderProjectsSection();
        });
        expect(await page.locator('.sidebar-conversation-nav').evaluate(el => el.scrollTop)).toBe(0);
        await page.evaluate(() => (window as any).setView('settings'));
        await expect(page.locator('.project-row.active')).toHaveCount(0);
      }
    } finally {
      await page.evaluate(() => (window as any).setView('new-chat'));
    }
  });

  test('keeps member invitation visible as a commercial download guide', async ({ orkas }, testInfo) => {
    const projectName = 'E2E Invite Guide';
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');
    const page = orkas.page;
    const rendererRequests: string[] = [];
    page.on('request', request => {
      const url = new URL(request.url());
      if (url.protocol === 'http:' || url.protocol === 'https:') rendererRequests.push(url.origin + url.pathname);
    });
    await orkas.electronApp!.evaluate(({ shell, net }) => {
      const root = globalThis as any;
      root.__projectInviteExternalUrls = [];
      root.__projectEntryRequests = [];
      root.__projectBackgroundRequests = [];
      const backgroundRequests = new Set([
        'GET /api/config/client',
        'POST /api/marketplace/defaults',
        'POST /api/marketplace/agents/list',
        'POST /api/marketplace/agents/detail',
        'POST /api/marketplace/skills/list',
      ]);
      shell.openExternal = async (url: string) => { root.__projectInviteExternalUrls.push(url); };
      for (const owner of [root, net]) {
        const original = owner.fetch;
        owner.fetch = function (input: any, ...args: any[]) {
          const url = new URL(typeof input === 'string' ? input : input.url || String(input));
          const method = String(args[0]?.method || input?.method || 'GET').toUpperCase();
          // Startup refreshes can overlap this local project journey. Keep every
          // other endpoint, origin and method in the prohibited-request ledger.
          const isBackground = url.origin === 'https://orkas.ai'
            && backgroundRequests.has(`${method} ${url.pathname}`);
          (isBackground ? root.__projectBackgroundRequests : root.__projectEntryRequests)
            .push(url.origin + url.pathname);
          return original.call(this, input, ...args);
        };
      }
    });
    await createProject(orkas, projectName);
    await expect(page.locator('#project-detail-content')).toHaveAttribute('aria-busy', 'false');
    await expect(page.locator('#project-detail-content')).not.toHaveClass(/\bis-loading\b/);
    expect(await page.locator('#panel-project .project-detail-header').evaluate(header =>
      getComputedStyle(header, '::after').animationName)).toBe('none');
    const row = page.locator('.project-row', {
      has: page.locator('.project-name', { hasText: projectName }),
    });
    const cancelGuide = async () => {
      const guidance = await page.evaluate(() => (globalThis as any).t('project.invite_members.commercial_only'));
      const dialog = page.locator('.ui-dialog-overlay:visible');
      await expect(dialog.locator('.ui-dialog-message')).toHaveText(guidance);
      await expect(dialog.locator('[data-act="ok"]')).toBeVisible();
      await dialog.locator('[data-act="cancel"]').click();
      await expect(page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
      expect(await orkas.electronApp!.evaluate(() => (globalThis as any).__projectInviteExternalUrls)).toEqual([]);
      expect(await orkas.electronApp!.evaluate(() => (globalThis as any).__projectEntryRequests)).toEqual([]);
      expect(rendererRequests).toEqual([]);
      await expect(page.locator('#project-detail-title')).toHaveText(projectName);
      await expect(row).toHaveCount(1);
    };
    for (const { locale, width, inviteLabel } of [
      { locale: 'en', width: 1280, inviteLabel: 'Invite members' },
      { locale: 'zh', width: 800, inviteLabel: '邀请成员' },
    ]) {
      await page.setViewportSize({ width, height: 800 });
      await page.evaluate(lang => (globalThis as any).setLang(lang), locale);
      await page.locator('#project-action-more').click();
      const headerInvite = page.locator('.context-menu-item').getByText(inviteLabel, { exact: true });
      await expect(headerInvite).toBeVisible();
      await page.screenshot({ path: testInfo.outputPath(`project-header-invite-${locale}.png`) });
      await headerInvite.click();
      await cancelGuide();

      await row.hover();
      await row.locator('[data-project-menu]').click();
      const invite = page.locator('#project-row-menu [data-action="invite-members"]');
      await expect(invite).toHaveText(inviteLabel);
      await page.screenshot({ path: testInfo.outputPath(`project-sidebar-invite-${locale}.png`) });
      await invite.click();
      await cancelGuide();
    }
  });

  test('creates a project and keeps it after an app relaunch', async ({ orkas }) => {
    const projectName = 'E2E Persistent Project';
    await createProject(orkas, projectName);

    const relaunchedPage = await orkas.relaunch();
    const projectRow = relaunchedPage.locator('.project-row', {
      has: relaunchedPage.locator('.project-name', { hasText: projectName }),
    });
    await expect(projectRow).toHaveCount(1);
    await projectRow.click();
    await expect(relaunchedPage.locator('#panel-project')).toHaveClass(/\bactive\b/);
    await expect(relaunchedPage.locator('#project-detail-title')).toHaveText(projectName);
  });

  test('persists project instructions, memory, and to-do state across a relaunch', async ({ orkas }) => {
    const projectName = 'E2E Project Context';
    await createProject(orkas, projectName);
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');
    let page = orkas.page;

    // A project with no rules yet shows the empty state; the textarea lives in
    // the editor dialog behind it.
    await page.locator('#project-instructions-setup-btn').click();
    const instructions = page.locator('#project-instructions-input');
    await expect(instructions).toBeEnabled();
    await instructions.fill('Always verify generated artifacts before reporting completion.');
    await page.locator('#project-instructions-save-btn').click();
    await expect(page.locator('#project-instructions-save-btn')).toBeDisabled();
    await expect(page.locator('#project-instructions-modal')).not.toHaveClass(/open/);
    await expect(page.locator('#project-instructions-read')).toHaveText(
      'Always verify generated artifacts before reporting completion.',
    );

    await page.locator('[data-project-side-tabs="context"] [data-project-side-tab="memory"]').click();
    await expect(page.locator('[data-project-side-panel="memory"]')).toBeVisible();
    // No memory yet, so the empty state owns the call to action.
    await page.locator('#project-memory-add-empty-btn').click();
    await page.locator('#project-memory-editor-input').fill('The release checklist is the source of truth.');
    await page.locator('#project-memory-editor-save').click();
    await expect(page.locator('.project-memory-item', { hasText: 'The release checklist is the source of truth.' })).toBeVisible();

    await page.locator('[data-project-tab="todo"]').click();
    await expect(page.locator('[data-project-panel="todo"]')).toBeVisible();
    await page.locator('#project-todo-add-btn').click();
    await page.locator('#project-todo-input').fill('Run the desktop E2E regression');
    await page.locator('#project-todo-save').click();
    let todo = page.locator('.project-todo-item', { hasText: 'Run the desktop E2E regression' });
    await expect(todo).toHaveAttribute('data-status', 'todo');
    // Project and account cards share the same current-status chip on hover.
    const move = todo.locator('[data-action="todo-status"]');
    await expect(move).toHaveText('Pending');
    await page.locator('#project-detail-title').hover();
    await expect(move).toHaveCSS('opacity', '0');
    await todo.hover();
    await expect(move).toHaveCSS('opacity', '1');
    await move.click();
    await page.locator('.context-menu-item', { hasText: 'Done' }).click();
    await expect(todo).toHaveAttribute('data-status', 'done');

    page = await orkas.relaunch();
    const projectRow = page.locator('.project-row', {
      has: page.locator('.project-name', { hasText: projectName }),
    });
    await projectRow.click();
    await expect(page.locator('#project-instructions-read')).toHaveText(
      'Always verify generated artifacts before reporting completion.',
    );
    await page.locator('[data-project-side-tabs="context"] [data-project-side-tab="memory"]').click();
    const memory = page.locator('.project-memory-item', { hasText: 'The release checklist is the source of truth.' });
    await expect(memory).toBeVisible();
    await page.locator('[data-project-tab="todo"]').click();
    await expect(page.locator('[data-project-panel="todo"]')).toBeVisible();
    todo = page.locator('.project-todo-item', { hasText: 'Run the desktop E2E regression' });
    await expect(todo).toHaveAttribute('data-status', 'done');
    await expect(todo.locator('[data-action="todo-menu"]')).toHaveCount(1);

    // The card no longer exposes an overflow menu. Remove the fixture through
    // the owning IPC boundary after persistence has been observed so this case
    // does not preserve an obsolete UI action merely for cleanup.
    const projectRows = await orkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');
    const projectId = projectRows.projects.find((project) => project.name === projectName)?.project_id;
    const taskId = await todo.getAttribute('data-tid');
    expect(projectId).toBeTruthy();
    expect(taskId).toBeTruthy();
    await orkas.invoke('projects.tasks.delete', { projectId, taskId });
    await expect(todo).toHaveCount(0);
    await page.locator('[data-project-tab="tasks"]').click();
    // Memory actions become interactive when the user hovers the entry.
    await memory.hover();
    await memory.locator('[data-action="project-memory-delete"]').click();
    await expect(page.locator('.ui-dialog-overlay:visible .ui-dialog')).toBeVisible();
    await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();
    await expect(memory).toHaveCount(0);
  });

  test('locks unreadable project instructions and restores the saved rules after recovery', async ({ orkas }) => {
    const name = 'E2E Instructions Read Recovery';
    const original = 'Keep the approved venue and do not contact vendors.';
    await createProject(orkas, name);
    const page = orkas.page!;
    const listed = await orkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');
    const projectId = listed.projects.find(project => project.name === name)!.project_id;
    await orkas.invoke('projects.instructions.set', { projectId, content: original });
    await expect(page.locator('#project-instructions-read')).toHaveText(original);
    const file = readdirSync(orkas.workspaceRoot)
      .map(uid => path.join(orkas.workspaceRoot, uid, 'cloud', 'projects', projectId, 'ORKAS.md'))
      .find(candidate => existsSync(candidate))!;
    expect(file).toBeTruthy();
    const preserved = file + '.preserved';
    // A directory at the file path triggers a real read failure without
    // relying on permission bits that elevated users or Windows may ignore.
    renameSync(file, preserved);
    mkdirSync(file);
    try {
      await page.evaluate(pid => (window as any).loadProjectDetail(pid), projectId);
      await expect(page.locator('#project-instructions-input')).toBeDisabled();
      await expect(page.locator('#project-instructions-edit-btn')).toBeDisabled();
      await expect(page.locator('#project-instructions-setup-btn')).toBeDisabled();
      await expect(page.locator('#project-instructions-save-btn')).toBeDisabled();
      await expect(page.locator('#project-instructions-modal')).not.toHaveClass(/open/);
      expect(readFileSync(preserved, 'utf8')).toBe(original);
    } finally {
      rmdirSync(file);
      renameSync(preserved, file);
    }
    await page.evaluate(pid => (window as any).loadProjectDetail(pid), projectId);
    await expect(page.locator('#project-instructions-read')).toHaveText(original);
    await page.locator('#project-instructions-edit-btn').click();
    await expect(page.locator('#project-instructions-input')).toHaveValue(original);
    await page.locator('#project-instructions-input').fill('Unsaved recovery draft.');
    await page.locator('#project-instructions-cancel-btn').click();
    expect(await orkas.invoke('projects.instructions.get', { projectId })).toMatchObject({ content: original });
    await expect(page.locator('#project-instructions-read')).toHaveText(original);
  });

  test('uploads, previews, persists, and deletes a project Library file', async ({ orkas }) => {
    const projectName = 'E2E Project Library';
    const fileName = 'E2E project source.md';
    const source = orkas.createFixtureFile(fileName, '# Project Library\n\nUnique project-only preview body.\n');
    await createProject(orkas, projectName);
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');
    let page = orkas.page;

    await page.locator('[data-project-side-tabs="resources"] [data-project-side-tab="files"]').click();
    await expect(page.locator('[data-project-side-panel="files"]')).toBeVisible();
    await orkas.selectFilesOnNextDialog([source]);
    await page.locator('#project-library-root-menu-btn').click();
    await page.locator('#project-file-row-menu [data-action="upload"]').click();

    let row = page.locator(`.project-file-row[data-project-file="${fileName}"]`);
    await expect(row).toBeVisible();
    await expect(page.locator('#project-detail-files-count')).toHaveText('1');
    await row.locator(':scope > .skill-tree-node').click();
    const viewer = page.locator('#project-library-viewer-modal');
    await expect(viewer).toHaveClass(/\bopen\b/);
    await expect(page.locator('#project-library-editor-path')).toHaveText(fileName);
    await expect(page.locator('#project-library-viewer-body')).toContainText('Unique project-only preview body.');
    await viewer.locator('[data-action="project-library-viewer-close"]').click();
    await expect(viewer).not.toHaveClass(/\bopen\b/);

    const projects = await orkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');
    const projectId = projects.projects.find((project) => project.name === projectName)!.project_id;
    await expectProjectFileReady(orkas, projectId, fileName);
    page = await orkas.relaunch();
    await page.locator('.project-row', {
      has: page.locator('.project-name', { hasText: projectName }),
    }).click();
    await page.locator('[data-project-side-tabs="resources"] [data-project-side-tab="files"]').click();
    row = page.locator(`.project-file-row[data-project-file="${fileName}"]`);
    await expect(row).toBeVisible();
    await row.hover();
    await row.locator('[data-action="project-file-menu"]').click();
    await page.locator('#project-file-row-menu [data-action="delete"]').click();
    await expect(page.locator('.ui-dialog-overlay:visible .ui-dialog')).toBeVisible();
    await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();
    await expect(row).toHaveCount(0);
    await expect(page.locator('#project-detail-files-count')).toBeEmpty();
  });

  test('adds an attachment from the project composer and adopts it into the new conversation', async ({
    modelOrkas,
  }) => {
    if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
    const page = modelOrkas.page;
    const projectName = 'E2E Project Composer Attachment';
    const fileName = 'E2E project conversation brief.md';
    const sourcePath = modelOrkas.createFixtureFile(
      fileName,
      '# Project conversation attachment\n\nUnique project attachment body.\n',
    );
    await createProject(modelOrkas, projectName);
    const projects = await modelOrkas.invoke<{
      projects: Array<{ project_id: string; name: string }>;
    }>('projects.list');
    const projectId = projects.projects.find((item) => item.name === projectName)?.project_id;
    expect(projectId).toBeTruthy();

    await modelOrkas.selectFilesOnNextDialog([sourcePath]);
    await page.locator('#project-chat-attach-btn').click();
    const attachment = page.locator('#project-chat-attachments .chat-attach-chip', {
      hasText: fileName,
    });
    await expect(attachment).toBeVisible();
    await expect(attachment).not.toHaveClass(/\bis-uploading\b/);
    await expect.poll(async () => {
      const result = await modelOrkas.invoke<{
        items: Array<{ name: string }>;
      }>('conversations.attachments.list', {
        cid: `projchat-${projectId}`,
      });
      return result.items.map((item) => item.name);
    }).toEqual([fileName]);
    const projectFiles = await modelOrkas.invoke<{ files: Array<{ name: string }> }>(
      'projects.files.list',
      { projectId },
    );
    expect(projectFiles.files.map((file) => file.name)).not.toContain(fileName);

    modelOrkas.setModelTextReplies(['E2E project attachment received.']);
    await page.locator('#project-chat-input').fill('Use the attached project brief.');
    await page.locator('#project-chat-send-btn').click();
    await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
      'E2E project attachment received.',
      { timeout: 20_000 },
    );
    const userMessage = page.locator('#chat-history .chat-message.user');
    await expect(userMessage).toContainText(fileName);
    expect(JSON.stringify(modelOrkas.modelRequests[0])).toContain(fileName);

    const conversations = await modelOrkas.invoke<{
      conversations: Array<{ conversation_id: string; project_id?: string }>;
    }>('conversations.list');
    const conversation = conversations.conversations.find((item) => item.project_id === projectId);
    expect(conversation?.conversation_id).toBeTruthy();
    const remainingDraft = await modelOrkas.invoke<{ items: unknown[] }>(
      'conversations.attachments.list',
      { cid: `projchat-${projectId}` },
    );
    expect(remainingDraft.items).toHaveLength(0);
  });

  test('adds a produced file to the owning Project Library and confirms the destination', async ({
    modelOrkas,
  }) => {
    if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
    const page = modelOrkas.page;
    const fileName = 'produced-project-library-e2e.png';
    const projectName = 'E2E Produced Project Library';
    const taskText = 'Create an image deliverable for the Project Library regression.';
    await createProject(modelOrkas, projectName);
    const projects = await modelOrkas.invoke<{
      projects: Array<{ project_id: string; name: string }>;
    }>('projects.list');
    const projectId = projects.projects.find((item) => item.name === projectName)?.project_id;
    expect(projectId).toBeTruthy();
    modelOrkas.setModelTextReplies(['E2E image deliverable is ready.']);
    await page.locator('#project-chat-input').fill(taskText);
    await page.locator('#project-chat-send-btn').click();
    await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
      'E2E image deliverable is ready.',
      { timeout: 20_000 },
    );
    const conversations = await modelOrkas.invoke<{
      conversations: Array<{ conversation_id: string; project_id?: string }>;
    }>('conversations.list');
    const cid = conversations.conversations.find((item) => item.project_id === projectId)?.conversation_id;
    expect(cid).toBeTruthy();
    const workspace = await modelOrkas.invoke<{ root: string }>('conversations.files.list', { cid });
    mkdirSync(workspace.root, { recursive: true });
    writeFileSync(
      path.join(workspace.root, fileName),
      Buffer.from(
        'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
        'base64',
      ),
    );

    await page.locator('#conversation-info-toggle').click();
    const row = page.locator('.conversation-info-file', { hasText: fileName });
    await expect(row).toBeVisible();
    await row.hover();
    await row.locator('.conversation-info-file-menu-btn').click();
    const addAction = page.locator('#conversation-info-file-menu [data-action="add-to-library"]');
    await expect(addAction).toHaveCount(1);
    // The live workspace refresh can close this transient menu between
    // Playwright's actionability checks. Dispatch the already-bound DOM action
    // so this E2E remains about the full renderer → IPC → persisted-result
    // contract instead of timing the hover-only menu surface.
    await addAction.dispatchEvent('click');

    await expect(page.locator('.ui-toast.is-success')).toContainText('Added to Project Library');
    await expect.poll(async () => {
      const result = await modelOrkas.invoke<{
        files: Array<{ name: string }>;
      }>('projects.files.list', { projectId });
      return result.files.map((file) => file.name);
    }).toContain(fileName);
    const globalTree = await modelOrkas.invoke<{ tree: unknown }>('contexts.tree');
    expect(JSON.stringify(globalTree.tree)).not.toContain(fileName);
    await expectProjectFileReady(modelOrkas, projectId!, fileName);
  });

  test('injects project context into a self-contained model conversation and keeps its assignment', async ({
    modelOrkas,
  }) => {
    const projectName = 'E2E Project Conversation';
    const projectInstructions = 'E2E_PROJECT_POLICY: report release status with an explicit verification note.';
    const projectMemory = 'E2E_PROJECT_MEMORY: the desktop regression is the release source of truth.';
    const modelReply = 'E2E project context reached the model without a history lookup.';
    await createProject(modelOrkas, projectName);
    if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
    const page = modelOrkas.page;
    const project = await modelOrkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');
    const projectId = project.projects.find((item) => item.name === projectName)?.project_id;
    expect(projectId).toBeTruthy();
    await modelOrkas.invoke('projects.instructions.set', {
      projectId,
      content: projectInstructions,
    });
    await modelOrkas.invoke('memory.add', {
      target: 'project',
      projectId,
      content: projectMemory,
    });
    modelOrkas.setModelTextReplies([modelReply]);

    await page.locator('#project-chat-input').fill('Give a self-contained status update for this project.');
    await page.locator('#project-chat-send-btn').click();
    await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
    await expect(page.locator('#chat-history .chat-message.user')).toContainText(
      'Give a self-contained status update for this project.',
    );
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
      modelReply,
      { timeout: 20_000 },
    );
    await expect.poll(() => modelOrkas.modelRequests.length).toBe(1);
    const modelRequest = JSON.stringify(modelOrkas.modelRequests[0]);
    expect(modelRequest).toContain(projectInstructions);
    expect(modelRequest).toContain(projectMemory);
    expect(modelRequest).toContain('Project context policy');

    const conversations = await modelOrkas.invoke<{
      conversations: Array<{ conversation_id: string; project_id?: string }>;
    }>('conversations.list');
    const projectConversation = conversations.conversations.find((item) => item.project_id === projectId);
    expect(projectConversation).toBeTruthy();
    const conversationId = projectConversation?.conversation_id;

    await page.locator('.project-row', {
      has: page.locator('.project-name', { hasText: projectName }),
    }).click();
    await expect(page.locator('#panel-project')).toHaveClass(/\bactive\b/);
    await expect(page.locator('#project-tasks-count')).toHaveText('1');
    await expect(page.locator(`#project-tasks-list .conv-item[data-cid="${conversationId}"]`)).toBeVisible();
  });

  test('lets Commander replace project instructions and injects the saved result on the next turn', async ({
    modelOrkas,
  }) => {
    const projectName = 'E2E Commander Instructions';
    const original = 'Keep release links without www.';
    const replacement = `${original}\nAll customer copy must be English.`;
    const toolReply = 'E2E project instructions were updated through Commander.';
    const nextTurnReply = 'E2E refreshed project instructions reached the next turn.';
    await createProject(modelOrkas, projectName);
    if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
    const page = modelOrkas.page;
    const listed = await modelOrkas.invoke<{
      projects: Array<{ project_id: string; name: string }>;
    }>('projects.list');
    const projectId = listed.projects.find((item) => item.name === projectName)?.project_id;
    expect(projectId).toBeTruthy();
    await modelOrkas.invoke('projects.instructions.set', {
      projectId,
      content: original,
    });
    modelOrkas.setProjectInstructionsScenario(replacement, toolReply);

    await page.locator('#project-chat-input').fill(
      'Keep the existing project instructions and add that all customer copy must be English.',
    );
    await page.locator('#project-chat-send-btn').click();
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body')).toContainText(
      toolReply,
      { timeout: 20_000 },
    );
    await expect.poll(() => modelOrkas.modelRequests.length).toBe(2);
    expect(JSON.stringify(modelOrkas.modelRequests[0])).toContain(original);
    expect(JSON.stringify(modelOrkas.modelRequests[1])).toMatch(/ok\\?":true/);
    await expect.poll(async () => (
      await modelOrkas.invoke<{ content: string }>('projects.instructions.get', { projectId })
    ).content).toBe(replacement);

    // A visible final body can precede stream teardown. Wait until this
    // control is Send; clicking it while streaming invokes Stop instead.
    await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
    modelOrkas.clearModelToolScenario();
    modelOrkas.setModelTextReplies([nextTurnReply]);
    await page.locator('#chat-input').fill('Confirm the current project rules.');
    await page.locator('#chat-send-btn').click();
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
      hasText: nextTurnReply,
    })).toBeVisible({ timeout: 20_000 });
    await expect.poll(() => modelOrkas.modelRequests.length).toBe(3);
    const nextTurnRequest = JSON.stringify(modelOrkas.modelRequests[2]);
    expect(nextTurnRequest).toContain(original);
    expect(nextTurnRequest).toContain('All customer copy must be English.');

    await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
    const concurrentUiEdit = `${replacement}\nUse the July launch checklist.`;
    const staleModelReplacement = `${replacement}\nPublish on Friday.`;
    const conflictReply = 'E2E stale project-instructions replacement was rejected.';
    // Hold the tool response until the concurrent edit is actually persisted.
    // A fixed delay races the IPC round trip on a busy host and can test the
    // opposite ordering, where accepting the tool write is correct.
    let releaseTool!: () => void;
    const beforeTool = new Promise<void>((resolve) => { releaseTool = resolve; });
    modelOrkas.setProjectInstructionsScenario(staleModelReplacement, conflictReply, { beforeTool });
    await page.locator('#chat-input').fill('Also add that publishing happens on Friday.');
    await page.locator('#chat-send-btn').click();
    try {
      await expect.poll(() => modelOrkas.modelRequests.length).toBe(4);
      await modelOrkas.invoke('projects.instructions.set', {
        projectId,
        content: concurrentUiEdit,
      });
    } finally { releaseTool(); }
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
      hasText: conflictReply,
    })).toBeVisible({ timeout: 20_000 });
    await expect.poll(() => modelOrkas.modelRequests.length).toBe(5);
    expect(JSON.stringify(modelOrkas.modelRequests[4])).toContain(
      'conflict: project instructions changed after this turn started',
    );
    expect(await modelOrkas.invoke<{ content: string }>(
      'projects.instructions.get',
      { projectId },
    )).toMatchObject({ content: concurrentUiEdit });
  });

  test('finds an earlier project conversation, reads the evidence, and keeps the continuation after relaunch', async ({
    modelOrkas,
  }) => {
    const projectName = 'E2E Project History';
    const historyQuery = 'E2E_NIMBUS_PAYMENTS';
    const sourceReply = [
      `${historyQuery}: use AcmePay as the provider.`,
      'Keep RMB settlement and make refunds idempotent.',
    ].join(' ');
    const finalReply = 'Continued with AcmePay, RMB settlement, and idempotent refunds—no restatement needed.';
    await createProject(modelOrkas, projectName);
    if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
    let page = modelOrkas.page;
    const projects = await modelOrkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');
    const projectId = projects.projects.find((item) => item.name === projectName)?.project_id;
    expect(projectId).toBeTruthy();

    modelOrkas.setModelTextReplies([sourceReply]);
    await page.locator('#project-chat-input').fill('Record the Nimbus payments decision for this project.');
    await page.locator('#project-chat-send-btn').click();
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
      sourceReply,
      { timeout: 20_000 },
    );
    await expect.poll(() => modelOrkas.modelRequests.length).toBe(1);
    const sourceConversations = await modelOrkas.invoke<{
      conversations: Array<{ conversation_id: string; project_id?: string }>;
    }>('conversations.list');
    const sourceCid = sourceConversations.conversations.find(
      (item) => item.project_id === projectId,
    )?.conversation_id;
    expect(sourceCid).toBeTruthy();

    await page.locator('.project-row', {
      has: page.locator('.project-name', { hasText: projectName }),
    }).click();
    modelOrkas.setProjectHistoryScenario(historyQuery, sourceCid!, finalReply);
    await page.locator('#project-chat-input').fill(
      'Continue the earlier Nimbus payments plan from this project. Do not make me repeat its constraints.',
    );
    await page.locator('#project-chat-send-btn').click();
    await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
      finalReply,
      { timeout: 20_000 },
    );
    await expect.poll(() => modelOrkas.modelRequests.length).toBe(4);

    const searchFollowUp = JSON.stringify(modelOrkas.modelRequests[2]);
    const readFollowUp = JSON.stringify(modelOrkas.modelRequests[3]);
    expect(searchFollowUp).toContain(sourceCid);
    expect(searchFollowUp).toContain(historyQuery);
    expect(searchFollowUp).toMatch(new RegExp(`cid=${sourceCid} msg=\\d+`));
    expect(readFollowUp).toContain(`<chat-history cid=\\"${sourceCid}\\"`);
    expect(readFollowUp).toContain(sourceReply);
    await expect(page.locator('#chat-history .chat-message.assistant')).not.toContainText(
      /please.{0,20}(?:repeat|restate)|请.{0,20}(?:重复|重述)/i,
    );
    await expect(
      page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])'),
    ).not.toContainText(/chat_history|<chat-history/i);

    const allConversations = await modelOrkas.invoke<{
      conversations: Array<{ conversation_id: string; project_id?: string }>;
    }>('conversations.list');
    const continuationCid = allConversations.conversations.find(
      (item) => item.project_id === projectId && item.conversation_id !== sourceCid,
    )?.conversation_id;
    expect(continuationCid).toBeTruthy();
    const requestsBeforeRelaunch = modelOrkas.modelRequests.length;

    page = await modelOrkas.relaunch();
    await page.locator('.project-row', {
      has: page.locator('.project-name', { hasText: projectName }),
    }).click();
    await page.locator(`#project-tasks-list .conv-item[data-cid="${continuationCid}"]`).click();
    await expect(page.locator('#chat-history .chat-message.assistant', {
      hasText: finalReply,
    })).toHaveCount(1);
    expect(modelOrkas.modelRequests).toHaveLength(requestsBeforeRelaunch);
  });

  test('binds a project agent, selects it as recipient, and removes it', async ({ orkas }) => {
    const createdAgent = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
      name: 'E2EProjectAgent',
      description: 'A project-scoped test agent.',
      category: 'general',
    });
    await createProject(orkas, 'E2E Agent Binding Project');
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');
    const page = orkas.page;

    await page.locator('#project-add-agent-btn').click();
    const picker = page.locator('#project-binding-picker-overlay');
    await expect(picker).toBeVisible();
    const pickerDialog = picker.locator('.project-binding-picker-modal');
    const headerCenters = await pickerDialog.evaluate((dialog) => {
      const title = dialog.querySelector('.project-binding-picker-title')!.getBoundingClientRect();
      const close = dialog.querySelector('.project-binding-picker-close')!.getBoundingClientRect();
      return [title.top + title.height / 2, close.top + close.height / 2];
    });
    expect(Math.abs(headerCenters[0] - headerCenters[1])).toBeLessThan(2);
    const searchInput = picker.locator('#project-binding-picker-search-input');
    const initialPickerHeight = await pickerDialog.evaluate((element) => element.getBoundingClientRect().height);
    await expect(searchInput).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)');
    await searchInput.fill('E2E-no-such-project-agent');
    await expect(picker.locator('#project-binding-picker-empty')).toBeVisible();
    const emptyPickerHeight = await pickerDialog.evaluate((element) => element.getBoundingClientRect().height);
    expect(emptyPickerHeight).toBeCloseTo(initialPickerHeight, 1);
    await searchInput.fill('E2EProjectAgent');
    const candidate = picker.locator('.project-binding-picker-item', { hasText: 'E2EProjectAgent' });
    await expect(candidate).toBeVisible();
    const filteredPickerHeight = await pickerDialog.evaluate((element) => element.getBoundingClientRect().height);
    expect(filteredPickerHeight).toBeCloseTo(initialPickerHeight, 1);
    await candidate.locator('[data-action="pick"]').click();
    await picker.locator('[data-action="close"]').click();

    const bound = page.locator(`.project-agent-row[data-project-agent-id="${createdAgent.agent.agent_id}"]`);
    await expect(bound).toContainText('E2EProjectAgent');
    const projects = await orkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');
    const projectId = projects.projects.find((item) => item.name === 'E2E Agent Binding Project')?.project_id;
    const bindings = await orkas.invoke<{ bindings: { agents: string[] } }>('projects.bindings.list', { projectId });
    expect(bindings.bindings.agents).toContain(createdAgent.agent.agent_id);

    await bound.hover();
    await bound.locator('[data-project-agent-run]').click();
    await expect(page.locator('#project-chat-recipient-name')).toHaveText('E2EProjectAgent');
    await bound.hover();
    await bound.locator('[data-project-agent-remove]').click();
    await expect(bound).toHaveCount(0);
    const removed = await orkas.invoke<{ bindings: { agents: string[] } }>('projects.bindings.list', { projectId });
    expect(removed.bindings.agents).not.toContain(createdAgent.agent.agent_id);
  });

  test('rejects a duplicate project name without losing the editor', async ({ orkas }) => {
    const projectName = 'E2E Unique Project';
    await createProject(orkas, projectName);
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');

    await orkas.page.locator('#projects-add-btn').click();
    const input = orkas.page.locator('#project-create-input');
    await input.fill(projectName);
    await input.press('Enter');

    await expect(input).toHaveValue(projectName);
    await expect(input).toHaveClass(/\bis-error\b/);
    await expect(input.locator('xpath=..').locator('.project-inline-error')).toBeVisible();
    await expect(input).toBeFocused();
    await expect(orkas.page.locator('.project-name', { hasText: projectName })).toHaveCount(1);

    const correctedName = 'E2E Unique Project Retry';
    await input.fill(correctedName);
    await input.press('Enter');
    const projectNames = orkas.page.locator('.project-name');
    await expect.poll(async () => (
      await projectNames.allTextContents()
    ).filter((name) => name === correctedName).length).toBe(1);
    await expect.poll(async () => (
      await projectNames.allTextContents()
    ).filter((name) => name === projectName).length).toBe(1);
  });

  test('keeps an unsaved project draft focused without creating it during a background refresh', async ({
    orkas,
  }) => {
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');
    const draftName = 'E2E Unsaved Project Draft';
    await orkas.page.locator('#projects-add-btn').click();
    let input = orkas.page.locator('#project-create-input');
    await input.fill(draftName);
    await expect(input).toBeFocused();

    await orkas.page.evaluate(async () => {
      await (window as any).loadProjects(true);
    });

    input = orkas.page.locator('#project-create-input');
    await expect(input).toHaveValue(draftName);
    await expect(input).toBeFocused();
    const listed = await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list');
    expect(listed.projects.some((project) => project.name === draftName)).toBe(false);
    await input.press('Escape');
    await expect(input).toHaveCount(0);
    const afterCancel = await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list');
    expect(afterCancel.projects.some((project) => project.name === draftName)).toBe(false);
  });

  for (const [locale, width, height] of [['zh', 1280, 900], ['en', 960, 720]] as const) {
    test(`renames a project and keeps the new name after relaunch (${locale})`, async ({ orkas }, testInfo) => {
      const originalName = 'E2E Project Before Rename';
      const renamedName = 'E2E Project After Rename';
      await createProject(orkas, originalName);
      if (!orkas.page) throw new Error('Orkas renderer is unavailable');

      await orkas.page.setViewportSize({ width, height });
      await orkas.page.evaluate(lang => (window as any).setLang(lang), locale);
      const composer = orkas.page.locator('#project-chat-input');
      await composer.fill('Keep this unsent project draft');
      await orkas.page.evaluate(() => (window as any).composerSetSelection('project-chat-input', 3, 7));
      const composerNode = await composer.elementHandle();

      const originalRow = orkas.page.locator('.project-row', {
        has: orkas.page.locator('.project-name', { hasText: originalName }),
      });
      await originalRow.hover();
      const renameMenuButton = originalRow.locator('[data-project-menu]');
      await expect(renameMenuButton).toBeVisible();
      await renameMenuButton.click();
      await orkas.page.locator('#project-row-menu [data-action="rename"]').click();
      const renameInput = orkas.page.locator('input.project-rename-input[data-rename-pid]');
      await expect(renameInput).toBeFocused();
      await renameInput.fill(renamedName);
      await renameInput.press('Enter');

      await expect(orkas.page.locator('.project-name', { hasText: originalName })).toHaveCount(0);
      await expect(orkas.page.locator('.project-name', { hasText: renamedName })).toHaveCount(1);

      await expect(orkas.page.locator('#project-detail-title')).toHaveText(renamedName);
      expect(await orkas.page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('Keep this unsent project draft');
      expect(await composerNode!.evaluate(el => el === document.getElementById('project-chat-input'))).toBe(true);
      expect(await orkas.page.evaluate(() => (window as any).composerSelection('project-chat-input'))).toEqual({ start: 3, end: 7 });
      await orkas.page.screenshot({ path: testInfo.outputPath(`project-sidebar-rename-${locale}.png`) });

      const relaunchedPage = await orkas.relaunch();
      const renamedRow = relaunchedPage.locator('.project-row', {
        has: relaunchedPage.locator('.project-name', { hasText: renamedName }),
      });
      await expect(renamedRow).toHaveCount(1);
      await renamedRow.click();
      await expect(relaunchedPage.locator('#project-detail-title')).toHaveText(renamedName);
    });

  }

  // The project page header keeps only the title; invite, rename and delete live in its
  // "⋯" menu, and "Done" stands in for the menu while the title is edited.
  test('renames from the project header menu and keeps delete behind its confirmation', async ({ orkas }, testInfo) => {
    const originalName = 'E2E Header Rename Before';
    const renamedName = 'E2E Header Rename After';
    await createProject(orkas, originalName);
    const page = orkas.page!;
    await expect(page.locator('#project-action-invite')).toHaveCount(0);
    const more = page.locator('#project-action-more');
    const done = page.locator('#project-action-rename');
    const title = page.locator('#project-detail-title');
    await expect(more).toBeVisible();
    await expect(done).toBeHidden();
    await more.click();
    await expect(page.locator('.context-menu-item')).toHaveText(['Invite members', 'Rename', 'Delete']);
    await page.screenshot({ path: testInfo.outputPath('project-header-local-actions.png') });
    await page.locator('.context-menu-item', { hasText: 'Rename' }).click();
    const input = page.locator('#project-detail-title-input');
    await expect(input).toBeFocused();
    await expect(input).toHaveValue(originalName);
    await expect(more).toBeHidden();
    await expect(done).toHaveText('Done');
    await page.locator('#panel-project .project-detail-header').screenshot({ path: testInfo.outputPath('project-header-rename-mode.png') });
    await input.fill(renamedName);
    await done.click();
    await expect(title).toHaveText(renamedName);
    await expect(done).toBeHidden();
    await expect(more).toBeVisible();
    await expect.poll(async () => (await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list'))
      .projects.some((project) => project.name === renamedName)).toBe(true);

    await more.click();
    await page.locator('.context-menu-item', { hasText: 'Delete' }).click();
    await expect(page.locator('.ui-dialog-overlay:visible .ui-dialog-danger')).toBeVisible();
    await page.locator('.ui-dialog-overlay:visible [data-act="cancel"]').click();
    await expect(page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
    await expect(title).toHaveText(renamedName);
    const listed = await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list');
    expect(listed.projects.some((project) => project.name === renamedName)).toBe(true);
  });

  test('keeps an unsaved rename draft without applying it during a background refresh', async ({
    orkas,
  }) => {
    const originalName = 'E2E Rename Refresh Original';
    const draftName = 'E2E Rename Refresh Draft';
    await createProject(orkas, originalName);
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');

    const originalRow = orkas.page.locator('.project-row', {
      has: orkas.page.locator('.project-name', { hasText: originalName }),
    });
    await originalRow.hover();
    await originalRow.locator('[data-project-menu]').click();
    await orkas.page.locator('#project-row-menu [data-action="rename"]').click();
    let input = orkas.page.locator('input.project-rename-input[data-rename-pid]');
    await input.fill(draftName);
    await expect(input).toBeFocused();

    await orkas.page.evaluate(async () => {
      await (window as any).loadProjects(true);
    });

    input = orkas.page.locator('input.project-rename-input[data-rename-pid]');
    await expect(input).toHaveValue(draftName);
    await expect(input).toBeFocused();
    const listed = await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list');
    expect(listed.projects.some((project) => project.name === originalName)).toBe(true);
    expect(listed.projects.some((project) => project.name === draftName)).toBe(false);
    await input.press('Escape');
    await expect(orkas.page.locator('.project-name', { hasText: originalName })).toHaveCount(1);
    await expect(orkas.page.locator('.project-name', { hasText: draftName })).toHaveCount(0);
  });

  test('cancels deletion, then deletes and restores a project from the recycle bin', async ({ orkas }) => {
    const projectName = 'E2E Recyclable Project';
    await createProject(orkas, projectName);
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');
    const page = orkas.page;
    const projectNameLocator = page.locator('.project-name', { hasText: projectName });
    const listed = await orkas.invoke<{
      projects: Array<{ project_id: string; name: string }>;
    }>('projects.list');
    const projectId = listed.projects.find((project) => project.name === projectName)?.project_id;
    expect(projectId).toBeTruthy();
    const sourceName = 'recyclable-source.md';
    await orkas.invoke('projects.files.upload', {
      projectId,
      name: sourceName,
      data: Buffer.from('Project deletion must remove derived vectors.').toString('base64'),
    });
    await expect.poll(async () => {
      const status = await orkas.invoke<{
        files: Array<{ path: string; status: string }>;
      }>('projects.files.status', { projectId });
      return status.files.find((file) => file.path === sourceName)?.status;
    }).toBe('ready');
    const localProjectDir = path.join(
      orkas.workspaceRoot,
      'account-e2e',
      'local',
      'projects',
      projectId!,
    );
    expect(existsSync(localProjectDir)).toBe(true);

    const openDeleteDialog = async (): Promise<void> => {
      const row = page.locator('.project-row', { has: projectNameLocator });
      await row.hover();
      const menuButton = row.locator('[data-project-menu]');
      await expect(menuButton).toBeVisible();
      await menuButton.click();
      await page.locator('#project-row-menu [data-action="delete"]').click();
      await expect(page.locator('.ui-dialog-overlay:visible .ui-dialog-danger')).toBeVisible();
    };

    await openDeleteDialog();
    await page.locator('.ui-dialog-overlay:visible [data-act="cancel"]').click();
    await expect(page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
    await expect(projectNameLocator).toHaveCount(1);
    expect(existsSync(localProjectDir)).toBe(true);

    await openDeleteDialog();
    await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();
    await expect(projectNameLocator).toHaveCount(0, { timeout: 30_000 });
    await expect(page.locator('#panel-new-chat')).toHaveClass(/\bactive\b/);
    await expect.poll(() => existsSync(localProjectDir)).toBe(false);

    await page.locator('#settings-btn').click();
    await page.locator('.settings-tab[data-settings-tab="data"]').click();
    const recycleRow = page.locator('.settings-recycle-row', { hasText: projectName });
    const restoreButton = recycleRow.locator('[data-recycle-restore]');
    await expect(restoreButton).toBeVisible();
    await restoreButton.click();
    await expect(page.locator('.ui-dialog-overlay:visible .ui-dialog')).toBeVisible();
    await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();

    await expect(projectNameLocator).toHaveCount(1);
    await expect(recycleRow).toBeVisible();
    await expect(restoreButton).toBeEnabled();
    await expect.poll(async () => {
      const status = await orkas.invoke<{
        files: Array<{ path: string; status: string }>;
      }>('projects.files.status', { projectId });
      return status.files.find((file) => file.path === sourceName)?.status;
    }).toBe('ready');
    const relaunchedPage = await orkas.relaunch();
    await expect(relaunchedPage.locator('.project-name', { hasText: projectName })).toHaveCount(1);
  });

  // Filing a loose task under a project relocates its messages, sessions,
  // attachments and artifacts on disk, so the check is that the task still
  // opens and reads the same afterwards — not just that a row moved.
  test('keeps the conversation project picker modal and settles replaced pickers', async ({ orkas }) => {
    const page = orkas.page!;
    await page.evaluate(() => {
      const host = window as any;
      host.__pickerResult = 'pending';
      host._openConversationProjectPicker([{ project_id: 'p_one', name: 'One' }])
        .then((result: unknown) => { host.__pickerResult = result; });
    });
    const overlay = page.locator('#conv-project-picker-overlay');
    const row = overlay.locator('.conv-project-pick-row');
    await expect(row).toBeFocused();
    await page.keyboard.press('Shift+Tab');
    await expect(overlay.locator('[data-act="cancel"]')).toBeFocused();
    await page.keyboard.press('Tab');
    await expect(row).toBeFocused();
    await page.evaluate(() => {
      const host = window as any;
      host.__replacementResult = 'pending';
      host._openConversationProjectPicker([{ project_id: 'p_two', name: 'Two' }])
        .then((result: unknown) => { host.__replacementResult = result; });
    });
    await expect.poll(() => page.evaluate(() => (window as any).__pickerResult)).toBe(null);
    await expect(overlay.locator('.conv-project-pick-row')).toHaveText('Two');
    await page.keyboard.press('Escape');
    await expect(overlay).toHaveCount(0);
    await expect.poll(() => page.evaluate(() => (window as any).__replacementResult)).toBe(null);
    await page.evaluate(() => { (window as any)._openConversationProjectPicker([]); });
    await expect(overlay.locator('[data-act="new"]')).toBeFocused();
    await expect(overlay.locator('[data-act="ok"]')).toBeDisabled();
    await page.keyboard.press('Escape');
    await expect(overlay).toHaveCount(0);

  });

  test('hides commander-only agents and scrolls long project and agent lists inside the panel', async ({ orkas }, testInfo) => {
    const page = orkas.page!;
    const { conversation } = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Commander only' });
    await page.evaluate(() => (window as any).loadConversations());
    const row = page.locator(`#conversation-list .conv-item[data-cid="${conversation.conversation_id}"]`);
    await row.hover();
    await row.locator('.conv-item-menu').click();
    await page.locator('#conversation-action-menu [data-action="to-project"]').click();
    const picker = page.locator('#conv-project-picker-overlay');
    await expect(picker).toBeVisible();
    await expect(picker.locator('.conv-project-agents')).toHaveCount(0);
    await page.keyboard.press('Escape');

    await page.setViewportSize({ width: 1000, height: 600 });
    await page.evaluate(() => {
      const host = window as any;
      host.__longPickerResult = null;
      host._openConversationProjectPicker(
        Array.from({ length: 20 }, (_, index) => ({ project_id: `p_${index}`, name: `Project ${index + 1}` })),
        Array.from({ length: 20 }, (_, index) => ({ id: `agent_${index}`, name: `Agent ${index + 1}` })),
      ).then((result: unknown) => { host.__longPickerResult = result; });
    });
    await expect(picker.getByRole('checkbox')).toHaveCount(20);
    for (const [selector, max] of [['.conv-project-pick-list', 252], ['.conv-project-agent-list', 150]] as const) {
      const list = picker.locator(selector);
      const metrics = await list.evaluate((el) => ({ height: el.clientHeight, content: el.scrollHeight }));
      expect(metrics.height).toBeGreaterThan(0);
      expect(metrics.height).toBeLessThanOrEqual(max);
      expect(metrics.content).toBeGreaterThan(metrics.height);
      await list.evaluate((el) => { el.scrollTop = el.scrollHeight; });
      expect(await list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
    }
    await picker.locator('.conv-project-pick-row').last().click();
    await picker.getByRole('checkbox').last().uncheck();
    const bounds = await picker.locator('[role="dialog"]').evaluate((el) => ({
      top: el.getBoundingClientRect().top, bottom: el.getBoundingClientRect().bottom,
      height: el.clientHeight, content: el.scrollHeight,
    }));
    expect(bounds.top).toBeGreaterThanOrEqual(0);
    expect(bounds.bottom).toBeLessThanOrEqual(600);
    expect(bounds.content).toBeLessThanOrEqual(bounds.height + 1);
    const agentBottom = await picker.locator('.conv-project-agent-list').evaluate((el) => el.getBoundingClientRect().bottom);
    const actionsTop = await picker.locator('.modal-actions').evaluate((el) => el.getBoundingClientRect().top);
    expect(agentBottom).toBeLessThanOrEqual(actionsTop);
    await page.evaluate(() => (window as any).setLang('zh'));
    await picker.locator('[role="dialog"]').screenshot({ path: testInfo.outputPath('add-to-project-scroll-zh.png') });
    await picker.locator('[data-act="ok"]').click();
    await expect.poll(() => page.evaluate(() => (window as any).__longPickerResult)).toEqual({
      projectId: 'p_19', agentIds: Array.from({ length: 19 }, (_, index) => `agent_${index}`),
    });
  });

  test('files a loose task into new and existing projects with the selected agents', async ({ orkas }, testInfo) => {
    if (!orkas.page) throw new Error('Orkas renderer is unavailable');
    const agent = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
      name: 'E2EFilingAgent',
      description: 'Takes part in the task being filed.',
      category: 'general',
    });
    const agentId = agent.agent.agent_id;
    const optionalAgent = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
      name: 'E2EOptionalAgent', description: 'Can be excluded when filing.', category: 'general',
    });
    const optionalId = optionalAgent.agent.agent_id;

    const loose = await orkas.invoke<{ conversation: { conversation_id: string } }>(
      'conversations.create', { title: 'Loose filing task' });
    const cid = loose.conversation.conversation_id;
    const second = await orkas.invoke<{ conversation: { conversation_id: string } }>(
      'conversations.create', { title: 'Second loose task' });

    // The participant roster is what the new-project flow binds. Seeding it is
    // the deterministic stand-in for an @-mention turn.
    const chatsDir = globalChatsDir(orkas.workspaceRoot);
    mkdirSync(path.join(chatsDir, cid), { recursive: true });
    writeFileSync(path.join(chatsDir, cid, 'members.json'), JSON.stringify({
      version: 1,
      actors: [
        { kind: 'agent', id: agentId, name: 'E2EFilingAgent', joined_at: new Date().toISOString() },
        { kind: 'agent', id: optionalId, name: 'E2EOptionalAgent', joined_at: new Date().toISOString() },
      ],
    }));
    writeFileSync(path.join(chatsDir, `${cid}.jsonl`),
      `${JSON.stringify({ from: 'user', text: 'filed message body', ts: new Date().toISOString() })}\n`);

    mkdirSync(path.join(chatsDir, second.conversation.conversation_id), { recursive: true });
    writeFileSync(path.join(chatsDir, second.conversation.conversation_id, 'members.json'), JSON.stringify({
      version: 1, actors: [
        { kind: 'agent', id: agentId, name: 'E2EFilingAgent' },
        { kind: 'agent', id: optionalId, name: 'E2EOptionalAgent' },
      ],
    }));
    const page = await orkas.relaunch();
    const row = page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`);
    await expect(row).toHaveCount(1);

    // A running task keeps a visible, disabled entry. Finishing the task
    // enables the already-open menu without reopening or navigating away.
    await page.evaluate((taskId) => {
      (window as any).setGroupConversationBusy(taskId, true);
    }, cid);
    await row.hover();
    await row.locator('.conv-item-menu').click();
    const moveItem = page.locator('#conversation-action-menu [data-action="to-project"]');
    await expect(moveItem).toHaveAttribute('aria-disabled', 'true');
    await expect(moveItem).toHaveClass(/is-disabled/);
    await moveItem.dispatchEvent('click');
    await expect(page.locator('#conv-project-picker-overlay')).toHaveCount(0);
    await page.evaluate((taskId) => {
      (window as any).setGroupConversationBusy(taskId, false);
      (window as any)._updateConvSidebarBadge(taskId);
    }, cid);
    await expect(moveItem).toHaveAttribute('aria-disabled', 'false');
    await row.locator('.conv-item-menu').click();

    // New project: name it, and the task plus its agent land inside.
    await row.hover();
    await row.locator('.conv-item-menu').click();
    await expect(page.locator('#conversation-action-menu [data-action="to-new-project"]')).toHaveCount(0);
    await page.locator('#conversation-action-menu [data-action="to-project"]').click();
    const firstPicker = page.locator('#conv-project-picker-overlay');
    await expect(firstPicker.locator('.avatar-circle svg')).toHaveCount(2);
    await expect(firstPicker.locator('.conv-project-agents .conv-project-picker-hint')).toHaveCount(0);
    await expect(firstPicker.getByRole('checkbox', { name: 'E2EFilingAgent', exact: true })).toBeChecked();
    await expect(firstPicker.getByRole('checkbox', { name: 'E2EOptionalAgent', exact: true })).toBeChecked();
    await firstPicker.getByRole('checkbox', { name: 'E2EOptionalAgent', exact: true }).uncheck();
    await firstPicker.locator('[data-act="new"]').click();
    const promptInput = page.locator('.ui-dialog-overlay:visible .ui-dialog-input');
    await expect(promptInput).toBeVisible();
    await promptInput.fill('E2E Filed Project');
    await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();

    const projects = page.locator('.project-row', {
      has: page.locator('.project-name', { hasText: 'E2E Filed Project' }),
    });
    await expect(projects).toHaveCount(1);
    await expect(page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`)).toHaveCount(0);
    await expect.poll(async () => {
      const list = await orkas.invoke<{ conversations: Array<{ conversation_id: string; project_id?: string }> }>(
        'conversations.list');
      return list.conversations.find((c) => c.conversation_id === cid)?.project_id || '';
    }, { timeout: 15_000 }).not.toBe('');

    const all = await orkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');
    const projectId = all.projects.find((p) => p.name === 'E2E Filed Project')?.project_id;
    expect(projectId).toBeTruthy();
    await expect.poll(async () => {
      const bindings = await orkas.invoke<{ bindings: { agents: string[] } }>(
        'projects.bindings.list', { projectId });
      return bindings.bindings.agents;
    }, { timeout: 15_000 }).toContain(agentId);

    const initialBindings = await orkas.invoke<{ bindings: { agents: string[] } }>('projects.bindings.list', { projectId });
    expect(initialBindings.bindings.agents).not.toContain(optionalId);

    // The history moved with it: reading the task through the normal path
    // still returns the message that was written before the move.
    const history = await orkas.invoke<{ history: Array<{ text?: string }> }>(
      'conversations.history', { cid });
    expect(history.history.some((m) => String(m.text || '').includes('filed message body'))).toBe(true);

    // Add to project: the second loose task joins the same project, and the
    // menu no longer offers filing for a task that already has one.
    const secondRow = page.locator(`#conversation-list .conv-item[data-cid="${second.conversation.conversation_id}"]`);
    await secondRow.hover();
    await secondRow.locator('.conv-item-menu').click();
    await page.locator('#conversation-action-menu [data-action="to-project"]').click();
    const picker = page.locator('#conv-project-picker-overlay');
    await expect(picker).toBeVisible();
    // The primary action stays out of reach until a row is chosen, so a stray
    // click cannot move the task.
    const confirm = picker.locator('[data-act="ok"]');
    await expect(confirm).toBeDisabled();
    await picker.locator('.conv-project-pick-row', { hasText: 'E2E Filed Project' }).click();
    await expect(confirm).toBeEnabled();
    await expect(picker.getByRole('checkbox', { name: 'E2EFilingAgent', exact: true })).toBeChecked();
    await expect(picker.getByRole('checkbox', { name: 'E2EOptionalAgent', exact: true })).toBeChecked();
    // Capture the actual localized panel, then keep the selection while switching back.
    await page.evaluate(() => (window as any).setLang('zh'));
    await expect(picker.locator('legend')).toHaveText('同时添加任务中的 Agent');
    await picker.locator('[role="dialog"]').screenshot({ path: testInfo.outputPath('add-to-project-zh.png') });
    await page.evaluate(() => (window as any).setLang('en'));
    await picker.getByRole('checkbox', { name: 'E2EFilingAgent', exact: true }).uncheck();
    await confirm.click();
    await expect(secondRow).toHaveCount(0);
    await expect.poll(async () => (await orkas.invoke<{ bindings: { agents: string[] } }>(
      'projects.bindings.list', { projectId })).bindings.agents.sort()).toEqual([agentId, optionalId].sort());

    const filedRow = page.locator(`.conv-item[data-cid="${cid}"]`).first();
    await filedRow.hover();
    await filedRow.locator('.conv-item-menu').click();
    await expect(page.locator('#conversation-action-menu [data-action="to-new-project"]')).toHaveCount(0);
    await expect(page.locator('#conversation-action-menu [data-action="to-project"]')).toHaveCount(0);
  });
  test('keeps a filed task and reports an agent disabled after the picker opened', async ({ orkas }) => {
    const { project } = await orkas.invoke<{ project: { project_id: string } }>('projects.create', { name: 'Partial filing' });
    const { agent } = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
      name: 'UnavailableAgent', description: 'Disabled after selection.', category: 'general',
    });
    const { conversation } = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', {
      title: 'Partial filing task',
    });
    // Conversation creation does not accept an agent. Seed the persisted roster
    // as in the filing happy path, then restart to discard any roster cache.
    const rosterDir = path.join(globalChatsDir(orkas.workspaceRoot), conversation.conversation_id);
    mkdirSync(rosterDir, { recursive: true });
    writeFileSync(path.join(rosterDir, 'members.json'), JSON.stringify({
      version: 1, actors: [{ kind: 'agent', id: agent.agent_id, name: 'UnavailableAgent' }],
    }));
    const page = await orkas.relaunch();
    const row = page.locator(`#conversation-list .conv-item[data-cid="${conversation.conversation_id}"]`);
    await row.hover();
    await row.locator('.conv-item-menu').click();
    await page.locator('#conversation-action-menu [data-action="to-project"]').click();
    const picker = page.locator('#conv-project-picker-overlay');
    await expect(picker.getByRole('checkbox', { name: 'UnavailableAgent' })).toBeChecked();
    await orkas.invoke('agents.setEnabled', { agent_id: agent.agent_id, enabled: false });
    await picker.locator('.conv-project-pick-row', { hasText: 'Partial filing' }).click();
    await picker.locator('[data-act="ok"]').click();
    await expect(page.locator('.ui-toast')).toContainText('1 agent(s) could not be added');
    const list = await orkas.invoke<{ conversations: Array<{ conversation_id: string; project_id?: string }> }>('conversations.list');
    expect(list.conversations.find((item) => item.conversation_id === conversation.conversation_id)?.project_id).toBe(project.project_id);
    const bindings = await orkas.invoke<{ bindings: { agents: string[] } }>('projects.bindings.list', { projectId: project.project_id });
    expect(bindings.bindings.agents).not.toContain(agent.agent_id);
  });

});