Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

14.1 KB
Raw Blame
import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';

const tmpRoots = [];
const makeTmp = async (prefix) => {
  const dir = await mkdtemp(join(tmpdir(), prefix));
  tmpRoots.push(dir);
  return dir;
};
const musicDir = await makeTmp('chiptune-music-');

vi.mock('./tracks/index.js', () => ({
  getTrack: vi.fn(),
  updateTrack: vi.fn(),
  appendActiveTake: vi.fn(async (id, take) => ({ id, ...take })),
}));

vi.mock('./promptRunner.js', () => ({
  resolveProviderAndModel: vi.fn(),
  assertProvider: vi.fn(),
  runPromptThroughProvider: vi.fn(),
}));

vi.mock('./apps.js', () => ({
  getAppById: vi.fn(),
  PORTOS_APP_ID: 'portos-default',
}));

// No ffmpeg in tests — the render path keeps the deterministic WAV output.
vi.mock('../lib/ffmpeg.js', () => ({
  findFfmpeg: vi.fn().mockResolvedValue(null),
  runFfmpegProcess: vi.fn(),
}));

vi.mock('../lib/fileUtils.js', async (importOriginal) => {
  const actual = await importOriginal();
  return { ...actual, PATHS: { ...actual.PATHS, music: musicDir } };
});

const tracks = await import('./tracks/index.js');
const promptRunner = await import('./promptRunner.js');
const apps = await import('./apps.js');
const { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack, buildChiptunePrompt } = await import('./chiptune.js');

const validScore = () => ({
  version: 1,
  bpm: 120,
  stepsPerBeat: 4,
  beatsPerBar: 4,
  channels: [{ id: 'pulse1', wave: 'square', duty: 0.5, gain: 0.5 }],
  patterns: { A: { bars: 1, notes: { pulse1: [{ step: 0, pitch: 'C5', len: 4 }] } } },
  order: ['A'],
});

const baseTrack = (extra = {}) => ({
  id: 'track-1', title: 'Farm Theme', renders: [], chiptuneScore: null, chiptunePrompt: '', ...extra,
});

afterAll(async () => {
  await Promise.all(tmpRoots.map((dir) => rm(dir, { recursive: true, force: true })));
});

beforeEach(() => {
  vi.clearAllMocks();
  promptRunner.resolveProviderAndModel.mockResolvedValue({
    provider: { id: 'prov-1', type: 'api' }, selectedModel: 'model-x',
  });
  tracks.updateTrack.mockImplementation(async (id, patch) => ({ ...baseTrack(), ...patch }));
});

describe('generateChiptuneScore', () => {
  it('runs the provider with the score schema and persists the validated score', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack());
    promptRunner.runPromptThroughProvider.mockResolvedValue({
      text: JSON.stringify(validScore()), provider: { id: 'prov-1' }, model: 'model-x',
    });

    const result = await generateChiptuneScore({ trackId: 'track-1', prompt: 'upbeat farm theme', providerId: 'prov-1', model: 'model-x' });

    expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({
      provider: { id: 'prov-1', type: 'api' },
      source: 'chiptune-score',
      model: 'model-x',
      responseSchema: expect.anything(),
    }));
    expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', {
      chiptuneScore: expect.objectContaining({ bpm: 120 }),
      chiptunePrompt: 'upbeat farm theme',
    });
    expect(result.providerId).toBe('prov-1');
    expect(result.model).toBe('model-x');
  });

  it('iterates on an existing score by default and starts fresh when asked', async () => {
    const existing = validScore();
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: existing }));
    promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(validScore()), provider: { id: 'prov-1' }, model: null });

    await generateChiptuneScore({ trackId: 'track-1', prompt: 'faster' });
    expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).toContain('CURRENT SCORE');

    await generateChiptuneScore({ trackId: 'track-1', prompt: 'faster', fresh: true });
    expect(promptRunner.runPromptThroughProvider.mock.calls[1][0].prompt).not.toContain('CURRENT SCORE');
  });

  it('rejects a response that fails schema validation after the runner', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack());
    promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify({ version: 1 }), provider: { id: 'prov-1' } });
    await expect(generateChiptuneScore({ trackId: 'track-1', prompt: 'x' }))
      .rejects.toMatchObject({ code: 'CHIPTUNE_BAD_RESPONSE' });
    expect(tracks.updateTrack).not.toHaveBeenCalled();
  });

  it('404s on an unknown track', async () => {
    tracks.getTrack.mockResolvedValue(null);
    await expect(generateChiptuneScore({ trackId: 'nope', prompt: 'x' }))
      .rejects.toMatchObject({ status: 404 });
  });
});

