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.

18.5 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest';
import { conversationCacheSource } from './conversation-cache-test-source';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';

const conversationSource = fs.readFileSync(
  path.join(__dirname, '../../src/renderer/modules/conversation.js'),
  'utf8',
);
const draftSource = fs.readFileSync(
  path.join(__dirname, '../../src/renderer/modules/queue-draft.js'),
  'utf8',
);
const styleSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/style.css'), 'utf8');
const projectDetailSource = fs.readFileSync(
  path.join(__dirname, '../../src/renderer/modules/project-detail.js'),
  'utf8',
);
const indexSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/index.html'), 'utf8');

describe('conversation cross-task message reference UI', () => {
  it('keeps one target task and its newer metadata when creation is already visible during a quote handoff', async () => {
    const current = { conversation_id: 'target', title: 'Renamed target', project_id: 'p-new',
      created_at: '2026-05-15T09:00:00Z', updated_at: '2026-05-15T09:01:00Z', processing: true };
    const payload = { msgId: 'source-message', text: 'Quoted message' };
    const context = vm.createContext({
      conversations: [current],
      _addQuote: vi.fn(), _closeReferenceTargetPicker: vi.fn(), _exitMessageSelection: vi.fn(),
      setView: vi.fn(), renderConversationList: vi.fn(), _renderQuotePreview: vi.fn(),
      document: { getElementById: () => null },
    });
    vm.runInContext(conversationCacheSource + '\n' + conversationSource.slice(
      conversationSource.indexOf('async function _transferSelectedReferences('),
      conversationSource.indexOf('function _referenceTargetProject('),
    ), context);
    await context._transferSelectedReferences('target', [payload], { fresh: true,
      conversation: { conversation_id: 'target', title: 'Creation title', project_id: 'p-old',
        created_at: '2026-05-15T09:00:00Z', updated_at: '2026-05-15T09:00:00Z' },
    });
    expect(context.conversations).toEqual([current]);
    expect(context._addQuote).toHaveBeenCalledExactlyOnceWith('target', payload);
    expect(context.setView).toHaveBeenCalledExactlyOnceWith('conversation', 'target', { skipLoad: true });
    expect(context._exitMessageSelection).toHaveBeenCalledOnce();
  });

  it('exposes secondary actions after the quote without an overflow menu', () => {
    expect(conversationSource).toContain('<span class="chat-bubble-direct-actions">${quoteButton}</span>');
    expect(conversationSource).toContain('${secondaryActions}');
    const secondary = conversationSource.slice(
      conversationSource.indexOf('const secondaryActions ='),
      conversationSource.indexOf('actions.innerHTML = `', conversationSource.indexOf('const secondaryActions =')),
    );
    expect(secondary.indexOf('bubble-copy-btn')).toBeLessThan(secondary.indexOf('bubble-select-btn'));
    expect(secondary.indexOf('bubble-select-btn')).toBeLessThan(secondary.indexOf('bubble-archive-btn'));
    for (const retiredClass of ['bubble-more-btn', 'chat-bubble-more-menu', 'chat-bubble-menu-item']) {
      expect(conversationSource).not.toContain(retiredClass);
      expect(styleSource).not.toContain(retiredClass);
    }
  });

  it('adds quote plus copy/select overflow actions to persisted user messages', () => {
    expect(conversationSource).toContain("} else if (role === 'user' && opts.messageActions !== 'errors-only') {");
    expect(conversationSource).toContain('_attachBubbleActions(msgDiv, () => (');
    expect(conversationSource).toContain('), { archive: false });');
    expect(conversationSource).not.toContain('bubble-share-btn');
    expect(conversationSource).toContain("msgDiv.dataset.fromActor || (msgDiv.classList.contains('user') ? 'user' : '')");
    expect(conversationSource).toContain("'.bubble-quote-btn, .bubble-select-btn'");
  });

  it('does not expose hosted message-sharing entry points', () => {
    expect(conversationSource).not.toContain('bubble-share-btn');
    expect(conversationSource).not.toContain('data-selection-share');
    expect(conversationSource).not.toContain('openConversationShareDialog');
  });

  it('enters multi-select with the clicked message already selected', () => {
    expect(conversationSource).toContain('selected: new Set([msgId])');
    expect(conversationSource).not.toContain('data-selection-share');
    expect(conversationSource).not.toContain('data-selection-delete');
    expect(conversationSource).toContain('data-selection-reference');
    expect(styleSource).toContain('.chat-message-selection-bar');
    expect(styleSource).toContain('.chat-message.is-message-selected > .chat-bubble');
    expect(conversationSource).toContain("document.querySelectorAll('#chat-history .chat-message[data-msg-id]')");
  });

  it('uses a secondary reference action and exits selection after a successful handoff', () => {
    expect(conversationSource).toContain('class="btn btn-sm" data-selection-reference');
    expect(conversationSource).not.toContain('btn btn-sm btn-primary" data-selection-reference');
    expect(conversationSource).toMatch(/function _transferSelectedReferences[\s\S]*?_exitMessageSelection\(\)/);
    expect(conversationSource).toMatch(/function _stageReferencesForNewTask[\s\S]*?_exitMessageSelection\(\)/);
  });

  it('toggles selection when the message bubble is clicked without hijacking embedded controls', () => {
    expect(conversationSource).toContain("bubble.addEventListener('click', (event) => _messageBubbleSelectionClick(event, msg))");
    expect(conversationSource).toContain("event.target?.closest?.('a, button, input, textarea, select, label, summary, iframe, video, audio, [role=\"button\"], [contenteditable=\"true\"]')");
    expect(conversationSource).toContain('_toggleMessageSelection(msg)');
    expect(styleSource).toContain('.chat-message.is-message-selectable > .chat-bubble');
  });

  it('supports both new and existing destination tasks without auto-sending', () => {
    expect(conversationSource).toContain('data-new-task="1"');
    expect(conversationSource).toContain('data-target-cid=');
    expect(conversationSource).toContain("setView('conversation', targetCid");
    expect(conversationSource).toContain("setView('new-chat')");
    expect(conversationSource).toContain("setView('project', projectId)");
    expect(conversationSource).toContain('_stageReferencesForNewTask(payloads, picker.projectId)');
    expect(conversationSource).toContain("_stageReferencesForNewTask(payloads, '')");
    expect(conversationSource).toContain('_stageReferencesForNewTask(payloads, target.dataset.createProjectId)');
    expect(conversationSource).not.toContain('function _createReferenceTargetTask');
    expect(conversationSource).not.toContain('_transferSelectedReferences(targetCid, payloads);\n  sendInCurrentConversation');
  });

  it('lets the user pick the new-task owner and browse every task of a scope in batches', () => {
    expect(conversationSource).not.toContain('const sourceProjectId = _projectIdForConversation(currentCid)');
    expect(conversationSource).toContain('return projectId ? `projchat-${projectId}` : DRAFT_CID');
    expect(conversationSource).toContain("const res = await apiFetch('/api/conversations/list')");
    expect(conversationSource).toContain('const [targetConversations] = await Promise.all(loads)');
    expect(conversationSource).toContain('Array.isArray(targetConversations) ? targetConversations : []');
    expect(conversationSource).not.toContain('matches.slice(0, 80)');
    expect(conversationSource).not.toContain('matches.slice(0, 5)');
    expect(conversationSource).toContain('const shown = matches.slice(0, picker.limit)');
    expect(conversationSource).toContain('picker.limit += _REFERENCE_TARGET_PAGE_SIZE');
    expect(conversationSource).toContain("if (picker.scope === 'global') return !conv.project_id");
    expect(conversationSource).toContain("if (picker.scope === 'project') return conv.project_id === picker.projectId");
    expect(conversationSource).toContain('_referenceTargetActivity(b).localeCompare(_referenceTargetActivity(a))');
    expect(conversationSource).toContain("String(conv.title || '').toLowerCase().includes(needle)");
    expect(conversationSource).not.toContain('_referenceTargetAreaLabel(conv).toLowerCase().includes(needle)');
  });

  it('places new-task above search in the browse pane and uses compact picker typography', () => {
    const browseStart = conversationSource.indexOf('class="chat-reference-browse"');
    const newTaskStart = conversationSource.indexOf('class="chat-reference-new-task"');
    const searchStart = conversationSource.indexOf('class="chat-reference-target-search-wrap"');
    expect(browseStart).toBeGreaterThanOrEqual(0);
    expect(newTaskStart).toBeGreaterThan(browseStart);
    expect(searchStart).toBeGreaterThan(newTaskStart);
    expect(conversationSource.indexOf('class="chat-reference-scopes"')).toBeLessThan(browseStart);
    expect(styleSource).toContain('width: min(744px, calc(100vw - 40px));');
    expect(styleSource).toContain('grid-template-columns: 184px minmax(0, 1fr);');
    expect(styleSource).toContain('.chat-reference-create[hidden] { display: none; }');
    expect(styleSource).toContain('.chat-reference-target-header h2');
    expect(styleSource).toContain('font-size: 13px;');
    expect(styleSource).toContain('height: 38px;');
    expect(conversationSource).not.toContain('chat-reference-new-task-icon');
    expect(conversationSource).not.toContain('chat-reference-target-item-icon');
    expect(conversationSource).not.toContain('chat-reference-target-chevron');
    expect(conversationSource).toContain('class="chat-reference-leading-plus"');
    expect(conversationSource).toContain('class="chat-reference-row-arrow"');
  });

  it('sends references as structured sidecar data and persists them with drafts', () => {
    expect(conversationSource).toContain('const references = _referenceSnapshotsForQuotes(quotes)');
    expect(conversationSource).toContain('...(references.length ? { references } : {})');
    expect(conversationSource).toMatch(/const titleText = \(typeof transformChatUseTokens === 'function'\)[\s\S]*?transformChatUseTokens\(titleSeed\)/);
    expect(conversationSource).toContain('if (titleText) conv.title = _autoTitle(titleText)');
    expect(projectDetailSource).toContain('const references = (typeof _referenceSnapshotsForQuotes === \'function\')');
    expect(projectDetailSource).toContain('...(references.length ? { references } : {})');
    expect(projectDetailSource).toMatch(/const titleText = \(typeof transformChatUseTokens === 'function'\)[\s\S]*?transformChatUseTokens\(titleSeed\)/);
    expect(projectDetailSource).toContain('if (titleText) {');
    expect(indexSource).toContain('id="new-chat-quote-preview"');
    expect(indexSource).toContain('id="project-chat-quote-preview"');
    expect(draftSource).toContain('function _persistQuoteDraft(cid)');
    expect(draftSource).toContain('{ references: safeReferences }');
    expect(draftSource).toContain('_quotesByCid.set(cid, references)');
  });

  it('flattens nested references and retains attachment locators in the draft bundle', () => {
    expect(conversationSource).toContain('for (const nested of quote.references || []) push(nested)');
    expect(conversationSource).toContain('...(quote.attachments?.length ? { attachments: quote.attachments.slice() } : {})');
    expect(conversationSource).toContain('msgDiv.dataset.references = JSON.stringify(message.references.slice(0, 20))');
    expect(conversationSource).toContain(".chat-reference-file.is-attachment[data-attach-name][data-attach-cid]");
    expect(styleSource).toContain('.chat-reference-file.is-attachment');
  });

  it('renders references as a static quote block and limits source titles to cross-task references', () => {
    expect(conversationSource).toContain('function _renderMessageReferencesHtml(references, targetCid)');
    expect(conversationSource).toContain('_renderMessageReferencesHtml(message.references, messageCid)');
    expect(conversationSource).toContain('_quotePreviewAttribution(ref, targetCid)');
    expect(conversationSource).toContain('class="chat-reference-author"');
    expect(conversationSource).not.toContain('class="chat-reference-title"');
    expect(conversationSource).not.toContain('<details class="chat-reference-bundle"');
    expect(conversationSource).not.toContain('chat.reference_bundle_summary');
    expect(styleSource).toContain('border-left: 3px solid rgba(37, 99, 235, 0.45);');
    expect(styleSource).toContain('background: rgba(37, 99, 235, 0.04);');
    expect(styleSource).toContain('.chat-reference-author { display: block; margin-bottom: 1px; color: #2563eb; font-size: 12px; font-weight: 500; }');
  });
});

