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.

16.7 KB
Raw Blame
// Lock in the kind-classifier behaviour of chat-file-viewer.js. The viewer
// dispatches by `_kindOf(name)` — every misclassification surfaces as
// "I clicked a .md but it tried to load in an iframe" or vice versa, which
// is hard to spot in code review. This is the multi-branch decision
// function category from PC/CLAUDE.md §9.

import { readFileSync } from 'node:fs';
import * as vm from 'node:vm';
import { describe, it, expect, vi } from 'vitest';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const viewer = require('../../src/renderer/modules/chat-file-viewer.js');
const { _kindOf, _extOf, _chatMediaLocalUrl, _viewerAbsPathFromChatMediaLocalUrl, _viewerCanAddToLibrary, _viewerVideoPlaybackOptions, _viewerVideoSeekTarget, _htmlCanvasDimensions, _htmlCanvasWidthFit } = viewer as {
  _kindOf: (name: string) => string;
  _extOf: (name: string) => string;
  _chatMediaLocalUrl: (abs: string) => string;
  _viewerAbsPathFromChatMediaLocalUrl: (src: string) => string;
  _viewerCanAddToLibrary: (name: string, options?: { projectScoped?: boolean }) => boolean;
  _viewerVideoPlaybackOptions: (opts?: { autoplay?: boolean; startTime?: number; duration?: number; ended?: boolean }) => { autoplay: boolean; startTime: number };
  _viewerVideoSeekTarget: (startTime: number, duration?: number) => number;
  _htmlCanvasDimensions: (layout: unknown) => { width: number; height: number } | null;
  _htmlCanvasWidthFit: (width: number, height: number, viewportWidth: number) => { scale: number; renderedHeight: number } | null;
};

describe('chat-file-viewer › _kindOf', () => {
  // Set A — known kinds. One representative per ext set; the lists in the
  // module are the contract, so coverage of one ext per kind is enough
  // (the Set membership check makes per-ext coverage redundant).
  it.each([
    ['photo.png', 'image'],
    ['art.jpg', 'image'],
    ['art.jpeg', 'image'],
    ['art.webp', 'image'],
    ['art.gif', 'image'],
    ['contact-sheet.svg', 'image'],
    ['report.pdf', 'pdf'],
    ['doc.docx', 'office'],
    ['macro.docm', 'office'],
    ['workbook.xlsx', 'office'],
    ['sheet.xlsm', 'office'],
    ['legacy.xls', 'office'],
    ['slides.pptx', 'office'],
    ['deck.pptm', 'office'],
    ['page.html', 'html'],
    ['old.htm', 'html'],
    ['note.md', 'markdown'],
    ['old.markdown', 'markdown'],
    ['plain.txt', 'text'],
    ['data.json', 'text'],
    ['table.csv', 'text'],
    ['script.py', 'text'],
    ['app.ts', 'text'],
    ['style.css', 'text'],
    ['log.log', 'text'],
    ['video.mp4', 'video'],
    ['voice.mp3', 'audio'],
  ])('classifies "%s" as %s', (name, kind) => {
    expect(_kindOf(name)).toBe(kind);
  });

  // Set B — unsupported / look-alike shapes. These specifically check
  // that the classifier doesn't promote "looks like text" → text or
  // "html-ish" → html when the actual ext doesn't match.
  it.each([
    ['archive.zip', 'unsupported'],
    ['legacy.doc', 'unsupported'],
    ['legacy.xls.exe', 'unsupported'],
    ['legacy.ppt', 'unsupported'],
    ['binary.exe', 'unsupported'],
    ['photo.heic', 'unsupported'], // image-ish but not in the allow-list
    ['no-extension', 'unsupported'],
    ['', 'unsupported'],
    ['file.', 'unsupported'],
    ['file.UPPER', 'unsupported'],
  ])('refuses "%s" → fallback dialog', (name, kind) => {
    expect(_kindOf(name)).toBe(kind);
  });

  it('is case-insensitive on the extension portion', () => {
    expect(_kindOf('REPORT.PDF')).toBe('pdf');
    expect(_kindOf('REPORT.XLSX')).toBe('office');
    expect(_kindOf('REPORT.XLS')).toBe('office');
    expect(_kindOf('Note.MD')).toBe('markdown');
    expect(_kindOf('Page.Html')).toBe('html');
    expect(_kindOf('Voice.MP3')).toBe('audio');
    expect(_kindOf('CONTACT-SHEET.SVG')).toBe('image');
  });

  it('handles paths with directories — only the basename ext matters', () => {
    expect(_kindOf('/Users/test/Documents/note.md')).toBe('markdown');
    expect(_kindOf('C:\\\\work\\\\report.pdf')).toBe('pdf');
  });
});

