Skip to content

moonlight-lupin/agent-skills / creative/clips-studio

clips-studio

Verified

Use when the user wants to "make a video/clip", "generate a video from text", "animate this image/photo", "create a marketing reel / social video / teaser", "do a 3D / parallax move", "pan/zoom/orbit a shot", or mentions fal.ai, Kling, Veo or Seedance for video. Staged fal.ai workflow — brainstorm, draft cheaply, produce the final at quality. Three modes: text-to-video, animate (still to motion), camera-move (push-in/pan/orbit). Not for still images (image-studio), slide decks, or charts. Honesty discipline: never depict real identifiable subjects via text-to-video.

FileKindSize
README.mdmarkdown1.9 KB
SKILL.mdskill md23.5 KB
examples/example-run.mdmarkdown8.1 KB
references/fal-video-models.mdmarkdown11.9 KB
references/motion-honesty-guide.mdmarkdown11.4 KB
references/video-prompting-techniques.mdmarkdown3.4 KB
scripts/falvid.pyscript34.5 KB
tests/__init__.pyscript0 B
tests/test_falvid.pyscript31.3 KB

tests/test_falvid.py

View on GitHub
#!/usr/bin/env python3
"""Unit tests for falvid.py pure-Python helpers and dry-run behavior."""

import argparse
import io
import os
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import MagicMock, patch

SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
sys.path.insert(0, str(SCRIPTS_DIR))

import falvid  # noqa: E402


class TestVideoCostPerSecond(unittest.TestCase):
    def test_kling_basic(self):
        cost, basis, exact = falvid._video_cost("fal-ai/kling-video/v2.5-turbo/pro/image-to-video", 5, {})
        self.assertAlmostEqual(cost, 0.35, places=4)
        self.assertFalse(exact)
        self.assertIn("5s", basis)

    def test_veo_audio(self):
        cost, basis, _ = falvid._video_cost("fal-ai/veo3.1/image-to-video", 5, {"generate_audio": True})
        self.assertAlmostEqual(cost, 2.0, places=4)
        self.assertIn("audio", basis)

    def test_veo_4k(self):
        cost, basis, _ = falvid._video_cost("fal-ai/veo3.1/image-to-video", 5, {"resolution": "4K"})
        self.assertAlmostEqual(cost, 2.0, places=4)
        self.assertIn("4K", basis)

    def test_flux3_draft_720p(self):
        cost, basis, _ = falvid._video_cost("blackforestlabs/flux-3/text-to-video/draft", 5, {})
        self.assertAlmostEqual(cost, 0.30, places=4)
        self.assertIn("0.06", basis)

    def test_flux3_full_720p(self):
        cost, basis, _ = falvid._video_cost("blackforestlabs/flux-3/text-to-video", 5, {})
        self.assertAlmostEqual(cost, 0.85, places=4)
        self.assertIn("0.17", basis)

    def test_flux3_full_1080p(self):
        cost, basis, _ = falvid._video_cost("blackforestlabs/flux-3/text-to-video", 5, {"resolution": "1080p"})
        self.assertAlmostEqual(cost, 1.45, places=4)
        self.assertIn("FHD", basis)

    def test_flux3_extend_720p(self):
        cost, basis, _ = falvid._video_cost("blackforestlabs/flux-3/extend-video", 5, {})
        self.assertAlmostEqual(cost, 2.05, places=4)

    def test_seedance_25_720p(self):
        cost, basis, _ = falvid._video_cost("fal-ai/bytedance/seedance-2.5/image-to-video", 5, {})
        self.assertAlmostEqual(cost, 2.365, places=4)

    def test_seedance_20_720p(self):
        cost, basis, _ = falvid._video_cost("fal-ai/bytedance/seedance-2.0/image-to-video", 5, {})
        self.assertAlmostEqual(cost, 1.512, places=4)


