Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

18.9 KB
Raw Blame
/**
 * artifactDownloadService coverage (#3024).
 *
 * Exercises every branch of `downloadArtifact`, `deleteArtifact`, and
 * `revealArtifact` — including the typed error-code
 * payloads, the title double-extension guard, and the non-Tauri /
 * empty-id / RPC-error / invoke-error paths.
 *
 * Mocks: `safeInvoke` + `isTauri` from `utils/tauriCommands/common`,
 * `callCoreRpc` from `services/coreRpcClient`, and `revealPath` from
 * `utils/openUrl`. The service has no other I/O.
 */
import { beforeEach, describe, expect, it, vi } from 'vitest';

import {
  deleteArtifact,
  downloadArtifact,
  listArtifactsForThread,
  revealArtifact,
  saveArtifactViaDialog,
} from '../artifactDownloadService';
import { callCoreRpc } from '../coreRpcClient';

const hoisted = vi.hoisted(() => ({
  invoke: vi.fn(),
  isTauri: vi.fn(() => true),
  revealPath: vi.fn(),
}));

vi.mock('../../utils/tauriCommands/common', () => ({
  isTauri: hoisted.isTauri,
  safeInvoke: (...args: unknown[]) => hoisted.invoke(...args),
}));

vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));

vi.mock('../../utils/openUrl', () => ({
  revealPath: (...args: unknown[]) => hoisted.revealPath(...args),
}));

describe('listArtifactsForThread', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('returns an error for empty / whitespace thread ids without calling the RPC', async () => {
    const outcome = await listArtifactsForThread('   ');
    expect(outcome).toEqual({ ok: false, artifacts: [], error: 'thread id missing' });
    expect(callCoreRpc).not.toHaveBeenCalled();
  });

  it('calls ai_list_artifacts with a thread filter and maps ready artifacts', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      artifacts: [
        {
          id: 'art-1',
          kind: 'document',
          title: 'Report',
          path: 'artifacts/art-1/report.pdf',
          size_bytes: 1234,
          status: 'ready',
        },
        {
          id: 'art-pending',
          kind: 'presentation',
          title: 'Pending Deck',
          path: 'artifacts/art-pending/deck.pptx',
          size_bytes: 55,
          status: 'pending',
        },
        {
          id: 'art-video',
          kind: 'video',
          title: 'Generated Clip',
          path: 'artifacts/art-video/video.mp4',
          size_bytes: 99,
          status: 'ready',
        },
      ],
    });

    const outcome = await listArtifactsForThread(' thread-1 ');

    expect(callCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.ai_list_artifacts',
      params: { thread_id: 'thread-1', offset: 0, limit: 200 },
    });
    expect(outcome).toEqual({
      ok: true,
      artifacts: [
        {
          artifactId: 'art-1',
          kind: 'document',
          title: 'Report',
          path: 'artifacts/art-1/report.pdf',
          sizeBytes: 1234,
        },
        {
          artifactId: 'art-video',
          kind: 'video',
          title: 'Generated Clip',
          path: 'artifacts/art-video/video.mp4',
          sizeBytes: 99,
        },
      ],
    });
  });

  it('fetches subsequent artifact pages before returning mapped artifacts', async () => {
    const firstPage = Array.from({ length: 200 }, (_, idx) => ({
      id: `pending-${idx}`,
      kind: 'document',
      title: `Pending ${idx}`,
      path: `artifacts/pending-${idx}/pending.pdf`,
      size_bytes: idx + 1,
      status: 'pending',
    }));
    firstPage[0] = {
      id: 'art-page-1',
      kind: 'document',
      title: 'First Page Report',
      path: 'artifacts/art-page-1/report.pdf',
      size_bytes: 100,
      status: 'ready',
    };
    vi.mocked(callCoreRpc)
      .mockResolvedValueOnce({ artifacts: firstPage })
      .mockResolvedValueOnce({
        artifacts: [
          {
            id: 'art-page-2',
            kind: 'image',
            title: 'Second Page Image',
            path: 'artifacts/art-page-2/image.png',
            size_bytes: 200,
            status: 'ready',
          },
        ],
      });

    const outcome = await listArtifactsForThread('thread-1');

    expect(callCoreRpc).toHaveBeenNthCalledWith(1, {
      method: 'openhuman.ai_list_artifacts',
      params: { thread_id: 'thread-1', offset: 0, limit: 200 },
    });
    expect(callCoreRpc).toHaveBeenNthCalledWith(2, {
      method: 'openhuman.ai_list_artifacts',
      params: { thread_id: 'thread-1', offset: 200, limit: 200 },
    });
    expect(outcome).toEqual({
      ok: true,
      artifacts: [
        {
          artifactId: 'art-page-1',
          kind: 'document',
          title: 'First Page Report',
          path: 'artifacts/art-page-1/report.pdf',
          sizeBytes: 100,
        },
        {
          artifactId: 'art-page-2',
          kind: 'image',
          title: 'Second Page Image',
          path: 'artifacts/art-page-2/image.png',
          sizeBytes: 200,
        },
      ],
    });
  });

  it('returns an empty list for nullish core payloads', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce(null);
    const outcome = await listArtifactsForThread('thread-1');
    expect(outcome).toEqual({ ok: true, artifacts: [] });
  });

  it('returns a failed outcome when the core RPC throws', async () => {
    vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('rpc down'));
    const outcome = await listArtifactsForThread('thread-1');
    expect(outcome).toEqual({ ok: false, artifacts: [], error: 'rpc down' });
  });
});