// History is paginated: all-select must not silently omit older messages or
// overwrite a new selection after the user cancels a pending load.
function selectionHarness() {
  const context: any = {
    currentCid: 'task',
    t: (key: string) => key,
    uiToast: vi.fn(),
    _messageSelectionState: { cid: 'task', selected: new Set(['latest']) },
    _historyRequestUrl: (_cid: string, cursor: number) => cursor,
    _isVisibleGroupHistoryRecord: (row: any) => !row.dispatch,
    _collapseSupersededInterruptionRecords: (rows: any[]) => rows,
    _mergeNativeSegmentRecords: (rows: any[]) => rows,
    _groupMsgToLegacy: (row: any) => ({ _msg_id: row.id }),
    _updateMessageSelectionToolbar: () => {},
    _syncMessageSelectionUi: () => {},
    // Select-all must never need a mounted row or create any transcript DOM.
    document: new Proxy({}, { get() { throw new Error('Unexpected DOM access'); } }),
  };
  vm.createContext(context);
  vm.runInContext(conversationSource.slice(
    conversationSource.indexOf('function _historyNextCursor('),
    conversationSource.indexOf('function _setEarlierHistoryLoaderState('),
  ) + conversationSource.slice(
    conversationSource.indexOf('function _allMessagesSelected('),
    conversationSource.indexOf('function _toggleMessageSelection('),
  ), context);
  return context;
}