describe('file preview availability feedback', () => {
  it.each(['stat', 'reveal', 'reveal-response'])('keeps private file details out of %s failure diagnostics', async (failure) => {
    const privatePath = '/private/account/todo/brief.png';
    const privateError = `EACCES: ${privatePath}`;
    const warnings: unknown[] = [];
    const invoke = vi.fn(async (channel: string) => {
      if (channel === 'workspace.statPath') {
        if (failure === 'stat') throw new Error(privateError);
        return { ok: false, error: 'unavailable' };
      }
      if (failure === 'reveal-response') return { ok: false, error: privateError };
      throw new Error(privateError);
    });
    const openChatImageLightbox = vi.fn();
    const context = vm.createContext({ clearTimeout, setTimeout,
      window: { orkas: { invoke } },
      createLogger: () => ({ warn: (...args: unknown[]) => warnings.push(args), info: () => {}, error: () => {} }),
      uiConfirm: vi.fn(async () => true),
      openChatImageLightbox,
      console,
    });
    vm.runInContext(readFileSync(require.resolve('../../src/renderer/modules/chat-file-viewer.js'), 'utf8'), context);
    await context.openChatFileViewer(privatePath, 'brief.png');
    expect(warnings).toHaveLength(1);
    expect(JSON.stringify(warnings)).not.toContain(privatePath);
    expect(JSON.stringify(warnings)).not.toContain('EACCES');
    expect(warnings).toEqual([[expect.any(String), { error_code: failure === 'stat' ? 'stat_failed' : 'reveal_failed' }]]);
    expect(openChatImageLightbox).toHaveBeenCalledTimes(failure === 'stat' ? 1 : 0);
    expect(context.uiConfirm).toHaveBeenCalledTimes(failure === 'stat' ? 0 : 1);
    expect(invoke.mock.calls.map(([channel]) => channel)).toEqual(failure === 'stat'
      ? ['workspace.statPath'] : ['workspace.statPath', 'workspace.revealPath']);
  });

  it.each(['read', 'inspect', 'destroy'])('keeps %s failure diagnostics private while preserving recovery', async (failure) => {
    const privatePath = '/private/account/todo/brief.txt';
    const warnings: unknown[] = [];
    const fail = () => { throw new Error(`EACCES: ${privatePath}`); };
    const invoke = vi.fn(async () => fail());
    const button = { hidden: false, disabled: false };
    const classes = new Set(['is-open']);
    const root = {
      classList: {
        contains: (name: string) => classes.has(name),
        remove: (...names: string[]) => names.forEach((name) => classes.delete(name)),
      },
      setAttribute: vi.fn(),
    };
    const setDirty = vi.fn();
    const context = vm.createContext({ clearTimeout, setTimeout,
      window: { orkas: { invoke }, OrkasPreviewHost: { setDirty } },
      createLogger: () => ({ warn: (...args: unknown[]) => warnings.push(args), info: () => {}, error: () => {} }),
      uiConfirm: vi.fn(async () => false),
      root, button, privatePath, fail, console,
    });
    vm.runInContext(readFileSync(require.resolve('../../src/renderer/modules/chat-file-viewer.js'), 'utf8'), context);
    vm.runInContext('_viewerEl = root; _viewerCurrentPath = privatePath; _viewerSaveAppBtn = button;', context);
    if (failure === 'read') {
      expect(await context._readTextFile(privatePath, 'task', 'project')).toBeNull();
      expect(classes.has('is-open')).toBe(false);
      expect(context.uiConfirm).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
        message: 'Could not read this file. Open the containing folder?',
      }));
      expect(invoke).toHaveBeenCalledExactlyOnceWith('produced.readText', { path: privatePath, cid: 'task', projectId: 'project' });
    } else if (failure === 'inspect') {
      await context._refreshSaveAppButton(privatePath);
      expect(button).toEqual({ hidden: true, disabled: true });
      expect(classes.has('is-open')).toBe(true);
      expect(invoke).toHaveBeenCalledExactlyOnceWith('savedApps.inspectBundleFromPath', { path: privatePath });
    } else {
      vm.runInContext('_viewerEditController = { destroy: fail }; _viewerDirty = true;', context);
      expect(await context.closeChatFileViewer({ force: true })).toBe(true);
      expect(classes.has('is-open')).toBe(false);
      expect(setDirty).toHaveBeenCalledExactlyOnceWith(false);
      await context.closeChatFileViewer({ force: true });
      expect(invoke).not.toHaveBeenCalled();
    }
    expect(warnings).toEqual([[expect.any(String), { error_code: `${failure}_failed` }]]);
  });

  it.each([
    [{ ok: true, exists: false }, 'missing'],
    [{ ok: false, error: 'path is outside the user workspace' }, 'unreadable'],
    [null, 'unreadable'],
    [{ ok: true, exists: true, isFile: true }, 'open'],
  ])('handles stat result %j without misreporting availability', async (response, outcome) => {
    const invoke = vi.fn(async () => response);
    const uiToast = vi.fn();
    const uiConfirm = vi.fn(async () => false);
    const openChatImageLightbox = vi.fn();
    const context = vm.createContext({ clearTimeout, setTimeout,
      window: { orkas: { invoke } }, uiToast, uiConfirm, openChatImageLightbox,
      console,
    });
    vm.runInContext(readFileSync(require.resolve('../../src/renderer/modules/chat-file-viewer.js'), 'utf8'), context);
    await context.openChatFileViewer('/repository/cover.png', 'cover.png', { cid: 'code-task' });
    expect(invoke).toHaveBeenCalledExactlyOnceWith('workspace.statPath', { path: '/repository/cover.png', cid: 'code-task' });
    expect(openChatImageLightbox).toHaveBeenCalledTimes(outcome === 'open' ? 1 : 0);
    expect(uiToast).toHaveBeenCalledTimes(outcome === 'missing' ? 1 : 0);
    expect(uiConfirm).toHaveBeenCalledTimes(outcome === 'unreadable' ? 1 : 0);
    if (outcome === 'unreadable') {
      expect(uiConfirm).toHaveBeenCalledWith(expect.objectContaining({ message: 'Could not read this file. Open the containing folder?' }));
    }
  });
});