describe('buildChiptunePrompt', () => {
  it('embeds the request and, when iterating, the current score JSON', () => {
    const fresh = buildChiptunePrompt({ prompt: 'spooky cave theme', currentScore: null });
    expect(fresh).toContain('spooky cave theme');
    expect(fresh).not.toContain('CURRENT SCORE');
    const iterate = buildChiptunePrompt({ prompt: 'more drums', currentScore: validScore() });
    expect(iterate).toContain('CURRENT SCORE');
    expect(iterate).toContain('"order":["A"]');
  });
});

describe('renderChiptuneTrack', () => {
  it('400s when the track has no score', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack());
    await expect(renderChiptuneTrack({ trackId: 'track-1' }))
      .rejects.toMatchObject({ code: 'CHIPTUNE_NO_SCORE' });
  });

  it('renders a WAV into the music library and appends a chiptune render', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore(), chiptunePrompt: 'farm loop' }));

    const result = await renderChiptuneTrack({ trackId: 'track-1' });

    expect(result.filename).toMatch(/^music-.+\.wav$/);
    const files = await readdir(musicDir);
    expect(files).toContain(result.filename);
    expect(result.durationSec).toBe(2); // 16 steps · 0.125s = 2s
    expect(tracks.appendActiveTake).toHaveBeenCalledWith('track-1', {
      audioFilename: result.filename,
      prompt: 'farm loop',
      engine: 'chiptune',
      durationSec: result.durationSec,
    });
  });
});