const selectionPage = (ids: string[], next: number | null = null) => ({
  json: async () => ({ ok: true, history: ids.map(id => ({ id })), next_cursor: next }),
});

describe('select all across conversation history pages', () => {
  it('selects the complete conversation without mounting rows and deselects it atomically', async () => {
    const context = selectionHarness();
    context.apiFetch = async (cursor: number | null) => cursor === null
      ? selectionPage(['latest'], 20) : cursor === 20
        ? selectionPage(['middle'], 10) : selectionPage(['oldest']);
    await context._toggleAllMessageSelection();
    expect(Array.from(context._messageSelectionState.selected)).toEqual(['oldest', 'middle', 'latest']);
    expect(context.uiToast).not.toHaveBeenCalled();
    expect(context._messageSelectionState.loadingAll).toBe(false);
    await context._toggleAllMessageSelection();
    expect(context._messageSelectionState.selected.size).toBe(0);
  });

  it.each(['failure', 'repeated cursor'])('preserves prior selection on %s and supports retry', async mode => {
    const context = selectionHarness();
    context.apiFetch = async (cursor: number | null) => {
      if (cursor === null || mode === 'repeated cursor') return selectionPage(['latest'], 20);
      throw new Error('Fixture read failure');
    };
    await context._toggleAllMessageSelection();
    expect(Array.from(context._messageSelectionState.selected)).toEqual(['latest']);
    expect(context._messageSelectionState.loadingAll).toBe(false);
    expect(context._allMessagesSelected()).toBe(false);
    expect(context.uiToast).toHaveBeenCalledTimes(1);
    context.apiFetch = async () => selectionPage(['oldest', 'latest']);
    await context._toggleAllMessageSelection();
    expect(Array.from(context._messageSelectionState.selected)).toEqual(['oldest', 'latest']);
    expect(context._allMessagesSelected()).toBe(true);
  });

  it('leaves the new task selection untouched when a pending read completes', async () => {
    const context = selectionHarness();
    let finish!: (value: any) => void;
    context.apiFetch = () => new Promise(resolve => { finish = resolve; });
    const pending = context._toggleAllMessageSelection();
    expect(context._messageSelectionState.loadingAll).toBe(true);
    context.currentCid = 'other';
    context._messageSelectionState = { cid: 'other', selected: new Set(['chosen']) };
    finish(selectionPage(['oldest']));
    await pending;
    expect(Array.from(context._messageSelectionState.selected)).toEqual(['chosen']);
    expect(context.uiToast).not.toHaveBeenCalled();
  });
});