describe('downloadArtifact', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    hoisted.isTauri.mockReturnValue(true);
  });

  it('returns NOT_DESKTOP code when called outside Tauri', async () => {
    hoisted.isTauri.mockReturnValueOnce(false);
    const outcome = await downloadArtifact('art-1', 'Deck', 'pptx');
    expect(outcome).toEqual({
      ok: false,
      code: 'NOT_DESKTOP',
      error: expect.stringContaining('desktop'),
    });
    expect(callCoreRpc).not.toHaveBeenCalled();
    expect(hoisted.invoke).not.toHaveBeenCalled();
  });

  it('returns MISSING_ARTIFACT_ID for empty / whitespace ids', async () => {
    const outcome = await downloadArtifact('   ', 'Deck', 'pptx');
    expect(outcome.ok).toBe(false);
    expect(outcome.code).toBe('MISSING_ARTIFACT_ID');
    expect(callCoreRpc).not.toHaveBeenCalled();
  });

  it('returns RESOLVE_FAILED when the core RPC throws (Error instance)', async () => {
    vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('boom'));
    const outcome = await downloadArtifact('art-1', 'Deck', 'pptx');
    expect(outcome).toEqual({ ok: false, code: 'RESOLVE_FAILED', error: 'boom' });
  });

  it('returns RESOLVE_FAILED with String coercion when RPC throws a non-Error', async () => {
    vi.mocked(callCoreRpc).mockRejectedValueOnce('plain-string-rejection');
    const outcome = await downloadArtifact('art-1', 'Deck', 'pptx');
    expect(outcome.code).toBe('RESOLVE_FAILED');
    expect(outcome.error).toBe('plain-string-rejection');
  });

  it('returns MISSING_ARTIFACT_PATH when core resolves without absolute_path', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({ meta: { id: 'art-1', title: 'Deck' } });
    const outcome = await downloadArtifact('art-1', 'Deck', 'pptx');
    expect(outcome.code).toBe('MISSING_ARTIFACT_PATH');
  });

  it('returns MISSING_ARTIFACT_PATH when core returns nullish payload', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce(null);
    const outcome = await downloadArtifact('art-1', 'Deck', 'pptx');
    expect(outcome.code).toBe('MISSING_ARTIFACT_PATH');
  });

  it('happy path: resolves → invokes download → returns ok + dest path', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/workspace/artifacts/art-1/deck.pptx',
      meta: { id: 'art-1', title: 'climate-deck' },
    });
    hoisted.invoke.mockResolvedValueOnce('/Users/me/Downloads/climate-deck.pptx');
    const outcome = await downloadArtifact('art-1', 'fallback-title', 'pptx');
    expect(outcome).toEqual({ ok: true, path: '/Users/me/Downloads/climate-deck.pptx' });
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'climate-deck.pptx',
    });
  });

  it('falls back to the caller-supplied title when meta.title is blank', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { id: 'art-1', title: '   ' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/file.pdf');
    await downloadArtifact('art-1', 'caller-fallback', 'pdf');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'caller-fallback.pdf',
    });
  });

  it('falls back to "artifact" when both meta.title and fallbackTitle are blank', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({ absolute_path: '/p/file' });
    hoisted.invoke.mockResolvedValueOnce('/dest/x');
    await downloadArtifact('art-1', '   ', 'bin');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'artifact.bin',
    });
  });

  it('strips leading dots from the extension hint', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'deck' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/deck.pptx');
    await downloadArtifact('art-1', 'deck', '...pptx');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'deck.pptx',
    });
  });

  it('does NOT double-append the extension when the title already carries it (same ext)', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'deck.pptx' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/deck.pptx');
    await downloadArtifact('art-1', 'deck.pptx', 'pptx');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'deck.pptx',
    });
  });

  it('does NOT double-append the extension (case-insensitive match on existing ext)', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'DECK.PPTX' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/x');
    await downloadArtifact('art-1', 'DECK.PPTX', 'pptx');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'DECK.PPTX',
    });
  });

  it('appends the extension to a title that only looks like it has one', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/workspace/files/release-v1.2.md',
      meta: { title: 'Release v1.2' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/Release v1.2.md');
    await downloadArtifact('art-1', 'Release v1.2', 'md');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'Release v1.2.md',
    });
  });

  it('does NOT double-append when the title already has any trailing extension', async () => {
    // Title says .pdf but caller asked for pptx — defensive: keep the
    // user-visible title untouched rather than synthesising deck.pdf.pptx.
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'deck.pdf' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/x');
    await downloadArtifact('art-1', 'deck.pdf', 'pptx');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'deck.pdf',
    });
  });

  it('appends the extension when the title has no extension', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'climate-overview' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/climate-overview.pptx');
    await downloadArtifact('art-1', 'climate-overview', 'pptx');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'climate-overview.pptx',
    });
  });

  it('keeps the title bare when the extension hint is empty', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'just-a-title' },
    });
    hoisted.invoke.mockResolvedValueOnce('/dest/just-a-title');
    await downloadArtifact('art-1', 'just-a-title', '');
    expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', {
      artifactId: 'art-1',
      filename: 'just-a-title',
    });
  });

  it('returns DOWNLOAD_FAILED when the Tauri invoke throws', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'deck' },
    });
    hoisted.invoke.mockRejectedValueOnce(new Error('disk full'));
    const outcome = await downloadArtifact('art-1', 'deck', 'pptx');
    expect(outcome).toEqual({ ok: false, code: 'DOWNLOAD_FAILED', error: 'disk full' });
  });

  it('returns DOWNLOAD_FAILED with String coercion when invoke rejects with a non-Error', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/p/file',
      meta: { title: 'deck' },
    });
    hoisted.invoke.mockRejectedValueOnce('not-an-Error');
    const outcome = await downloadArtifact('art-1', 'deck', 'pptx');
    expect(outcome).toEqual({ ok: false, code: 'DOWNLOAD_FAILED', error: 'not-an-Error' });
  });
});