class TestVideoCostOtherUnits(unittest.TestCase):
    def test_seedance_per_clip_prorated(self):
        cost, basis, _ = falvid._video_cost("fal-ai/bytedance/seedance/v1.5/pro/image-to-video", 10, {})
        self.assertAlmostEqual(cost, 0.52, places=4)
        self.assertIn("10/5s", basis)

    def test_ltx_per_output_frame_megapixel(self):
        cost, basis, _ = falvid._video_cost("fal-ai/ltx-2-19b/text-to-video", 5, {})
        expected_mp = (1920 * 1080 / 1_000_000) * 24 * 5
        self.assertAlmostEqual(cost, 0.0018 * expected_mp, places=4)
        self.assertIn("output-frame MP", basis)
        self.assertGreater(cost, 0.44)

    def test_unknown_model(self):
        cost, basis, _ = falvid._video_cost("fal-ai/nonexistent/model", 5, {})
        self.assertIsNone(cost)
        self.assertIn("no rate on file", basis)


class TestParsing(unittest.TestCase):
    def test_parse_scalar(self):
        self.assertEqual(falvid._parse_scalar("42"), 42)
        self.assertAlmostEqual(falvid._parse_scalar("3.14"), 3.14)
        self.assertIs(falvid._parse_scalar("true"), True)
        self.assertEqual(falvid._parse_scalar('[1, 2]'), [1, 2])
        self.assertEqual(falvid._parse_scalar("blurry, distorted"), "blurry, distorted")

    def test_parse_extra_args(self):
        self.assertEqual(
            falvid._parse_extra_args(["seed=42"], ['{"negative_prompt":"blurry"}']),
            {"negative_prompt": "blurry", "seed": 42},
        )

    def test_bad_arg_exits(self):
        with self.assertRaises(SystemExit):
            falvid._parse_extra_args(["bad"])
        with self.assertRaises(SystemExit):
            falvid._parse_extra_args([], ["[1, 2]"])


class TestDurationAndModelMatching(unittest.TestCase):
    def test_duration_bounds(self):
        falvid._check_duration("fal-ai/kling-video/v2.5-turbo/pro/image-to-video", 10)
        with self.assertRaises(SystemExit):
            falvid._check_duration("fal-ai/veo3.1/image-to-video", 15)

    def test_unknown_model_no_duration_check(self):
        falvid._check_duration("fal-ai/unknown/model", 999)

    def test_model_has(self):
        self.assertTrue(falvid._model_has("fal-ai/kling-video/v3/pro/image-to-video", ("kling-video/v3",)))
        self.assertFalse(falvid._model_has("fal-ai/veo3.1/image-to-video", ("seedance",)))


class TestDryRun(unittest.TestCase):
    def test_generate_dry_run_does_not_require_fal_key(self):
        args = argparse.Namespace(
            prompt="a short clip",
            duration=5,
            resolution=None,
            aspect="16:9",
            audio=False,
            seed=None,
            model=None,
            out_dir="_workings",
            name="vid",
            arg=None,
            arg_json=None,
            cost_log=None,
            run_log=None,
            verbose=False,
            dry_run=True,
        )
        with patch.dict(os.environ, {}, clear=True):
            buf = io.StringIO()
            with redirect_stdout(buf):
                falvid.cmd_generate(args)
        out = buf.getvalue()
        self.assertIn("DRY RUN", out)
        self.assertIn("no fal.ai call", out)
        self.assertIn("blackforestlabs/flux-3/text-to-video/draft", out)

    def test_animate_dry_run_redacts_image_url(self):
        args = argparse.Namespace(
            prompt="slow push",
            image="still.png",
            duration=5,
            resolution=None,
            aspect="16:9",
            audio=False,
            seed=None,
            model=None,
            out_dir="_workings",
            name="vid",
            arg=None,
            arg_json=None,
            cost_log=None,
            run_log=None,
            verbose=False,
            dry_run=True,
        )
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_animate(args)
        out = buf.getvalue()
        self.assertIn("Input image", out)
        self.assertIn("[omitted from log; see input_images]", out)