describe('selection toolbar actual controls', () => {
  it('selects every history page and deselects through the rendered Select all button', async () => {
    const context = selectionHarness();
    const buttons = new Map<string, EventTarget>();
    let toolbar: any = null;
    const pane = { classList: { toggle: vi.fn() }, querySelector: () => ({
      insertBefore: (bar: any) => { toolbar = bar; }, querySelector: () => null,
    }) };
    context.escapeHtml = (value: string) => value;
    context._exitMessageSelection = vi.fn();
    context.document = {
      querySelector: () => pane,
      querySelectorAll: () => [],
      getElementById: () => toolbar,
      createElement: () => ({
        set innerHTML(html: string) {
          for (const match of html.matchAll(/<button\b[^>]*\b(data-selection-[a-z]+)\b/g)) buttons.set(match[1], new EventTarget());
        },
        querySelector: (selector: string) => buttons.get(selector.slice(1, -1)),
      }),
    };
    let resolveRead!: (response: any) => void;
    const firstRead = new Promise(resolve => { resolveRead = resolve; });
    context.apiFetch = vi.fn((cursor: number | null) => cursor === null ? firstRead : Promise.resolve(selectionPage(['oldest'])));
    vm.runInContext(conversationSource.slice(
      conversationSource.indexOf('function _syncMessageSelectionUi('),
      conversationSource.indexOf('function _enterMessageSelection('),
    ), context);
    context._syncMessageSelectionUi();
    const selectAll = buttons.get('data-selection-all');
    expect(selectAll).toBeDefined();
    selectAll!.dispatchEvent(new Event('click'));
    expect(context.apiFetch).toHaveBeenCalledExactlyOnceWith(null);
    resolveRead(selectionPage(['latest'], 10));
    await vi.waitFor(() => expect(Array.from(context._messageSelectionState.selected)).toEqual(['oldest', 'latest']));
    expect(context.apiFetch).toHaveBeenCalledTimes(2);
    selectAll!.dispatchEvent(new Event('click'));
    expect(context._messageSelectionState.selected.size).toBe(0);
    expect(context.apiFetch).toHaveBeenCalledTimes(2);
  });
});