describe('publishChiptuneTrack', () => {
  it('404s when the app is unknown or has no repoPath', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
    apps.getAppById.mockResolvedValue(null);
    await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'nope' }))
      .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_FOUND' });
    apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: '' });
    await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' }))
      .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_FOUND' });
  });

  it('refuses PortOS itself and archived apps as publish targets', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
    apps.getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS', repoPath: '/tmp' });
    await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'portos-default' }))
      .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_PUBLISHABLE' });
    apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: '/tmp', archived: true });
    await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' }))
      .rejects.toMatchObject({ code: 'CHIPTUNE_APP_NOT_PUBLISHABLE' });
  });

  it('rejects traversal and absolute subdirs before touching the filesystem', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
    const repo = await makeTmp('chiptune-repo-');
    apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });
    for (const subdir of ['../outside', 'a/../../b', '/etc', 'a\\..\\b']) {
      await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1', subdir }))
        .rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
    }
  });

  it('400s when the repo path does not exist on disk', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
    apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: '/nonexistent/path/for/test' });
    await expect(publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' }))
      .rejects.toMatchObject({ code: 'CHIPTUNE_APP_REPO_MISSING' });
  });

  it('writes the audio + score JSON under the default subdir with a slugged name', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
    const repo = await makeTmp('chiptune-repo-');
    apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });

    const result = await publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1' });

    expect(result.files).toEqual(['game/assets/music/farm-theme.wav', 'game/assets/music/farm-theme.score.json']);
    expect(result.format).toBe('wav'); // ffmpeg mocked away → WAV fallback
    const published = JSON.parse(await readFile(join(repo, 'game/assets/music/farm-theme.score.json'), 'utf8'));
    expect(published.bpm).toBe(120);
    const audio = await readFile(join(repo, 'game/assets/music/farm-theme.wav'));
    expect(audio.toString('ascii', 0, 4)).toBe('RIFF');
  });

  it('honors a custom subdir and slug', async () => {
    tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
    const repo = await makeTmp('chiptune-repo-');
    apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });

    const result = await publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1', subdir: 'assets/bgm', slug: 'Overworld Theme!' });
    expect(result.files[0]).toBe('assets/bgm/overworld-theme.wav');
  });

  describe('symlink containment (#10894)', () => {
    // Disposable synthetic roots: <root>/app is the managed repo, <root>/outside is
    // an unrelated directory holding pre-existing files a publish must not touch.
    const setup = async () => {
      const root = await makeTmp('chiptune-symlink-');
      const repo = join(root, 'app');
      const outside = join(root, 'outside');
      await mkdir(repo);
      await mkdir(outside);
      await writeFile(join(outside, 'example.wav'), 'outside-wav');
      await writeFile(join(outside, 'example.score.json'), 'outside-score');
      tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
      apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });
      return { repo, outside };
    };
    const publish = (subdir) => publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1', subdir, slug: 'example' });
    const expectOutsideUntouched = async (outside) => {
      expect(await readFile(join(outside, 'example.wav'), 'utf8')).toBe('outside-wav');
      expect(await readFile(join(outside, 'example.score.json'), 'utf8')).toBe('outside-score');
      expect((await readdir(outside)).sort()).toEqual(['example.score.json', 'example.wav']);
    };

    it('refuses a subdir that is a directory symlink out of the app, leaving outside files unchanged', async () => {
      const { repo, outside } = await setup();
      await symlink(outside, join(repo, 'linked-assets'));
      await expect(publish('linked-assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
      await expectOutsideUntouched(outside);
    });

    it('refuses a symlink in the middle of a nested subdir and a dangling directory link', async () => {
      const { repo, outside } = await setup();
      await symlink(outside, join(repo, 'shared'));
      await expect(publish('shared/music')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
      await symlink(join(outside, 'nope'), join(repo, 'dangling'));
      await expect(publish('dangling')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
      await expectOutsideUntouched(outside);
      await expect(readdir(join(outside, 'nope'))).rejects.toMatchObject({ code: 'ENOENT' });
    });

    it('refuses a symlinked destination leaf before any write, so there is no partial publish', async () => {
      const { repo, outside } = await setup();
      const dir = join(repo, 'assets');
      await mkdir(dir);
      // Only the LAST destination (the score sidecar) is invalid: the WAV must not be written first.
      await symlink(join(outside, 'example.score.json'), join(dir, 'example.score.json'));
      await expect(publish('assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
      expect(await readdir(dir)).toEqual(['example.score.json']);
      expect(await readFile(join(outside, 'example.score.json'), 'utf8')).toBe('outside-score');

      await rm(join(dir, 'example.score.json'));
      await symlink(join(outside, 'missing.ogg'), join(dir, 'example.ogg')); // dangling OGG link
      await expect(publish('assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
      expect(await readdir(dir)).toEqual(['example.ogg']);
      await expectOutsideUntouched(outside);
    });

    it('refuses a link substituted between two requests', async () => {
      const { repo, outside } = await setup();
      await publish('assets');
      expect((await lstat(join(repo, 'assets/example.wav'))).isFile()).toBe(true);
      await rm(join(repo, 'assets'), { recursive: true });
      await symlink(outside, join(repo, 'assets'));
      await expect(publish('assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
      await expectOutsideUntouched(outside);
    });

    it('still creates missing nested directories and publishes through a symlinked repo root', async () => {
      const { repo, outside } = await setup();
      const alias = join(await makeTmp('chiptune-alias-'), 'repo-link');
      await symlink(repo, alias); // the checkout path itself may legitimately be a link
      apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: alias });
      const result = await publish('a/b/music/');
      expect(result.files).toEqual(['a/b/music/example.wav', 'a/b/music/example.score.json']);
      const realRepo = await realpath(repo);
      expect((await lstat(join(realRepo, 'a/b/music/example.wav'))).isFile()).toBe(true);
      expect((await lstat(join(realRepo, 'a/b/music/example.score.json'))).isFile()).toBe(true);
      await expectOutsideUntouched(outside);
    });
  });
});