class TestEnhanceGuard(unittest.TestCase):
    """Draft Enhance is FLUX 3-specific — non-FLUX-3 models must be rejected."""

    def _enhance_args(self, model=None):
        return argparse.Namespace(
            prompt="test motion",
            image="still.png",
            seed=12345,
            mode="animate",
            duration=5,
            resolution=None,
            aspect=None,
            audio=False,
            model=model,
            out_dir=".",
            name="vid_enhanced",
            arg=None,
            arg_json=None,
            cost_log=None,
            run_log=None,
            verbose=False,
            dry_run=True,
        )

    def test_enhance_with_kling_rejected(self):
        args = self._enhance_args(model="fal-ai/kling-video/v3/pro/image-to-video")
        with self.assertRaises(SystemExit) as ctx:
            falvid.cmd_enhance(args)
        self.assertIn("FLUX 3-specific", str(ctx.exception))

    def test_enhance_with_seedance_25_rejected(self):
        args = self._enhance_args(model="fal-ai/bytedance/seedance-2.5/image-to-video")
        with self.assertRaises(SystemExit) as ctx:
            falvid.cmd_enhance(args)
        self.assertIn("FLUX 3-specific", str(ctx.exception))

    def test_enhance_with_flux3_accepted_dry_run(self):
        args = self._enhance_args(model="blackforestlabs/flux-3/image-to-video")
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_enhance(args)
        out = buf.getvalue()
        self.assertIn("DRY RUN", out)
        self.assertIn("flux-3/image-to-video", out)

    def test_enhance_default_is_flux3(self):
        args = self._enhance_args(model=None)
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_enhance(args)
        out = buf.getvalue()
        self.assertIn("flux-3/image-to-video", out)


class TestCameraDryRun(unittest.TestCase):
    """cmd_camera dry-run: should build a camera-move prompt and produce output."""

    def _camera_args(self, **overrides):
        defaults = dict(
            prompt=None,
            move="push-in",
            static=False,
            image="still.png",
            duration=5,
            resolution=None,
            aspect="16:9",
            audio=False,
            seed=None,
            model=None,
            out_dir="_workings",
            name="vid_camera",
            arg=None,
            arg_json=None,
            cost_log=None,
            run_log=None,
            verbose=False,
            dry_run=True,
        )
        defaults.update(overrides)
        return argparse.Namespace(**defaults)

    def test_camera_dry_run_uses_seedance_default(self):
        args = self._camera_args()
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_camera(args)
        out = buf.getvalue()
        self.assertIn("DRY RUN", out)
        self.assertIn("seedance/v1.5/pro/image-to-video", out)

    def test_camera_move_in_prompt(self):
        args = self._camera_args(move="push-in")
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_camera(args)
        out = buf.getvalue()
        self.assertIn("push-in", out.lower())

    def test_camera_static_adds_camera_fixed(self):
        args = self._camera_args(static=True, move=None, prompt="a calm scene")
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_camera(args)
        out = buf.getvalue()
        # Seedance supports camera_fixed, so it should be set
        self.assertIn("camera_fixed", out)

    def test_camera_static_non_seedance_uses_prompt_language(self):
        args = self._camera_args(
            static=True, move=None, prompt="a calm scene",
            model="fal-ai/veo3.1/image-to-video",
        )
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_camera(args)
        out = buf.getvalue()
        self.assertIn("Static shot", out)
        self.assertNotIn("camera_fixed", out)

    def test_camera_invalid_move_exits(self):
        args = self._camera_args(move="teleport")
        with self.assertRaises(SystemExit):
            falvid.cmd_camera(args)

    def test_camera_no_move_no_prompt_exits(self):
        args = self._camera_args(move=None, prompt=None)
        with self.assertRaises(SystemExit):
            falvid.cmd_camera(args)