describe('chat-file-viewer › _extOf', () => {
  it('returns lowercased trailing extension', () => {
    expect(_extOf('note.MD')).toBe('.md');
    expect(_extOf('report.pdf')).toBe('.pdf');
  });
  it('returns "" for names with no dot', () => {
    expect(_extOf('README')).toBe('');
  });
  it('uses the LAST dot, not the first', () => {
    expect(_extOf('a.b.tar.gz')).toBe('.gz');
  });
});

describe('chat-file-viewer › _chatMediaLocalUrl', () => {
  // The URL has to round-trip cleanly through new URL() + the main-side
  // `_pathnameToAbsPath`, so it must encode reserved filename characters and
  // non-ASCII text while preserving `/` separators.
  it('builds chat-media://local/ + path for a unix abs path', () => {
    expect(_chatMediaLocalUrl('/Users/test/file.pdf')).toBe('chat-media://local/Users/test/file.pdf');
  });
  it('URL-encodes spaces in the path', () => {
    expect(_chatMediaLocalUrl('/Users/test/has space.pdf')).toBe('chat-media://local/Users/test/has%20space.pdf');
  });
  it('URL-encodes fragment/query delimiters and literal percent signs in filenames', () => {
    expect(_chatMediaLocalUrl('/Users/user/hero #1?.png')).toBe('chat-media://local/Users/user/hero%20%231%3F.png');
    expect(_chatMediaLocalUrl('/Users/user/100%/图.png')).toBe('chat-media://local/Users/user/100%25/%E5%9B%BE.png');
  });
  it('preserves "/" separators (doesn\'t use encodeURIComponent)', () => {
    const url = _chatMediaLocalUrl('/a/b/c/d.pdf');
    expect(url).not.toContain('%2F');
    expect(url).toContain('/a/b/c/d.pdf');
  });
  it('converts Windows-style "\\\\" to "/" so URL parsing stays well-formed', () => {
    expect(_chatMediaLocalUrl('C:\\Users\\test\\file.pdf')).toBe('chat-media://local/C:/Users/test/file.pdf');
  });
});

describe('chat-file-viewer › _viewerAbsPathFromChatMediaLocalUrl', () => {
  it('decodes local chat-media video URLs for file-backed preview actions', () => {
    expect(_viewerAbsPathFromChatMediaLocalUrl('chat-media://local/Users/test/has%20space.mp4')).toBe('/Users/test/has space.mp4');
    expect(_viewerAbsPathFromChatMediaLocalUrl('chat-media://local/C:/Users/test/clip.mp4')).toBe('C:/Users/test/clip.mp4');
  });

  it('refuses non-local media URLs', () => {
    expect(_viewerAbsPathFromChatMediaLocalUrl('chat-media://cid/main/clip.mp4')).toBe('');
    expect(_viewerAbsPathFromChatMediaLocalUrl('https://example.test/clip.mp4')).toBe('');
  });
});

describe('chat-file-viewer › _viewerCanAddToLibrary', () => {
  it('offers Add to Library only for Library-supported file extensions', () => {
    expect(_viewerCanAddToLibrary('/tmp/report.pdf')).toBe(true);
    expect(_viewerCanAddToLibrary('/tmp/scores.xlsx')).toBe(true);
    expect(_viewerCanAddToLibrary('/tmp/slides.pptx')).toBe(true);
    expect(_viewerCanAddToLibrary('/tmp/note.md')).toBe(true);
    expect(_viewerCanAddToLibrary('/tmp/page.html')).toBe(true);
    expect(_viewerCanAddToLibrary('/tmp/photo.png')).toBe(true);
    expect(_viewerCanAddToLibrary('/tmp/movie.mp4')).toBe(false);
    expect(_viewerCanAddToLibrary('/tmp/movie.mp4', { projectScoped: true })).toBe(true);
    expect(_viewerCanAddToLibrary('/tmp/voice.mp3', { projectScoped: true })).toBe(false);
    expect(_viewerCanAddToLibrary('/tmp/archive.zip')).toBe(false);
    expect(_viewerCanAddToLibrary('/tmp/no-extension')).toBe(false);
  });
});

describe('file-backed native video entry', () => {
  it.each([true, false])('preserves file validation and playback context when normalizing a video source: exists=%s', async (exists) => {
    const open = vi.fn();
    const context: any = vm.createContext({ clearTimeout, setTimeout,
      window: { orkas: { invoke: async () => ({ ok: true, exists, isFile: true }) },
        OrkasPreviewWindows: { open, options: (value: unknown) => value } },
      uiToast: vi.fn(),
    });
    vm.runInContext(readFileSync(require.resolve('../../src/renderer/modules/chat-file-viewer.js'), 'utf8'), context);
    await context.openChatFileViewer('/fixture/clip.mp4', 'Clip', { cid: 'task', projectId: 'project', autoplay: true, startTime: 2 });
    if (exists) expect(open).toHaveBeenCalledWith({ kind: 'video', src: 'chat-media://local/fixture/clip.mp4', title: 'Clip',
      options: { cid: 'task', projectId: 'project', autoplay: true, startTime: 2, absPath: '/fixture/clip.mp4' } });
    else {
      expect(open).not.toHaveBeenCalled();
      expect(context.uiToast).toHaveBeenCalledOnce();
    }
  });
});

describe('chat-file-viewer › _viewerVideoPlaybackOptions', () => {
  it('keeps explicit autoplay and a positive start time', () => {
    expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 12.5 })).toEqual({ autoplay: true, startTime: 12.5 });
  });

  it('normalizes missing or invalid playback options', () => {
    expect(_viewerVideoPlaybackOptions()).toEqual({ autoplay: false, startTime: 0 });
    expect(_viewerVideoPlaybackOptions({ autoplay: false, startTime: -1 })).toEqual({ autoplay: false, startTime: 0 });
  });

  it('replays from the beginning when the source video has ended', () => {
    expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 9.5, duration: 10, ended: true })).toEqual({ autoplay: true, startTime: 0 });
  });

  it('replays from the beginning when the source position is at the end', () => {
    expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 9.9, duration: 10 })).toEqual({ autoplay: true, startTime: 0 });
  });

  it('keeps mid-video resume positions', () => {
    expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 5, duration: 10 })).toEqual({ autoplay: true, startTime: 5 });
  });
});

describe('chat-file-viewer › _viewerVideoSeekTarget', () => {
  it('seeks to the beginning when metadata reveals an end position', () => {
    expect(_viewerVideoSeekTarget(9.9, 10)).toBe(0);
  });

  it('keeps a safe in-range mid-video seek target', () => {
    expect(_viewerVideoSeekTarget(4.25, 10)).toBe(4.25);
  });
});

describe('chat-file-viewer › generic fixed-canvas HTML layout', () => {
  it('accepts normalized fixed-canvas metadata', () => {
    expect(_htmlCanvasDimensions({ kind: 'fixed-canvas', width: 1920, height: 1080 }))
      .toEqual({ width: 1920, height: 1080 });
  });

  it('rejects missing or invalid layout metadata', () => {
    expect(_htmlCanvasDimensions(null)).toBeNull();
    expect(_htmlCanvasDimensions({ kind: 'responsive', width: 1920, height: 1080 })).toBeNull();
    expect(_htmlCanvasDimensions({ kind: 'fixed-canvas', width: 99999, height: 1080 })).toBeNull();
  });

  it('fits by width and preserves the scaled content height', () => {
    expect(_htmlCanvasWidthFit(1600, 1600, 1200)).toEqual({ scale: 0.75, renderedHeight: 1200 });
    expect(_htmlCanvasWidthFit(1920, 1080, 1280)).toEqual({ scale: 2 / 3, renderedHeight: 720 });
  });

  it('does not shrink a tall canvas just to fit the viewport height', () => {
    expect(_htmlCanvasWidthFit(1000, 3000, 800)).toEqual({ scale: 0.8, renderedHeight: 2400 });
  });

  it('does not upscale a canvas narrower than the viewer', () => {
    expect(_htmlCanvasWidthFit(800, 600, 1200)).toEqual({ scale: 1, renderedHeight: 600 });
  });
});