describe('deleteArtifact', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('returns MISSING_ARTIFACT_ID for empty / whitespace ids without calling the RPC', async () => {
    const outcome = await deleteArtifact('   ');
    expect(outcome).toEqual({
      ok: false,
      code: 'MISSING_ARTIFACT_ID',
      error: 'artifact id missing',
    });
    expect(callCoreRpc).not.toHaveBeenCalled();
  });

  it('returns ok when the core RPC resolves', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce(null);
    const outcome = await deleteArtifact('art-1');
    expect(outcome).toEqual({ ok: true });
    expect(callCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.ai_delete_artifact',
      params: { artifact_id: 'art-1' },
    });
  });

  it('returns DELETE_FAILED when the core RPC throws', async () => {
    vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('rpc down'));
    const outcome = await deleteArtifact('art-1');
    expect(outcome).toEqual({ ok: false, code: 'DELETE_FAILED', error: 'rpc down' });
  });

  it('returns DELETE_FAILED with String coercion on non-Error rejection', async () => {
    vi.mocked(callCoreRpc).mockRejectedValueOnce({ code: 500 });
    const outcome = await deleteArtifact('art-1');
    expect(outcome.code).toBe('DELETE_FAILED');
    expect(outcome.error).toBe('[object Object]');
  });
});

describe('revealArtifact', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    hoisted.isTauri.mockReturnValue(true);
  });

  it('needs the desktop app', async () => {
    hoisted.isTauri.mockReturnValueOnce(false);
    const outcome = await revealArtifact('art-1');
    expect(outcome).toEqual(expect.objectContaining({ ok: false, code: 'NOT_DESKTOP' }));
    expect(callCoreRpc).not.toHaveBeenCalled();
    expect(hoisted.revealPath).not.toHaveBeenCalled();
  });

  it('reveals the real file the core reports, not a Downloads copy', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({
      absolute_path: '/Users/me/OpenHuman/projects/Files/deck.pptx',
    });
    hoisted.revealPath.mockResolvedValueOnce(undefined);

    const outcome = await revealArtifact('art-1');

    expect(outcome).toEqual({ ok: true });
    expect(callCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.ai_get_artifact',
      params: { artifact_id: 'art-1' },
    });
    expect(hoisted.revealPath).toHaveBeenCalledWith('/Users/me/OpenHuman/projects/Files/deck.pptx');
  });

  it('reports a file the core cannot resolve (e.g. moved or deleted)', async () => {
    vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('file missing for id=art-1'));
    const outcome = await revealArtifact('art-1');
    expect(outcome).toEqual({
      ok: false,
      code: 'RESOLVE_FAILED',
      error: 'file missing for id=art-1',
    });
    expect(hoisted.revealPath).not.toHaveBeenCalled();
  });

  it('reports a file manager that refuses the path', async () => {
    vi.mocked(callCoreRpc).mockResolvedValueOnce({ absolute_path: 'C:\\Users\\x\\deck.pptx' });
    hoisted.revealPath.mockRejectedValueOnce(new Error('path on another OS'));
    const outcome = await revealArtifact('art-1');
    expect(outcome).toEqual({ ok: false, code: 'REVEAL_FAILED', error: 'path on another OS' });
  });

  it('rejects an empty id without calling the core', async () => {
    const outcome = await revealArtifact('   ');
    expect(outcome).toEqual(expect.objectContaining({ ok: false, code: 'MISSING_ARTIFACT_ID' }));
    expect(callCoreRpc).not.toHaveBeenCalled();
  });
});

describe('saveArtifactViaDialog (OS save dialog)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    hoisted.isTauri.mockReturnValue(true);
  });

  const resolveOk = () =>
    vi
      .mocked(callCoreRpc)
      .mockResolvedValueOnce({
        absolute_path: '/ws/artifacts/a-1/deck.pptx',
        meta: { id: 'a-1', title: 'Deck' },
      } as never);

  it('returns NOT_DESKTOP outside Tauri', async () => {
    hoisted.isTauri.mockReturnValueOnce(false);
    const outcome = await saveArtifactViaDialog('a-1', 'Deck', 'pptx');
    expect(outcome).toEqual({
      ok: false,
      code: 'NOT_DESKTOP',
      error: expect.stringContaining('desktop'),
    });
    expect(callCoreRpc).not.toHaveBeenCalled();
  });

  it('opens the save dialog prefilled with the artifact filename', async () => {
    resolveOk();
    hoisted.invoke.mockResolvedValueOnce('/Users/me/Desktop/Deck.pptx');
    const outcome = await saveArtifactViaDialog('a-1', 'Deck', 'pptx');
    expect(outcome).toEqual({ ok: true, path: '/Users/me/Desktop/Deck.pptx' });
    expect(hoisted.invoke).toHaveBeenCalledWith('save_artifact_as', {
      artifactId: 'a-1',
      filename: 'Deck.pptx',
    });
  });

  it('reports a closed dialog as CANCELLED', async () => {
    resolveOk();
    hoisted.invoke.mockResolvedValueOnce(null);
    const outcome = await saveArtifactViaDialog('a-1', 'Deck', 'pptx');
    expect(outcome).toEqual({ ok: false, code: 'CANCELLED' });
  });

  it('surfaces a save failure as DOWNLOAD_FAILED', async () => {
    resolveOk();
    hoisted.invoke.mockRejectedValueOnce(new Error('disk full'));
    const outcome = await saveArtifactViaDialog('a-1', 'Deck', 'pptx');
    expect(outcome).toEqual({ ok: false, code: 'DOWNLOAD_FAILED', error: 'disk full' });
  });

  it('propagates resolve failures without invoking the shell', async () => {
    vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('rpc down'));
    const outcome = await saveArtifactViaDialog('a-1', 'Deck', 'pptx');
    expect(outcome).toEqual({ ok: false, code: 'RESOLVE_FAILED', error: 'rpc down' });
    expect(hoisted.invoke).not.toHaveBeenCalled();
  });
});