class TestCmdCosts(unittest.TestCase):
    """cmd_costs: cost log reading, reset, and empty log handling."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()
        self.cost_log = str(Path(self._tmp.name) / "costs.jsonl")

    def tearDown(self):
        self._tmp.cleanup()

    def _costs_args(self, **overrides):
        defaults = dict(cost_log=self.cost_log, reset=False)
        defaults.update(overrides)
        return argparse.Namespace(**defaults)

    def test_costs_no_log_prints_message(self):
        args = self._costs_args()
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_costs(args)
        out = buf.getvalue()
        self.assertIn("No cost log", out)

    def test_costs_reset_clears_log(self):
        # Write a fake cost log
        Path(self.cost_log).write_text('{"cost": 0.85, "currency": "USD", "command": "generate", "model": "test", "basis": "5s x $0.17/s", "time": "2026-01-01 00:00:00"}\n')
        args = self._costs_args(reset=True)
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_costs(args)
        out = buf.getvalue()
        self.assertIn("cleared", out)
        self.assertFalse(Path(self.cost_log).exists())

    def test_costs_displays_entries_and_total(self):
        import json as _json
        entries = [
            {"cost": 0.30, "currency": "USD", "command": "generate", "model": "flux3-draft", "basis": "5s x $0.06/s", "time": "2026-01-01 10:00:00"},
            {"cost": 0.85, "currency": "USD", "command": "generate", "model": "flux3-full", "basis": "5s x $0.17/s", "time": "2026-01-01 11:00:00"},
        ]
        with open(self.cost_log, "w") as f:
            for e in entries:
                f.write(_json.dumps(e) + "\n")
        args = self._costs_args()
        buf = io.StringIO()
        with redirect_stdout(buf):
            falvid.cmd_costs(args)
        out = buf.getvalue()
        self.assertIn("flux3-draft", out)
        self.assertIn("flux3-full", out)
        self.assertIn("TOTAL", out)
        self.assertIn("$1.15", out)


class TestBuildVideoArgs(unittest.TestCase):
    """_build_video_args: correct key mapping for different models."""

    def test_kling_v3_uses_start_image_url(self):
        args = argparse.Namespace(
            image="still.png", duration=5, resolution=None, aspect="16:9",
            audio=False, seed=None, arg=None, arg_json=None,
        )
        _, built, _ = falvid._build_video_args(args, "fal-ai/kling-video/v3/pro/image-to-video", "test", dry_run=True)
        self.assertIn("start_image_url", built)
        self.assertNotIn("image_url", built)

    def test_non_kling_uses_image_url(self):
        args = argparse.Namespace(
            image="still.png", duration=5, resolution=None, aspect="16:9",
            audio=False, seed=None, arg=None, arg_json=None,
        )
        _, built, _ = falvid._build_video_args(args, "fal-ai/veo3.1/image-to-video", "test", dry_run=True)
        self.assertIn("image_url", built)
        self.assertNotIn("start_image_url", built)

    def test_kling_duration_is_string(self):
        args = argparse.Namespace(
            image="still.png", duration=5, resolution=None, aspect="16:9",
            audio=False, seed=None, arg=None, arg_json=None,
        )
        _, built, _ = falvid._build_video_args(args, "fal-ai/kling-video/v3/pro/image-to-video", "test", dry_run=True)
        self.assertEqual(built["duration"], "5")

    def test_non_kling_duration_is_int(self):
        args = argparse.Namespace(
            image="still.png", duration=5, resolution=None, aspect="16:9",
            audio=False, seed=None, arg=None, arg_json=None,
        )
        _, built, _ = falvid._build_video_args(args, "fal-ai/veo3.1/image-to-video", "test", dry_run=True)
        self.assertEqual(built["duration"], 5)

    def test_audio_flag_added_for_audio_models(self):
        args = argparse.Namespace(
            image="still.png", duration=5, resolution=None, aspect="16:9",
            audio=True, seed=None, arg=None, arg_json=None,
        )
        _, built, _ = falvid._build_video_args(args, "fal-ai/veo3.1/image-to-video", "test", dry_run=True)
        self.assertTrue(built["generate_audio"])

    def test_audio_flag_omitted_for_non_audio_models(self):
        args = argparse.Namespace(
            image="still.png", duration=5, resolution=None, aspect="16:9",
            audio=True, seed=None, arg=None, arg_json=None,
        )
        _, built, _ = falvid._build_video_args(args, "fal-ai/wan/v2.2-a14b/text-to-video", "test", dry_run=True)
        self.assertNotIn("generate_audio", built)

    def test_flux3_audio_flag_added(self):
        args = argparse.Namespace(
            image="still.png", duration=5, resolution=None, aspect="16:9",
            audio=True, seed=42, arg=None, arg_json=None,
        )
        _, built, _ = falvid._build_video_args(args, "blackforestlabs/flux-3/image-to-video", "test", dry_run=True)
        self.assertTrue(built["generate_audio"])
        self.assertEqual(built["seed"], 42)


class TestExtractFalKey(unittest.TestCase):
    """Tests for _extract_fal_key — content-based key detection from file text."""

    SAMPLE_KEY = "a1b2c3d4-e5f6-7890-abcd-ef1234567890:abcdef0123456789abcdef0123456789"

    def test_fal_key_equals_assignment(self):
        text = f"FAL_KEY={self.SAMPLE_KEY}"
        self.assertEqual(falvid._extract_fal_key(text), self.SAMPLE_KEY)

    def test_fal_key_colon_assignment(self):
        text = f"FAL_KEY: {self.SAMPLE_KEY}"
        self.assertEqual(falvid._extract_fal_key(text), self.SAMPLE_KEY)

    def test_fal_key_quoted(self):
        text = f'FAL_KEY="{self.SAMPLE_KEY}"'
        self.assertEqual(falvid._extract_fal_key(text), self.SAMPLE_KEY)

    def test_fal_key_in_multiline_file(self):
        text = f"# my keys\nFAL_KEY={self.SAMPLE_KEY}\nOTHER=xyz\n"
        self.assertEqual(falvid._extract_fal_key(text), self.SAMPLE_KEY)

    def test_bare_id_secret_pattern(self):
        """A raw id:secret UUID token anywhere in text is detected."""
        text = f"some preamble\n{self.SAMPLE_KEY}\nmore stuff"
        self.assertEqual(falvid._extract_fal_key(text), self.SAMPLE_KEY)

    def test_fal_key_assignment_takes_priority_over_bare_token(self):
        """If both a FAL_KEY= line and a bare token exist, the assignment wins."""
        bare = "00000000-0000-0000-0000-000000000000:0000000000000000000000000000000000"
        text = f"FAL_KEY={self.SAMPLE_KEY}\nalso here: {bare}"
        self.assertEqual(falvid._extract_fal_key(text), self.SAMPLE_KEY)

    def test_name_hinted_returns_stripped_single_line(self):
        """For a file whose name hints fal/key, a bare single-line token is accepted."""
        token = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:0123456789abcdef0123456789abcdef"
        self.assertEqual(falvid._extract_fal_key(token, name_hinted=True), token)

    def test_name_hinted_rejects_multiline(self):
        text = "line one\nline two\n"
        self.assertIsNone(falvid._extract_fal_key(text, name_hinted=True))

    def test_name_hinted_rejects_no_colon(self):
        self.assertIsNone(falvid._extract_fal_key("just-a-string", name_hinted=True))

    def test_name_hinted_rejects_too_short(self):
        self.assertIsNone(falvid._extract_fal_key("ab:cd", name_hinted=True))

    def test_name_hinted_rejects_with_spaces(self):
        self.assertIsNone(falvid._extract_fal_key("a b c d e f : x y z", name_hinted=True))

    def test_no_match_returns_none(self):
        self.assertIsNone(falvid._extract_fal_key("nothing useful here"))

    def test_no_match_name_hinted_returns_none(self):
        self.assertIsNone(falvid._extract_fal_key("nothing useful", name_hinted=True))


class TestAutoloadFalKeys(unittest.TestCase):
    """Tests for _autoload_fal_keys — env-var-wins, then cwd, then home, by content."""

    SAMPLE_KEY = "a1b2c3d4-e5f6-7890-abcd-ef1234567890:abcdef0123456789abcdef0123456789"
    ADMIN_KEY = "11111111-2222-3333-4444-555555555555:fedcba9876543210fedcba9876543210"

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()
        self._orig_cwd = Path.cwd()
        self._orig_home = os.environ.get("HOME")

    def tearDown(self):
        os.chdir(str(self._orig_cwd))
        os.environ.pop("FAL_KEY", None)
        os.environ.pop("FAL_ADMIN_KEY", None)
        if self._orig_home is not None:
            os.environ["HOME"] = self._orig_home
        else:
            os.environ.pop("HOME", None)
        self._tmp.cleanup()

    def _set_cwd(self, path):
        os.chdir(str(path))

    def _set_home(self, path):
        os.environ["HOME"] = str(path)

    def _clean_env(self):
        """Env with FAL_KEY/FAL_ADMIN_KEY removed but HOME preserved."""
        return {k: v for k, v in os.environ.items() if k not in ("FAL_KEY", "FAL_ADMIN_KEY")}

    def test_env_var_wins_over_file(self):
        """If FAL_KEY is already in env, no file is read."""
        d = Path(self._tmp.name) / "work"
        d.mkdir()
        (d / "fal key.txt").write_text(f"FAL_KEY={self.SAMPLE_KEY}")
        self._set_cwd(d)
        with patch.dict(os.environ, {"FAL_KEY": "env-var-key"}, clear=False):
            falvid._autoload_fal_keys()
            self.assertEqual(os.environ["FAL_KEY"], "env-var-key")

    def test_finds_key_in_cwd_file(self):
        d = Path(self._tmp.name) / "work"
        d.mkdir()
        (d / "fal key.txt").write_text(f"FAL_KEY={self.SAMPLE_KEY}")
        self._set_cwd(d)
        home = Path(self._tmp.name) / "home"
        home.mkdir()
        self._set_home(home)
        with patch.dict(os.environ, self._clean_env(), clear=True):
            falvid._autoload_fal_keys()
            self.assertEqual(os.environ["FAL_KEY"], self.SAMPLE_KEY)

    def test_finds_bare_id_secret_in_cwd(self):
        d = Path(self._tmp.name) / "work"
        d.mkdir()
        (d / "notes.txt").write_text(f"my key is {self.SAMPLE_KEY}")
        self._set_cwd(d)
        home = Path(self._tmp.name) / "home"
        home.mkdir()
        self._set_home(home)
        with patch.dict(os.environ, self._clean_env(), clear=True):
            falvid._autoload_fal_keys()
            self.assertEqual(os.environ["FAL_KEY"], self.SAMPLE_KEY)

    def test_finds_key_in_home_when_cwd_empty(self):
        work = Path(self._tmp.name) / "work"
        work.mkdir()
        self._set_cwd(work)
        home = Path(self._tmp.name) / "home"
        home.mkdir()
        (home / "fal key.txt").write_text(f"FAL_KEY={self.SAMPLE_KEY}")
        self._set_home(home)
        with patch.dict(os.environ, self._clean_env(), clear=True):
            falvid._autoload_fal_keys()
            self.assertEqual(os.environ["FAL_KEY"], self.SAMPLE_KEY)

    def test_skips_large_files(self):
        """Files >100KB are skipped."""
        d = Path(self._tmp.name) / "work"
        d.mkdir()
        big = d / "fal key.txt"
        big.write_text(f"FAL_KEY={self.SAMPLE_KEY}\n" + "x" * 110_000)
        self._set_cwd(d)
        home = Path(self._tmp.name) / "home"
        home.mkdir()
        self._set_home(home)
        with patch.dict(os.environ, self._clean_env(), clear=True):
            falvid._autoload_fal_keys()
            self.assertNotIn("FAL_KEY", os.environ)

    def test_picks_up_admin_key_too(self):
        d = Path(self._tmp.name) / "work"
        d.mkdir()
        (d / "keys.txt").write_text(
            f"FAL_KEY={self.SAMPLE_KEY}\nFAL_ADMIN_KEY={self.ADMIN_KEY}"
        )
        self._set_cwd(d)
        home = Path(self._tmp.name) / "home"
        home.mkdir()
        self._set_home(home)
        with patch.dict(os.environ, self._clean_env(), clear=True):
            falvid._autoload_fal_keys()
            self.assertEqual(os.environ["FAL_KEY"], self.SAMPLE_KEY)
            self.assertEqual(os.environ["FAL_ADMIN_KEY"], self.ADMIN_KEY)

    def test_no_key_found_leaves_env_unset(self):
        d = Path(self._tmp.name) / "work"
        d.mkdir()
        (d / "random.txt").write_text("nothing useful")
        self._set_cwd(d)
        home = Path(self._tmp.name) / "home"
        home.mkdir()
        self._set_home(home)
        with patch.dict(os.environ, self._clean_env(), clear=True):
            falvid._autoload_fal_keys()
            self.assertNotIn("FAL_KEY", os.environ)


class TestSearchModels(unittest.TestCase):
    """Tests for _search_models — live catalogue search with mock HTTP."""

    def _mock_response(self, models, status=200):
        resp = MagicMock()
        resp.status_code = status
        resp.json.return_value = {"models": models}
        return resp

    def test_returns_models_on_success(self):
        models = [
            {"endpoint_id": "fal-ai/test-1", "metadata": {
                "display_name": "Test 1", "category": "text-to-video",
                "license_type": "MIT", "description": "desc", "status": "active",
            }},
        ]
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response(models)
        result = falvid._search_models("test", requests_mod)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]["endpoint_id"], "fal-ai/test-1")
        self.assertEqual(result[0]["name"], "Test 1")

    def test_filters_inactive_models(self):
        models = [
            {"endpoint_id": "fal-ai/active", "metadata": {"status": "active"}},
            {"endpoint_id": "fal-ai/inactive", "metadata": {"status": "deprecated"}},
        ]
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response(models)
        result = falvid._search_models("test", requests_mod)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]["endpoint_id"], "fal-ai/active")

    def test_category_filter(self):
        models = [
            {"endpoint_id": "fal-ai/a", "metadata": {"category": "text-to-video", "status": "active"}},
            {"endpoint_id": "fal-ai/b", "metadata": {"category": "image-to-video", "status": "active"}},
        ]
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response(models)
        result = falvid._search_models("test", requests_mod, category="text-to-video")
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]["endpoint_id"], "fal-ai/a")

    def test_limit_respected(self):
        models = [
            {"endpoint_id": f"fal-ai/m{i}", "metadata": {"status": "active"}}
            for i in range(10)
        ]
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response(models)
        result = falvid._search_models("test", requests_mod, limit=3)
        self.assertEqual(len(result), 3)

    def test_non_200_returns_empty(self):
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response([], status=403)
        result = falvid._search_models("test", requests_mod)
        self.assertEqual(result, [])

    def test_exception_returns_empty(self):
        requests_mod = MagicMock()
        requests_mod.get.side_effect = ConnectionError("boom")
        result = falvid._search_models("test", requests_mod)
        self.assertEqual(result, [])


class TestPricesBatch(unittest.TestCase):
    """Tests for _prices_batch — batch pricing lookup with mock HTTP."""

    def _mock_response(self, prices, status=200):
        resp = MagicMock()
        resp.status_code = status
        resp.json.return_value = {"prices": prices}
        return resp

    def test_returns_price_map_on_success(self):
        prices = [
            {"endpoint_id": "fal-ai/a", "unit_price": 0.20, "unit": "second"},
            {"endpoint_id": "fal-ai/b", "unit_price": 0.26, "unit": "clip"},
        ]
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response(prices)
        result = falvid._prices_batch(["fal-ai/a", "fal-ai/b"], requests_mod)
        self.assertEqual(result["fal-ai/a"], (0.20, "second"))
        self.assertEqual(result["fal-ai/b"], (0.26, "clip"))

    def test_deduplicates_endpoint_ids(self):
        prices = [{"endpoint_id": "fal-ai/a", "unit_price": 0.20, "unit": "second"}]
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response(prices)
        result = falvid._prices_batch(["fal-ai/a", "fal-ai/a", ""], requests_mod)
        self.assertEqual(len(result), 1)

    def test_empty_input_returns_empty(self):
        requests_mod = MagicMock()
        result = falvid._prices_batch([], requests_mod)
        self.assertEqual(result, {})
        requests_mod.get.assert_not_called()

    def test_non_200_returns_empty(self):
        requests_mod = MagicMock()
        requests_mod.get.return_value = self._mock_response([], status=500)
        result = falvid._prices_batch(["fal-ai/a"], requests_mod)
        self.assertEqual(result, {})

    def test_exception_returns_empty(self):
        requests_mod = MagicMock()
        requests_mod.get.side_effect = TimeoutError("slow")
        result = falvid._prices_batch(["fal-ai/a"], requests_mod)
        self.assertEqual(result, {})


class TestPriceStr(unittest.TestCase):
    """Tests for _price_str — pure formatting helper."""

    def test_with_price(self):
        self.assertEqual(falvid._price_str((0.20, "second")), "$0.2/second")

    def test_none(self):
        self.assertEqual(falvid._price_str(None), "price n/a")

    def test_none_unit_price(self):
        self.assertEqual(falvid._price_str((None, "second")), "price n/a")


class TestCmdSearch(unittest.TestCase):
    """Tests for cmd_search — output formatting with mocked deps."""

    def setUp(self):
        self._fal_client = MagicMock()
        self._requests = MagicMock()

    def _patch_deps(self):
        return patch.object(falvid, "_import_deps", return_value=(self._fal_client, self._requests))

    def _patch_key(self):
        return patch.dict(os.environ, {"FAL_KEY": "test-key"}, clear=False)

    def test_search_prints_results(self):
        models = [
            {"endpoint_id": "fal-ai/test-1", "metadata": {
                "display_name": "Test 1", "category": "text-to-video",
                "license_type": "MIT", "description": "A test model", "status": "active",
            }},
        ]
        resp = MagicMock()
        resp.status_code = 200
        resp.json.return_value = {"models": models}
        self._requests.get.return_value = resp

        args = argparse.Namespace(query="test", category=None, limit=15)
        with self._patch_deps(), self._patch_key():
            buf = io.StringIO()
            with redirect_stdout(buf):
                falvid.cmd_search(args)
        out = buf.getvalue()
        self.assertIn("fal-ai/test-1", out)
        self.assertIn("Test 1", out)
        self.assertIn("Default-first", out)

    def test_search_no_results_message(self):
        resp = MagicMock()
        resp.status_code = 200
        resp.json.return_value = {"models": []}
        self._requests.get.return_value = resp

        args = argparse.Namespace(query="zzz", category=None, limit=15)
        with self._patch_deps(), self._patch_key():
            buf = io.StringIO()
            with redirect_stdout(buf):
                falvid.cmd_search(args)
        out = buf.getvalue()
        self.assertIn("No active models matched", out)
        self.assertIn("fal.ai/models", out)


class TestCmdRecommend(unittest.TestCase):
    """Tests for cmd_recommend — prints default models with live pricing."""

    def setUp(self):
        self._fal_client = MagicMock()
        self._requests = MagicMock()

    def _patch_deps(self):
        return patch.object(falvid, "_import_deps", return_value=(self._fal_client, self._requests))

    def _patch_key(self):
        return patch.dict(os.environ, {"FAL_KEY": "test-key"}, clear=False)

    def test_recommend_prints_all_defaults(self):
        # Mock pricing to return a price for each default model
        prices = [
            {"endpoint_id": mid, "unit_price": 0.01, "unit": "second"}
            for mid in falvid.DEFAULT_MODELS.values()
        ]
        resp = MagicMock()
        resp.status_code = 200
        resp.json.return_value = {"prices": prices}
        self._requests.get.return_value = resp

        args = argparse.Namespace()
        with self._patch_deps(), self._patch_key():
            buf = io.StringIO()
            with redirect_stdout(buf):
                falvid.cmd_recommend(args)
        out = buf.getvalue()
        self.assertIn("Recommended default", out)
        for mode in falvid.DEFAULT_MODELS:
            self.assertIn(mode, out)
        for mid in falvid.DEFAULT_MODELS.values():
            self.assertIn(mid, out)

    def test_recommend_with_no_pricing_shows_na(self):
        resp = MagicMock()
        resp.status_code = 500
        resp.json.return_value = {"prices": []}
        self._requests.get.return_value = resp

        args = argparse.Namespace()
        with self._patch_deps(), self._patch_key():
            buf = io.StringIO()
            with redirect_stdout(buf):
                falvid.cmd_recommend(args)
        out = buf.getvalue()
        self.assertIn("price n/a", out)


if __name__ == "__main__":
    unittest.main(verbosity=2)
canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall