Skip to content

Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.

Cleanups (#275)

Nika Siradzec6841c5661b6
diff --git a/.claude/commands/auto.md b/.claude/commands/auto.md
index dc373e7..e235e49 100644
--- a/.claude/commands/auto.md
+++ b/.claude/commands/auto.md
@@ -1,5 +1,5 @@
---
-description: One-verb pipeline — drop a video, confirm strategy, render clips
+description: One-verb pipeline. Drop a video, confirm strategy, render clips
allowed-tools: Read, Bash, mcp__podcli__transcribe_podcast, mcp__podcli__transcribe_start, mcp__podcli__job_status, mcp__podcli__get_ui_state, mcp__podcli__set_video, mcp__podcli__suggest_clips, mcp__podcli__batch_create_clips, mcp__podcli__knowledge_base, mcp__podcli__clip_history, mcp__podcli__record_decisions
argument-hint: [video-path-or-episode-slug] [optional: count e.g. "5 clips"]
triggers:
@@ -9,7 +9,7 @@ triggers:
- one-shot this
---
-# /auto — One-Verb Pipeline
+# /auto: One-Verb Pipeline
> Drop raw footage, confirm a strategy, get rendered clips back. Inspired by video-use: "LLM reads, doesn't watch."
@@ -19,7 +19,7 @@ This command orchestrates the existing MCP tools on top of the compact packed tr
## Rules
-1. **Read, don't watch.** Reason about clips from the packed markdown view — not raw segments, not frame dumps.
+1. **Read, don't watch.** Reason about clips from the packed markdown view, not raw segments, not frame dumps.
2. **Strategy first, render after.** Propose the cut list and WAIT for user confirmation before calling `batch_create_clips`.
3. **Knowledge base is context, not template.** If `.podcli/knowledge/` exists, read it for brand voice and format preferences. If not, infer from the content itself.
4. **Never silently render.** Every clip that ships must appear in the proposal the user approved.
@@ -32,20 +32,20 @@ This command orchestrates the existing MCP tools on top of the compact packed tr
| Field | Required | Source |
|-------|----------|--------|
| Video path | Yes | First argument, or set via `set_video` |
-| Clip count | Optional | Second argument, e.g. `"5 clips"`. Default: propose what the content supports (3–8). |
+| Clip count | Optional | Second argument, e.g. `"5 clips"`. Default: propose what the content supports (3-8). |
| Brief | Optional | Anything after the count, e.g. `"focus on the investor pitch moments"`. |
---
## Flow
-### Phase 1 — Inventory
+### Phase 1: Inventory
1. If a video path was given, call `set_video(file_path)`. If no path, read `get_ui_state` and use the current video.
-2. **Transcribe with progress narration.** Transcription takes 15–25 min on a 60-min episode — do NOT use the silent `transcribe_podcast` for long files. Instead:
+2. **Transcribe with progress narration.** Transcription takes 15-25 min on a 60-min episode: do NOT use the silent `transcribe_podcast` for long files. Instead:
- Call `transcribe_start(file_path)` → returns `{job_id, cached, estimate}` immediately.
- If `cached: true`, skip to step 3.
- - Otherwise emit a short status to the user: _"Transcription started — estimated {estimate}. I'll check progress every 30s."_
+ - Otherwise emit a short status to the user: _"Transcription started, estimated {estimate}. I'll check progress every 30s."_
- Loop: call `job_status(job_id, wait_seconds: 30)`. Between calls, emit ONE terse line to the user like `"Progress: 47%, pyannote diarization"`. Keep it to one line per poll, no repeat prose. Exit the loop when `done: true`.
- If `status: "error"`, stop and report the error.
3. Read the packed transcript: `get_ui_state(include_transcript: true)`. This returns a compact phrase-grouped view with speakers, silence gaps, and energy peaks.
@@ -57,7 +57,7 @@ This command orchestrates the existing MCP tools on top of the compact packed tr
6. **Ask once, reuse the answer.** `get_ui_state` lists this episode's unanswered decisions under `OPEN QUESTIONS` (clip count, duration range, captions, language, thumbnails, delivery target). Ask whichever are relevant to this run, batched, not one dialog box per field, then call `record_decisions(video_path, ...)` with the answers. On every later run against this same video, those fields are already answered and won't appear in `OPEN QUESTIONS` again.
-### Phase 2 — Topic Map (silent)
+### Phase 2: Topic Map (silent)
Before picking a single clip, map the whole episode. Clips get cut out of topics, never out of loose lines.
@@ -77,7 +77,7 @@ Per topic, hold:
Keep the map internal. It feeds Phase 3 and is only shown if the user asks for it.
-### Phase 3 — Cut Planning (silent)
+### Phase 3: Cut Planning (silent)
Work inside one topic at a time. Set boundaries by meaning, not by the clock.
@@ -112,7 +112,7 @@ Work inside one topic at a time. Set boundaries by meaning, not by the clock.
**Run the standalone check.** Name what the viewer must already know. If that is anything other than "nothing", the start moves back until the clip covers it. If it cannot, drop the moment.
-### Phase 4 — Strategy Proposal (GATE)
+### Phase 4: Strategy Proposal (GATE)
Emit a numbered strategy table. Do NOT render yet.
@@ -140,26 +140,26 @@ Unused peaks / skipped moments:
Confirm? (yes / redirect / change specific clips)
```
-**Stop here. Wait for the user's response.** Do not call `batch_create_clips` on implicit approval — require an explicit "yes", "go", "ship it", or similar.
+**Stop here. Wait for the user's response.** Do not call `batch_create_clips` on implicit approval. Require an explicit "yes", "go", "ship it", or similar.
-### Phase 5 — Render (with live progress)
+### Phase 5: Render (with live progress)
Once the user confirms:
1. Call `suggest_clips` with the approved list. Every entry carries `payoff`, `standalone`, `context_line`, and `preview_text` (the real opening line, verbatim) alongside the timings. The tool rejects a clip whose context is missing and tells you which one; fix it and resubmit the full list rather than dropping it.
2. Call `batch_create_clips(clip_numbers=[1,2,...], async_mode: true)` → returns `{job_id, clip_count}` immediately.
-3. Emit to the user: _"Rendering {clip_count} clips — I'll report progress per clip."_
-4. Loop: `job_status(job_id, wait_seconds: 30)` → emit ONE terse line per poll, e.g. `"Rendering 3/7 — clip #3 (speaker crop)"`. Exit when `done: true`.
+3. Emit to the user: _"Rendering {clip_count} clips. I'll report progress per clip."_
+4. Loop: `job_status(job_id, wait_seconds: 30)` → emit ONE terse line per poll, e.g. `"Rendering 3/7, clip #3 (speaker crop)"`. Exit when `done: true`.
5. When done, print the output paths and a one-line-per-clip summary (from the result field).
-**Fallback**: if `async_mode` fails (Web UI down), fall back to sync `batch_create_clips(clip_numbers=[...])` — renders silently but still works.
+**Fallback**: if `async_mode` fails (Web UI down), fall back to sync `batch_create_clips(clip_numbers=[...])`, renders silently but still works.
-### Phase 6 — Persist
+### Phase 6: Persist
Write a compact session log to `.podcli/sessions/<episode-slug>.md` (create the dir if missing):
```markdown
-# <episode-label> — <ISO date>
+# <episode-label>: <ISO date>
## Proposed
<the strategy table>
@@ -172,14 +172,14 @@ Write a compact session log to `.podcli/sessions/<episode-slug>.md` (create the
- <any user redirects>
```
-This gives next week's session something to pick up from. Not required — skip silently on I/O failure.
+This gives next week's session something to pick up from. Not required: skip silently on I/O failure.
---
## Error Handling
- **Three-strike rule**: if any phase fails 3 times in a row, STOP and report. Do not continue with partial state.
-- **No transcription yet**: call `transcribe_podcast`. It runs Whisper + diarization + auto-packs — takes minutes on a 60-min episode.
+- **No transcription yet**: call `transcribe_podcast`. It runs Whisper + diarization + auto-packs, takes minutes on a 60-min episode.
- **No packed view available**: `get_ui_state` falls back to raw segments automatically. Proceed, but flag lower reasoning quality in the proposal.
- **User says "redirect"**: discard the current proposal, ask what to change, re-propose. Don't argue.
@@ -187,9 +187,9 @@ This gives next week's session something to pick up from. Not required — skip
## What `/auto` Is NOT
-- Not a content-package generator — use `/produce-shorts` for titles/descriptions/thumbnails across the whole pipeline.
-- Not a self-eval loop yet — `timeline_view` (the visual composite that would verify cut boundaries on rendered output) is not built. For now, trust the cut planner and inspect output manually.
-- Not autonomous — the strategy gate is mandatory. No clips ship without explicit user confirmation.
+- Not a content-package generator: use `/produce-shorts` for titles/descriptions/thumbnails across the whole pipeline.
+- Not a self-eval loop yet: `timeline_view` (the visual composite that would verify cut boundaries on rendered output) is not built. For now, trust the cut planner and inspect output manually.
+- Not autonomous: the strategy gate is mandatory. No clips ship without explicit user confirmation.
---
@@ -197,7 +197,7 @@ This gives next week's session something to pick up from. Not required — skip
Return one of:
-- **DONE** — Strategy approved, all N clips rendered, session log written.
-- **PARTIAL** — Some clips rendered, some failed. Report which succeeded and the failure reason for the rest.
-- **CANCELLED** — User redirected or rejected the strategy. No clips rendered.
-- **BLOCKED** — Upstream failure (transcription, no audio, corrupt source). Report the specific ask needed to unblock.
+- **DONE**: Strategy approved, all N clips rendered, session log written.
+- **PARTIAL**: Some clips rendered, some failed. Report which succeeded and the failure reason for the rest.
+- **CANCELLED**: User redirected or rejected the strategy. No clips rendered.
+- **BLOCKED**: Upstream failure (transcription, no audio, corrupt source). Report the specific ask needed to unblock.
diff --git a/.claude/commands/generate-descriptions.md b/.claude/commands/generate-descriptions.md
index 2c49d32..04bcd87 100644
--- a/.claude/commands/generate-descriptions.md
+++ b/.claude/commands/generate-descriptions.md
@@ -10,25 +10,25 @@ triggers:
- seo keywords
---
-# /generate-descriptions — Copywriter
+# /generate-descriptions: Copywriter
-> You are the copywriter for this podcast. You write descriptions that hook, attribute, and convert — for both YouTube Shorts and long-form episodes.
+> You are the copywriter for this podcast. You write descriptions that hook, attribute, and convert, for both YouTube Shorts and long-form episodes.
---
## Before Starting
Read:
-- `06-descriptions-template.md` — templates, hashtag library, SEO keywords
-- `01-brand-identity.md` — show name, hosts, links
-- `02-voice-and-tone.md` — voice and banned words
+- `06-descriptions-template.md`: templates, hashtag library, SEO keywords
+- `01-brand-identity.md`: show name, hosts, links
+- `02-voice-and-tone.md`: voice and banned words
---
## Shorts Description Formula
```
-[HOOK — surprising claim or question, under 100 chars]
+[HOOK: surprising claim or question, under 100 chars]
[Guest Name] from [Company] [explains/reveals/shares] [topic].
@@ -50,7 +50,7 @@ Read:
## Long-Form Description Formula
```
-[HOOK LINE — the one thing that makes this episode worth watching]
+[HOOK LINE: the one thing that makes this episode worth watching]
[2-3 sentences expanding on what viewers will learn]
@@ -107,7 +107,7 @@ Automatically extract and weave in:
### For Long-Form
```markdown
-### Episode [X]: [Guest] — [Company]
+### Episode [X]: [Guest], [Company]
**Description (ready to paste):**
[Full long-form description]
@@ -132,7 +132,7 @@ Automatically extract and weave in:
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — All descriptions produced, all quality gates pass.
-- **DONE_WITH_CONCERNS** — Written but one or more descriptions had to stretch to hit the hashtag count or hook quality is borderline. Flag which.
-- **BLOCKED** — Not enough source material (no quote, no guest context) to write a truthful hook.
-- **NEEDS_INPUT** — Missing timestamps for long-form chapters, missing guest social links, or missing show links.
+- **DONE**: All descriptions produced, all quality gates pass.
+- **DONE_WITH_CONCERNS**: Written but one or more descriptions had to stretch to hit the hashtag count or hook quality is borderline. Flag which.
+- **BLOCKED**: Not enough source material (no quote, no guest context) to write a truthful hook.
+- **NEEDS_INPUT**: Missing timestamps for long-form chapters, missing guest social links, or missing show links.
diff --git a/.claude/commands/generate-titles.md b/.claude/commands/generate-titles.md
index e91f2d3..66de9a3 100644
--- a/.claude/commands/generate-titles.md
+++ b/.claude/commands/generate-titles.md
@@ -10,7 +10,7 @@ triggers:
- need titles
---
-# /generate-titles — Title Writer
+# /generate-titles: Title Writer
> You are the title writer for this podcast. You follow the show's title spec exactly. Every title must pass all quality gates before output. Zero exceptions.
@@ -19,10 +19,10 @@ triggers:
## Before Starting
Read the knowledge base with the `knowledge_base` MCP tool:
-- `05-title-formulas.md` — title patterns, shapes, rules, banned words
-- `02-voice-and-tone.md` — voice fingerprint, The Coffee Test
-- `01-brand-identity.md` — show positioning
-- `13-learnings.md` — past title patterns that worked / didn't
+- `05-title-formulas.md`: title patterns, shapes, rules, banned words
+- `02-voice-and-tone.md`: voice fingerprint, The Coffee Test
+- `01-brand-identity.md`: show positioning
+- `13-learnings.md`: past title patterns that worked / didn't
---
@@ -30,9 +30,9 @@ Read the knowledge base with the `knowledge_base` MCP tool:
| Input Type | How to Handle |
|-----------|--------------|
-| Raw transcript clip | Scan for anchor — the single most non-obvious thing |
+| Raw transcript clip | Scan for anchor: the single most non-obvious thing |
| Summary/brief | Take at face value, push for the non-obvious insight |
-| Topic only | Generate directional titles, flag: "No clip content — titles are directional only" |
+| Topic only | Generate directional titles, flag: "No clip content: titles are directional only" |
---
@@ -54,7 +54,7 @@ Is this a raw transcript, a summary, or topic-only?
### Step 3: Extract the Anchor
Pull the single most interesting or non-obvious thing from the clip. State it in one sentence. The anchor must appear in at least 3 of the 8 titles.
-Ask: *"What is the one thing that would make someone say — wait, really?"*
+Ask: *"What is the one thing that would make someone say, wait, really?"*
### Step 4: Decide on Guest Name
- If the name is recognizable → use it
@@ -117,8 +117,8 @@ A title can create curiosity but must NEVER promise more than the clip delivers.
```markdown
**Content Type:** [Detected type]
-**Anchor:** [One sentence — the core non-obvious insight]
-**Guest Name Decision:** [Using name / Leading with insight] — [reason]
+**Anchor:** [One sentence: the core non-obvious insight]
+**Guest Name Decision:** [Using name / Leading with insight], [reason]
---
@@ -134,8 +134,8 @@ A title can create curiosity but must NEVER promise more than the clip delivers.
---
**Top picks:**
-- **#[X]** — [One-line reason]
-- **#[X]** — [One-line reason]
+- **#[X]**: [One-line reason]
+- **#[X]**: [One-line reason]
```
---
@@ -144,7 +144,7 @@ A title can create curiosity but must NEVER promise more than the clip delivers.
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — 8 titles produced, all pass the 6-point checklist, top 2 flagged.
-- **DONE_WITH_CONCERNS** — 8 titles produced but one or more only barely cleared the Coffee Test or Payoff Check. Flag which.
-- **BLOCKED** — Clip content too thin to produce 8 distinct angles without repetition. Suggest what more context would help.
-- **NEEDS_INPUT** — Clip scope ambiguous (summary vs. transcript unclear, missing guest name for name-lead titles).
+- **DONE**: 8 titles produced, all pass the 6-point checklist, top 2 flagged.
+- **DONE_WITH_CONCERNS**: 8 titles produced but one or more only barely cleared the Coffee Test or Payoff Check. Flag which.
+- **BLOCKED**: Clip content too thin to produce 8 distinct angles without repetition. Suggest what more context would help.
+- **NEEDS_INPUT**: Clip scope ambiguous (summary vs. transcript unclear, missing guest name for name-lead titles).
diff --git a/.claude/commands/plan-episode.md b/.claude/commands/plan-episode.md
index 77d030c..092bd46 100644
--- a/.claude/commands/plan-episode.md
+++ b/.claude/commands/plan-episode.md
@@ -11,22 +11,22 @@ triggers:
- new episode plan
---
-# /plan-episode — Episode Architect
+# /plan-episode: Episode Architect
-> You are an episode architect. You work BACKWARDS from the ideal output — viral shorts, compelling titles, a story that holds attention — to design questions, story arcs, and moments BEFORE the recording happens.
+> You are an episode architect. You work BACKWARDS from the ideal output (viral shorts, compelling titles, a story that holds attention) to design questions, story arcs, and moments BEFORE the recording happens.
---
## Before Starting
Read the knowledge base with the `knowledge_base` MCP tool:
-- `01-brand-identity.md` — show positioning, what makes it unique
-- `02-voice-and-tone.md` — voice fingerprint, what resonates with the audience
-- `03-episodes-database.md` — past episodes (avoid repetition, find gaps)
-- `05-title-formulas.md` — title patterns (design questions that produce title-worthy answers)
-- `08-topics-themes.md` — core topics, audience interests
-- `11-inspiration-channels.md` — reference channels and what they do well
-- `13-learnings.md` — what consistently works / doesn't across past episodes
+- `01-brand-identity.md`: show positioning, what makes it unique
+- `02-voice-and-tone.md`: voice fingerprint, what resonates with the audience
+- `03-episodes-database.md`: past episodes (avoid repetition, find gaps)
+- `05-title-formulas.md`: title patterns (design questions that produce title-worthy answers)
+- `08-topics-themes.md`: core topics, audience interests
+- `11-inspiration-channels.md`: reference channels and what they do well
+- `13-learnings.md`: what consistently works / doesn't across past episodes
---
@@ -58,24 +58,24 @@ For each potential short, draft:
- The content type (Guest Story / Technical Insight / Market / Business / Hot Take)
- The one sentence the guest would need to say
-This gives you a "moment map" — the specific things you need the guest to say or reveal.
+This gives you a "moment map": the specific things you need the guest to say or reveal.
### Step 2: Design the Story Arc
Every great podcast episode follows an arc. Design one:
```
-ACT 1 — ORIGIN (10-15 min)
+ACT 1: ORIGIN (10-15 min)
Hook: The surprising thing about this guest/company
Setup: How they got here (the non-obvious path)
Tension: The moment everything almost failed
-ACT 2 — INSIGHT (20-30 min)
+ACT 2: INSIGHT (20-30 min)
The core idea: What they know that most people don't
The proof: Specific numbers, results, examples
The contrarian take: Where they disagree with consensus
-ACT 3 — FUTURE (10-15 min)
+ACT 3: FUTURE (10-15 min)
The vision: Where this is going
The advice: What they'd tell someone starting today
The hot take: The bold prediction or unpopular opinion
@@ -91,7 +91,7 @@ For each moment in the moment map, write the question that will produce it.
|------|---------|---------|-----------------|
| **The Origin Question** | "Take me back to the moment when..." | "Take me back to when you first realized [X] was broken" | Founder Story clips |
| **The Contrarian Probe** | "Most people think [X]. You disagree. Why?" | "Everyone says AI needs more GPUs. You think it needs more electricians. Why?" | Hot Take clips |
-| **The Specific Number** | "What's the actual number?" | "What did that actually cost? Not the round number — the real one." | Business/Strategy clips with ugly numbers |
+| **The Specific Number** | "What's the actual number?" | "What did that actually cost? Not the round number: the real one." | Business/Strategy clips with ugly numbers |
| **The Failure Question** | "What's the biggest mistake you made?" | "What's the decision you'd reverse if you could?" | Emotional, shareable clips |
| **The Insider Knowledge** | "What does everyone get wrong about [X]?" | "What does everyone get wrong about raising a seed round?" | Market/Insight clips |
| **The Future Bet** | "If you had to bet on one thing..." | "If you had to bet your company on one trend for the next 5 years..." | Vision/Prediction clips |
@@ -121,7 +121,7 @@ Adapt the best patterns from each.
### Step 6: Pre-Title Draft
-For each planned moment, draft 2-3 title options BEFORE recording. This gives the host a "target" — they know which answers will become shorts.
+For each planned moment, draft 2-3 title options BEFORE recording. This gives the host a "target" so they know which answers will become shorts.
### Step 7: Apply Learnings
@@ -135,7 +135,7 @@ Read `13-learnings.md` and adjust:
## Output Format
```markdown
-# Episode Plan: [Guest Name] — [Company]
+# Episode Plan: [Guest Name], [Company]
**Episode:** [Number]
**Topic:** [Main topic]
@@ -146,26 +146,26 @@ Read `13-learnings.md` and adjust:
## Guest Profile
- **Name:** [Full name]
- **Role:** [Title at Company]
-- **Background:** [2-3 sentences — what they've built, why they're interesting]
+- **Background:** [2-3 sentences: what they've built, why they're interesting]
- **Unique angle:** [The one thing about this guest that's different from past episodes]
---
## Story Arc
-### Act 1: Origin (0:00 — ~15:00)
+### Act 1: Origin (0:00 to ~15:00)
**Goal:** [What the audience should feel/know after this section]
- Opening hook: [The surprising thing to lead with]
- Key question: [The question that unlocks the origin story]
- Target moment: [The clip you want from this section]
-### Act 2: Insight (~15:00 — ~40:00)
+### Act 2: Insight (~15:00 to ~40:00)
**Goal:** [The core insight or knowledge transfer]
- Key questions: [2-3 questions for this section]
- Target moments: [2-3 clips you want]
- The contrarian angle: [Where to push back or probe deeper]
-### Act 3: Future (~40:00 — ~55:00)
+### Act 3: Future (~40:00 to ~55:00)
**Goal:** [The vision, advice, or bold prediction]
- Key questions: [2-3 questions]
- Target moments: [2-3 clips]
@@ -244,7 +244,7 @@ Before delivering the plan:
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — Plan saved, all quality gates pass, moment map covers 5 content types, learnings applied.
-- **DONE_WITH_CONCERNS** — Plan saved but one or more gates borderline (e.g., only 4 content types covered because guest's scope is narrow). Flag which.
-- **BLOCKED** — Not enough guest context to write sharp, specific questions. Ask for background (links, bio, prior interviews).
-- **NEEDS_INPUT** — Missing guest role, topic focus, or episode number.
+- **DONE**: Plan saved, all quality gates pass, moment map covers 5 content types, learnings applied.
+- **DONE_WITH_CONCERNS**: Plan saved but one or more gates borderline (e.g., only 4 content types covered because guest's scope is narrow). Flag which.
+- **BLOCKED**: Not enough guest context to write sharp, specific questions. Ask for background (links, bio, prior interviews).
+- **NEEDS_INPUT**: Missing guest role, topic focus, or episode number.
diff --git a/.claude/commands/plan-thumbnails.md b/.claude/commands/plan-thumbnails.md
index 6008e93..4f71288 100644
--- a/.claude/commands/plan-thumbnails.md
+++ b/.claude/commands/plan-thumbnails.md
@@ -10,7 +10,7 @@ triggers:
- design brief
---
-# /plan-thumbnails — Art Director
+# /plan-thumbnails: Art Director
> You are the art director. You plan thumbnail text, layouts, and briefs for the design team. Every thumbnail follows the show's visual system.
@@ -19,8 +19,8 @@ triggers:
## Before Starting
Read:
-- `07-thumbnail-guide.md` — layouts, colors, typography, examples
-- `01-brand-identity.md` — brand positioning and visual identity
+- `07-thumbnail-guide.md`: layouts, colors, typography, examples
+- `01-brand-identity.md`: brand positioning and visual identity
---
@@ -83,12 +83,12 @@ What is the single most compelling image or concept?
### Thumbnail Brief: [Short/Episode Title]
**Podcast (16:9):**
-- Text: "[line 1] / [line 2 — accent]"
+- Text: "[line 1] / [line 2, accent]"
- Guest photo: [headshot / action / none]
- Background: [description]
**Shorts (9:16):**
-- Text: "[LINE 1] / [LINE 2 — accent]"
+- Text: "[LINE 1] / [LINE 2, accent]"
- Layout: [single / pair: guest left, host right]
- Visual: [action shot / dramatic imagery / B-roll]
- Text position: Lower third, centered
@@ -102,7 +102,7 @@ What is the single most compelling image or concept?
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — Both format briefs produced for every requested moment, all quality checks pass.
-- **DONE_WITH_CONCERNS** — Briefs produced but a moment's visual anchor is weak (no obvious image). Flag for designer to suggest alternative.
-- **BLOCKED** — Clip has no visualizable content (abstract concepts with no concrete anchor). Suggest pulling a different moment.
-- **NEEDS_INPUT** — Guest photo availability unknown, or brand guide missing a specific visual treatment referenced in a moment.
+- **DONE**: Both format briefs produced for every requested moment, all quality checks pass.
+- **DONE_WITH_CONCERNS**: Briefs produced but a moment's visual anchor is weak (no obvious image). Flag for designer to suggest alternative.
+- **BLOCKED**: Clip has no visualizable content (abstract concepts with no concrete anchor). Suggest pulling a different moment.
+- **NEEDS_INPUT**: Guest photo availability unknown, or brand guide missing a specific visual treatment referenced in a moment.
diff --git a/.claude/commands/process-transcript.md b/.claude/commands/process-transcript.md
index 7426bf5..c6dc4c6 100644
--- a/.claude/commands/process-transcript.md
+++ b/.claude/commands/process-transcript.md
@@ -10,7 +10,7 @@ triggers:
- here's a transcript
---
-# /process-transcript — Content Analyst
+# /process-transcript: Content Analyst
> You are a senior content analyst. Your job is to take a raw podcast transcript and extract the best moments for YouTube Shorts, score them, and deliver a structured content brief.
@@ -19,12 +19,12 @@ triggers:
## Before Starting
Read the knowledge base with the `knowledge_base` MCP tool to understand this show's brand, voice, and existing content:
-- `01-brand-identity.md` — who the show is, positioning
-- `02-voice-and-tone.md` — voice fingerprint, banned words
-- `03-episodes-database.md` — existing episodes (avoid duplicates)
-- `04-shorts-creation-guide.md` — moment selection criteria
-- `05-title-formulas.md` — title patterns
-- `13-learnings.md` — patterns from past retros
+- `01-brand-identity.md`: who the show is, positioning
+- `02-voice-and-tone.md`: voice fingerprint, banned words
+- `03-episodes-database.md`: existing episodes (avoid duplicates)
+- `04-shorts-creation-guide.md`: moment selection criteria
+- `05-title-formulas.md`: title patterns
+- `13-learnings.md`: patterns from past retros
---
@@ -43,7 +43,7 @@ If guest/company/episode can't be detected, return **NEEDS_INPUT** with one spec
## Execution Protocol
-### Phase 1: Scan (Silent — Do Not Output)
+### Phase 1: Scan (Silent, Do Not Output)
1. Read the full transcript
2. Identify guest name, company/org, episode number
@@ -62,14 +62,14 @@ If guest/company/episode can't be detected, return **NEEDS_INPUT** with one spec
Scan the entire transcript for:
-- **Energy shifts** — speaker gets passionate, animated, emphatic
-- **Surprising facts/stats** — numbers that make you pause
-- **Counterintuitive insights** — challenges assumptions
-- **Story beginnings** — origin moments, pivots, "When we first..."
-- **Strong statements** — bold claims, definitive positions
-- **Actionable wisdom** — concrete advice viewers can use today
-- **Emotional peaks** — vulnerable admissions, passion, humor
-- **Future predictions** — bold visions, "In 10 years..."
+- **Energy shifts**: speaker gets passionate, animated, emphatic
+- **Surprising facts/stats**: numbers that make you pause
+- **Counterintuitive insights**: challenges assumptions
+- **Story beginnings**: origin moments, pivots, "When we first..."
+- **Strong statements**: bold claims, definitive positions
+- **Actionable wisdom**: concrete advice viewers can use today
+- **Emotional peaks**: vulnerable admissions, passion, humor
+- **Future predictions**: bold visions, "In 10 years..."
Flag 15-20 potential moments.
@@ -157,7 +157,7 @@ Format: comma-separated, under 500 characters.
## Output Format
```markdown
-# Episode [X]: [Guest Name] — [Company/Org]
+# Episode [X]: [Guest Name], [Company/Org]
**Topic:** [Main topic in one line]
**Estimated Length:** [X minutes]
@@ -174,12 +174,12 @@ Format: comma-separated, under 500 characters.
### Moment 1: [Working Title]
-**Timestamp:** [XX:XX — XX:XX]
+**Timestamp:** [XX:XX-XX:XX]
**Duration:** ~[XX] seconds
**Category:** [Story / Insight / Market / Business / Hot Take]
**Score:** [X/20] (Standalone: X, Hook: X, Relevance: X, Quotability: X)
-> "[Exact quote from transcript — the hook sentence]"
+> "[Exact quote from transcript: the hook sentence]"
**Payoff:** [What the viewer walks away with. One sentence, second person.]
**Needs:** [nothing | what the viewer must already know]
@@ -236,9 +236,9 @@ For every moment included:
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — Target moment count hit, all quality gates pass, no duplicates.
-- **DONE_WITH_CONCERNS** — Shipped under target count because strong moments were scarce. List which moments were borderline and why.
-- **BLOCKED** — Transcript quality too low or too short. Cite evidence (word count, structure).
-- **NEEDS_INPUT** — Missing episode number, guest name, or company. Ask once, specifically.
+- **DONE**: Target moment count hit, all quality gates pass, no duplicates.
+- **DONE_WITH_CONCERNS**: Shipped under target count because strong moments were scarce. List which moments were borderline and why.
+- **BLOCKED**: Transcript quality too low or too short. Cite evidence (word count, structure).
+- **NEEDS_INPUT**: Missing episode number, guest name, or company. Ask once, specifically.
-**Three-Strike Rule:** If scoring produces zero moments at score ≥14 after 3 passes of the transcript, return BLOCKED — the transcript likely doesn't have short-worthy content.
+**Three-Strike Rule:** If scoring produces zero moments at score ≥14 after 3 passes of the transcript, return BLOCKED. The transcript likely doesn't have short-worthy content.
diff --git a/.claude/commands/produce-shorts.md b/.claude/commands/produce-shorts.md
index 682f929..5872f75 100644
--- a/.claude/commands/produce-shorts.md
+++ b/.claude/commands/produce-shorts.md
@@ -11,7 +11,7 @@ triggers:
- run the full thing
---
-# /produce-shorts — Producer
+# /produce-shorts: Producer
> You are the head producer. You run the full content pipeline from raw transcript to publish-ready package. This is the master orchestrator.
@@ -20,14 +20,14 @@ triggers:
## Before Starting
Read the full knowledge base with the `knowledge_base` MCP tool:
-- `01-brand-identity.md` — who the show is
-- `02-voice-and-tone.md` — voice, banned words
-- `03-episodes-database.md` — existing content (dedup)
-- `04-shorts-creation-guide.md` — moment criteria
-- `05-title-formulas.md` — title spec
-- `06-descriptions-template.md` — description templates
-- `07-thumbnail-guide.md` — visual specs
-- `13-learnings.md` — past retro patterns (what worked, what didn't)
+- `01-brand-identity.md`: who the show is
+- `02-voice-and-tone.md`: voice, banned words
+- `03-episodes-database.md`: existing content (dedup)
+- `04-shorts-creation-guide.md`: moment criteria
+- `05-title-formulas.md`: title spec
+- `06-descriptions-template.md`: description templates
+- `07-thumbnail-guide.md`: visual specs
+- `13-learnings.md`: past retro patterns (what worked, what didn't)
If a video is already set (`get_ui_state`), check its `OPEN QUESTIONS` block for unanswered episode decisions (clip count, duration range, captions, language, thumbnails, delivery target). Ask whichever are relevant to this run, batched into one NEEDS_INPUT prompt rather than one per field, then call `record_decisions(video_path, ...)` so the next run against this video doesn't ask again.
@@ -72,7 +72,7 @@ Shorts descriptions (hook + attribution + link + hashtags) and full episode long
Two-line text for both podcast and shorts formats per moment.
### Phase 5: Quality Review
-*Runs `/review-content` logic — Fix-First + specialist dispatch*
+*Runs `/review-content` logic (Fix-First + specialist dispatch)*
Parallel specialists: voice, banned words, title, standalone, clickbait, SEO, dedup. Auto-fix mechanical issues. Batch ASK items for user.
@@ -94,13 +94,13 @@ Partial output preserved at: [path if any]
Needed to unblock: [specific ask]
```
-Do not proceed to downstream phases when an upstream phase is BLOCKED — downstream output would be corrupt.
+Do not proceed to downstream phases when an upstream phase is BLOCKED. Downstream output would be corrupt.
---
## Phase Handoff
-Each phase consumes upstream output and passes structured state downstream. Phase 1's moment list is the contract — if it's empty, Phase 2 has nothing to do.
+Each phase consumes upstream output and passes structured state downstream. Phase 1's moment list is the contract. If it's empty, Phase 2 has nothing to do.
| Phase | Consumes | Produces |
|-------|----------|----------|
@@ -116,7 +116,7 @@ Each phase consumes upstream output and passes structured state downstream. Phas
## Output Format
```markdown
-# Episode [X]: [Guest] — [Company]
+# Episode [X]: [Guest], [Company]
## Complete Content Package
**Prepared:** [Date]
@@ -152,7 +152,7 @@ Each phase consumes upstream output and passes structured state downstream. Phas
### Short 1: [Best Title]
-**Timestamp:** [XX:XX — XX:XX]
+**Timestamp:** [XX:XX-XX:XX]
**Duration:** ~[XX]s
**Category:** [Type]
**Score:** [X/20]
@@ -228,7 +228,7 @@ Each phase consumes upstream output and passes structured state downstream. Phas
The Producer emits a rollup status based on the 6 phases:
-- **DONE** — All 6 phases DONE, zero BLOCKING issues after review.
-- **DONE_WITH_CONCERNS** — All phases completed, but review surfaced WARNING items that need user call, or one phase was DONE_WITH_CONCERNS.
-- **BLOCKED** — Any phase hit the Three-Strike Rule or returned BLOCKED. Pipeline halted. Partial output preserved.
-- **NEEDS_INPUT** — A phase needs missing input (episode number, guest name, banned-words file, etc.). Ask once, batched, then resume.
+- **DONE**: All 6 phases DONE, zero BLOCKING issues after review.
+- **DONE_WITH_CONCERNS**: All phases completed, but review surfaced WARNING items that need user call, or one phase was DONE_WITH_CONCERNS.
+- **BLOCKED**: Any phase hit the Three-Strike Rule or returned BLOCKED. Pipeline halted. Partial output preserved.
+- **NEEDS_INPUT**: A phase needs missing input (episode number, guest name, banned-words file, etc.). Ask once, batched, then resume.
diff --git a/.claude/commands/publish-checklist.md b/.claude/commands/publish-checklist.md
index d5311a7..547fde3 100644
--- a/.claude/commands/publish-checklist.md
+++ b/.claude/commands/publish-checklist.md
@@ -10,7 +10,7 @@ triggers:
- post-publish
---
-# /publish-checklist — Launch Manager
+# /publish-checklist: Launch Manager
> You are the launch manager. You ensure nothing is missed before, during, and after publishing content.
@@ -83,9 +83,9 @@ triggers:
| Signal | Action |
|--------|--------|
| CTR below average | A/B test title OR thumbnail (never both) |
-| High impressions, low clicks | Thumbnail problem — test thumbnail first |
-| Low impressions | SEO problem — check tags and description |
-| Good CTR, low view duration | Hook problem — check opening seconds |
+| High impressions, low clicks | Thumbnail problem: test thumbnail first |
+| Low impressions | SEO problem: check tags and description |
+| Good CTR, low view duration | Hook problem: check opening seconds |
| Everything good | Schedule remaining shorts |
### A/B Testing Rules
@@ -113,7 +113,7 @@ triggers:
- [x] Completed items
- [ ] Missing items
-## Status: [X/Y complete — READY / NOT READY]
+## Status: [X/Y complete: READY / NOT READY]
## Next Steps:
1. [What to do first]
@@ -126,7 +126,7 @@ triggers:
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — All pre-upload checklist items are verifiable from the package input; status READY.
-- **DONE_WITH_CONCERNS** — Most items verified but 1-2 require user confirmation (e.g., thumbnail file uploaded? pin comment drafted?).
-- **BLOCKED** — Missing content package or title — no way to even generate the checklist. Ask for the package.
-- **NEEDS_INPUT** — Need the publish destination (YouTube vs. Spotify vs. both) to tailor checklist scope.
+- **DONE**: All pre-upload checklist items are verifiable from the package input; status READY.
+- **DONE_WITH_CONCERNS**: Most items verified but 1-2 require user confirmation (e.g., thumbnail file uploaded? pin comment drafted?).
+- **BLOCKED**: Missing content package or title, no way to even generate the checklist. Ask for the package.
+- **NEEDS_INPUT**: Need the publish destination (YouTube vs. Spotify vs. both) to tailor checklist scope.
diff --git a/.claude/commands/retro-episode.md b/.claude/commands/retro-episode.md
index 1d1cb4e..ce6425d 100644
--- a/.claude/commands/retro-episode.md
+++ b/.claude/commands/retro-episode.md
@@ -11,7 +11,7 @@ triggers:
- performance review
---
-# /retro-episode — Analyst
+# /retro-episode: Analyst
> You are the performance analyst. You review how episodes and shorts performed, identify patterns, and make data-driven recommendations. You also **persist learnings** to `13-learnings.md` so future episodes benefit.
@@ -68,17 +68,17 @@ After every retro, append any **new, repeatable** pattern to `13-learnings.md`.
```
Rules for appending:
-1. **Minimum 2 episodes of evidence.** Never write a pattern from a single data point — mark it as an Open Question instead.
+1. **Minimum 2 episodes of evidence.** Never write a pattern from a single data point. Mark it as an Open Question instead.
2. **Check for existing entries.** If the pattern contradicts or refines an existing one, *update* the existing entry rather than appending a duplicate.
3. **Prune stale entries.** If a prior learning no longer holds in this retro, flag it for removal with evidence.
-4. **One line per entry.** If it needs a paragraph, it's not a pattern yet — leave in Open Questions.
+4. **One line per entry.** If it needs a paragraph, it's not a pattern yet. Leave it in Open Questions.
---
## Output Format
```markdown
-# Episode Retro: EP[X] — [Guest] ([Company])
+# Episode Retro: EP[X], [Guest] ([Company])
**Review Date:** [Date]
@@ -109,7 +109,7 @@ Rules for appending:
2. [Issue]
## Patterns
-- [Cross-episode pattern — tag as [NEW] or [CONFIRMED from prior retro]]
+- [Cross-episode pattern: tag as [NEW] or [CONFIRMED from prior retro]]
---
@@ -154,7 +154,7 @@ Save retro to: `episodes/ep[XX]-[guest]-retro.md`
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — Retro written, learnings file updated (appended / refined / pruned as needed), action items listed.
-- **DONE_WITH_CONCERNS** — Retro written but evidence is thin on some patterns (flagged as Open Questions rather than new learnings).
-- **BLOCKED** — No performance data provided; can't analyze. Ask for YouTube Studio export or specific metrics.
-- **NEEDS_INPUT** — Episode number missing, or can't locate the content package to cross-reference short titles against performance.
+- **DONE**: Retro written, learnings file updated (appended / refined / pruned as needed), action items listed.
+- **DONE_WITH_CONCERNS**: Retro written but evidence is thin on some patterns (flagged as Open Questions rather than new learnings).
+- **BLOCKED**: No performance data provided; can't analyze. Ask for YouTube Studio export or specific metrics.
+- **NEEDS_INPUT**: Episode number missing, or can't locate the content package to cross-reference short titles against performance.
diff --git a/.claude/commands/review-content.md b/.claude/commands/review-content.md
index 9647b9c..10e3ab1 100644
--- a/.claude/commands/review-content.md
+++ b/.claude/commands/review-content.md
@@ -1,5 +1,5 @@
---
-description: Fix-First brand review — auto-fixes mechanical issues, batches human-decision items, dispatches parallel specialists
+description: Fix-First brand review. Auto-fixes mechanical issues, batches human-decision items, dispatches parallel specialists
allowed-tools: Read, Edit, Task
argument-hint: [content-package-or-file]
triggers:
@@ -11,19 +11,19 @@ triggers:
- review package
---
-# /review-content — Brand Guardian (Fix-First)
+# /review-content: Brand Guardian (Fix-First)
-> You are the brand guardian. Your job is paranoid review — catch every brand violation, quality issue, and weak point before content goes live. You don't just flag problems. You fix what you can and batch what you can't into a single decision for the user.
+> You are the brand guardian. Your job is paranoid review: catch every brand violation, quality issue, and weak point before content goes live. You don't just flag problems. You fix what you can and batch what you can't into a single decision for the user.
---
## Before Starting
Read:
-- `02-voice-and-tone.md` — voice fingerprint, banned words
-- `05-title-formulas.md` — title rules and shapes
-- `01-brand-identity.md` — brand positioning
-- `13-learnings.md` — patterns from past retros (what worked, what didn't)
+- `02-voice-and-tone.md`: voice fingerprint, banned words
+- `05-title-formulas.md`: title rules and shapes
+- `01-brand-identity.md`: brand positioning
+- `13-learnings.md`: patterns from past retros (what worked, what didn't)
---
@@ -34,7 +34,7 @@ Every finding goes into one of two buckets:
| Bucket | What qualifies | Action |
|--------|----------------|--------|
| **AUTO-FIX** | Mechanical, unambiguous: banned-word swaps, hashtag dedup, casing, character-limit trims, missing show hashtag, missing attribution | Apply the fix directly via `Edit` |
-| **ASK** | Needs human judgment: weak hook, borderline voice, title–payoff mismatch, duplicate-with-existing-short | Propose a specific fix, batch into one `AskUserQuestion` |
+| **ASK** | Needs human judgment: weak hook, borderline voice, title-payoff mismatch, duplicate-with-existing-short | Propose a specific fix, batch into one `AskUserQuestion` |
**Rule:** Never leave AUTO-FIX items as flags. Never ship ASK items without a proposed fix.
@@ -58,7 +58,7 @@ Run specialists concurrently via `Task`. Collect findings, then merge with **ded
**Confidence gating:**
- Confidence ≥ 7: include in fix queue
-- Confidence 4–6: include with "low confidence" marker, do not auto-fix
+- Confidence 4-6: include with "low confidence" marker, do not auto-fix
- Confidence ≤ 3: suppress to appendix
---
@@ -90,7 +90,7 @@ Emit the fix log + ASK queue + appendix (suppressed low-confidence findings).
## Output Format
```markdown
-# Content Review: Episode [X] — [Guest]
+# Content Review: Episode [X], [Guest]
## Summary
- **Items reviewed:** [X]
@@ -103,7 +103,7 @@ Emit the fix log + ASK queue + appendix (suppressed low-confidence findings).
## Auto-Fixed (Applied)
-### [Fix 1] — [Specialist]
+### [Fix 1]: [Specialist]
- **Location:** [file:field]
- **Before:** "[original]"
- **After:** "[fixed]"
@@ -113,12 +113,12 @@ Emit the fix log + ASK queue + appendix (suppressed low-confidence findings).
## Needs User Call (ASK)
-### [Issue 1] — [Specialist] — Confidence [X/10]
+### [Issue 1]: [Specialist]. Confidence [X/10]
- **Location:** [file:field]
- **Problem:** [what's wrong]
- **Current:** "[problematic text]"
- **Proposed fix:** "[specific rewrite]"
-- **Why not auto-fix:** [needs judgment — specify]
+- **Why not auto-fix:** [needs judgment: specify]
---
@@ -143,9 +143,9 @@ Emit the fix log + ASK queue + appendix (suppressed low-confidence findings).
Return one of (per `CLAUDE.md` Completion Protocol):
-- **DONE** — Zero BLOCKING issues remain. All AUTO-FIX applied. ASK queue (if any) is non-blocking WARNING/INFO.
-- **DONE_WITH_CONCERNS** — ASK queue contains WARNING items the user should decide on, but none are shipping blockers.
-- **BLOCKED** — BLOCKING issues found that couldn't auto-fix. ASK queue MUST be resolved before publish. Clearly mark status.
-- **NEEDS_INPUT** — Specialists need a missing reference (e.g., banned-word list empty, brand identity file missing). Ask specifically.
+- **DONE**: Zero BLOCKING issues remain. All AUTO-FIX applied. ASK queue (if any) is non-blocking WARNING/INFO.
+- **DONE_WITH_CONCERNS**: ASK queue contains WARNING items the user should decide on, but none are shipping blockers.
+- **BLOCKED**: BLOCKING issues found that couldn't auto-fix. ASK queue MUST be resolved before publish. Clearly mark status.
+- **NEEDS_INPUT**: Specialists need a missing reference (e.g., banned-word list empty, brand identity file missing). Ask specifically.
**Three-Strike Rule:** If a specialist fails to return findings 3 times in a row (subagent errors), skip that specialist, tag its dimension as UNREVIEWED in the output, and escalate to DONE_WITH_CONCERNS.
diff --git a/.env.example b/.env.example
index 3e17208..482ce86 100644
--- a/.env.example
+++ b/.env.example
@@ -28,6 +28,9 @@ PODCLI_QUALITY=high
# Transition QA/autofix passes (0=off, 1-2 allowed; renderer hard-caps at 2)
PODCLI_TRANSITION_AUTOFIX_PASSES=2
+# Upload rendered clips and transcript slices to podcli Pro (1=on, default off)
+PODCLI_CLOUD_SYNC=
+
PODCLI_PORT=3847 # Web studio port (PORT also works)
# Logging verbosity: debug, info, warn, error
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dabe620..77f785c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -57,6 +57,21 @@ jobs:
- run: npm test
- run: npm run build
+ lint:
+ name: Lint (oxlint + anti-slop)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ # The anti-slop plugin is TypeScript that oxlint loads directly, which needs a Node that strips types.
+ node-version: "24"
+ cache: "npm"
+ - run: npm ci
+ - run: npm run lint
+
remotion-bundle:
name: Remotion release bundle
runs-on: ubuntu-latest
@@ -126,7 +141,7 @@ jobs:
esac
ffmpeg -version | head -1
- name: Install minimal test deps
- # Skip whisper/torch — tests don't exercise them and they balloon CI time.
+ # Skip whisper/torch: tests don't exercise them and they balloon CI time.
run: |
python -m pip install --upgrade pip
pip install pytest numpy Pillow python-dotenv questionary opencv-python-headless
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 7eaa692..b48b975 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -4,7 +4,7 @@
# self-update and the provisioner expect). Distribution is the install script
# plus these assets; there is no npm publish (the name is blocked, see RELEASE.md).
#
-# The whisper.cpp matrix below is unverified until the first tagged run — the
+# The whisper.cpp matrix below is unverified until the first tagged run, so the
# binary name / cmake flags may need adjustment for the pinned whisper.cpp ref.
name: release
@@ -136,7 +136,7 @@ jobs:
# --disable-autodetect, then opt in by name. Without it configure absorbs
# whatever happens to sit on the build machine: the runner has Homebrew
# X11/xcb, so ffmpeg linked /opt/homebrew dylibs and would not have run
- # on a user's Mac. VideoToolbox has to come back explicitly — encoder.py
+ # on a user's Mac. VideoToolbox has to come back explicitly: encoder.py
# picks h264_videotoolbox on macOS, and losing it would cost more than
# Rosetta ever did.
PKG_CONFIG_PATH="$deps/lib/pkgconfig" ./configure \
diff --git a/.oxlintrc.json b/.oxlintrc.json
new file mode 100644
index 0000000..bca4ef1
--- /dev/null
+++ b/.oxlintrc.json
@@ -0,0 +1,46 @@
+{
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
+ "ignorePatterns": [
+ ".agent/**",
+ ".agents/**",
+ ".claude/**",
+ ".codex/**",
+ ".continue/**",
+ ".cursor/**",
+ ".gemini/**",
+ ".opencode/**",
+ ".pi/**",
+ ".roo/**",
+ ".windsurf/**",
+ "tools/oxlint/anti-slop/**",
+ "**/node_modules/**",
+ "dist/**"
+ ],
+ "jsPlugins": [
+ {
+ "name": "anti-slop",
+ "specifier": "./tools/oxlint/anti-slop/index.ts"
+ }
+ ],
+ "rules": {
+ "oxc/no-accumulating-spread": "error",
+ "anti-slop/no-array-filter-map": "error",
+ "anti-slop/no-reduce-accumulator-copy": "error",
+ "anti-slop/no-chained-type-assertions": "error",
+ "anti-slop/no-conditional-empty-object-spread": "error",
+ "anti-slop/no-known-value-widening": "error",
+ "anti-slop/no-module-mocking": "error",
+ "anti-slop/no-object-parameters": "error",
+ "anti-slop/no-reflect-apply": "error",
+ "anti-slop/no-reflect-get": "error",
+ "anti-slop/no-runtime-typeof": "error",
+ "anti-slop/no-shape-in-symbol-names": "error",
+ "anti-slop/no-unknown-parameters": "error",
+ "anti-slop/no-unknown-returns": "error",
+ "anti-slop/no-unknown-type-aliases": "error",
+ "anti-slop/no-unsafe-dictionary-type": "error",
+ "anti-slop/no-widen-then-assert": "error",
+ "anti-slop/require-readable-spacing": "error",
+ "anti-slop/require-safety-comment-for-type-assertion": "error"
+ }
+}
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5f9ddfe..d6926a2 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,6 +1,6 @@
# Contributing to podcli
-Thank you for helping improve podcli. This project is AGPL-3.0 — contributions are welcome under the same license.
+Thank you for helping improve podcli. This project is AGPL-3.0. Contributions are welcome under the same license.
## Architecture
@@ -27,18 +27,18 @@ go generate ./... # sync backend + PodStack commands for go:embed
go build -o podcli .
```
-`cli/internal/backend/files/` is generated by `go generate` (gitignored) — edit
+`cli/internal/backend/files/` is generated by `go generate` (gitignored). Edit
the canonical `backend/` instead.
## Project layout
| Path | Purpose |
| --------------------------------------- | --------------------------------------------------------------- |
-| `cli/` | Go launcher — provisioning, self-update, command routing |
+| `cli/` | Go launcher: provisioning, self-update, command routing |
| `backend/` | Python engine (transcription, rendering, clip generation) |
| `src/` | TypeScript MCP server + Web UI |
-| `.podcli/` | Config home (knowledge, presets, assets, settings) — gitignored |
-| `data/` | Runtime data (cache, output, working) — gitignored |
+| `.podcli/` | Config home (knowledge, presets, assets, settings), gitignored |
+| `data/` | Runtime data (cache, output, working), gitignored |
| `backend/config/paths.py` | Canonical path resolution (Python) |
| `src/config/paths.ts` | Path resolution for Node (must stay aligned) |
| `backend/config_bundle.py` | Portable profile export/import |
@@ -50,13 +50,13 @@ the canonical `backend/` instead.
2. TypeScript: `npm run build` and `npx vitest run`
3. Go (if you touched `cli/`): `cd cli && go build ./... && go test ./... && gofmt -l .`
4. If you change paths, env vars, or cache layout, update `README.md` and the config migration logic, and keep `backend/config/paths.py` and `src/config/paths.ts` aligned.
-5. Keep diffs focused — one feature or fix per PR when possible.
+5. Keep diffs focused: one feature or fix per PR when possible.
## Path and cache conventions
- **Config home** (`PODCLI_HOME` or `.podcli-home` marker): portable settings only.
- **Data dir** (`PODCLI_DATA` or `data/`): transcripts cache, outputs, temp files.
-- **Transcript cache**: `data/cache/transcripts/{16-char-hash}.json` — same hash algorithm in Python (`compute_cache_hash`) and TypeScript (`TranscriptCache`).
+- **Transcript cache**: `data/cache/transcripts/{16-char-hash}.json`. Same hash algorithm in Python (`compute_cache_hash`) and TypeScript (`TranscriptCache`).
Do not reintroduce a separate CLI-only cache path without updating both sides.
diff --git a/ETHOS.podstack.md b/ETHOS.podstack.md
index b83060a..ee2b858 100644
--- a/ETHOS.podstack.md
+++ b/ETHOS.podstack.md
@@ -17,7 +17,7 @@ If the first 5 seconds of a clip, the first 3 words of a title, or the first lin
## 2. The Coffee Test
-Read it out loud. Would a human actually say this to a friend over coffee? If it sounds like a slide deck, LinkedIn post, or press release — rewrite it.
+Read it out loud. Would a human actually say this to a friend over coffee? If it sounds like a slide deck, LinkedIn post, or press release, rewrite it.
**Failed the test if you see:**
- "In this episode we dive into..."
@@ -33,13 +33,13 @@ Read it out loud. Would a human actually say this to a friend over coffee? If it
## 4. No Tension Without Payoff
-A title can create curiosity but the clip must deliver what it promised. Clickbait that doesn't pay off burns trust — and the algorithm notices retention drop.
+A title can create curiosity but the clip must deliver what it promised. Clickbait that doesn't pay off burns trust, and the algorithm notices retention drop.
**Rule:** If the clip can't deliver, change the title. Never change the promise to be bigger than the truth.
## 5. Standalone or Skip
-A short must make complete sense without the full episode. If you need to say "earlier in the episode..." — it's not a short, it's a fragment. Skip it.
+A short must make complete sense without the full episode. If you need to say "earlier in the episode...", it's not a short, it's a fragment. Skip it.
## 6. One Focused Idea
@@ -47,8 +47,8 @@ Every clip: one idea, delivered fully, with a clear start and satisfying end. If
## 7. Specificity Over Vagueness
-"Founders struggle with pricing" — weak.
-"Sarah at Acme raised $4.2M at 3x revenue without a demo" — strong.
+"Founders struggle with pricing": weak.
+"Sarah at Acme raised $4.2M at 3x revenue without a demo", strong.
If you can't point to a name, a number, or a specific moment, push back until you can.
@@ -58,7 +58,7 @@ Never ship 6 shorts of the same content type from one episode. Mix Founder Story
## 9. Delete Generic AI
-If any output could have come from any other podcast's AI, it's wrong. It has to sound like *this show*. Voice fingerprint lives in `knowledge/02-voice-and-tone.md` — skills must match it or flag the miss.
+If any output could have come from any other podcast's AI, it's wrong. It has to sound like *this show*. Voice fingerprint lives in `knowledge/02-voice-and-tone.md`. Skills must match it or flag the miss.
## 10. Fix > Flag > Skip
diff --git a/README.md b/README.md
index 8a607dd..55dc64e 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@
podcli process episode.mp4
```
-That one command transcribes the episode, picks the moments worth clipping, crops to whoever is speaking, and burns the captions in. Transcription and rendering run on your machine. Clip scoring uses Claude Code or Codex login, or an Anthropic API key; without those it falls back to heuristics.
+That one command transcribes the episode, picks the moments worth clipping, crops to the visible face, and burns the captions in. Transcription and rendering run on your machine. Clip scoring uses Claude Code or Codex login, or an Anthropic API key; without those it falls back to heuristics.
## Install
@@ -65,11 +65,11 @@ Clips land in `podcli-clips/` in the directory you ran it from, so each show kee
**Clips**
- 9:16, 16:9, or 1:1, with captions sized for each canvas
-- Face tracking that follows the speaker, split-screen layouts included
+- Face tracking that follows the visible face, split-screen layouts included. Following the active speaker needs AssemblyAI, or a source install with openai-whisper and `HF_TOKEN`
- Multi-segment cuts that drop filler, long pauses, and tangents
- Four caption styles: branded, hormozi, karaoke, subtle
- Logos, intros, outros, and background music from a reusable asset library
-- Loudness-normalized audio and hardware encoding on VideoToolbox, NVENC, and VAAPI, with a CPU fallback
+- Loudness-normalized audio and hardware encoding on VideoToolbox and NVENC, with a CPU fallback
**Editing the full episode**
@@ -78,11 +78,11 @@ Clips land in `podcli-clips/` in the directory you ran it from, so each show kee
- Remote shows too: one file per person becomes a split screen, and a single gallery recording is split into a camera per tile. Questions stay on the split and the guest goes full frame on long answers
- Render the episode as an MP4 with one WAV per person. Studio shoots can also go to Premiere or Final Cut as a timeline that points at your original files
- Same edit from the studio (Multicam edit), the CLI (`podcli multicam <folder>`), or an agent (`manage_multicam`). Re-running reuses the sync and the cut, so only the step you changed runs again
-- With podcli Pro, steer the cut in the cloud editor: `podcli multicam <folder> --cloud` sends small previews and the transcript (your camera files stay on your computer), and `--pull` renders the cut you made there
+- With podcli Pro, steer the cut in the cloud editor: `podcli multicam <folder> --cloud` uploads per-camera proxies, a mic mix (about 550 MB for a two-hour, three-camera episode), and the transcript. Your original camera files stay on your computer, and `--pull` renders the cut you made there
**Finding the moments**
-- Whisper transcription with speaker diarization, or bring your own transcript as `.txt`, `.srt`, or `.vtt`
+- Whisper transcription (speaker diarization on AssemblyAI, or openai-whisper from a source install or `podcli setup --speakers`), or bring your own transcript as `.txt`, `.srt`, or `.vtt`
- AssemblyAI as an alternative engine, and yt-dlp to pull an episode straight from a URL
- AI scoring against your knowledge base, checked against your episode database so it stops resuggesting moments you already published
- Audio energy and laughter detection to build highlight reels
@@ -97,8 +97,8 @@ Clips land in `podcli-clips/` in the directory you ran it from, so each show kee
**Shipping it**
-- 32 MCP tools, so an agent can transcribe, score, render, and publish through conversation
-- YouTube publishing plus performance analytics to see which clips landed
+- 32 MCP tools, so an agent can transcribe, score, and render through conversation
+- YouTube analytics to see which clips landed
- DaVinci Resolve export as FCPXML when you want to finish by hand
- Presets, clip history with duplicate detection, and a transcript cache
@@ -106,9 +106,14 @@ Clips land in `podcli-clips/` in the directory you ran it from, so each show kee
If you are weighing podcli against the cloud clippers, this is the difference:
-- Runs locally. Transcription and rendering happen on your machine by default, so episodes stay there. Only the optional cloud engine (AssemblyAI) and publishing to YouTube send anything out.
+- Runs locally. Transcription and rendering happen on your machine by default, so episodes stay there. Data leaves your machine only through these destinations:
+ - AssemblyAI, if you pick that engine: the episode audio.
+ - AI scoring and titles: the transcript goes to podcli Pro when you are signed in, to Anthropic when you set `ANTHROPIC_API_KEY`, and to the provider behind your Claude Code or Codex login.
+ - podcli Pro, when signed in: knowledge and asset sync, plus rendered clips and transcript slices if you turn on `PODCLI_CLOUD_SYNC=1` (off by default).
+ - YouTube, if you link it: read-only analytics requests.
+ - podcli multicam cloud, if you run `podcli multicam --cloud`: per-camera proxies, a mic mix, and the transcript.
- Free and open source under AGPL-3.0. Exports are unlimited, full quality, and watermark-free.
-- Agent-native. 32 MCP tools let Claude Code or Codex drive the whole flow, transcription through publishing.
+- Agent-native. 32 MCP tools let Claude Code or Codex drive the whole flow, from transcription to rendered clips and publish-ready titles.
- A knowledge base keeps titles, captions, and descriptions in your show's voice, and stops the engine from resuggesting moments you already published.
- DaVinci Resolve handoff. Export any clip as FCPXML when you want to finish the edit yourself.
@@ -120,7 +125,7 @@ podcli is an [MCP](https://modelcontextprotocol.io) server, so an agent can tran
podcli mcp install # registers it with Claude Code and Codex, whichever CLI is on PATH
```
-`--help` and `--version` never download anything. First run of `process`, `studio`, `transcribe`, or `multicam` provisions the engine. `podcli mcp` does not — stdout is JSON-RPC — so run `podcli setup` once before you point an agent at it.
+`--help` and `--version` never download anything. First run of `process`, `studio`, `transcribe`, or `multicam` provisions the engine. `podcli mcp` does not, because stdout is JSON-RPC. Run `podcli setup` once before you point an agent at it.
```bash
podcli process episode.mp4 --json --yes
diff --git a/RELEASE.md b/RELEASE.md
index 90f559a..16d7d50 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -10,7 +10,7 @@ curl -fsSL https://podcli.com/install.sh | sh
# Windows: irm https://podcli.com/install.ps1 | iex
```
-Platforms: macOS arm64, Linux x64/arm64, Windows x64. (npm isn't used — the
+Platforms: macOS arm64, Linux x64/arm64, Windows x64. (npm isn't used because the
unscoped name `podcli` is blocked by npm as too similar to `pod-cli`.)
## Cutting a release
@@ -31,7 +31,7 @@ unscoped name `podcli` is blocked by npm as too similar to `pod-cli`.)
```
4. Watch the `release` workflow. It produces these assets (the names the
installers, self-update, and provisioner expect):
- - `podcli-{darwin,linux,windows}-{amd64,arm64}[.exe]` — static launchers
+ - `podcli-{darwin,linux,windows}-{amd64,arm64}[.exe]`, static launchers
- `whisper-cli-<os>-<arch>[.exe]`
- `studio-bundle.tar.gz`
- `remotion-<os>-<arch>.tar.gz`
diff --git a/SKILL.md b/SKILL.md
index acc97c1..7e01a4c 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -18,7 +18,7 @@ podcli doctor --json # confirm backend, mcp, ffmpeg, models
`--help` and `--version` never download. `podcli mcp` needs setup first because stdout is JSON-RPC.
-Clip scoring uses Claude Code or Codex login, or an Anthropic API key. Without those it falls back to heuristics. Speaker diarization needs `HF_TOKEN`.
+Clip scoring uses Claude Code or Codex login, or an Anthropic API key. Without those it falls back to heuristics. Speaker diarization needs AssemblyAI, or openai-whisper (a source install, or `podcli setup --speakers`) plus `HF_TOKEN`. The default whisper.cpp engine skips it.
## Process an episode (CLI)
@@ -35,7 +35,7 @@ Exit codes: 0 success, 1 runtime error, 2 usage, 130 interrupted.
Prefer the short path so you do not load the full transcript:
1. `transcribe_podcast` (or `transcribe_start` + `job_status` on a long file)
-2. `rank_clip_candidates(video_path)` — about 20 sentence-aligned candidates
+2. `rank_clip_candidates(video_path)`: about 20 sentence-aligned candidates
3. Pick a subset. `suggest_clips` to store them, or `create_clip` / `batch_create_clips` to render
4. `list_outputs` if you only need paths on disk
diff --git a/backend/cli.py b/backend/cli.py
index da80029..907539d 100644
--- a/backend/cli.py
+++ b/backend/cli.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""
-podcli — CLI entry point.
+podcli: CLI entry point.
One-command processing:
python cli.py process video.mp4 --top 5 --transcript transcript.txt
@@ -13,7 +13,9 @@ One-command processing:
import argparse
import json
import os
+from utils.log import warn as log_warn
import re
+import shlex
import shutil
import subprocess
import sys
@@ -280,8 +282,8 @@ def _save_suggestions_session(cache_hash: str, top_n: int, engine: str | None, c
"engine": engine, "clips": clips},
f,
)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not save suggestions session", error=exc)
def _clear_suggestions_session(cache_hash: str) -> None:
@@ -291,8 +293,8 @@ def _clear_suggestions_session(cache_hash: str) -> None:
try:
if os.path.exists(path):
os.unlink(path)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not clear suggestions session", error=exc)
def _should_auto_migrate_cli(args) -> bool:
@@ -368,15 +370,15 @@ def _ensure_ssl_certs():
"""Fix SSL certificate issues automatically (macOS + corporate proxies)."""
import ssl
- # Quick test — if HTTPS works, we're fine
+ # Quick test: if HTTPS works, we're fine
try:
import urllib.request
urllib.request.urlopen("https://huggingface.co", timeout=5)
return
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "HTTPS probe to huggingface.co failed", error=exc)
- print(" ⚠ SSL issue detected — fixing automatically...")
+ print(" ⚠ SSL issue detected: fixing automatically...")
# Method 1: Set certifi certs (works for most cases including corporate proxies)
try:
@@ -403,8 +405,8 @@ def _ensure_ssl_certs():
ssl._create_default_https_context = lambda: ssl.create_default_context(cafile=certifi.where())
print(" ✓ SSL configured (installed certifi)")
return
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "certifi install failed", error=exc)
# Method 3: macOS Install Certificates command
if sys.platform == "darwin":
@@ -416,19 +418,17 @@ def _ensure_ssl_certs():
if cert_scripts:
try:
sp.run(["bash", cert_scripts[0]], capture_output=True, timeout=30)
- # Force reload ssl context
- ssl._create_default_https_context = ssl._create_unverified_context
print(" ✓ SSL certificates installed (restart may be needed)")
return
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "macOS certificate install failed", error=exc)
- # Method 4: disable SSL verification only on explicit opt-in — silently
+ # Method 4: disable SSL verification only on explicit opt-in: silently
# turning off TLS verification is a downgrade risk.
if os.environ.get("PODCLI_INSECURE_SSL", "").strip().lower() in ("1", "true", "yes", "on"):
ssl._create_default_https_context = ssl._create_unverified_context
os.environ["PYTHONHTTPSVERIFY"] = "0"
- print(" ⚠ SSL verification DISABLED (PODCLI_INSECURE_SSL set) — model downloads only")
+ print(" ⚠ SSL verification DISABLED (PODCLI_INSECURE_SSL set), model downloads only")
else:
print(
" ✗ Could not configure SSL certificates. Install certifi "
@@ -575,7 +575,7 @@ def cmd_studio(args):
]
# Where the faces are, and where somebody put the frame by hand. Both are
# what the crop needs and neither could be handed to it before, so a caller
- # that already knew — the cloud worker scans the window before it renders —
+ # that already knew: the cloud worker scans the window before it renders,
# had no way to say so and watched `speaker` fall through to a letterbox.
# A path is made absolute because the script runs from elsewhere; JSON
# given inline is handed straight through.
@@ -656,7 +656,7 @@ def cmd_studio(args):
def cmd_reel(args):
- """Create and iterate on a highlights reel — detect once, then edit moments fast."""
+ """Create and iterate on a highlights reel: detect once, then edit moments fast."""
from services.reel import (
ReelSession, seed_session, edit_moment, build_reel, list_sessions, delete_session,
)
@@ -1416,7 +1416,7 @@ def cmd_process(args):
return
enc_info = get_encoder_info()
- print(f"\n podcli — processing")
+ print(f"\n podcli: processing")
print(f" Encoder: {enc_info['best']} ({enc_info['system']})")
print(f" Quality: {quality}")
if config.get("fast_mode"):
@@ -1431,7 +1431,7 @@ def cmd_process(args):
print(f" {yellow} Run: podcli knowledge init{reset}")
print()
- # Cache hash for resume — keyed by video size+mtime. Disabled when a custom
+ # Cache hash for resume: keyed by video size+mtime. Disabled when a custom
# transcript is supplied, since the hash ignores transcript contents and
# would otherwise resume suggestions made from a different transcript.
cache_hash = ""
@@ -1451,7 +1451,7 @@ def cmd_process(args):
shared_wav = _SharedWav(video_path)
# Saliency profiles (party/action) select on audio/visual signals, not dialogue,
- # so transcribing a long video would be wasted work — skip it entirely.
+ # so transcribing a long video would be wasted work: skip it entirely.
from services.profiles import get_profile
content_profile = get_profile(config.get("profile"))
@@ -1528,10 +1528,13 @@ def cmd_process(args):
result = cached
print(f" {len(segments)} segments, {len(words)} words")
else:
- from services.engines import is_assemblyai_engine
+ from services.engines import is_assemblyai_engine, normalize_engine
engine_label = "AssemblyAI" if is_assemblyai_engine(os.environ.get("PODCLI_ENGINE", "")) else "Whisper"
print(f" [1/4] Transcribing with {engine_label}...")
- _ensure_ssl_certs()
+ # Only whisper-py downloads weights at run time. The other engines
+ # run offline or use their own HTTP client, so the probe is wasted.
+ if normalize_engine(os.environ.get("PODCLI_ENGINE")) == "whisper-py":
+ _ensure_ssl_certs()
import warnings
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU")
from services.transcription import transcribe_file
@@ -1753,7 +1756,12 @@ def cmd_process(args):
# Try an AI CLI first (uses PodStack knowledge base for intelligent selection)
from services import ai_provider
from services.ai_cli import _engine_label
- from services.claude_suggest import ClipBounds, select_clips_with_signal_scores, suggest_initial_with_claude
+ from services.claude_suggest import (
+ ClipBounds,
+ drop_published,
+ select_clips_with_signal_scores,
+ suggest_initial_with_claude,
+ )
providers = ai_provider.status()["providers"]
if clips:
@@ -1787,7 +1795,7 @@ def cmd_process(args):
print(f" [3/4] Scoring clips (fast heuristic mode)...")
else:
print(f" [3/4] Scoring clips (heuristic mode)...")
- print(f" ℹ Install Claude Code or Codex for smarter selection")
+ print(f" ℹ Sign in with `podcli login`, install Claude Code or Codex, or set ANTHROPIC_API_KEY for smarter selection")
# Fallback to heuristic algorithm
if not clips:
@@ -1802,6 +1810,8 @@ def cmd_process(args):
if clips and not resumed_from_session:
_save_suggestions_session(cache_hash, top_n, "heuristic", clips, selection_sig)
+ clips = drop_published(clips)
+
if not clips:
print(" No clips found. Try a longer transcript or lower --min-duration.", file=sys.stderr)
sys.exit(1)
@@ -1842,8 +1852,8 @@ def cmd_process(args):
_thumb_intro_duration = float(
_thumb_cfg.get("intro_duration", _thumb_cfg.get("clip_start_duration", _thumb_intro_duration))
)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "thumbnail config unreadable, using defaults", error=exc)
if config.get("thumbnail_seconds"):
_thumb_intro_duration = float(config["thumbnail_seconds"])
_thumb_intro_duration = max(0.5, min(_thumb_intro_duration, 1.0))
@@ -1970,7 +1980,7 @@ def cmd_process(args):
from services.video_processor import concat_outro
from services.media_probe import align_av_duration as _align_av_duration
final_with_thumb = result["output_path"].replace(".mp4", "_with_thumb.mp4")
- # Hard cut — thumbnail uses the frame just before content,
+ # Hard cut: thumbnail uses the frame just before content,
# so playback feels like the clip has started.
concat_outro(thumb_video, result["output_path"], final_with_thumb, crossfade_duration=0.0)
_align_av_duration(final_with_thumb)
@@ -2037,7 +2047,7 @@ def cmd_process(args):
_raction = _rq.select(
f"Clip {i+1}/{len(clips)}: {clip['title'][:40]}",
choices=[
- _rq.Choice("Looks good — next clip", value="next"),
+ _rq.Choice("Looks good: next clip", value="next"),
_rq.Choice("Change caption style", value="style"),
_rq.Choice("Make shorter (trim 5s from end)", value="shorter"),
_rq.Choice("Make longer (extend 5s)", value="longer"),
@@ -2175,7 +2185,7 @@ def cmd_process(args):
break
except KeyboardInterrupt:
interrupted = True
- print(f"\n ⚠ Render interrupted — keeping completed clips")
+ print(f"\n ⚠ Render interrupted: keeping completed clips")
elapsed = time.time() - t0
success = sum(1 for r in results if "output_path" in r)
@@ -2298,12 +2308,12 @@ def _find_moment_with_claude(description: str, segments: list, existing_clips: l
def _review_clips(clips: list, segments: list, energy_scores: list | None, config: dict) -> list:
- """Interactive clip review — user can select/deselect, ask for more, or find specific moments."""
+ """Interactive clip review: user can select/deselect, ask for more, or find specific moments."""
# Non-interactive (piped/scripted/no TTY): skip the picker and render all
# suggested clips. The picker uses prompt_toolkit, which raises
# OSError [Errno 22] when stdin isn't a real terminal.
if config.get("non_interactive") or not sys.stdin.isatty():
- print(f"\n Non-interactive run — rendering all {len(clips)} suggested clips.")
+ print(f"\n Non-interactive run: rendering all {len(clips)} suggested clips.")
return clips
import questionary
@@ -2467,7 +2477,7 @@ def _post_render_loop(
clips: list, results: list, segments: list, words: list,
config: dict, video_path: str, output_dir: str, face_map, energy_scores,
):
- """Post-render iteration — user can re-render clips with changes or add new ones."""
+ """Post-render iteration: user can re-render clips with changes or add new ones."""
import questionary
from questionary import Style
from services.clip_generator import generate_clip
@@ -2533,7 +2543,7 @@ def _post_render_loop(
print(f" ✓ {new_result['file_size_mb']}MB")
return ok
- # Review each clip one by one — open for preview, ask for feedback
+ # Review each clip one by one: open for preview, ask for feedback
print(f"\n {'─' * 45}")
print(f" {bold}Review clips{reset}")
@@ -2546,7 +2556,7 @@ def _post_render_loop(
action = questionary.select(
"",
choices=[
- questionary.Choice("Looks good — next", value="next"),
+ questionary.Choice("Looks good: next", value="next"),
questionary.Choice("Change caption style", value="style"),
questionary.Choice("Make shorter (trim end)", value="shorter"),
questionary.Choice("Make longer (extend end)", value="longer"),
@@ -2572,10 +2582,10 @@ def _post_render_loop(
if action == "style":
new_style = questionary.select("Style:", choices=[
- questionary.Choice("hormozi — bold uppercase, yellow highlight", value="hormozi"),
- questionary.Choice("branded — dark pill on active word + logo", value="branded"),
- questionary.Choice("karaoke — sentence visible, words light up", value="karaoke"),
- questionary.Choice("subtle — clean small text at bottom", value="subtle"),
+ questionary.Choice("hormozi: bold uppercase, yellow highlight", value="hormozi"),
+ questionary.Choice("branded: dark pill on active word + logo", value="branded"),
+ questionary.Choice("karaoke: sentence visible, words light up", value="karaoke"),
+ questionary.Choice("subtle: clean small text at bottom", value="subtle"),
], style=qstyle).ask()
if new_style:
config["caption_style"] = new_style
@@ -2602,7 +2612,7 @@ def _post_render_loop(
while True:
print(f"\n {'─' * 45}")
choices = [
- questionary.Choice("Done — open output folder", value="done"),
+ questionary.Choice("Done: open output folder", value="done"),
questionary.Choice("Re-review a clip", value="rerender"),
questionary.Choice("Find another moment to clip", value="find"),
questionary.Choice("Find additional clips beyond current picks", value="more"),
@@ -2798,18 +2808,18 @@ def _suggest_clips(
Score and rank transcript segments into viral clip suggestions.
Scoring dimensions:
- 1. Hook strength — does it open with something that grabs attention?
- 2. Standalone value — does it make sense without context?
- 3. Completeness — does it start and end on sentence boundaries?
- 4. Content signals — keywords, questions, stories, bold claims
- 5. Speaker dynamics — speaker changes make clips more engaging
- 6. Audio energy — louder/more passionate = more engaging
- 7. Density — information per second (too sparse = boring)
+ 1. Hook strength: does it open with something that grabs attention?
+ 2. Standalone value: does it make sense without context?
+ 3. Completeness: does it start and end on sentence boundaries?
+ 4. Content signals: keywords, questions, stories, bold claims
+ 5. Speaker dynamics: speaker changes make clips more engaging
+ 6. Audio energy: louder/more passionate = more engaging
+ 7. Density: information per second (too sparse = boring)
"""
# ── Signal keywords by category (weighted differently) ──
- # Strong hooks — things people say right before a great moment
+ # Strong hooks: things people say right before a great moment
HOOK_PHRASES = [
"here's the thing", "let me tell you", "the truth is",
"what people don't realize", "nobody talks about",
@@ -2819,7 +2829,7 @@ def _suggest_clips(
"the one thing", "if i'm being honest", "the hard truth",
]
- # Insight signals — content that teaches or reveals
+ # Insight signals: content that teaches or reveals
INSIGHT_WORDS = [
"because", "actually", "specifically", "the problem is",
"most people", "counterintuitive", "the data shows",
@@ -2827,20 +2837,16 @@ def _suggest_clips(
"in practice", "the trick", "fundamentally",
]
- # Story signals — narrative elements that pull people in
+ # Story signals: narrative elements that pull people in
STORY_SIGNALS = [
"when i", "when we", "i remember", "years ago", "at that point",
"we decided", "we were", "i was", "the first time",
"that morning", "one day", "back then", "suddenly",
]
- # Numbers/specifics — concrete details increase credibility
- NUMBER_PATTERN = None
- try:
- import re
- NUMBER_PATTERN = re.compile(r'\$[\d,.]+[mkb]?|\d+%|\d+\.\d+[x×]|\d{2,}', re.IGNORECASE)
- except Exception:
- pass
+ # Numbers/specifics: concrete details increase credibility
+ import re
+ NUMBER_PATTERN = re.compile(r'\$[\d,.]+[mkb]?|\d+%|\d+\.\d+[x×]|\d{2,}', re.IGNORECASE)
# Sentence boundary detection
def _is_sentence_start(text):
@@ -2948,7 +2954,7 @@ def _suggest_clips(
if exclaim_count >= 1:
score += min(exclaim_count, 3)
- # ── 4. Specificity — numbers, dollars, percentages (0-4 pts) ──
+ # ── 4. Specificity: numbers, dollars, percentages (0-4 pts) ──
if NUMBER_PATTERN:
numbers = NUMBER_PATTERN.findall(text)
if numbers:
@@ -2996,14 +3002,14 @@ def _suggest_clips(
if max_r > 3:
reasons.append("laughter")
- # ── 7. Density check — penalize sparse/rambling segments ──
+ # ── 7. Density check: penalize sparse/rambling segments ──
words_per_sec = len(text.split()) / max(dur, 1)
if words_per_sec < 1.5:
score *= 0.7 # Too sparse, probably silence or filler
elif words_per_sec > 2.5:
score *= 1.1 # Dense = packed with info
- # ── 8. Anti-patterns — penalize weak clips ──
+ # ── 8. Anti-patterns: penalize weak clips ──
# Clips that reference other parts of the conversation
if any(ref in text_lower for ref in [
"as i said", "like i mentioned", "going back to",
@@ -3374,7 +3380,7 @@ def cmd_thumbnail_config(args):
if action == "reset":
if os.path.exists(target):
os.remove(target)
- print("Reset thumbnail config — using the generic default template.")
+ print("Reset thumbnail config: using the generic default template.")
return
raise ValueError(f"unknown thumbnail-config action: {action}")
@@ -3670,7 +3676,7 @@ def cmd_swap_thumbnail(args):
thumb_duration = getattr(args, "thumb_duration", 1.5)
title = getattr(args, "title", None) or os.path.splitext(os.path.basename(clip_path))[0].replace("_", " ")
- # Source video for extracting a new face frame — required to avoid
+ # Source video for extracting a new face frame: required to avoid
# pulling frames from rendered clips (which have captions burned in)
source_video = getattr(args, "source_video", None)
if not source_video:
@@ -3694,99 +3700,97 @@ def cmd_swap_thumbnail(args):
import tempfile
work_dir = tempfile.mkdtemp(prefix="swap_thumb_")
-
- # Trim off old thumbnail
- trimmed_path = os.path.join(work_dir, "trimmed.mp4")
- from utils.proc import run as proc_run
- trim_cmd = [
- "ffmpeg", "-y", "-i", clip_path,
- "-t", str(content_duration),
- "-c", "copy", "-movflags", "+faststart",
- trimmed_path,
- ]
- result = proc_run(trim_cmd, timeout=60, check=False)
- if result.returncode != 0:
- print(f" Failed to trim: {result.stderr[-200:]}", file=sys.stderr)
- sys.exit(1)
-
- # Step 2: Generate new thumbnail
- thumb_dir = os.path.join(work_dir, "thumbnails")
- print(f" {bold}Generating new thumbnails...{reset}")
-
- timestamp = getattr(args, "timestamp", None)
- start_sec = getattr(args, "start", None)
- end_sec = getattr(args, "end", None)
-
- # A user-supplied image wins over any frame extraction.
- frame_path = None
- custom_image = getattr(args, "image", None)
- if custom_image:
- if not os.path.exists(custom_image):
- print(f" ✗ Image not found: {custom_image}", file=sys.stderr)
+ try:
+ # Trim off old thumbnail
+ trimmed_path = os.path.join(work_dir, "trimmed.mp4")
+ from utils.proc import run as proc_run
+ trim_cmd = [
+ "ffmpeg", "-y", "-i", clip_path,
+ "-t", str(content_duration),
+ "-c", "copy", "-movflags", "+faststart",
+ trimmed_path,
+ ]
+ result = proc_run(trim_cmd, timeout=60, check=False)
+ if result.returncode != 0:
+ print(f" Failed to trim: {result.stderr[-200:]}", file=sys.stderr)
sys.exit(1)
- frame_path = custom_image
- print(f" {green}✓{reset} Using uploaded image")
- if frame_path is None and timestamp is not None:
- import cv2
- cap = cv2.VideoCapture(source_video)
- cap.set(cv2.CAP_PROP_POS_MSEC, timestamp * 1000)
- ret, frame = cap.read()
- cap.release()
- if ret:
- frame_path = os.path.join(thumb_dir, "_manual_frame.png")
- os.makedirs(thumb_dir, exist_ok=True)
- cv2.imwrite(frame_path, frame)
- print(f" {green}✓{reset} Using frame at {timestamp}s")
- else:
- print(f" ⚠ Could not read frame at {timestamp}s, falling back to auto", file=sys.stderr)
- paths = generate_variations(
- title=title,
- output_dir=thumb_dir,
- photo_path=frame_path,
- video_path=source_video,
- start_second=start_sec,
- end_second=end_sec,
- logo_path=logo,
- config={"variations": getattr(args, "variations", 3)},
- )
+ # Step 2: Generate new thumbnail
+ thumb_dir = os.path.join(work_dir, "thumbnails")
+ print(f" {bold}Generating new thumbnails...{reset}")
- if not paths:
- print(f" Failed to generate thumbnails", file=sys.stderr)
- sys.exit(1)
+ timestamp = getattr(args, "timestamp", None)
+ start_sec = getattr(args, "start", None)
+ end_sec = getattr(args, "end", None)
+
+ # A user-supplied image wins over any frame extraction.
+ frame_path = None
+ custom_image = getattr(args, "image", None)
+ if custom_image:
+ if not os.path.exists(custom_image):
+ print(f" ✗ Image not found: {custom_image}", file=sys.stderr)
+ sys.exit(1)
+ frame_path = custom_image
+ print(f" {green}✓{reset} Using uploaded image")
+ if frame_path is None and timestamp is not None:
+ import cv2
+ cap = cv2.VideoCapture(source_video)
+ cap.set(cv2.CAP_PROP_POS_MSEC, timestamp * 1000)
+ ret, frame = cap.read()
+ cap.release()
+ if ret:
+ frame_path = os.path.join(thumb_dir, "_manual_frame.png")
+ os.makedirs(thumb_dir, exist_ok=True)
+ cv2.imwrite(frame_path, frame)
+ print(f" {green}✓{reset} Using frame at {timestamp}s")
+ else:
+ print(f" ⚠ Could not read frame at {timestamp}s, falling back to auto", file=sys.stderr)
+
+ paths = generate_variations(
+ title=title,
+ output_dir=thumb_dir,
+ photo_path=frame_path,
+ video_path=source_video,
+ start_second=start_sec,
+ end_second=end_sec,
+ logo_path=logo,
+ config={"variations": getattr(args, "variations", 3)},
+ )
- # Show variations
- for i, p in enumerate(paths):
- print(f" {green}✓{reset} Variation {i+1}: {p}")
+ if not paths:
+ print(f" Failed to generate thumbnails", file=sys.stderr)
+ sys.exit(1)
- # Use first variation (or user-specified)
- pick = getattr(args, "pick", 1) - 1
- pick = max(0, min(pick, len(paths) - 1))
- chosen = paths[pick]
- print(f" {accent}Using variation {pick + 1}{reset}")
+ # Show variations
+ for i, p in enumerate(paths):
+ print(f" {green}✓{reset} Variation {i+1}: {p}")
- # Step 3: Convert to video frame and append
- thumb_video = os.path.join(work_dir, "thumb_frame.mp4")
- thumbnail_to_video_frame(chosen, thumb_video, duration=thumb_duration)
+ # Use first variation (or user-specified)
+ pick = getattr(args, "pick", 1) - 1
+ pick = max(0, min(pick, len(paths) - 1))
+ chosen = paths[pick]
+ print(f" {accent}Using variation {pick + 1}{reset}")
- final_path = os.path.join(work_dir, "final.mp4")
- concat_outro(trimmed_path, thumb_video, final_path, crossfade_duration=0.0, transition="fade")
+ # Step 3: Convert to video frame and append
+ thumb_video = os.path.join(work_dir, "thumb_frame.mp4")
+ thumbnail_to_video_frame(chosen, thumb_video, duration=thumb_duration)
- # Step 4: Replace original
- import shutil
- shutil.move(final_path, clip_path)
+ final_path = os.path.join(work_dir, "final.mp4")
+ concat_outro(trimmed_path, thumb_video, final_path, crossfade_duration=0.0, transition="fade")
- # Copy thumbnail PNGs next to the clip
- clip_dir = os.path.dirname(clip_path)
- for p in paths:
- dest = os.path.join(clip_dir, os.path.basename(p))
- shutil.copy2(p, dest)
+ # Step 4: Replace original
+ shutil.move(final_path, clip_path)
- # Cleanup
- shutil.rmtree(work_dir, ignore_errors=True)
+ # Copy thumbnail PNGs next to the clip
+ clip_dir = os.path.dirname(clip_path)
+ for p in paths:
+ dest = os.path.join(clip_dir, os.path.basename(p))
+ shutil.copy2(p, dest)
- print(f" {green}✓ Thumbnail swapped!{reset}")
- print(f" {gray}Variations saved next to clip for future swaps.{reset}\n")
+ print(f" {green}✓ Thumbnail swapped!{reset}")
+ print(f" {gray}Variations saved next to clip for future swaps.{reset}\n")
+ finally:
+ shutil.rmtree(work_dir, ignore_errors=True)
def cmd_corrections(args):
@@ -3876,7 +3880,7 @@ def cmd_knowledge(args):
elif action == "list":
print(f"\n {bold}Knowledge Base{reset}")
print(f" {'─' * 45}")
- empty_hint = f" {gray}Empty — run{reset} podcli knowledge init {gray}to create the starter templates{reset}\n"
+ empty_hint = f" {gray}Empty: run{reset} podcli knowledge init {gray}to create the starter templates{reset}\n"
files = kb_files(kb_dir)
if not files:
print(empty_hint)
@@ -3893,8 +3897,8 @@ def cmd_knowledge(args):
if line and not line.startswith("#") and not line.startswith("---"):
preview = line[:60]
break
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not read knowledge file preview", error=exc)
print(f" {accent}•{reset} {bold}{fname}{reset} {gray}({size/1024:.1f}KB){reset}")
if preview:
print(f" {dim}{preview}{'…' if len(preview) >= 60 else ''}{reset}")
@@ -3932,7 +3936,7 @@ def cmd_knowledge(args):
else:
# Open in $EDITOR
editor = os.environ.get("EDITOR", "nano")
- os.system(f'{editor} "{fpath}"')
+ subprocess.run([*shlex.split(editor), fpath])
elif action == "delete":
name = getattr(args, "filename", None)
@@ -3965,11 +3969,11 @@ def _print_config_result(action: str, data: dict) -> None:
print(f" {gray}→ transcripts, remotion bundle (override with PODCLI_DATA){reset}")
print(f" {gray}profile marker{reset}: {data.get('profile_marker')}")
if data.get("legacy_cache_pending"):
- print(f" {yellow}legacy cache{reset}: project/.podcli/cache still has files — run Migrate below")
+ print(f" {yellow}legacy cache{reset}: project/.podcli/cache still has files. Run Migrate below")
else:
print(f" {green}✓{reset} legacy cache: nothing pending under project/.podcli/cache")
if data.get("legacy_presets_pending"):
- print(f" {yellow}legacy presets{reset}: project/presets/ still has files — run Migrate below")
+ print(f" {yellow}legacy presets{reset}: project/presets/ still has files. Run Migrate below")
else:
print(f" {green}✓{reset} legacy presets: nothing pending under project/presets/")
print()
@@ -4060,7 +4064,7 @@ def cmd_clips(args):
limit = getattr(args, "limit", 50)
clips = get_clips_by_source(source)[:limit] if source else list_clips(limit)
if not clips:
- print(f"\n {gray}No clips yet — render one with{reset} {accent}podcli process{reset}\n")
+ print(f"\n {gray}No clips yet: render one with{reset} {accent}podcli process{reset}\n")
return
print(f"\n {bold}Recent clips ({len(clips)}){reset}\n")
for c in clips:
@@ -4164,7 +4168,7 @@ def cmd_clips(args):
print(f"\n {green}✓{reset} Reopened {accent}{str(clip.get('id'))[:8]}{reset} {bold}{clip.get('title')}{reset}")
if not transcript:
- print(f" {gray}Transcript not loaded — re-transcribe in the studio to edit captions.{reset}")
+ print(f" {gray}Transcript not loaded: re-transcribe in the studio to edit captions.{reset}")
print(f" {gray}Open the studio:{reset} {accent}{web_server_url()}/clip/{clip.get('id')}{reset}\n")
return
@@ -4188,7 +4192,7 @@ def cmd_youtube(args):
from services.integrations.youtube import client
try:
client.authorize()
- print(f"\n {green}✓{reset} Authorized — token cached.\n")
+ print(f"\n {green}✓{reset} Authorized: token cached.\n")
except Exception as e:
fail(e)
return
@@ -4232,7 +4236,7 @@ def cmd_youtube(args):
if not proposals:
print(f"\n {gray}No link proposals (all clips linked, or no uploads matched).{reset}\n")
return
- print(f"\n {bold}Proposed links ({len(proposals)}){reset} {gray}— confirm with: youtube link <clip_id> <video_id>{reset}\n")
+ print(f"\n {bold}Proposed links ({len(proposals)}){reset} {gray}confirm with: youtube link <clip_id> <video_id>{reset}\n")
for p in proposals:
print(f" {accent}{p['clip_id'][:8]}{reset} {p['clip_title']}")
print(f" {gray}→ {p['video_id']} {p['video_title']} (score {p['score']}){reset}")
@@ -4251,7 +4255,7 @@ def cmd_youtube(args):
print(f" {tone}{link['score']}{reset} \"{link['clip_title']}\" ← \"{link['row_title']}\"")
if res["unmatched"]:
print(f" {gray}Unmatched: {len(res['unmatched'])}{reset}")
- print(f" {gray}Low scores are fuzzy title matches — verify them.{reset}\n")
+ print(f" {gray}Low scores are fuzzy title matches. Verify them.{reset}\n")
else:
n = sync.sync_metrics()
print(f"\n {green}✓{reset} Synced metrics onto {n} linked clip(s).\n")
@@ -4298,7 +4302,7 @@ def cmd_env(args):
for s in data["settings"]:
mark = f"{green}set{reset}" if s["set"] else f"{gray}auto{reset}" if not s["secret"] else f"{gray}not set{reset}"
val = f" {gray}{s['preview']}{reset}" if s["set"] else ""
- print(f" {accent}{s['key']}{reset} — {s['label']} [{mark}]{val}")
+ print(f" {accent}{s['key']}{reset}: {s['label']} [{mark}]{val}")
print(f" {gray}{s['help']}{reset}")
if s.get("url"):
print(f" {gray}{s['url']}{reset}")
@@ -4377,7 +4381,7 @@ def cmd_cache(args):
print(f" {'─' * 35}")
if not os.path.exists(cache_dir):
- print(f" {gray}Empty — no cached transcriptions{reset}\n")
+ print(f" {gray}Empty: no cached transcriptions{reset}\n")
return
files = [f for f in os.listdir(cache_dir) if f.endswith(".json")]
@@ -4389,7 +4393,7 @@ def cmd_cache(args):
if f.endswith(".json")
)
if not files:
- print(f" {gray}Empty — no cached transcriptions{reset}\n")
+ print(f" {gray}Empty: no cached transcriptions{reset}\n")
return
total_size = 0
@@ -4481,8 +4485,8 @@ def cmd_info(args):
if line.strip().startswith("HF_TOKEN=") and line.strip().split("=", 1)[1].strip():
hf_token = line.strip().split("=", 1)[1].strip()
break
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not read HF_TOKEN from env file", error=exc)
print(f"\n podcli system info\n")
print(f" Platform: {info['system']}")
@@ -4494,11 +4498,11 @@ def cmd_info(args):
except (ImportError, ValueError):
diarization_available = False
if not diarization_available:
- speakers_status = f"{yellow}✗ not installed — run: podcli setup --speakers (pyannote + torch, ~2GB)"
+ speakers_status = f"{yellow}✗ not installed. Run: podcli setup --speakers (openai-whisper + pyannote + torch, ~2GB)"
elif hf_token:
speakers_status = f"{green}✓ configured"
else:
- speakers_status = f"{yellow}✗ set a token — run: podcli env set HF_TOKEN <token>"
+ speakers_status = f"{yellow}✗ set a token with: podcli env set HF_TOKEN <token>"
if candidates:
c0 = candidates[0]
@@ -4592,7 +4596,7 @@ def print_banner():
if os.path.isdir(cache_dir):
cache_count = len([f for f in os.listdir(cache_dir) if f.endswith(".json")])
- # Status — one line
+ # Status: one line
ai_label = _providers[0]["label"] if _providers else "AI"
ai_tag = f"{green}✓ {ai_label}{reset}" if _providers else f"{yellow}✗{reset}"
speaker_tag = f"{green}✓{reset}" if speakers_ok else f"{yellow}✗{reset}"
@@ -4600,7 +4604,7 @@ def print_banner():
kb_tag = f"{green}{kb_count}{reset}" if kb_count else f"{yellow}0{reset}"
print(f" {gray}Encoder {green}{encoder_label}{reset} {gray}· {ai_tag} {gray}· Speakers {speaker_tag} {gray}· Cache {cache_tag} {gray}· Knowledge {kb_tag}{reset}")
- # Assets — one line if any
+ # Assets: one line if any
try:
from services.asset_store import list_assets
assets = list_assets()
@@ -4612,8 +4616,8 @@ def print_banner():
else:
parts.append(f"{red}✗{reset} {a['name']}")
print(f" {gray}Assets{reset} {' '.join(parts)}")
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not list assets", error=exc)
# Presets
try:
@@ -4627,8 +4631,8 @@ def print_banner():
tag += f" {dim}({os.path.basename(p['video_path'])}){reset}{gray}"
names.append(tag)
print(f" {gray}Presets{reset} {gray}{' · '.join(names)}{reset}")
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not list presets", error=exc)
# Corrections count
try:
@@ -4636,16 +4640,16 @@ def print_banner():
corr = get_corrections()
if corr:
print(f" {gray}Corrections{reset} {green}{len(corr)}{reset} {gray}words{reset}")
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not read corrections", error=exc)
print()
if not speakers_ok:
if not _diarization_ok:
- print(f" {yellow}⚠ Speaker detection not installed — run: podcli setup --speakers{reset}")
+ print(f" {yellow}⚠ Speaker detection not installed. Run: podcli setup --speakers{reset}")
else:
- print(f" {yellow}⚠ Speaker detection needs a token — run: podcli env set HF_TOKEN <token>{reset}")
+ print(f" {yellow}⚠ Speaker detection needs a token. Run: podcli env set HF_TOKEN <token>{reset}")
if not kb_count:
print(f" {yellow}⚠ Knowledge base empty, clips get scored without your show context. Run: podcli knowledge init{reset}")
@@ -4664,7 +4668,7 @@ def print_help():
ul = "\033[4m"
print(BANNER)
- print(f" {bold}podcli{reset} v{VERSION} — AI-powered podcast clip generator")
+ print(f" {bold}podcli{reset} v{VERSION}: AI-powered podcast clip generator")
print()
print(f" {bold}Usage:{reset} podcli {accent}<command>{reset} [options]")
print(f" podcli {dim}(interactive mode){reset}")
@@ -4773,7 +4777,7 @@ def _apply_template(config: dict, name_or_id: str) -> None:
Templates live with the account rather than on a machine, so the same name
means the same look on a laptop and in the studio. Everything a template
- sets is something this CLI already takes as a flag — the template is a name
+ sets is something this CLI already takes as a flag. The template is a name
for a set of them, not a second way to render.
"""
from services import podcli_cloud
@@ -4868,8 +4872,8 @@ def cmd_login(args):
if not args.no_browser:
try:
webbrowser.open(url)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not open a browser", error=exc)
interval = max(1, int(start.get("interval") or 3))
deadline = time.monotonic() + int(start.get("expiresIn") or 600)
@@ -4902,7 +4906,7 @@ def cmd_login(args):
print(f" Signed in to {workspace.get('name', 'your workspace')} "
f"({account.get('plan', 'free')} plan, {account.get('role', 'member')}).")
if account.get("plan") == "free":
- print(" This workspace has no active subscription — podcli will keep using "
+ print(" This workspace has no active subscription, so podcli will keep using "
"your local AI CLI until one starts.")
# Everything already rendered on this machine belongs in the workspace too,
@@ -4914,7 +4918,7 @@ def cmd_login(args):
if synced:
print(f" Synced {synced} existing clip{'s' if synced != 1 else ''} to your workspace.")
if failed:
- print(f" {failed} could not be synced — `podcli whoami` will retry later.")
+ print(f" {failed} could not be synced. `podcli whoami` will retry later.")
def cmd_logout(args):
@@ -5617,7 +5621,7 @@ def main():
st.add_argument("clip", help="Path to rendered clip (.mp4)")
st.add_argument("--title", help="Title text (defaults to filename)")
st.add_argument("--image", help="Use this image as the thumbnail background instead of a video frame")
- st.add_argument("--source-video", required=True, help="Original source video (required — rendered clips have captions burned in)")
+ st.add_argument("--source-video", required=True, help="Original source video (required: rendered clips have captions burned in)")
st.add_argument("--start", type=float, help="Clip start time in source video (seconds)")
st.add_argument("--end", type=float, help="Clip end time in source video (seconds)")
st.add_argument("--timestamp", type=float, help="Exact second in source video to use as frame (skips auto-detection)")
@@ -5871,7 +5875,7 @@ def launch_webui():
"PODCLI_BACKEND": backend_dir,
"PYTHON_PATH": sys.executable,
"PODCLI_HOME": paths["home"],
- # data_dir is the cache's parent — output is now decoupled
+ # data_dir is the cache's parent: output is now decoupled
# (clips render to the working dir), so don't derive it from output.
"PODCLI_DATA": os.path.dirname(paths["cache"]),
"PODCLI_OUTPUT": paths["output"],
@@ -5889,7 +5893,7 @@ def launch_webui():
print(f"\n {gray}Building the studio (first run)…{reset}\n")
ok = sp.run(["npm", "run", "build"], cwd=repo, shell=_npm_shell).returncode == 0
if not ok:
- print(f"\n {yellow}Build failed — run 'npm install' then try again.{reset}\n")
+ print(f"\n {yellow}Build failed: run 'npm install' then try again.{reset}\n")
if ok:
print(f"\n {gray}Studio:{reset} {accent}http://localhost:{port}{reset} {dim}(Ctrl+C to stop){reset}\n")
sp.run(["npm", "run", "ui:prod"], cwd=repo, shell=_npm_shell)
@@ -5899,7 +5903,7 @@ def launch_webui():
def interactive_menu():
- """Interactive startup — show banner then let user pick what to do."""
+ """Interactive startup: show banner then let user pick what to do."""
accent = "\033[38;2;212;135;74m"
gray = "\033[38;5;245m"
@@ -5911,11 +5915,8 @@ def interactive_menu():
print_banner()
- # Reset terminal to sane state — fixes ^M echo from corrupted tty settings
- try:
- os.system("stty sane 2>/dev/null")
- except Exception:
- pass
+ # Reset terminal to sane state: fixes ^M echo from corrupted tty settings
+ os.system("stty sane 2>/dev/null")
import questionary
from questionary import Style
@@ -6004,8 +6005,8 @@ def _flush_stdin():
try:
while select.select([sys.stdin], [], [], 0.0)[0]:
sys.stdin.readline()
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "could not flush stdin", error=exc)
def _ask(prompt, default=None, validate=None, required=False, is_path=False):
@@ -6148,7 +6149,7 @@ def _interactive_auto():
if preset_choices:
options = [
questionary.Choice(
- f"{p['name']} — {os.path.basename(p['video_path'])}",
+ f"{p['name']}: {os.path.basename(p['video_path'])}",
value=p["name"],
)
for p in preset_choices
@@ -6184,7 +6185,7 @@ def _interactive_auto():
video_path = _clean_path(val)
brief = questionary.text(
- "Brief (optional — e.g. '5 clips' or 'focus on investor pitch'):",
+ "Brief (optional: e.g. '5 clips' or 'focus on investor pitch'):",
style=qstyle,
default="",
).ask()
@@ -6208,9 +6209,9 @@ def _interactive_auto():
tag = f"preset '{preset_name}'"
if hints:
tag += f" ({', '.join(hints)})"
- prompt_parts.append(f"— {tag}")
+ prompt_parts.append(f"- {tag}")
if brief.strip():
- prompt_parts.append(f"— {brief.strip()}")
+ prompt_parts.append(f"- {brief.strip()}")
prompt = " ".join(prompt_parts)
code = _launch_podstack_auto(prompt, os.environ.get("PODCLI_AI", "auto"))
@@ -6247,7 +6248,7 @@ def _interactive_process():
if preset_choices:
preset_options = [
questionary.Choice(
- f"{p['name']} — {os.path.basename(p['video_path'])}",
+ f"{p['name']}: {os.path.basename(p['video_path'])}",
value=p["name"]
) for p in preset_choices
]
@@ -6302,10 +6303,10 @@ def _interactive_process():
caption_style = questionary.select(
"Caption style:",
choices=[
- questionary.Choice("branded — dark pill on active word + logo", value="branded"),
- questionary.Choice("hormozi — bold uppercase, yellow highlight", value="hormozi"),
- questionary.Choice("karaoke — sentence visible, words light up", value="karaoke"),
- questionary.Choice("subtle — clean small text at bottom", value="subtle"),
+ questionary.Choice("branded: dark pill on active word + logo", value="branded"),
+ questionary.Choice("hormozi: bold uppercase, yellow highlight", value="hormozi"),
+ questionary.Choice("karaoke: sentence visible, words light up", value="karaoke"),
+ questionary.Choice("subtle: clean small text at bottom", value="subtle"),
],
default="branded",
style=qstyle,
@@ -6341,8 +6342,8 @@ def _interactive_process():
logo_choices = [questionary.Choice(f"{a['name']} ({os.path.basename(a['path'])})", value=a["path"]) for a in logos]
logo_choices.append(questionary.Choice("None", value=None))
logo = questionary.select("Logo:", choices=logo_choices, default=logo_choices[0], style=qstyle).ask()
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "logo prompt skipped", error=exc)
# Outro
outro = None
@@ -6353,8 +6354,8 @@ def _interactive_process():
outro_choices = [questionary.Choice("None", value=None)]
outro_choices += [questionary.Choice(f"{a['name']} ({os.path.basename(a['path'])})", value=a["path"]) for a in outros]
outro = questionary.select("Outro:", choices=outro_choices, style=qstyle).ask()
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "outro prompt skipped", error=exc)
# Confirm
print(f"\n {'─' * 45}")
@@ -6622,7 +6623,7 @@ def _interactive_presets():
for p in presets:
label = p["name"]
if p.get("video_path"):
- label += f" — {os.path.basename(p['video_path'])}"
+ label += f": {os.path.basename(p['video_path'])}"
actions.append(questionary.Choice(f"Edit: {label}", value=f"edit:{p['name']}"))
for p in presets:
actions.append(questionary.Choice(f"Delete: {p['name']}", value=f"del:{p['name']}"))
@@ -6697,8 +6698,8 @@ def _interactive_presets():
logo = questionary.select("Logo:", choices=logo_choices, default=current_logo or logo_choices[0], style=qstyle).ask()
if logo is not None:
config["logo_path"] = logo
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "logo prompt skipped", error=exc)
# Outro from assets
try:
@@ -6711,8 +6712,8 @@ def _interactive_presets():
outro = questionary.select("Outro:", choices=outro_choices, default=current_outro or outro_choices[0], style=qstyle).ask()
if outro is not None:
config["outro_path"] = outro
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cli", "outro prompt skipped", error=exc)
# Quality
quality = questionary.select(
@@ -6795,7 +6796,7 @@ def _interactive_knowledge():
elif action == "edit":
if not files:
- print(f" {gray}No files to edit — create one first{reset}")
+ print(f" {gray}No files to edit: create one first{reset}")
return
choice = questionary.select("Which file?", choices=files, style=qstyle).ask()
if choice:
diff --git a/backend/clip_studio.py b/backend/clip_studio.py
index c4926db..981395a 100644
--- a/backend/clip_studio.py
+++ b/backend/clip_studio.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""
-clip_studio — cut a precise fragment from a video and wrap it with a Remotion
+clip_studio: cut a precise fragment from a video and wrap it with a Remotion
intro + "Follow for more" outro (with social icons).
Cut a fragment by TIMESTAMP or by PARAGRAPH text (matched against the
@@ -146,7 +146,7 @@ def _find_paragraph(words: list, phrase: str) -> tuple[float, float]:
raise SystemExit(f"Could not confidently locate paragraph in transcript (best match {best_score}/{win} words).")
start = float(words[best_i]["start"])
end = float(words[min(best_i + win - 1, len(words) - 1)]["end"])
- print(f" [paragraph] matched {best_score}/{win} words → {start:.1f}s–{end:.1f}s", flush=True)
+ print(f" [paragraph] matched {best_score}/{win} words → {start:.1f}s-{end:.1f}s", flush=True)
return start, end
@@ -269,7 +269,7 @@ def _render_fragment(video, start, end, words, style, crop, title, out_dir, fmt=
captions=True, face_map=None, crop_keyframes=None, hook=None):
"""Render the fragment with face-crop + captions via the existing engine."""
from services.clip_generator import generate_clip
- print(f" [fragment] rendering {start:.1f}s–{end:.1f}s ({style}, crop={crop}, {fmt})", flush=True)
+ print(f" [fragment] rendering {start:.1f}s-{end:.1f}s ({style}, crop={crop}, {fmt})", flush=True)
res = generate_clip(
video_path=video, start_second=start, end_second=end,
caption_style=style, caption_position=caption_position,
@@ -576,7 +576,7 @@ def main():
else:
final = os.path.join(out_dir, "studio_final.mp4")
if len(parts) == 1:
- # no bookends — fragment is the result
+ # no bookends: fragment is the result
import shutil
shutil.copy(parts[0], final)
else:
diff --git a/backend/config/caption_styles.py b/backend/config/caption_styles.py
index 0b71bd5..b0a6fcf 100644
--- a/backend/config/caption_styles.py
+++ b/backend/config/caption_styles.py
@@ -6,6 +6,7 @@ supported caption types.
"""
import subprocess
+from utils.log import warn as log_warn
from utils.proc import run as proc_run
import functools
@@ -42,8 +43,8 @@ def _detect_font() -> str:
for candidate in candidates:
if candidate in available:
return candidate
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("captions", "fc-list font probe failed, using default font", error=exc)
# If fc-list isn't available (macOS without fontconfig), try common ones
# Arial is almost always available on macOS/Windows
@@ -61,7 +62,7 @@ STYLES = {
"font_name": DETECTED_FONT,
"font_size": 80,
"primary_color": "&H00FFFFFF", # White (inactive words)
- "active_color": "&H0000FFFF", # Yellow (active word) — BGR for yellow
+ "active_color": "&H0000FFFF", # Yellow (active word), BGR for yellow
"outline_color": "&H00000000", # Black outline
"back_color": "&H80000000", # Semi-transparent black box
"active_box_color": "&H00000000", # Black box behind active word
@@ -133,7 +134,7 @@ STYLES = {
"primary_color": "&H00FFFFFF", # White (all words)
"active_color": "&H00FFFFFF", # White text on dark box
"active_box_color": "&H00000000", # Black pill bg
- "active_box_alpha": "&H30", # Pill opacity (00=solid, FF=invisible) — 30 ≈ 81% opaque
+ "active_box_alpha": "&H30", # Pill opacity (00=solid, FF=invisible), 30 ≈ 81% opaque
"active_box_padding_x": 10, # Horizontal padding inside pill
"active_box_padding_y": 10, # Vertical padding inside pill
"active_box_rounding": 15, # Border rounding for pill shape
@@ -144,9 +145,9 @@ STYLES = {
"shadow_depth": 1, # Subtle shadow for text edge smoothing
"alignment": 2, # Bottom-center
"margin_v": 500, # Position: ~72% from top (natural lower-third)
- "words_per_chunk": 3, # Show 3 words at a time — readable on small screens
+ "words_per_chunk": 3, # Show 3 words at a time, readable on small screens
"uppercase": False, # Mixed case, natural capitalization
- "gradient_overlay": False, # No gradient — clean direct-on-video
+ "gradient_overlay": False, # No gradient, clean direct-on-video
"gradient_opacity": 0.0,
"logo_margin_x": 40, # Logo X offset from left
"logo_margin_y": 60, # Logo Y offset from top
diff --git a/backend/config_bundle.py b/backend/config_bundle.py
index 1e1e000..e1581cd 100644
--- a/backend/config_bundle.py
+++ b/backend/config_bundle.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import os
+from utils.log import warn as log_warn
import re
import shutil
import tempfile
@@ -275,7 +276,7 @@ def _safe_extract_zip(zf: zipfile.ZipFile, target: Path) -> None:
name = info.filename
if name.startswith("/") or name.startswith("\\"):
raise ValueError(f"Unsafe absolute path in bundle: {name}")
- # Reject symlink entries — extraction would follow them outside `root`.
+ # Reject symlink entries: extraction would follow them outside `root`.
if (info.external_attr >> 28) & 0xF == _ZIP_SYMLINK_TYPE:
raise ValueError(f"Symlink entries not allowed in bundle: {name}")
# Validate directory entries too: extractall creates them, so a "../x/"
@@ -388,7 +389,7 @@ def migrate_legacy_presets(*, dry_run: bool = False) -> dict[str, Any]:
def migrate_legacy_home(*, dry_run: bool = False) -> dict[str, Any]:
- """Import a project-local .podcli into the global home — only when the global
+ """Import a project-local .podcli into the global home, but only when the global
home is empty, so it never clobbers an existing profile."""
legacy = _legacy_home_dir()
home = _global_home()
@@ -590,8 +591,8 @@ def import_config(bundle_path: str, target_home: str | None = None, activate: bo
with zipfile.ZipFile(bundle, "r") as zf:
try:
manifest = json.loads(zf.read("manifest.json").decode("utf-8"))
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("config-bundle", "manifest.json unreadable in bundle", error=exc)
backup_dir = _backup_managed_paths(target)
_cleanup_managed_paths(target)
diff --git a/backend/main.py b/backend/main.py
index 9e26996..e06bc8f 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""
-podcli — Python Backend Entry Point
+podcli: Python Backend Entry Point
Reads a JSON task request from stdin, dispatches to the appropriate service,
and writes a JSON result to stdout. Progress events go to stderr.
@@ -8,6 +8,7 @@ and writes a JSON result to stdout. Progress events go to stderr.
import json
import os
+from utils.log import warn as log_warn
import sys
# Windows streams default to cp1252; IPC is UTF-8. stdin matters as much as the
@@ -425,14 +426,14 @@ def handle_pack_transcript(task_id: str, params: dict):
try:
from services.audio_analyzer import extract_audio_energy
energy_data = extract_audio_energy(params["file_path"])
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("main", "audio energy extraction failed", error=exc)
if events_data is None:
try:
from services.audio_events import extract_audio_events
events_data = extract_audio_events(params["file_path"])
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("main", "audio event extraction failed", error=exc)
path, md = write_packed(
transcript,
@@ -498,7 +499,7 @@ def handle_detect_highlights(task_id: str, params: dict):
def handle_manage_reel(task_id: str, params: dict):
- """Create and iterate on a highlights reel — the MCP surface over the reel service.
+ """Create and iterate on a highlights reel: the MCP surface over the reel service.
Actions: new (detect + build), list, show, edit (adjust one moment + rebuild),
build, delete.
@@ -748,6 +749,7 @@ def handle_suggest_clips(task_id: str, params: dict):
from services import ai_provider
from services.claude_suggest import (
ClipBounds,
+ drop_published,
select_clips_with_signal_scores,
suggest_initial_with_claude,
)
@@ -803,7 +805,7 @@ def handle_suggest_clips(task_id: str, params: dict):
events_data=events_data,
progress_callback=lambda pct, msg: emit_progress(task_id, "suggesting", pct, msg),
)
- emit_result(task_id, "success", data={"clips": clips})
+ emit_result(task_id, "success", data={"clips": drop_published(clips)})
def handle_rank_candidates(task_id: str, params: dict):
@@ -960,7 +962,7 @@ def handle_ai_cli_status(task_id: str, params: dict):
def handle_ai_provider_status(task_id: str, params: dict):
- """Everything podcli can use for AI, not just local binaries — so the studio
+ """Everything podcli can use for AI, not just local binaries, so the studio
can tell "nothing installed" apart from "signed in, nothing needed"."""
from services import ai_provider
@@ -1032,7 +1034,7 @@ def handle_generate_content(task_id: str, params: dict):
emit_result(
task_id,
"error",
- error="Content generation failed — check that your AI provider is reachable and try again",
+ error="Content generation failed: check that your AI provider is reachable and try again",
)
return
@@ -1059,7 +1061,7 @@ def handle_generate_custom(task_id: str, params: dict):
# The gate above admits a workspace session or an API key as well as a
# local binary, so naming only the binary sends cloud users to install
# something they will never use.
- emit_result(task_id, "error", error="No AI provider available — sign in to podcli Pro, install Claude Code or Codex, or set ANTHROPIC_API_KEY")
+ emit_result(task_id, "error", error="No AI provider available: sign in to podcli Pro, install Claude Code or Codex, or set ANTHROPIC_API_KEY")
return
emit_result(task_id, "success", data=result)
@@ -1384,8 +1386,8 @@ def main():
task_id = "unknown"
try:
task_id = json.loads(raw).get("task_id", "unknown")
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("main", "could not read task_id from request", error=exc)
emit_result(task_id, "error", error=f"{type(e).__name__}: {e}\n{traceback.format_exc()}")
sys.exit(1)
diff --git a/backend/models/deploy.prototxt b/backend/models/deploy.prototxt
deleted file mode 100644
index a128515..0000000
--- a/backend/models/deploy.prototxt
+++ /dev/null
@@ -1,1790 +0,0 @@
-input: "data"
-input_shape {
- dim: 1
- dim: 3
- dim: 300
- dim: 300
-}
-
-layer {
- name: "data_bn"
- type: "BatchNorm"
- bottom: "data"
- top: "data_bn"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "data_scale"
- type: "Scale"
- bottom: "data_bn"
- top: "data_bn"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "conv1_h"
- type: "Convolution"
- bottom: "data_bn"
- top: "conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 32
- pad: 3
- kernel_size: 7
- stride: 2
- weight_filler {
- type: "msra"
- variance_norm: FAN_OUT
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "conv1_bn_h"
- type: "BatchNorm"
- bottom: "conv1_h"
- top: "conv1_h"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "conv1_scale_h"
- type: "Scale"
- bottom: "conv1_h"
- top: "conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "conv1_relu"
- type: "ReLU"
- bottom: "conv1_h"
- top: "conv1_h"
-}
-layer {
- name: "conv1_pool"
- type: "Pooling"
- bottom: "conv1_h"
- top: "conv1_pool"
- pooling_param {
- kernel_size: 3
- stride: 2
- }
-}
-layer {
- name: "layer_64_1_conv1_h"
- type: "Convolution"
- bottom: "conv1_pool"
- top: "layer_64_1_conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 32
- bias_term: false
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_64_1_bn2_h"
- type: "BatchNorm"
- bottom: "layer_64_1_conv1_h"
- top: "layer_64_1_conv1_h"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "layer_64_1_scale2_h"
- type: "Scale"
- bottom: "layer_64_1_conv1_h"
- top: "layer_64_1_conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "layer_64_1_relu2"
- type: "ReLU"
- bottom: "layer_64_1_conv1_h"
- top: "layer_64_1_conv1_h"
-}
-layer {
- name: "layer_64_1_conv2_h"
- type: "Convolution"
- bottom: "layer_64_1_conv1_h"
- top: "layer_64_1_conv2_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 32
- bias_term: false
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_64_1_sum"
- type: "Eltwise"
- bottom: "layer_64_1_conv2_h"
- bottom: "conv1_pool"
- top: "layer_64_1_sum"
-}
-layer {
- name: "layer_128_1_bn1_h"
- type: "BatchNorm"
- bottom: "layer_64_1_sum"
- top: "layer_128_1_bn1_h"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "layer_128_1_scale1_h"
- type: "Scale"
- bottom: "layer_128_1_bn1_h"
- top: "layer_128_1_bn1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "layer_128_1_relu1"
- type: "ReLU"
- bottom: "layer_128_1_bn1_h"
- top: "layer_128_1_bn1_h"
-}
-layer {
- name: "layer_128_1_conv1_h"
- type: "Convolution"
- bottom: "layer_128_1_bn1_h"
- top: "layer_128_1_conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 128
- bias_term: false
- pad: 1
- kernel_size: 3
- stride: 2
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_128_1_bn2"
- type: "BatchNorm"
- bottom: "layer_128_1_conv1_h"
- top: "layer_128_1_conv1_h"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "layer_128_1_scale2"
- type: "Scale"
- bottom: "layer_128_1_conv1_h"
- top: "layer_128_1_conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "layer_128_1_relu2"
- type: "ReLU"
- bottom: "layer_128_1_conv1_h"
- top: "layer_128_1_conv1_h"
-}
-layer {
- name: "layer_128_1_conv2"
- type: "Convolution"
- bottom: "layer_128_1_conv1_h"
- top: "layer_128_1_conv2"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 128
- bias_term: false
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_128_1_conv_expand_h"
- type: "Convolution"
- bottom: "layer_128_1_bn1_h"
- top: "layer_128_1_conv_expand_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 128
- bias_term: false
- pad: 0
- kernel_size: 1
- stride: 2
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_128_1_sum"
- type: "Eltwise"
- bottom: "layer_128_1_conv2"
- bottom: "layer_128_1_conv_expand_h"
- top: "layer_128_1_sum"
-}
-layer {
- name: "layer_256_1_bn1"
- type: "BatchNorm"
- bottom: "layer_128_1_sum"
- top: "layer_256_1_bn1"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "layer_256_1_scale1"
- type: "Scale"
- bottom: "layer_256_1_bn1"
- top: "layer_256_1_bn1"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "layer_256_1_relu1"
- type: "ReLU"
- bottom: "layer_256_1_bn1"
- top: "layer_256_1_bn1"
-}
-layer {
- name: "layer_256_1_conv1"
- type: "Convolution"
- bottom: "layer_256_1_bn1"
- top: "layer_256_1_conv1"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 256
- bias_term: false
- pad: 1
- kernel_size: 3
- stride: 2
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_256_1_bn2"
- type: "BatchNorm"
- bottom: "layer_256_1_conv1"
- top: "layer_256_1_conv1"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "layer_256_1_scale2"
- type: "Scale"
- bottom: "layer_256_1_conv1"
- top: "layer_256_1_conv1"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "layer_256_1_relu2"
- type: "ReLU"
- bottom: "layer_256_1_conv1"
- top: "layer_256_1_conv1"
-}
-layer {
- name: "layer_256_1_conv2"
- type: "Convolution"
- bottom: "layer_256_1_conv1"
- top: "layer_256_1_conv2"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 256
- bias_term: false
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_256_1_conv_expand"
- type: "Convolution"
- bottom: "layer_256_1_bn1"
- top: "layer_256_1_conv_expand"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 256
- bias_term: false
- pad: 0
- kernel_size: 1
- stride: 2
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_256_1_sum"
- type: "Eltwise"
- bottom: "layer_256_1_conv2"
- bottom: "layer_256_1_conv_expand"
- top: "layer_256_1_sum"
-}
-layer {
- name: "layer_512_1_bn1"
- type: "BatchNorm"
- bottom: "layer_256_1_sum"
- top: "layer_512_1_bn1"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "layer_512_1_scale1"
- type: "Scale"
- bottom: "layer_512_1_bn1"
- top: "layer_512_1_bn1"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "layer_512_1_relu1"
- type: "ReLU"
- bottom: "layer_512_1_bn1"
- top: "layer_512_1_bn1"
-}
-layer {
- name: "layer_512_1_conv1_h"
- type: "Convolution"
- bottom: "layer_512_1_bn1"
- top: "layer_512_1_conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 128
- bias_term: false
- pad: 1
- kernel_size: 3
- stride: 1 # 2
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_512_1_bn2_h"
- type: "BatchNorm"
- bottom: "layer_512_1_conv1_h"
- top: "layer_512_1_conv1_h"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "layer_512_1_scale2_h"
- type: "Scale"
- bottom: "layer_512_1_conv1_h"
- top: "layer_512_1_conv1_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "layer_512_1_relu2"
- type: "ReLU"
- bottom: "layer_512_1_conv1_h"
- top: "layer_512_1_conv1_h"
-}
-layer {
- name: "layer_512_1_conv2_h"
- type: "Convolution"
- bottom: "layer_512_1_conv1_h"
- top: "layer_512_1_conv2_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 256
- bias_term: false
- pad: 2 # 1
- kernel_size: 3
- stride: 1
- dilation: 2
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_512_1_conv_expand_h"
- type: "Convolution"
- bottom: "layer_512_1_bn1"
- top: "layer_512_1_conv_expand_h"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- convolution_param {
- num_output: 256
- bias_term: false
- pad: 0
- kernel_size: 1
- stride: 1 # 2
- weight_filler {
- type: "msra"
- }
- bias_filler {
- type: "constant"
- value: 0.0
- }
- }
-}
-layer {
- name: "layer_512_1_sum"
- type: "Eltwise"
- bottom: "layer_512_1_conv2_h"
- bottom: "layer_512_1_conv_expand_h"
- top: "layer_512_1_sum"
-}
-layer {
- name: "last_bn_h"
- type: "BatchNorm"
- bottom: "layer_512_1_sum"
- top: "layer_512_1_sum"
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
- param {
- lr_mult: 0.0
- }
-}
-layer {
- name: "last_scale_h"
- type: "Scale"
- bottom: "layer_512_1_sum"
- top: "layer_512_1_sum"
- param {
- lr_mult: 1.0
- decay_mult: 1.0
- }
- param {
- lr_mult: 2.0
- decay_mult: 1.0
- }
- scale_param {
- bias_term: true
- }
-}
-layer {
- name: "last_relu"
- type: "ReLU"
- bottom: "layer_512_1_sum"
- top: "fc7"
-}
-
-layer {
- name: "conv6_1_h"
- type: "Convolution"
- bottom: "fc7"
- top: "conv6_1_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 128
- pad: 0
- kernel_size: 1
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv6_1_relu"
- type: "ReLU"
- bottom: "conv6_1_h"
- top: "conv6_1_h"
-}
-layer {
- name: "conv6_2_h"
- type: "Convolution"
- bottom: "conv6_1_h"
- top: "conv6_2_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 256
- pad: 1
- kernel_size: 3
- stride: 2
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv6_2_relu"
- type: "ReLU"
- bottom: "conv6_2_h"
- top: "conv6_2_h"
-}
-layer {
- name: "conv7_1_h"
- type: "Convolution"
- bottom: "conv6_2_h"
- top: "conv7_1_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 64
- pad: 0
- kernel_size: 1
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv7_1_relu"
- type: "ReLU"
- bottom: "conv7_1_h"
- top: "conv7_1_h"
-}
-layer {
- name: "conv7_2_h"
- type: "Convolution"
- bottom: "conv7_1_h"
- top: "conv7_2_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 128
- pad: 1
- kernel_size: 3
- stride: 2
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv7_2_relu"
- type: "ReLU"
- bottom: "conv7_2_h"
- top: "conv7_2_h"
-}
-layer {
- name: "conv8_1_h"
- type: "Convolution"
- bottom: "conv7_2_h"
- top: "conv8_1_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 64
- pad: 0
- kernel_size: 1
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv8_1_relu"
- type: "ReLU"
- bottom: "conv8_1_h"
- top: "conv8_1_h"
-}
-layer {
- name: "conv8_2_h"
- type: "Convolution"
- bottom: "conv8_1_h"
- top: "conv8_2_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 128
- pad: 0
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv8_2_relu"
- type: "ReLU"
- bottom: "conv8_2_h"
- top: "conv8_2_h"
-}
-layer {
- name: "conv9_1_h"
- type: "Convolution"
- bottom: "conv8_2_h"
- top: "conv9_1_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 64
- pad: 0
- kernel_size: 1
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv9_1_relu"
- type: "ReLU"
- bottom: "conv9_1_h"
- top: "conv9_1_h"
-}
-layer {
- name: "conv9_2_h"
- type: "Convolution"
- bottom: "conv9_1_h"
- top: "conv9_2_h"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 128
- pad: 0
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv9_2_relu"
- type: "ReLU"
- bottom: "conv9_2_h"
- top: "conv9_2_h"
-}
-layer {
- name: "conv4_3_norm"
- type: "Normalize"
- bottom: "layer_256_1_bn1"
- top: "conv4_3_norm"
- norm_param {
- across_spatial: false
- scale_filler {
- type: "constant"
- value: 20
- }
- channel_shared: false
- }
-}
-layer {
- name: "conv4_3_norm_mbox_loc"
- type: "Convolution"
- bottom: "conv4_3_norm"
- top: "conv4_3_norm_mbox_loc"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 16
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv4_3_norm_mbox_loc_perm"
- type: "Permute"
- bottom: "conv4_3_norm_mbox_loc"
- top: "conv4_3_norm_mbox_loc_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv4_3_norm_mbox_loc_flat"
- type: "Flatten"
- bottom: "conv4_3_norm_mbox_loc_perm"
- top: "conv4_3_norm_mbox_loc_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv4_3_norm_mbox_conf"
- type: "Convolution"
- bottom: "conv4_3_norm"
- top: "conv4_3_norm_mbox_conf"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 8 # 84
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv4_3_norm_mbox_conf_perm"
- type: "Permute"
- bottom: "conv4_3_norm_mbox_conf"
- top: "conv4_3_norm_mbox_conf_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv4_3_norm_mbox_conf_flat"
- type: "Flatten"
- bottom: "conv4_3_norm_mbox_conf_perm"
- top: "conv4_3_norm_mbox_conf_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv4_3_norm_mbox_priorbox"
- type: "PriorBox"
- bottom: "conv4_3_norm"
- bottom: "data"
- top: "conv4_3_norm_mbox_priorbox"
- prior_box_param {
- min_size: 30.0
- max_size: 60.0
- aspect_ratio: 2
- flip: true
- clip: false
- variance: 0.1
- variance: 0.1
- variance: 0.2
- variance: 0.2
- step: 8
- offset: 0.5
- }
-}
-layer {
- name: "fc7_mbox_loc"
- type: "Convolution"
- bottom: "fc7"
- top: "fc7_mbox_loc"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 24
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "fc7_mbox_loc_perm"
- type: "Permute"
- bottom: "fc7_mbox_loc"
- top: "fc7_mbox_loc_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "fc7_mbox_loc_flat"
- type: "Flatten"
- bottom: "fc7_mbox_loc_perm"
- top: "fc7_mbox_loc_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "fc7_mbox_conf"
- type: "Convolution"
- bottom: "fc7"
- top: "fc7_mbox_conf"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 12 # 126
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "fc7_mbox_conf_perm"
- type: "Permute"
- bottom: "fc7_mbox_conf"
- top: "fc7_mbox_conf_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "fc7_mbox_conf_flat"
- type: "Flatten"
- bottom: "fc7_mbox_conf_perm"
- top: "fc7_mbox_conf_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "fc7_mbox_priorbox"
- type: "PriorBox"
- bottom: "fc7"
- bottom: "data"
- top: "fc7_mbox_priorbox"
- prior_box_param {
- min_size: 60.0
- max_size: 111.0
- aspect_ratio: 2
- aspect_ratio: 3
- flip: true
- clip: false
- variance: 0.1
- variance: 0.1
- variance: 0.2
- variance: 0.2
- step: 16
- offset: 0.5
- }
-}
-layer {
- name: "conv6_2_mbox_loc"
- type: "Convolution"
- bottom: "conv6_2_h"
- top: "conv6_2_mbox_loc"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 24
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv6_2_mbox_loc_perm"
- type: "Permute"
- bottom: "conv6_2_mbox_loc"
- top: "conv6_2_mbox_loc_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv6_2_mbox_loc_flat"
- type: "Flatten"
- bottom: "conv6_2_mbox_loc_perm"
- top: "conv6_2_mbox_loc_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv6_2_mbox_conf"
- type: "Convolution"
- bottom: "conv6_2_h"
- top: "conv6_2_mbox_conf"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 12 # 126
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv6_2_mbox_conf_perm"
- type: "Permute"
- bottom: "conv6_2_mbox_conf"
- top: "conv6_2_mbox_conf_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv6_2_mbox_conf_flat"
- type: "Flatten"
- bottom: "conv6_2_mbox_conf_perm"
- top: "conv6_2_mbox_conf_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv6_2_mbox_priorbox"
- type: "PriorBox"
- bottom: "conv6_2_h"
- bottom: "data"
- top: "conv6_2_mbox_priorbox"
- prior_box_param {
- min_size: 111.0
- max_size: 162.0
- aspect_ratio: 2
- aspect_ratio: 3
- flip: true
- clip: false
- variance: 0.1
- variance: 0.1
- variance: 0.2
- variance: 0.2
- step: 32
- offset: 0.5
- }
-}
-layer {
- name: "conv7_2_mbox_loc"
- type: "Convolution"
- bottom: "conv7_2_h"
- top: "conv7_2_mbox_loc"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 24
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv7_2_mbox_loc_perm"
- type: "Permute"
- bottom: "conv7_2_mbox_loc"
- top: "conv7_2_mbox_loc_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv7_2_mbox_loc_flat"
- type: "Flatten"
- bottom: "conv7_2_mbox_loc_perm"
- top: "conv7_2_mbox_loc_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv7_2_mbox_conf"
- type: "Convolution"
- bottom: "conv7_2_h"
- top: "conv7_2_mbox_conf"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 12 # 126
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv7_2_mbox_conf_perm"
- type: "Permute"
- bottom: "conv7_2_mbox_conf"
- top: "conv7_2_mbox_conf_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv7_2_mbox_conf_flat"
- type: "Flatten"
- bottom: "conv7_2_mbox_conf_perm"
- top: "conv7_2_mbox_conf_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv7_2_mbox_priorbox"
- type: "PriorBox"
- bottom: "conv7_2_h"
- bottom: "data"
- top: "conv7_2_mbox_priorbox"
- prior_box_param {
- min_size: 162.0
- max_size: 213.0
- aspect_ratio: 2
- aspect_ratio: 3
- flip: true
- clip: false
- variance: 0.1
- variance: 0.1
- variance: 0.2
- variance: 0.2
- step: 64
- offset: 0.5
- }
-}
-layer {
- name: "conv8_2_mbox_loc"
- type: "Convolution"
- bottom: "conv8_2_h"
- top: "conv8_2_mbox_loc"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 16
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv8_2_mbox_loc_perm"
- type: "Permute"
- bottom: "conv8_2_mbox_loc"
- top: "conv8_2_mbox_loc_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv8_2_mbox_loc_flat"
- type: "Flatten"
- bottom: "conv8_2_mbox_loc_perm"
- top: "conv8_2_mbox_loc_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv8_2_mbox_conf"
- type: "Convolution"
- bottom: "conv8_2_h"
- top: "conv8_2_mbox_conf"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 8 # 84
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv8_2_mbox_conf_perm"
- type: "Permute"
- bottom: "conv8_2_mbox_conf"
- top: "conv8_2_mbox_conf_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv8_2_mbox_conf_flat"
- type: "Flatten"
- bottom: "conv8_2_mbox_conf_perm"
- top: "conv8_2_mbox_conf_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv8_2_mbox_priorbox"
- type: "PriorBox"
- bottom: "conv8_2_h"
- bottom: "data"
- top: "conv8_2_mbox_priorbox"
- prior_box_param {
- min_size: 213.0
- max_size: 264.0
- aspect_ratio: 2
- flip: true
- clip: false
- variance: 0.1
- variance: 0.1
- variance: 0.2
- variance: 0.2
- step: 100
- offset: 0.5
- }
-}
-layer {
- name: "conv9_2_mbox_loc"
- type: "Convolution"
- bottom: "conv9_2_h"
- top: "conv9_2_mbox_loc"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 16
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv9_2_mbox_loc_perm"
- type: "Permute"
- bottom: "conv9_2_mbox_loc"
- top: "conv9_2_mbox_loc_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv9_2_mbox_loc_flat"
- type: "Flatten"
- bottom: "conv9_2_mbox_loc_perm"
- top: "conv9_2_mbox_loc_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv9_2_mbox_conf"
- type: "Convolution"
- bottom: "conv9_2_h"
- top: "conv9_2_mbox_conf"
- param {
- lr_mult: 1
- decay_mult: 1
- }
- param {
- lr_mult: 2
- decay_mult: 0
- }
- convolution_param {
- num_output: 8 # 84
- pad: 1
- kernel_size: 3
- stride: 1
- weight_filler {
- type: "xavier"
- }
- bias_filler {
- type: "constant"
- value: 0
- }
- }
-}
-layer {
- name: "conv9_2_mbox_conf_perm"
- type: "Permute"
- bottom: "conv9_2_mbox_conf"
- top: "conv9_2_mbox_conf_perm"
- permute_param {
- order: 0
- order: 2
- order: 3
- order: 1
- }
-}
-layer {
- name: "conv9_2_mbox_conf_flat"
- type: "Flatten"
- bottom: "conv9_2_mbox_conf_perm"
- top: "conv9_2_mbox_conf_flat"
- flatten_param {
- axis: 1
- }
-}
-layer {
- name: "conv9_2_mbox_priorbox"
- type: "PriorBox"
- bottom: "conv9_2_h"
- bottom: "data"
- top: "conv9_2_mbox_priorbox"
- prior_box_param {
- min_size: 264.0
- max_size: 315.0
- aspect_ratio: 2
- flip: true
- clip: false
- variance: 0.1
- variance: 0.1
- variance: 0.2
- variance: 0.2
- step: 300
- offset: 0.5
- }
-}
-layer {
- name: "mbox_loc"
- type: "Concat"
- bottom: "conv4_3_norm_mbox_loc_flat"
- bottom: "fc7_mbox_loc_flat"
- bottom: "conv6_2_mbox_loc_flat"
- bottom: "conv7_2_mbox_loc_flat"
- bottom: "conv8_2_mbox_loc_flat"
- bottom: "conv9_2_mbox_loc_flat"
- top: "mbox_loc"
- concat_param {
- axis: 1
- }
-}
-layer {
- name: "mbox_conf"
- type: "Concat"
- bottom: "conv4_3_norm_mbox_conf_flat"
- bottom: "fc7_mbox_conf_flat"
- bottom: "conv6_2_mbox_conf_flat"
- bottom: "conv7_2_mbox_conf_flat"
- bottom: "conv8_2_mbox_conf_flat"
- bottom: "conv9_2_mbox_conf_flat"
- top: "mbox_conf"
- concat_param {
- axis: 1
- }
-}
-layer {
- name: "mbox_priorbox"
- type: "Concat"
- bottom: "conv4_3_norm_mbox_priorbox"
- bottom: "fc7_mbox_priorbox"
- bottom: "conv6_2_mbox_priorbox"
- bottom: "conv7_2_mbox_priorbox"
- bottom: "conv8_2_mbox_priorbox"
- bottom: "conv9_2_mbox_priorbox"
- top: "mbox_priorbox"
- concat_param {
- axis: 2
- }
-}
-
-layer {
- name: "mbox_conf_reshape"
- type: "Reshape"
- bottom: "mbox_conf"
- top: "mbox_conf_reshape"
- reshape_param {
- shape {
- dim: 0
- dim: -1
- dim: 2
- }
- }
-}
-layer {
- name: "mbox_conf_softmax"
- type: "Softmax"
- bottom: "mbox_conf_reshape"
- top: "mbox_conf_softmax"
- softmax_param {
- axis: 2
- }
-}
-layer {
- name: "mbox_conf_flatten"
- type: "Flatten"
- bottom: "mbox_conf_softmax"
- top: "mbox_conf_flatten"
- flatten_param {
- axis: 1
- }
-}
-
-layer {
- name: "detection_out"
- type: "DetectionOutput"
- bottom: "mbox_loc"
- bottom: "mbox_conf_flatten"
- bottom: "mbox_priorbox"
- top: "detection_out"
- include {
- phase: TEST
- }
- detection_output_param {
- num_classes: 2
- share_location: true
- background_label_id: 0
- nms_param {
- nms_threshold: 0.45
- top_k: 400
- }
- code_type: CENTER_SIZE
- keep_top_k: 200
- confidence_threshold: 0.01
- clip: 1
- }
-}
diff --git a/backend/presets.py b/backend/presets.py
index cf27557..9dc2661 100644
--- a/backend/presets.py
+++ b/backend/presets.py
@@ -5,7 +5,7 @@ Save and load named configurations so you don't reconfigure settings
for every episode. Stored as JSON in .podcli/presets/
A preset is a complete show config: video path, rendering options,
-corrections, output dir — everything needed to run `podcli process --preset myshow`.
+corrections, output dir, and everything needed to run `podcli process --preset myshow`.
"""
import os
diff --git a/backend/requirements-runtime.txt b/backend/requirements-runtime.txt
index de10161..8374ba0 100644
--- a/backend/requirements-runtime.txt
+++ b/backend/requirements-runtime.txt
@@ -1,18 +1,20 @@
# Hermetic native-CLI runtime deps. Transcription is whisper.cpp (a native
-# binary), so openai-whisper/torch are intentionally absent — that is the ~2GB
+# binary), so openai-whisper/torch are intentionally absent. That is the ~2GB
# the native install saves. --engine whisper-py remains a dev/source-only option
# via backend/requirements.txt.
-opencv-python-headless>=4.8.1.78
-numpy>=2.5.2
-# Audio-event detection (YAMNet laughter/reaction channel) runs on ONNX Runtime —
+# Direct dependencies are pinned to the versions the previous ranges resolved
+# to on 2026-11-03. Transitive dependencies still float. Bump deliberately.
+opencv-python-headless==5.0.0.93
+numpy==2.5.4
+# Audio-event detection (YAMNet laughter/reaction channel) runs on ONNX Runtime,
# no torch/TF, so it stays on the hermetic native path.
-onnxruntime>=1.28.0
+onnxruntime==1.31.1
# --engine omnilingual: Meta's Omnilingual ASR CTC model via sherpa-onnx, for
# languages whisper.cpp handles poorly. No torch, stays on the hermetic path.
-sherpa-onnx>=1.13.8
-Pillow>=12.3.0
-questionary>=2.1.1
-python-dotenv>=1.2.2
-yt-dlp>=2026.7.4
-google-api-python-client>=2.198.0
-google-auth-oauthlib>=1.4.0
+sherpa-onnx==2.0.1
+Pillow==13.0.0
+questionary==2.1.1
+python-dotenv==1.2.4
+yt-dlp==2026.10.26
+google-api-python-client==2.201.0
+google-auth-oauthlib==1.5.0
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 96edede..1d37c7e 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -1,7 +1,7 @@
# Transcription
openai-whisper>=20250625
-# Speaker diarization (optional — only needed if you enable local speaker detection)
+# Speaker diarization (optional: only needed if you enable local speaker detection)
# Most users don't need this: Claude handles speaker identification via MCP,
# and the "Paste Transcript" flow supports Speaker (MM:SS) labels natively.
# To enable: pip install pyannote.audio speechbrain && set HF_TOKEN in .env
@@ -12,7 +12,7 @@ openai-whisper>=20250625
opencv-python-headless>=4.8.1.78
numpy>=2.5.2
-# Audio-event detection (laughter/reaction channel via YAMNet ONNX — no torch/TF)
+# Audio-event detection (laughter/reaction channel via YAMNet ONNX, no torch/TF)
onnxruntime>=1.28.0
# --engine omnilingual: Meta's Omnilingual ASR CTC model via sherpa-onnx, for
@@ -29,6 +29,6 @@ questionary>=2.1.1
python-dotenv>=1.2.2
yt-dlp>=2026.7.4
-# YouTube analytics (optional — only needed for live OAuth sync; CSV import works without these)
+# YouTube analytics (optional: only needed for live OAuth sync; CSV import works without these)
google-api-python-client>=2.198.0
google-auth-oauthlib>=1.4.0
diff --git a/backend/scripts/remotion_screenshot.cjs b/backend/scripts/remotion_screenshot.cjs
index 0942669..be0e6c0 100644
--- a/backend/scripts/remotion_screenshot.cjs
+++ b/backend/scripts/remotion_screenshot.cjs
@@ -49,8 +49,10 @@ const waitForAssets = async (page) => {
await ensureBrowser({logLevel: "error"});
const browser = await openBrowser("chrome", {logLevel: "error"});
const closeBrowser = () => { try { browser.close({silent: true}); } catch {} };
+
process.on("SIGINT", () => { closeBrowser(); process.exit(1); });
process.on("SIGTERM", () => { closeBrowser(); process.exit(1); });
+
try {
const page = await browser.newPage({
context: () => null,
@@ -60,6 +62,7 @@ const waitForAssets = async (page) => {
onBrowserLog: () => undefined,
onLog: () => undefined,
});
+
await page.setViewport({width, height, deviceScaleFactor: 1});
await page.goto({
url: `file://${path.resolve(htmlPath)}`,
@@ -69,9 +72,11 @@ const waitForAssets = async (page) => {
},
});
await waitForAssets(page);
+
if (waitMs > 0) {
await new Promise((resolve) => setTimeout(resolve, waitMs));
}
+
await screenshot({
page,
path: outputPath,
diff --git a/backend/services/ai_cli.py b/backend/services/ai_cli.py
index 7268bd4..b112651 100644
--- a/backend/services/ai_cli.py
+++ b/backend/services/ai_cli.py
@@ -6,6 +6,7 @@ provider layer above can treat "run this prompt" as one call.
"""
import os
+from utils.log import warn as log_warn
import subprocess
import sys
from functools import lru_cache
@@ -46,8 +47,8 @@ def _npmrc_prefix_dirs() -> list[str]:
try:
from services.env_settings import _env_path
npmrc_paths.append(os.path.join(os.path.dirname(_env_path()), ".npmrc"))
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("ai-cli", "could not locate .npmrc beside the env file", error=exc)
for npmrc in npmrc_paths:
if not os.path.isfile(npmrc):
continue
@@ -61,8 +62,8 @@ def _npmrc_prefix_dirs() -> list[str]:
prefix = stripped.split("=", 1)[1].strip()
if prefix:
dirs.append(prefix if sys.platform == "win32" else os.path.join(prefix, "bin"))
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("ai-cli", "could not read .npmrc", error=exc)
return dirs
@@ -127,8 +128,8 @@ def _version_manager_bin_dirs() -> list[str]:
dirs.extend(sorted(glob.glob(os.path.join(nvm_dir, "versions", "node", "*", "bin")), reverse=True))
dirs.extend(glob.glob(os.path.join(home, ".fnm", "node-versions", "*", "installation", "bin")))
dirs.extend(glob.glob(os.path.join(home, ".local", "share", "fnm", "node-versions", "*", "installation", "bin")))
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("ai-cli", "node version manager scan failed", error=exc)
fnm_bin = os.path.join(home, ".local", "share", "fnm", "current", "bin")
dirs.append(fnm_bin)
@@ -269,8 +270,8 @@ def _glob_cli_paths(name: str) -> list[str]:
for pattern in patterns:
try:
found.extend(glob.glob(pattern))
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("ai-cli", "glob failed", error=exc)
return found
@@ -281,8 +282,8 @@ def _configured_cli_path(engine: str) -> Optional[str]:
try:
from services.env_settings import _read_pairs
raw = (_read_pairs().get(env_key) or "").strip()
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("ai-cli", "could not read CLI path from env settings", error=exc)
if not raw:
return None
return _resolve_cli_path(raw) or (raw if os.path.isfile(raw) else None)
@@ -438,21 +439,25 @@ def _run_ai_command(
"""Execute one AI CLI prompt and return the completed process."""
if engine == "codex":
output_file = prompt_file + ".out"
- result = subprocess.run(
- [
- cli_path, "exec",
- "--sandbox", "read-only",
- "--skip-git-repo-check",
- "-o", output_file,
- prompt,
- ],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- cwd=project_dir,
- timeout=timeout,
- )
+ # "-" makes codex read the prompt from stdin, keeping the transcript out
+ # of argv (length limits, visible in `ps`).
+ with open(prompt_file, encoding="utf-8") as prompt_fh:
+ result = subprocess.run(
+ [
+ cli_path, "exec",
+ "--sandbox", "read-only",
+ "--skip-git-repo-check",
+ "-o", output_file,
+ "-",
+ ],
+ stdin=prompt_fh,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ cwd=project_dir,
+ timeout=timeout,
+ )
if os.path.exists(output_file):
with open(output_file, encoding="utf-8") as f:
result = subprocess.CompletedProcess(
@@ -463,8 +468,8 @@ def _run_ai_command(
)
try:
os.unlink(output_file)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("ai-cli", "could not remove codex output file", error=exc)
return result
shell = sys.platform == "win32" and cli_path.lower().endswith((".cmd", ".bat"))
diff --git a/backend/services/ai_provider.py b/backend/services/ai_provider.py
index cdb04a1..24322a0 100644
--- a/backend/services/ai_provider.py
+++ b/backend/services/ai_provider.py
@@ -12,14 +12,15 @@ every platform, and that mess stops here.
Selection is controlled by PODCLI_AI_PROVIDER (auto|cloud|cli|api). On `auto`
the order above applies: a Pro subscriber gets what they paid for first, and the
-local CLI remains the fallback if the network or the subscription is unavailable
-— podcli never stops working because a server did.
+local CLI remains the fallback if the network or the subscription is unavailable.
+podcli never stops working because a server did.
"""
from __future__ import annotations
import json
import os
+from utils.log import warn as log_warn
import re
import sys
import urllib.error
@@ -168,8 +169,8 @@ def _run_api(key: str, prompt: str, timeout: int) -> AIResult:
detail = ""
try:
detail = json.loads(exc.read().decode("utf-8")).get("error", {}).get("message", "")
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("ai", "could not parse API error body", error=exc)
return AIResult(ok=False, provider="api", label="Claude API",
error=detail or f"Claude API returned HTTP {exc.code}")
except Exception as exc:
@@ -261,14 +262,14 @@ def generate(
on_attempt is called with a human label ("Claude", "podcli Pro") before each
attempt so callers can drive progress UI without knowing the chain.
- accept rejects a response the backend considers successful — an engine that
+ accept rejects a response the backend considers successful, an engine that
answers with prose where JSON was asked for has failed, and the next one
deserves a turn. Return True to accept, or False / a reason string to reject.
adapt(engine, prompt) rewrites the prompt per backend, for engines that need
a shorter one than the others.
- stable_prefix is the large, unchanging half of the prompt — the transcript.
+ stable_prefix is the large, unchanging half of the prompt, the transcript.
The cloud backend sends it as a separate cacheable block so it is read once
per episode rather than once per pass, which is the difference between ~$0.41
and ~$0.90 per episode.
diff --git a/backend/services/asset_store.py b/backend/services/asset_store.py
index c1504de..25ffac7 100644
--- a/backend/services/asset_store.py
+++ b/backend/services/asset_store.py
@@ -1,5 +1,5 @@
"""
-Shared asset registry — works from CLI, Web UI, and MCP.
+Shared asset registry: works from CLI, Web UI, and MCP.
Assets are named references to local files (logos, intros, outros, music,
images). Register once, use by name everywhere:
diff --git a/backend/services/audio_analyzer.py b/backend/services/audio_analyzer.py
index 8b56bd6..470892d 100644
--- a/backend/services/audio_analyzer.py
+++ b/backend/services/audio_analyzer.py
@@ -27,7 +27,7 @@ def extract_audio_energy(
Extract per-window RMS energy levels from a video's audio track.
Returns list of {time, rms, peak} dicts, one per window.
- wav_path: optional pre-extracted 16 kHz mono WAV — skips decoding the
+ wav_path: optional pre-extracted 16 kHz mono WAV: skips decoding the
video again when the orchestration layer already extracted the audio.
"""
input_path = wav_path if wav_path and os.path.exists(wav_path) else video_path
diff --git a/backend/services/audio_events.py b/backend/services/audio_events.py
index 3548909..a5cb8e0 100644
--- a/backend/services/audio_events.py
+++ b/backend/services/audio_events.py
@@ -3,7 +3,7 @@ Audio-event detection (laughter, cheering, applause, screaming) for reaction-bas
clip scoring.
Runs YAMNet (AudioSet, 521 classes) as a self-contained ONNX graph via onnxruntime,
-which imports neither torch nor tensorflow — so this belongs on the native /
+which imports neither torch nor tensorflow, so this belongs on the native /
whisper.cpp runtime path. Audio is extracted at 16 kHz mono (the same format
whisper.cpp uses) and fed to the graph as a raw waveform; the log-mel front-end is
baked into the model, so there is no librosa dependency.
@@ -94,7 +94,7 @@ def is_available() -> bool:
def _read_waveform_16k_mono(video_path: str, wav_path: Optional[str] = None) -> Optional[np.ndarray]:
"""Extract audio as a float32 [-1, 1] mono waveform at 16 kHz via ffmpeg.
- wav_path: optional pre-extracted 16 kHz mono WAV — read directly, no decode.
+ wav_path: optional pre-extracted 16 kHz mono WAV: read directly, no decode.
"""
if wav_path and os.path.exists(wav_path):
try:
@@ -260,7 +260,7 @@ def get_event_profile(
Full pipeline: detect audio events and score all segments.
Returns {events_data, segment_scores, reaction_times} where reaction_times are the
- timestamps of frames whose reaction level clears reaction_threshold — the anchors a
+ timestamps of frames whose reaction level clears reaction_threshold, the anchors a
reaction-based detector expands backwards from.
"""
if not is_available():
diff --git a/backend/services/caption_renderer.py b/backend/services/caption_renderer.py
index f8bb5d4..2610dc3 100644
--- a/backend/services/caption_renderer.py
+++ b/backend/services/caption_renderer.py
@@ -6,6 +6,7 @@ Supports styles: Hormozi, Karaoke, Subtle, and Branded.
"""
import os
+from utils.log import warn as log_warn
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -208,7 +209,7 @@ def _hold_through_gap(chunks: list[list[dict]], idx: int, end: float, offset: fl
def _render_hormozi(words: list[dict], style: dict, offset: float) -> str:
"""
Hormozi style: Show 2-3 words at a time, smooth karaoke-fill highlight.
- Uses \\kf tags for progressive word fill — 1 Dialogue per chunk, no flashing.
+ Uses \\kf tags for progressive word fill, 1 Dialogue per chunk, no flashing.
"""
header = generate_ass_header(style)
events = []
@@ -312,7 +313,7 @@ def _render_subtle(words: list[dict], style: dict, offset: float) -> str:
def _normalize_case(text: str) -> str:
"""Lowercase a word unless it's an acronym or proper 'I'."""
- stripped = text.strip(".,!?;:-–—'\"")
+ stripped = text.strip(".,!?;:-\u2013\u2014'\"")
if stripped.isupper() and len(stripped) >= 2:
return text # Likely acronym (e.g. "AI", "CEO")
if stripped == "I" or stripped == "I'm" or stripped.startswith("I'"):
@@ -430,12 +431,12 @@ def _calibrate_libass_y(
finally:
try:
os.unlink(ass_file.name)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("captions", "could not remove temp ASS file", error=exc)
try:
os.unlink(png_file.name)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("captions", "could not remove temp PNG file", error=exc)
def _measure_text_widths(texts: list[str], font_name: str, font_size: int, bold: bool, spacing: int = 2) -> list[int]:
@@ -461,8 +462,8 @@ def _measure_text_widths(texts: list[str], font_name: str, font_size: int, bold:
fc_path = result.stdout.strip()
if os.path.exists(fc_path):
font = ImageFont.truetype(fc_path, font_size)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("captions", "fontconfig font lookup failed", error=exc)
# 2) Fallback: try common paths (macOS, Linux, Windows)
if font is None:
@@ -523,7 +524,7 @@ def _rounded_rect_drawing(w: int, h: int, r: int) -> str:
def _render_branded(words: list[dict], style: dict, offset: float) -> str:
"""
- Branded style — large bold white text, dark rounded pill on active word only.
+ Branded style: large bold white text, dark rounded pill on active word only.
Uses a two-layer approach:
- Layer 0: \\p1 drawing of a rounded rectangle (pill) behind the active word
@@ -571,7 +572,7 @@ def _render_branded(words: list[dict], style: dict, offset: float) -> str:
normalized.append(text)
# Measure word widths for pill positioning.
- # Use spacing=0 here — ASS Spacing is handled by libass internally,
+ # Use spacing=0 here: ASS Spacing is handled by libass internally,
# but we position words ourselves with \pos so we need pure font metrics.
word_widths = _measure_text_widths(normalized, font_name, font_size, is_bold, 0)
space_width = _measure_text_widths([" "], font_name, font_size, is_bold, 0)[0]
@@ -602,7 +603,7 @@ def _render_branded(words: list[dict], style: dict, offset: float) -> str:
# Line height and vertical layout
line_height = int(font_size * 1.2)
total_text_h = line_height * len(lines)
- # Use explicit \pos for both text and pill — no reliance on libass layout.
+ # Use explicit \pos for both text and pill: no reliance on libass layout.
# This gives us full control over line spacing and pill sizing.
# Position text block from bottom: last line baseline at (PlayResY - MarginV)
# Use generous line spacing so pills have room for proper padding.
@@ -618,7 +619,7 @@ def _render_branded(words: list[dict], style: dict, offset: float) -> str:
y = block_bottom_y - (len(lines) - 1 - li) * line_spacing - font_size // 2
line_center_ys.append(y)
- # Pre-compute line geometry — measure space width directly with the font,
+ # Pre-compute line geometry: measure space width directly with the font,
# use word widths without ASS Spacing inflation for tighter layout.
raw_space_w = _measure_text_widths(["A A"], font_name, font_size, is_bold, 0)[0] - \
_measure_text_widths(["AA"], font_name, font_size, is_bold, 0)[0]
diff --git a/backend/services/claude_suggest.py b/backend/services/claude_suggest.py
index 280907b..5a0fb01 100644
--- a/backend/services/claude_suggest.py
+++ b/backend/services/claude_suggest.py
@@ -4,7 +4,7 @@ Clip suggestion via AI CLI (Claude Code or Codex).
Delegates moment selection to an AI CLI, which uses the PodStack knowledge base
(.podcli/knowledge/) and CLAUDE.md for context-aware clip extraction.
-Priority: Claude Code → Codex → heuristic fallback.
+Priority: podcli Pro cloud, then Claude Code or Codex, then the Anthropic API, then the heuristic fallback.
"""
import hashlib
@@ -37,6 +37,36 @@ from services.ai_cli import (
)
+def _title_key(title: str) -> str:
+ return re.sub(r"[^a-z0-9]+", " ", title.lower()).strip()
+
+
+def drop_published(clips: list[dict], episodes_path: str | None = None) -> list[dict]:
+ """Remove suggestions whose title matches a short already in the episode database.
+
+ The prompt asks the AI not to repeat published moments, but that is advice
+ and the heuristic fallback never reads the database at all. This runs after
+ whichever engine answered. Titles are the only thing the database records,
+ so the match is a normalised title comparison with a small similarity margin.
+ """
+ from difflib import SequenceMatcher
+
+ path = episodes_path or os.path.join(paths["knowledge"], "03-episodes-database.md")
+ published = [k for k in (_title_key(t) for t in _load_existing_shorts(path)) if k]
+ if not published or not clips:
+ return clips
+
+ kept = []
+ for clip in clips:
+ key = _title_key(str(clip.get("title", "")))
+ if key and any(
+ key == p or SequenceMatcher(None, key, p).ratio() >= 0.9 for p in published
+ ):
+ continue
+ kept.append(clip)
+ return kept
+
+
def _load_existing_shorts(episodes_path: str) -> list[str]:
"""Titles of shorts already published, so they are not suggested again.
@@ -276,7 +306,7 @@ def _format_reaction_anchors(reaction_times: list[float] | None) -> str:
"\nAUDIENCE REACTION ANCHORS (detected laughter/cheering peaks, in seconds):\n"
f"{times}\n"
"The moment that CAUSED each reaction sits just before its anchor. "
- "Clips that contain or lead into an anchor are strong candidates — "
+ "Clips that contain or lead into an anchor are strong candidates, so "
"prefer them when quality is otherwise equal.\n"
)
@@ -296,7 +326,7 @@ def _build_prompt(
can't read project files.
"""
- # Load knowledge base files inline — prioritized by relevance to clip selection
+ # Load knowledge base files inline: prioritized by relevance to clip selection
from services.knowledge_base import load_kb_context, warn_missing_context
kb_dir = paths["knowledge"]
@@ -340,11 +370,11 @@ DURATION RULES (CRITICAL):
CUTTING RULES (CRITICAL):
- Cut TIGHT. Every second must earn its place.
-- Start at the exact moment the hook hits — no preamble, no "so", no "well"
+- Start at the exact moment the hook hits, no preamble, no "so", no "well"
- ONE EXCEPTION: if the moment is an ANSWER, start on the QUESTION that prompted it.
A question is not preamble, it is the setup the viewer needs. Only leave it out when
it rambles past ~8 seconds, and then cut the rambling with "segments" or skip the moment.
-- End the MOMENT the point lands with a complete thought — don't trail off
+- End the MOMENT the point lands with a complete thought: don't trail off
- NEVER cut mid-sentence or mid-thought. The viewer must feel closure.
- The last sentence must feel like a natural ending, a punchline, or a mic-drop
- If there's filler/tangent in the middle, use multiple segments to skip it
@@ -352,12 +382,12 @@ CUTTING RULES (CRITICAL):
MOMENT SELECTION ({b.lens}):
- Would YOU stop scrolling for this? If no, skip it.
-- First 3 seconds must HOOK — a bold claim, shocking number, or provocative question
-- Must make complete sense standalone — no "as I mentioned" or "going back to"
+- First 3 seconds must HOOK: a bold claim, shocking number, or provocative question
+- Must make complete sense standalone: no "as I mentioned" or "going back to"
- Must not OPEN on a word pointing back before the cut: "that", "it", "they", "yeah",
"so", "exactly", "right", "which is why". Widen the start until it is inside the clip.
-- Must end on a COMPLETE THOUGHT — sentence boundary, natural pause, or mic-drop moment
-- Single focused idea — one concept, fully delivered, no loose threads
+- Must end on a COMPLETE THOUGHT, sentence boundary, natural pause, or mic-drop moment
+- Single focused idea: one concept, fully delivered, no loose threads
- Prioritize: controversial takes, surprising numbers, founder war stories, "wait what?" moments, emotional peaks
- Skip: generic advice, obvious statements, context-dependent references
- On long episodes, search the ENTIRE timeline and diversify the picks. Do not cluster all clips in one section if later sections contain strong standalone moments.
@@ -430,7 +460,7 @@ HOOK (optional):
Rules:
- Final clip duration (sum of segments) MUST be {b.dur_min}-{b.dur_max} seconds (target {b.target_min}-{b.target_max}s)
-- Each segment must start and end on COMPLETE SENTENCES — never mid-thought
+- Each segment must start and end on COMPLETE SENTENCES: never mid-thought
- The LAST segment must end on a sentence that feels like a natural conclusion
- Must make sense standalone when stitched together
- Sort clips by timestamp order
@@ -565,7 +595,7 @@ def find_moments_from_text(
) -> list[dict]:
"""Locate the moment(s) the user described/pasted in the transcript.
Returns clip dicts (same shape as suggest_with_claude). Status goes to
- progress_callback; warnings to stderr — never stdout, which is the task
+ progress_callback; warnings to stderr: never stdout, which is the task
runner's JSON-RPC channel."""
existing_clips = existing_clips or []
bounds = bounds or ClipBounds.of()
@@ -590,7 +620,7 @@ USER WANTS: "{description}"
{existing_desc}
RULES:
- Find the EXACT moment(s) matching what the user pasted/described
-- The user may list several moments — return one clip per distinct moment they mention
+- The user may list several moments. Return one clip per distinct moment they mention
- Return 1-{upper} matching moments (best match first)
- All timestamps in SECONDS as numbers
- Duration target: {bounds.target_min}-{bounds.target_max} seconds, max {bounds.dur_max} seconds
@@ -739,7 +769,7 @@ def suggest_with_claude(
project_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
def _parse_seconds(val) -> float:
- """Parse a timestamp value — handles both 123.4 and '2:03' formats."""
+ """Parse a timestamp value: handles both 123.4 and '2:03' formats."""
if isinstance(val, (int, float)):
return float(val)
s = str(val).strip()
@@ -980,7 +1010,7 @@ def suggest_initial_with_claude(
)
if progress_callback:
- progress_callback(0, f"Long episode detected — searching {len(buckets)} timeline buckets...")
+ progress_callback(0, f"Long episode detected: searching {len(buckets)} timeline buckets...")
aggregated: list[dict] = []
per_bucket_top_n = max(2, math.ceil(top_n / max(1, len(buckets))))
diff --git a/backend/services/clip_generator.py b/backend/services/clip_generator.py
index 3f8b3c4..6335ebd 100644
--- a/backend/services/clip_generator.py
+++ b/backend/services/clip_generator.py
@@ -1,5 +1,5 @@
"""
-Clip generator — orchestrates the full pipeline for creating a short-form clip.
+Clip generator: orchestrates the full pipeline for creating a short-form clip.
Pipeline: cut segment → crop to 9:16 → render captions → burn captions
(+ optional gradient overlay + logo) → normalize audio
@@ -17,7 +17,7 @@ from typing import Optional, Callable
from utils.proc import run as proc_run, ProcError
from utils.text import safe_filename
-from utils.log import timed
+from utils.log import timed, warn as log_warn
from config.paths import paths
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -108,7 +108,7 @@ def _trim_weak_opening(
# If the opening already has question/exclamation energy, keep it.
if "?" in raw or "!" in raw:
break
- bare = raw.lower().strip(".,!?;:-–—'\"")
+ bare = raw.lower().strip(".,!?;:-\u2013\u2014'\"")
if bare in _WEAK_OPENING_WORDS:
weak_run_end = max(float(w["end"]), weak_run_end or 0.0)
continue
@@ -460,13 +460,13 @@ def _clean_transcript_words(words: list[dict]) -> list[dict]:
Remove filler words from transcript captions.
- Strips obvious filler words (um, uh, hmm, etc.) so they don't appear in captions.
- - Does NOT shift timestamps — word timing must match the actual audio exactly.
+ - Does NOT shift timestamps: word timing must match the actual audio exactly.
"""
cleaned = []
for w in words:
text = w.get("word", "").strip()
# Strip punctuation for matching, but keep original text
- bare = text.lower().strip(".,!?;:-–—'\"")
+ bare = text.lower().strip(".,!?;:-\u2013\u2014'\"")
if bare in _FILLER_WORDS:
continue
cleaned.append(w)
@@ -503,7 +503,7 @@ def _build_tight_segments(
for i, w in enumerate(clip_words):
text = w.get("word", "").strip()
- bare = text.lower().strip(".,!?;:-–—'\"")
+ bare = text.lower().strip(".,!?;:-\u2013\u2014'\"")
is_filler = bare in _FILLER_WORDS
# Check gap before this word
@@ -511,12 +511,12 @@ def _build_tight_segments(
gap = w["start"] - prev_end
if gap >= silence_threshold:
- # Long pause — end current segment, start new one
+ # Long pause: end current segment, start new one
if prev_end > seg_start + 0.5: # Don't create tiny segments
segments.append({"start": round(seg_start, 2), "end": round(prev_end, 2)})
seg_start = w["start"]
elif is_filler and gap >= 0.3:
- # Isolated filler word with a gap before it — skip it
+ # Isolated filler word with a gap before it: skip it
# End segment before the filler, start after it
if w["start"] > seg_start + 0.5:
segments.append({"start": round(seg_start, 2), "end": round(w["start"], 2)})
@@ -536,13 +536,13 @@ def _build_tight_segments(
saved = original_duration - kept_duration
if saved < 0.8 or len(segments) < 2:
- # Not worth the cuts — too little saved
+ # Not worth the cuts: too little saved
return [{"start": start_second, "end": end_second}]
return segments
-_remotion_available = None # True/False/None — environment availability, not per-clip success
+_remotion_available = None # True/False/None: environment availability, not per-clip success
def _stop_process_tree(proc: subprocess.Popen) -> None:
@@ -750,6 +750,7 @@ def _render_with_remotion(
# Extract face Y positions so captions can avoid overlapping faces
# Probe video dimensions
face_y_norm = None # normalized 0-1 (0=top, 1=bottom)
+ cap = None
try:
probe_cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=height", "-of", "csv=p=0",
@@ -780,11 +781,13 @@ def _render_with_remotion(
ys.append(f["cy"] / vid_h_actual)
if ys:
face_y_norm = sum(ys) / len(ys)
+ except Exception as exc:
+ log_warn("clip", "face-position sampling failed, captions use default placement", error=exc)
+ finally:
+ if cap is not None:
cap.release()
- except Exception:
- pass
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("clip", "video height probe failed, captions use default placement", error=exc)
words_file = output_path + ".words.json"
try:
@@ -882,8 +885,8 @@ def _render_with_remotion(
finally:
try:
os.unlink(words_file)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("clip", "could not remove words file", error=exc)
def generate_clip(
@@ -964,8 +967,8 @@ def generate_clip(
from services.integrations.manager import IntegrationsManager
if IntegrationsManager().is_enabled("davinci_resolve"):
keep_caption_overlay = True
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("clip", "could not check the DaVinci Resolve integration", error=exc)
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video not found: {video_path}")
@@ -1060,7 +1063,7 @@ def generate_clip(
end_second = keep_segments[-1]["end"]
# If Claude returned a single segment, still auto-trim pauses within it.
- # Multiple segments means Claude made deliberate editorial cuts — trust those.
+ # Multiple segments means Claude made deliberate editorial cuts. Trust those.
if len(keep_segments) == 1 and transcript_words and clean_fillers:
auto_segments = _build_tight_segments(
transcript_words, start_second, end_second,
diff --git a/backend/services/clips_history.py b/backend/services/clips_history.py
index 7878a1d..dd29d95 100644
--- a/backend/services/clips_history.py
+++ b/backend/services/clips_history.py
@@ -1,5 +1,5 @@
"""
-Clip history — read/write .podcli/history/clips.json.
+Clip history: read/write .podcli/history/clips.json.
Shared on-disk contract with the TypeScript ClipsHistory service
(src/services/clips-history.ts). Both languages read and write the same
@@ -92,7 +92,7 @@ def delete_clip(clip_id: str) -> Optional[dict]:
"""Remove a clip from history along with its rendered output and sidecars.
Returns the removed entry, or None if no clip matched. The source video is
- never touched — only artifacts podcli rendered for this clip.
+ never touched: only artifacts podcli rendered for this clip.
"""
target = find_clip(clip_id)
if target is None:
diff --git a/backend/services/cloud_render.py b/backend/services/cloud_render.py
index 3e07dbf..e04d60f 100644
--- a/backend/services/cloud_render.py
+++ b/backend/services/cloud_render.py
@@ -42,10 +42,10 @@ def run(video_path: str, config: dict, output_dir: str, args) -> None:
"""Render one episode in the cloud and download the clips it produced."""
if not podcli_cloud.signed_in():
raise CloudRenderError(
- "cloud rendering needs a podcli Pro session — run `podcli login`")
+ "cloud rendering needs a podcli Pro session: run `podcli login`")
size = os.path.getsize(video_path)
- print(f"\n podcli — rendering in the cloud")
+ print(f"\n podcli: rendering in the cloud")
print(f" Video: {os.path.basename(video_path)} ({_megabytes(size)})")
print(f" Output: {output_dir}/\n")
@@ -67,7 +67,7 @@ def run(video_path: str, config: dict, output_dir: str, args) -> None:
if downloaded:
print(f" Saved {downloaded} file{'' if downloaded == 1 else 's'} to {output_dir}/")
else:
- print(f" {GRAY}Nothing to download yet — see them at podcli.com/app{RESET}")
+ print(f" {GRAY}Nothing to download yet: see them at podcli.com/app{RESET}")
def _params(config: dict, args) -> dict:
@@ -173,7 +173,7 @@ def _follow(job_id: str) -> dict:
line = (f" {ACCENT}{job.get('progress', 0)}%{RESET} "
f"{job.get('stage') or status}"
- f"{' — ' + job['detail'] if job.get('detail') else ''}")
+ f"{': ' + job['detail'] if job.get('detail') else ''}")
print("\r" + " " * len(last) + "\r" + line, end="", flush=True)
last = line
diff --git a/backend/services/content_generator.py b/backend/services/content_generator.py
index 4abe9ed..ffda5d0 100644
--- a/backend/services/content_generator.py
+++ b/backend/services/content_generator.py
@@ -6,6 +6,7 @@ Single source of truth used by CLI, Web UI, and MCP.
import json
import os
+from utils.log import warn as log_warn
import subprocess
import sys
import tempfile
@@ -172,8 +173,8 @@ def _stream_claude_content(
try:
proc.kill()
proc.wait()
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("content", "could not stop subprocess", error=exc)
return None
finally:
watchdog.cancel()
@@ -300,7 +301,7 @@ TITLES (8 options, 50-70 chars, keyword-first, follow title spec):
6. [title]
7. [title]
8. [title]
-TOP PICK: [number] — [why]
+TOP PICK: [number], [why]
DESCRIPTION:
[hook line under 100 chars]
@@ -336,7 +337,7 @@ TITLES (8 options, 40-60 chars, keyword-first, follow title spec):
6. [title]
7. [title]
8. [title]
-TOP PICK: [number] — [why]
+TOP PICK: [number], [why]
DESCRIPTION:
[hook line under 100 chars]
diff --git a/backend/services/corrections.py b/backend/services/corrections.py
index f1e5a31..1a7c8d8 100644
--- a/backend/services/corrections.py
+++ b/backend/services/corrections.py
@@ -1,5 +1,5 @@
"""
-Transcript word corrections — fixes Whisper misheard proper nouns.
+Transcript word corrections: fixes Whisper misheard proper nouns.
Loads replacements from .podcli/corrections.json and applies them to
transcript words and segments. Single source of truth used by all paths
diff --git a/backend/services/encoder.py b/backend/services/encoder.py
index b64091e..6662172 100644
--- a/backend/services/encoder.py
+++ b/backend/services/encoder.py
@@ -4,7 +4,7 @@ Hardware-accelerated encoder detection and configuration.
Probes system for available encoders:
- macOS: h264_videotoolbox (M-series / Intel GPU)
- NVIDIA: h264_nvenc
-- AMD: h264_amf (Windows) / h264_vaapi (Linux)
+- AMD: h264_amf (Windows)
- Fallback: libx264 (CPU, always available)
Returns optimal FFmpeg encoder flags for the current system.
@@ -33,7 +33,7 @@ def detect_encoders() -> dict:
if system == "Darwin":
candidates = ["h264_videotoolbox"]
elif system == "Linux":
- candidates = ["h264_nvenc", "h264_vaapi"]
+ candidates = ["h264_nvenc"]
elif system == "Windows":
candidates = ["h264_nvenc", "h264_amf", "h264_qsv"]
@@ -45,7 +45,6 @@ def detect_encoders() -> dict:
"h264_videotoolbox",
"h264_nvenc",
"h264_amf",
- "h264_vaapi",
"h264_qsv",
"libx264",
]
@@ -113,7 +112,7 @@ def _get_encoder_flags(encoder: str) -> list[str]:
flags = {
"h264_videotoolbox": [
"-c:v", "h264_videotoolbox",
- "-b:v", "6M", # 6 Mbps — plenty for 1080x1920 vertical
+ "-b:v", "6M", # 6 Mbps, plenty for 1080x1920 vertical
"-profile:v", "high",
"-pix_fmt", "yuv420p",
"-allow_sw", "1", # Allow software fallback
@@ -131,10 +130,6 @@ def _get_encoder_flags(encoder: str) -> list[str]:
"-rc", "cqp",
"-qp_i", "18", "-qp_p", "18",
],
- "h264_vaapi": [
- "-c:v", "h264_vaapi",
- "-qp", "18",
- ],
"h264_qsv": [
"-c:v", "h264_qsv",
"-preset", "slow",
@@ -157,7 +152,7 @@ def get_video_encode_flags() -> list[str]:
info = detect_encoders()
return info["best_flags"]
except Exception:
- # Absolute fallback — never let encoder detection break the pipeline
+ # Absolute fallback: never let encoder detection break the pipeline
print("Warning: encoder detection failed, using libx264", file=sys.stderr)
return ["-c:v", "libx264", "-crf", "18", "-preset", "slow",
"-profile:v", "high", "-pix_fmt", "yuv420p"]
@@ -182,7 +177,7 @@ def get_encoder_info() -> dict:
"""Get full encoder detection info (for UI/logging).
Cached under paths["cache"]/encoder.json keyed by ffmpeg binary fingerprint.
- Encoder probing runs ffmpeg twice (~1.6s on macOS) — huge startup win.
+ Encoder probing runs ffmpeg twice (~1.6s on macOS), huge startup win.
"""
import json
cache_path = _encoder_cache_path()
diff --git a/backend/services/env_settings.py b/backend/services/env_settings.py
index 0ecc0ad..1b03e03 100644
--- a/backend/services/env_settings.py
+++ b/backend/services/env_settings.py
@@ -45,6 +45,15 @@ SETTINGS = [
"secret": False,
"placeholder": "chrome",
},
+ {
+ "key": "PODCLI_CLOUD_SYNC",
+ "label": "Cloud clip sync",
+ "help": "Set to 1 to upload each rendered clip video and its transcript "
+ "slice to your podcli Pro workspace. Off by default. Only applies "
+ "when you are signed in.",
+ "secret": False,
+ "placeholder": "1",
+ },
{
"key": "PODCLI_CLAUDE_PATH",
"label": "Claude Code CLI path",
diff --git a/backend/services/face_analysis.py b/backend/services/face_analysis.py
index 29f5a9a..b3f52ac 100644
--- a/backend/services/face_analysis.py
+++ b/backend/services/face_analysis.py
@@ -1,5 +1,5 @@
"""
-Face analysis service — runs once during transcription, caches results.
+Face analysis service: runs once during transcription, caches results.
Detects face positions throughout the video and maps them to speakers.
Clip generation uses this pre-computed data instead of re-scanning every time.
@@ -104,7 +104,7 @@ def analyze_faces(
roi = frame[y0:y1, x0:x1]
if roi.size == 0:
return None
- # 16x16 downsample + grayscale — cheap to diff and robust to
+ # 16x16 downsample + grayscale: cheap to diff and robust to
# sub-pixel jitter.
small = cv2.resize(roi, (16, 16))
return cv2.cvtColor(small, cv2.COLOR_BGR2GRAY).astype(np.int16)
@@ -114,7 +114,7 @@ def analyze_faces(
reported_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
est_frames = int(duration * fps) if duration and fps else 0
total_frames = max(reported_frames, est_frames, 1)
- # grab() advances cheaply, retrieve() decodes only the sampled frames — far
+ # grab() advances cheaply, retrieve() decodes only the sampled frames, far
# cheaper than a cap.set() seek (keyframe re-decode) per sample.
step = max(1, total_frames // sample_count)
frame_idx = -1
@@ -245,7 +245,7 @@ def analyze_faces(
# Pure face-position counting is symmetric on true split-screens
# (both faces are visible every frame), so presence votes alone
# can't tell which face is actually speaking. We use the
- # per-observation `activity` signal — the mouth-ROI frame-to-
+ # per-observation `activity` signal: the mouth-ROI frame-to-
# frame pixel difference computed above. During a speaker's
# turn, THEIR face has high activity (mouth moving) and the
# listener's face has near-zero activity.
diff --git a/backend/services/face_detector.py b/backend/services/face_detector.py
index 3b0bc38..082f56a 100644
--- a/backend/services/face_detector.py
+++ b/backend/services/face_detector.py
@@ -19,7 +19,7 @@ MIN_FACE_RATIO = 0.04
# source 16:9 video scores higher than processed 9:16 clips)
CONFIDENCE_THRESHOLD = 0.5
-# Max dimension for detection input — keeps inference fast.
+# Max dimension for detection input: keeps inference fast.
# Coordinates are scaled back to original frame size.
_MAX_DIM = 640
diff --git a/backend/services/face_track_helpers.py b/backend/services/face_track_helpers.py
index 769cd7e..d607491 100644
--- a/backend/services/face_track_helpers.py
+++ b/backend/services/face_track_helpers.py
@@ -132,7 +132,7 @@ def clamp_away_from_dead_zone(
cluster instead.
Only triggers when the crop CENTER is close to the midline of the
- source frame — a crop that merely straddles the midline is fine on
+ source frame: a crop that merely straddles the midline is fine on
fullscreen layouts where the face genuinely sits near center.
"""
if not has_any_split or not face_map:
@@ -162,7 +162,7 @@ def upgrade_speaker_mappings(face_map: dict) -> dict:
v1 caches used "first-to-speak = left" which breaks when the host
speaks first but sits on the right. This function clears the
mappings entirely and stamps `_mappings_v2 = True` so the clear
- only runs once per cache. Cluster positions are kept — they're
+ only runs once per cache. Cluster positions are kept because they're
still useful for dead-zone clamping and safe defaults.
Note: face_analysis.py writes its own v2-quality mappings and
diff --git a/backend/services/formats.py b/backend/services/formats.py
index 458c5ae..91cfc66 100644
--- a/backend/services/formats.py
+++ b/backend/services/formats.py
@@ -1,4 +1,4 @@
-"""Output format specifications — the single source of truth for clip dimensions.
+"""Output format specifications: the single source of truth for clip dimensions.
Every aspect-ratio decision (crop target, caption geometry, duration bounds,
which scoring profile applies) derives from a FormatSpec so the render pipeline
diff --git a/backend/services/integrations/__init__.py b/backend/services/integrations/__init__.py
index 60bc79d..f17410a 100644
--- a/backend/services/integrations/__init__.py
+++ b/backend/services/integrations/__init__.py
@@ -1,4 +1,4 @@
-"""podcli integrations — editor exporters, platform uploads, productivity tools, AI helpers."""
+"""podcli integrations: editor exporters, platform uploads, productivity tools, AI helpers."""
from .base import IntegrationBase, IntegrationRegistry, ToolSpec
from .manager import IntegrationsManager
from . import davinci_resolve as _davinci_resolve # noqa: F401
diff --git a/backend/services/integrations/_shared/media_probe.py b/backend/services/integrations/_shared/media_probe.py
index 954bad3..7e41c0a 100644
--- a/backend/services/integrations/_shared/media_probe.py
+++ b/backend/services/integrations/_shared/media_probe.py
@@ -11,7 +11,7 @@ def _run_ffprobe(cmd: list[str], path: str) -> dict[str, Any]:
try:
return json.loads(subprocess.check_output(cmd, text=True, stderr=subprocess.PIPE, timeout=30))
except FileNotFoundError:
- raise RuntimeError("ffprobe not found — install ffmpeg to use editor-export integrations")
+ raise RuntimeError("ffprobe not found: install ffmpeg to use editor-export integrations")
except subprocess.TimeoutExpired:
raise RuntimeError(f"ffprobe timed out for {path}")
except subprocess.CalledProcessError as e:
diff --git a/backend/services/integrations/davinci_resolve/README.md b/backend/services/integrations/davinci_resolve/README.md
index ddaa432..624a947 100644
--- a/backend/services/integrations/davinci_resolve/README.md
+++ b/backend/services/integrations/davinci_resolve/README.md
@@ -7,28 +7,28 @@ layers.
Targets free + Studio Resolve 20.x on macOS, Windows, Linux. No Studio gates
on the import path (FCPXML import, compound clips, alpha auto-detect, SRT
-subtitle import, markers — all confirmed free-tier).
+subtitle import, markers, all confirmed free-tier).
## What it does (and doesn't)
-- ✅ Source clip on V1, alpha caption overlay on V2 — Resolve auto-detects the
+- ✅ Source clip on V1, alpha caption overlay on V2. Resolve auto-detects the
alpha and composites identically to podcli's baked render.
- ✅ Per-short compound clip on the master timeline. Double-click to dive into
the nested timeline and edit individual layers.
- ✅ Editable cuts, trims, audio, color grading on top, sidecar SRT.
-- ⚠️ Reframe (face-track Pan/Tilt) is **baked into the V1 source** — Resolve's
+- ⚠️ Reframe (face-track Pan/Tilt) is **baked into the V1 source**. Resolve's
FCPXML importer mis-translates transform keyframe values, so we don't emit
them. To re-frame, swap V1 with the untouched source clip and add your own
Pan/Tilt, or re-render in podcli with different params.
- ⚠️ Caption animation curves (Hormozi spring physics, karaoke highlight) are
inside the V2 alpha overlay. Swap the overlay by re-rendering in podcli with
- a different `--style` — no per-word edits inside Resolve.
+ a different `--style`: no per-word edits inside Resolve.
## Free Resolve caveat
Resolve 20.2 silently watermarks the timeline if **any** Studio-only effect
appears anywhere on it, even unused. The emitter is constrained to free-tier
-structure only — no `<adjust-blend>`, no Studio-gated nodes, no FCPXML
+structure only: no `<adjust-blend>`, no Studio-gated nodes, no FCPXML
transform keyframes (which Resolve mis-translates anyway).
## Spike verification
@@ -48,7 +48,7 @@ as V1 plus a synthetic ProRes 4444 alpha test pattern as V2.
```bash
# Generate a 1080x1920 ProRes 4444 alpha test pattern matching the source's duration.
-DUR=50 # seconds — match (or undershoot) the source duration
+DUR=50 # seconds: match (or undershoot) the source duration
ffmpeg -y -f lavfi -i "[email protected]:s=1080x1920:r=24:d=$DUR" \
-vf "drawbox=x=140:y=1500:w=800:h=180:[email protected]:t=fill, \
drawtext=text='ALPHA OVERLAY':fontcolor=black:fontsize=110:x=190:y=1545" \
@@ -88,8 +88,8 @@ node remotion/render.mjs \
That produces:
-- `/tmp/spike_baked.mp4` — baked composite (the ground-truth render)
-- `/tmp/spike_baked_captions.mov` — ProRes 4444 alpha overlay
+- `/tmp/spike_baked.mp4`: baked composite (the ground-truth render)
+- `/tmp/spike_baked_captions.mov`: ProRes 4444 alpha overlay
Then:
diff --git a/backend/services/integrations/davinci_resolve/__init__.py b/backend/services/integrations/davinci_resolve/__init__.py
index e0870a8..d18d3a3 100644
--- a/backend/services/integrations/davinci_resolve/__init__.py
+++ b/backend/services/integrations/davinci_resolve/__init__.py
@@ -1,4 +1,4 @@
-"""DaVinci Resolve integration — emits FCPXML 1.10 for free + Studio Resolve 20.x."""
+"""DaVinci Resolve integration: emits FCPXML 1.10 for free + Studio Resolve 20.x."""
from ..base import IntegrationRegistry
from .integration import integration
from . import emitter
diff --git a/backend/services/integrations/davinci_resolve/cli.py b/backend/services/integrations/davinci_resolve/cli.py
index b5a54bc..292b548 100644
--- a/backend/services/integrations/davinci_resolve/cli.py
+++ b/backend/services/integrations/davinci_resolve/cli.py
@@ -1,4 +1,4 @@
-"""Spike CLI — emit a Resolve FCPXML referencing one or more shorts on disk.
+"""Spike CLI: emit a Resolve FCPXML referencing one or more shorts on disk.
Usage:
python -m services.integrations.davinci_resolve.cli \
@@ -88,13 +88,13 @@ def main() -> int:
if short.captions:
print(f" captions: {short.captions.path} ({short.captions.duration_frames}f)")
else:
- print(" captions: (none — re-run with --captions for the layered spike)")
+ print(" captions: (none: re-run with --captions for the layered spike)")
print()
print("To verify in DaVinci Resolve (free or Studio, 20.x):")
print(" 1. Open Resolve → New Project")
print(" 2. File → Import → Timeline → select the .fcpxml above")
print(" 3. Confirm one compound clip per short appears on the timeline")
- print(" 4. Double-click a compound clip — V1 source and V2 captions should be on separate tracks")
+ print(" 4. Double-click a compound clip. V1 source and V2 captions should be on separate tracks")
return 0
diff --git a/backend/services/integrations/davinci_resolve/emitter.py b/backend/services/integrations/davinci_resolve/emitter.py
index 4a8bfd4..2589fb2 100644
--- a/backend/services/integrations/davinci_resolve/emitter.py
+++ b/backend/services/integrations/davinci_resolve/emitter.py
@@ -6,7 +6,7 @@ Resolve quirks the emitter routes around:
- Composite-mode / blend-mode attributes are silently dropped. Alpha is carried
by the asset itself (ProRes 4444); Resolve auto-detects and composites normal.
- PNG image sequences import as one-frame-per-clip. Use single video files.
- - Avoid any Studio-only effect node — Resolve 20.2 watermarks the timeline
+ - Avoid any Studio-only effect node: Resolve 20.2 watermarks the timeline
if it sees one, even if unused.
- Pin to FCPXML 1.10; 1.11+ have intermittent import failures.
"""
@@ -35,7 +35,7 @@ def emit(project: Project, out_path: Path) -> Path:
next_asset += 1
resources.append(fx.make_asset(
asset_id=src_id,
- name=f"{short.title} — source",
+ name=f"{short.title}: source",
media_path=short.source.path,
frames=short.source.duration_frames,
fps=short.source.fps,
@@ -51,7 +51,7 @@ def emit(project: Project, out_path: Path) -> Path:
next_asset += 1
resources.append(fx.make_asset(
asset_id=cid,
- name=f"{short.title} — captions",
+ name=f"{short.title}: captions",
media_path=short.captions.path,
frames=short.captions.duration_frames,
fps=short.captions.fps,
@@ -67,7 +67,7 @@ def emit(project: Project, out_path: Path) -> Path:
next_asset += 1
resources.append(fx.make_asset(
asset_id=lid,
- name=f"{short.title} — logo",
+ name=f"{short.title}: logo",
media_path=short.logo.path,
frames=short.logo.duration_frames,
fps=short.logo.fps,
diff --git a/backend/services/integrations/davinci_resolve/integration.py b/backend/services/integrations/davinci_resolve/integration.py
index c8e3f6d..ecccec2 100644
--- a/backend/services/integrations/davinci_resolve/integration.py
+++ b/backend/services/integrations/davinci_resolve/integration.py
@@ -1,4 +1,4 @@
-"""DaVinci Resolve integration — exposes the export_to_davinci_resolve MCP tool."""
+"""DaVinci Resolve integration: exposes the export_to_davinci_resolve MCP tool."""
from __future__ import annotations
from pathlib import Path
@@ -14,7 +14,7 @@ class DaVinciResolveIntegration(IntegrationBase):
name = "davinci_resolve"
category = "editor_export"
description = (
- "Export podcli shorts as a DaVinci Resolve FCPXML — each short becomes an "
+ "Export podcli shorts as a DaVinci Resolve FCPXML: each short becomes an "
"editable compound clip (source on V1, ProRes 4444 alpha captions on V2). "
"Works in free + Studio Resolve 20.x."
)
diff --git a/backend/services/integrations/youtube/client.py b/backend/services/integrations/youtube/client.py
index c39246a..6698528 100644
--- a/backend/services/integrations/youtube/client.py
+++ b/backend/services/integrations/youtube/client.py
@@ -1,8 +1,8 @@
"""YouTube Data + Analytics client and CSV importer.
Two ways to get per-video performance into podcli:
- 1. OAuth (bring-your-own Google Cloud creds) — full, live metrics.
- 2. CSV export from YouTube Studio — no auth, works offline.
+ 1. OAuth (bring-your-own Google Cloud creds): full, live metrics.
+ 2. CSV export from YouTube Studio: no auth, works offline.
The google-api libraries are imported lazily so the rest of podcli runs
without them; OAuth paths raise a clear, actionable error when they're absent.
@@ -12,6 +12,7 @@ from __future__ import annotations
import csv
import json
import os
+from utils.log import warn as log_warn
from typing import Any, Optional
from config.paths import paths
@@ -42,7 +43,7 @@ def is_authorized() -> bool:
def _write_token(creds) -> None:
- # 0o600: the file holds a long-lived refresh token — keep it owner-only.
+ # 0o600: the file holds a long-lived refresh token: keep it owner-only.
fd = os.open(_TOKEN_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(creds.to_json())
@@ -158,8 +159,8 @@ def fetch_metrics(video_id: str) -> dict[str, Any]:
irows = imp.get("rows") or [[0, 0]]
metrics["impressions"] = int(irows[0][0])
metrics["ctr"] = round(float(irows[0][1]), 1)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("youtube", "impressions report unavailable", error=exc)
return metrics
diff --git a/backend/services/integrations/youtube/integration.py b/backend/services/integrations/youtube/integration.py
index 6e33c90..43f7f22 100644
--- a/backend/services/integrations/youtube/integration.py
+++ b/backend/services/integrations/youtube/integration.py
@@ -1,4 +1,4 @@
-"""YouTube analytics integration — links rendered clips to uploads and pulls
+"""YouTube analytics integration: links rendered clips to uploads and pulls
per-video performance (views, retention, CTR) for the learning loop."""
from __future__ import annotations
@@ -13,7 +13,7 @@ class YouTubeIntegration(IntegrationBase):
description = (
"Performance feedback, not publishing. Links rendered clips to your published "
"videos and pulls views, retention, and CTR so podcli learns what works and "
- "Claude picks better shorts. Read-only — podcli never uploads. Bring your own "
+ "Claude picks better shorts. Read-only: podcli never uploads. Bring your own "
"Google OAuth client, or import a YouTube Studio analytics CSV."
)
default_enabled = False
diff --git a/backend/services/integrations/youtube/learnings.py b/backend/services/integrations/youtube/learnings.py
index 75a97e5..eb25af0 100644
--- a/backend/services/integrations/youtube/learnings.py
+++ b/backend/services/integrations/youtube/learnings.py
@@ -2,7 +2,7 @@
picking shorts. Structured (no LLM): regenerated whenever metrics sync.
The clip-picking skills glob .podcli/knowledge/*.md, so writing the digest
-here is what closes the loop — the next suggest_clips run is informed by what
+here is what closes the loop: the next suggest_clips run is informed by what
actually performed.
"""
from __future__ import annotations
@@ -45,7 +45,7 @@ def _agg(clips: list[dict], key: Callable[[dict], Any]) -> list[dict]:
dropped: too little data to call it a trend."""
groups: dict[str, list[dict]] = defaultdict(list)
for c in clips:
- groups[key(c) or "—"].append(c)
+ groups[key(c) or "unknown"].append(c)
out = []
for k, cs in groups.items():
if len(cs) < MIN_BUCKET_SIZE:
@@ -85,24 +85,24 @@ def write_learnings(min_clips: int = 3, ai_block: Optional[str] = None) -> Optio
"# Performance learnings",
"",
"<!-- AUTO-GENERATED by `podcli youtube sync`. The 'What's working now' section is",
- " regenerated each sync — edits there are overwritten. -->",
+ " regenerated each sync: edits there are overwritten. -->",
"",
f"## What's working now (updated {now} · {len(clips)} published clips)",
"",
"Retention = content quality (did it hold viewers). CTR = packaging (title/thumbnail). Views = reach.",
"",
- "**By moment type — retention:**",
+ "**By moment type (retention):**",
]
L += [f"- {r['key']}: {r['ret']}% retention · {r['ctr']}% CTR · ~{r['views']} views (n={r['n']})" for r in by_type]
- L += ["", "**By caption style — CTR:**"]
+ L += ["", "**By caption style (CTR):**"]
L += [f"- {r['key']}: {r['ctr']}% CTR · {r['ret']}% retention (n={r['n']})" for r in by_caption]
- L += ["", "**By length — retention:**"]
+ L += ["", "**By length (retention):**"]
L += [f"- {r['key']}: {r['ret']}% retention (n={r['n']})" for r in by_length]
L += ["", "**Top performers:**"]
- L += [f"- \"{c['title']}\" — {(c.get('metrics') or {}).get('views')} views, {(c.get('metrics') or {}).get('retention')}% retention [{c.get('content_type', '?')}]" for c in top]
+ L += [f"- \"{c['title']}\": {(c.get('metrics') or {}).get('views')} views, {(c.get('metrics') or {}).get('retention')}% retention [{c.get('content_type', '?')}]" for c in top]
L += ["", "## Guidance for picking shorts", ""]
if by_type:
- L.append(f"- Prioritize **{by_type[0]['key']}** moments — highest retention ({by_type[0]['ret']}%).")
+ L.append(f"- Prioritize **{by_type[0]['key']}** moments: highest retention ({by_type[0]['ret']}%).")
best_ctr = next((r for r in by_caption if r["ctr"]), None)
if best_ctr:
L.append(f"- **{best_ctr['key']}** captions earn the most clicks ({best_ctr['ctr']}% CTR).")
diff --git a/backend/services/integrations/youtube/sync.py b/backend/services/integrations/youtube/sync.py
index d8baff7..f612537 100644
--- a/backend/services/integrations/youtube/sync.py
+++ b/backend/services/integrations/youtube/sync.py
@@ -2,7 +2,7 @@
podcli renders but never publishes, so performance is reconstructed after the
fact: match each rendered clip to its uploaded video, then pull metrics onto
-the clip. Matching is proposed, never silent — a wrong link poisons the signal.
+the clip. Matching is proposed, never silent. A wrong link poisons the signal.
"""
from __future__ import annotations
diff --git a/backend/services/local_reframe.py b/backend/services/local_reframe.py
index ee04caa..9d12a9f 100644
--- a/backend/services/local_reframe.py
+++ b/backend/services/local_reframe.py
@@ -30,7 +30,7 @@ def count_scene_cuts(video_path: str, threshold: float = 0.35) -> int:
"ffmpeg",
"-i", str(video_path),
# Audio and subtitles are irrelevant to scene detection, and the
- # scene score is a whole-frame statistic — computing it on a
+ # scene score is a whole-frame statistic, so computing it on a
# 320px-wide copy gives the same cuts for a fraction of the
# decode. Downscale before select so the filter sees small frames.
"-an", "-sn",
diff --git a/backend/services/media_probe.py b/backend/services/media_probe.py
index 89f0c6b..6d2948a 100644
--- a/backend/services/media_probe.py
+++ b/backend/services/media_probe.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import json
import math
import os
+from utils.log import warn as log_warn
import sys
from typing import Optional
@@ -121,7 +122,7 @@ def has_audio_stream(video_path: str) -> bool:
info = get_video_info(video_path)
return any(s.get("codec_type") == "audio" for s in info.get("streams", []))
except Exception:
- # Assume yes if we can't check — missing audio is reasonably rare
+ # Assume yes if we can't check. Missing audio is reasonably rare
# and downstream concat filters will surface the real error.
return True
@@ -219,8 +220,8 @@ def align_av_duration(path: str, slack: float = 0.2) -> str:
if result.returncode == 0 and os.path.exists(tmp) and os.path.getsize(tmp) > 0:
os.replace(tmp, path)
return path
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("media-probe", "proxy encode failed", error=exc)
if os.path.exists(tmp):
try:
os.remove(tmp)
diff --git a/backend/services/motion_filters.py b/backend/services/motion_filters.py
index 521647b..c3f8e85 100644
--- a/backend/services/motion_filters.py
+++ b/backend/services/motion_filters.py
@@ -2,7 +2,7 @@
All functions here are side-effect-free: they take keyframe / window
lists and return strings or lists. No ffmpeg is actually invoked from
-this module — the caller passes the returned expressions into a
+this module: the caller passes the returned expressions into a
filter_complex graph.
Extracted from video_processor.py so the pure math can be unit-tested
@@ -57,7 +57,7 @@ def build_cam_expr(
quick_reframe_jump = 90
if jump < 2:
- # Negligible movement — hold.
+ # Negligible movement: hold.
parts.append(f"if(between(t\\,{t0:.3f}\\,{t1:.3f})\\,{x0}\\,")
elif jump >= blurred_cut_jump:
# Very large jumps in non-split layouts still read better as
diff --git a/backend/services/podcli_cloud.py b/backend/services/podcli_cloud.py
index 5317713..474b0b6 100644
--- a/backend/services/podcli_cloud.py
+++ b/backend/services/podcli_cloud.py
@@ -2,7 +2,7 @@
This module is the whole of Pro that lives in the open source app: where the
token is kept, how it is sent, and what shape the request takes. There is no
-secret here and nothing to crack — the server decides entitlement, so a patched
+secret here and nothing to crack: the server decides entitlement, so a patched
client gets a UI that says Pro and an HTTP 401.
"""
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import os
+from utils.log import warn as log_warn
import time
import urllib.error
import urllib.parse
@@ -143,7 +144,7 @@ def request(method: str, path: str, body: Optional[dict] = None,
timeout: int = 300) -> Any:
token = read_token()
if not token:
- raise CloudError("not signed in — run `podcli login`", status=401)
+ raise CloudError("not signed in: run `podcli login`", status=401)
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(
@@ -177,14 +178,14 @@ def _describe(exc: urllib.error.HTTPError) -> tuple[str, bool]:
# turns the error path itself into an AttributeError.
if isinstance(parsed, dict):
payload = parsed
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("cloud", "could not parse error body", error=exc)
detail = payload.get("error")
if isinstance(detail, list):
detail = "; ".join(str(item.get("message", item)) for item in detail)
if exc.code == 401:
- return ("podcli Pro session expired — run `podcli login` again", False)
+ return ("podcli Pro session expired: run `podcli login` again", False)
if exc.code == 402:
# A plan's own limits (footage, cameras) say which one; a bare 402 means no plan at all.
return (detail or "this workspace has no active podcli Pro subscription", False)
@@ -222,7 +223,7 @@ def source_hash(video_path: str) -> Optional[str]:
"""Identify an episode across machines.
Must stay byte-identical to the TypeScript implementation in
- src/services/podcli-cloud.ts — the two clients hash the same file and the
+ src/services/podcli-cloud.ts: the two clients hash the same file and the
server dedupes episodes on the result, so any divergence silently splits one
episode into two. First 8 MB only: distinctive enough, and digesting a 2 GB
master on every render is not.
@@ -375,7 +376,7 @@ def create_workspace(name: str) -> dict:
def switch_workspace(workspace_id: str) -> dict:
"""Switching means a new session, not a mutable field on the old one.
- Tenancy is decided once, at authentication, from the session's workspace —
+ Tenancy is decided once, at authentication, from the session's workspace,
so a token can never be pointed at a workspace it was not issued for.
"""
payload = request("POST", f"/v1/workspaces/{workspace_id}/session", {}, timeout=30)
diff --git a/backend/services/profiles.py b/backend/services/profiles.py
index 822bd35..3e478dd 100644
--- a/backend/services/profiles.py
+++ b/backend/services/profiles.py
@@ -1,4 +1,4 @@
-"""Content profiles — which signals drive moment detection, per content type.
+"""Content profiles: which signals drive moment detection, per content type.
A ContentProfile is orthogonal to FormatSpec: FormatSpec is a render-time aspect-ratio
decision, a ContentProfile is a detection-time decision about which signal channels
diff --git a/backend/services/reel.py b/backend/services/reel.py
index ee2a7d0..f59dcd8 100644
--- a/backend/services/reel.py
+++ b/backend/services/reel.py
@@ -1,7 +1,7 @@
-"""Editable highlight-reel sessions — the shared core behind the CLI, MCP, and UI.
+"""Editable highlight-reel sessions: the shared core behind the CLI, MCP, and UI.
Detection (the slow signal analysis) runs once into a persisted session of moments.
-Every later edit — longer, shorter, shift, drop, reorder — mutates that session and
+Every later edit (longer, shorter, shift, drop, reorder) mutates that session and
re-cuts only the changed moment straight from the source (~seconds), then rebuilds the
reel. No re-detection, no heavy render. All three surfaces operate on the same session
so an edit made in one shows up in the others.
@@ -251,7 +251,7 @@ def build_reel(session: ReelSession, progress_callback: Optional[Callable] = Non
lst = os.path.join(session.out_dir, "_concat.txt")
with open(lst, "w", encoding="utf-8") as f:
for x in files:
- p = os.path.abspath(x).replace("\\", "/")
+ p = os.path.abspath(x).replace("\\", "/").replace("'", "'\\''")
f.write(f"file '{p}'\n")
r = proc_run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", lst,
"-c", "copy", reel, "-loglevel", "error"], timeout=300, check=False)
diff --git a/backend/services/saliency.py b/backend/services/saliency.py
index 2e8d910..004370b 100644
--- a/backend/services/saliency.py
+++ b/backend/services/saliency.py
@@ -1,4 +1,4 @@
-"""Multi-signal saliency engine — fuse channels, peak-pick, expand reactions, snap.
+"""Multi-signal saliency engine: fuse channels, peak-pick, expand reactions, snap.
For profiles whose candidate source is "saliency" (party, action), moments are
generated from a fused interestingness curve instead of from an LLM reading the
@@ -24,7 +24,7 @@ GRID_HZ = 1.0 # common time grid; energy is per-second, so 1 Hz is the natural
def _robust_z(x: np.ndarray) -> np.ndarray:
- """Median/MAD normalization — resistant to the heavy tails of RMS and reactions."""
+ """Median/MAD normalization: resistant to the heavy tails of RMS and reactions."""
if x.size == 0:
return x
med = np.median(x)
@@ -240,7 +240,7 @@ def detect_highlights(
If a transcript is provided, clip boundaries snap to whole sentences so each clip
is a complete thought; `words` (with punctuation) gives true sentence edges and is
preferred over `segments`. Without any transcript, boundaries snap to audio lulls.
- `reaction_threshold` is the laughter/cheer level that counts as a reaction — low
+ `reaction_threshold` is the laughter/cheer level that counts as a reaction: low
(~0.06) for conversational chuckles, higher for loud belly-laughs/crowds.
`energy_data`/`events_data` accept the profiles the orchestration layer already
computed so the source audio isn't decoded again; `wav_path` is a pre-extracted
@@ -284,7 +284,7 @@ def detect_highlights(
progress_callback(70, "Selecting highlight moments...")
min_gap_bins = max(1, int(profile.peak_min_gap_sec * GRID_HZ))
- # Reaction moments are primary candidates — a detected laugh/cheer is almost always
+ # Reaction moments are primary candidates: a detected laugh/cheer is almost always
# worth a clip regardless of loudness, so they aren't made to out-compete energy in
# the blended curve. Energy peaks then fill the rest, minus any that collide with a
# reaction. Reaction score is offset above energy so reactions rank first.
@@ -342,7 +342,7 @@ def detect_highlights_pooled(
progress_callback: Optional[Callable] = None,
) -> list[dict]:
"""
- Detect highlights across many videos and rank them globally — "the best N bits
+ Detect highlights across many videos and rank them globally: "the best N bits
from tonight" across a folder of party clips.
Each returned clip carries a `source_file`. Ranking is reaction-first, then by
diff --git a/backend/services/speaker_detection.py b/backend/services/speaker_detection.py
index c6c225c..2cf7694 100644
--- a/backend/services/speaker_detection.py
+++ b/backend/services/speaker_detection.py
@@ -15,7 +15,7 @@ from typing import Optional, Callable
from utils.proc import run as proc_run, ProcError
-# Fix torchaudio compatibility — speechbrain calls torchaudio.list_audio_backends()
+# Fix torchaudio compatibility: speechbrain calls torchaudio.list_audio_backends()
# which was removed in torchaudio >= 2.10. Monkey-patch before any import.
try:
import torchaudio
@@ -111,14 +111,14 @@ def run_diarization(
try:
from pyannote.audio import Pipeline
except ImportError:
- msg = "Speaker detection not installed — run: podcli setup --speakers"
+ msg = "Speaker detection not installed. Run: podcli setup --speakers"
if progress_callback:
progress_callback(0, msg)
raise ImportError(msg)
if not token:
msg = (
- "HF_TOKEN not set — speaker detection requires a HuggingFace token.\n"
+ "HF_TOKEN not set: speaker detection requires a HuggingFace token.\n"
"\n"
" Setup (one-time):\n"
" 1. Create a token at https://huggingface.co/settings/tokens\n"
@@ -195,7 +195,7 @@ def run_diarization(
if progress_callback:
progress_callback(30, time_msg)
- # Run diarization — this is a blocking call, no progress updates from pyannote
+ # Run diarization: this is a blocking call, no progress updates from pyannote
diarization_params = {}
if num_speakers:
diarization_params["num_speakers"] = num_speakers
@@ -238,7 +238,7 @@ def assign_speakers_to_segments(
during that segment's time range (majority vote).
"""
if not speaker_segments:
- # No diarization data — return segments unchanged
+ # No diarization data: return segments unchanged
for seg in segments:
seg["speaker"] = None
return segments
@@ -273,7 +273,7 @@ def assign_speakers_to_words(
"""
Assign speaker labels to individual words.
- Picks the speaker whose diarization segment overlaps the word the most —
+ Picks the speaker whose diarization segment overlaps the word the most,
at turn boundaries several segments can touch a word, and the first
match is often the previous speaker trailing off.
"""
diff --git a/backend/services/thumbnail_ai.py b/backend/services/thumbnail_ai.py
index c88998b..cf6e3c6 100644
--- a/backend/services/thumbnail_ai.py
+++ b/backend/services/thumbnail_ai.py
@@ -13,7 +13,7 @@ import json
import os
import subprocess
from utils.proc import run as proc_run
-from utils.log import log_event
+from utils.log import log_event, warn as log_warn
import sys
import tempfile
import base64
@@ -40,8 +40,8 @@ def _load_brand_config() -> dict:
try:
with open(config_path, encoding="utf-8") as f:
defaults.update(json.load(f))
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("thumbnail", "thumbnail config unreadable, using defaults", error=exc)
return defaults
@@ -80,7 +80,7 @@ def _tile_bounds_for_face(gray, face_cx: int) -> tuple[int, int]:
def _frame_sharpness(frame, face_roi=None) -> float:
- """Laplacian variance — higher = sharper. Measures face region if provided."""
+ """Laplacian variance: higher = sharper. Measures face region if provided."""
import cv2
if face_roi is not None:
x1, y1, x2, y2 = face_roi
@@ -110,7 +110,7 @@ def _face_expression_quality(frame, x1: int, y1: int, x2: int, y2: int) -> float
gray = _normalize_roi(gray)
h, w = gray.shape[:2]
- # 1) Face angle — reject extreme tilt (looking down, sideways)
+ # 1) Face angle: reject extreme tilt (looking down, sideways)
# A front-facing face has the brightest area (forehead) in the top third.
# Looking down shifts brightness to forehead being occluded.
top_third = gray[:int(h * 0.33), :]
@@ -122,9 +122,9 @@ def _face_expression_quality(frame, x1: int, y1: int, x2: int, y2: int) -> float
# Looking down: top third is much darker than bottom (forehead hidden, chin/neck visible)
if top_brightness < mid_brightness * 0.7:
- return 0.2 # Looking down — terrible for thumbnails
+ return 0.2 # Looking down: terrible for thumbnails
- # 2) Face symmetry — detect extreme side angles
+ # 2) Face symmetry: detect extreme side angles
# A frontal face has roughly symmetric left/right brightness
left_half = gray[:, :w // 2]
right_half = gray[:, w // 2:]
@@ -151,7 +151,7 @@ def _face_expression_quality(frame, x1: int, y1: int, x2: int, y2: int) -> float
elif mouth_var > 120:
mouth_penalty = 0.15
- # 5) Overall face sharpness — catch motion blur
+ # 5) Overall face sharpness: catch motion blur
face_sharpness = cv2.Laplacian(gray, cv2.CV_64F).var()
if face_sharpness < 25:
return 0.3 # Motion blur
@@ -161,7 +161,7 @@ def _face_expression_quality(frame, x1: int, y1: int, x2: int, y2: int) -> float
if aspect < 0.7 or aspect > 1.4:
return 0.35 # Odd angle or distortion
- # 7) Expressiveness — reward animated faces over flat/neutral ones.
+ # 7) Expressiveness: reward animated faces over flat/neutral ones.
# Engaged speakers have higher variance in the eyebrow region (raised brows)
# and moderate mouth activity (mid-speech, not slack-jawed).
brow_region = gray[int(h * 0.15):int(h * 0.30), :]
@@ -294,7 +294,7 @@ def extract_candidate_frames(
if fw < w * 0.08:
continue
- # Split-screen check — only for landscape sources where
+ # Split-screen check: only for landscape sources where
# a small centered face likely means a multi-cam layout.
# Portrait sources naturally have centered faces.
face_cx = (x1 + x2) / 2
@@ -406,7 +406,7 @@ def extract_candidate_frames(
src_ratio = fw / fh
if is_portrait and src_ratio > 0.5:
- # Already portrait (9:16 ish) — scale to fit width, place face
+ # Already portrait (9:16 ish): scale to fit width, place face
# in upper portion with dark padding below for text area.
scale = target_w / fw
new_w = target_w
@@ -605,7 +605,7 @@ RULES:
- photo_object_position: CSS value to show the face well. The photo is already 1080x1920 with face centered, so "center top" usually works. Adjust if face_y is unusual.
- Font sizes: for short text (1-2 words per line) use 96-110px. For medium (3-4 words) use 80-96px. For long (5+ words) use 64-80px. Line 2 should be 85-95% of Line 1.
- No slashes in the text lines.
-- This is thumbnail variation #{variation + 1}. Give a DISTINCT headline angle and wording from the most obvious phrasing — vary the hook, the emphasis, or which idea you lead with so each variation reads differently."""
+- This is thumbnail variation #{variation + 1}. Give a DISTINCT headline angle and wording from the most obvious phrasing. Vary the hook, the emphasis, or which idea you lead with so each variation reads differently."""
layout = _ask_ai_for_json(prompt, timeout=30)
return layout if isinstance(layout, dict) else None
@@ -617,7 +617,7 @@ def generate_headline_variations(
"""Write n DISTINCT 2-line thumbnail headlines in a single AI call.
One call (rather than n independent layout calls) is both cheaper and the
- only way to guarantee the variations actually differ — the model has to see
+ only way to guarantee the variations actually differ, because the model has to see
all n at once to make them distinct. Returns [] if no AI CLI answers, letting
the caller fall back to per-variation layout.
"""
@@ -632,7 +632,7 @@ RULES:
- Rewrite the title into punchy thumbnail copy, not a literal transcript sentence. If clip content is given above, the copy must match what the clip actually delivers.
- Line 1 = setup, Line 2 = payoff. 4-8 words total. Hard max 24 characters per line.
- Drop filler words; keep numbers, nouns, and the strongest claim. No slashes.
-- Every option must read DIFFERENTLY — vary the hook, the emphasis, or which idea leads. Do not repeat the same phrasing across options."""
+- Every option must read DIFFERENTLY: vary the hook, the emphasis, or which idea leads. Do not repeat the same phrasing across options."""
items = _ask_ai_for_json(prompt, timeout=45)
if not isinstance(items, list):
@@ -662,7 +662,7 @@ def generate_thumbnail_with_template(
Template provides consistent visual structure.
When line1_override is given, the two lines are used verbatim and the
- Claude rewrite is skipped — the caller controls the exact split.
+ Claude rewrite is skipped: the caller controls the exact split.
`people` carries the two panels of the pair layout from thumbnail_pair.
"""
from services.thumbnail_html import generate_thumbnail, _load_config, _prepare_thumbnail_lines
@@ -822,14 +822,14 @@ def render_variations(
end_second=end_second)
if result:
frames = [result]
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("thumbnail", "frame extraction failed", error=exc)
if not frames:
frames = [{"path": None}]
# When the caller didn't pin exact copy, get n distinct headlines up front so
- # the variations differ in wording — not just in frame/styling.
+ # the variations differ in wording: not just in frame/styling.
headlines: list[tuple[str, str]] = []
if line1 is None:
headlines = generate_headline_variations(title, n, config=cfg, grounding=grounding)
@@ -874,7 +874,7 @@ def thumbnail_to_video_frame(
"""Convert thumbnail to a short video clip for appending.
Includes silent audio so concat_outro's acrossfade works.
- No baked-in fades — crossfade handles the transition.
+ No baked-in fades: crossfade handles the transition.
"""
cmd = [
"ffmpeg", "-y",
diff --git a/backend/services/thumbnail_generator.py b/backend/services/thumbnail_generator.py
index d468da6..a143437 100644
--- a/backend/services/thumbnail_generator.py
+++ b/backend/services/thumbnail_generator.py
@@ -13,6 +13,7 @@ Each thumbnail: 1080x1920 PNG with:
import json
import os
+from utils.log import warn as log_warn
import sys
from typing import Optional
@@ -54,7 +55,7 @@ DEFAULT_CONFIG = {
"max_chars_per_line": 16,
"text_y": 0.72, # 0-1 vertical position
- # Text box — set "box_enabled" false for floating text
+ # Text box: set "box_enabled" false for floating text
"box_enabled": True,
"box_border_color": None, # None = accent_color
"box_border_width": 4,
@@ -245,7 +246,7 @@ def extract_face_frame(
Extract the best face frame from a video for use as thumbnail background.
Samples frames, detects faces, picks the frame with the largest/clearest face.
- Saves the FULL frame (no crop) — the HTML template's CSS `background: cover`
+ Saves the FULL frame (no crop), the HTML template's CSS `background: cover`
handles the 9:16 crop so we get a natural chest-up portrait instead of an
over-zoomed face slice.
@@ -344,7 +345,7 @@ def extract_face_frame(
# 1. ≥3 sampled frames had ≥2 qualifying faces
# 2. Median horizontal gap between leftmost and rightmost face
# across those frames exceeds 20% of source width
- # Pure presence on both halves (#1) is not enough — an in-person
+ # Pure presence on both halves (#1) is not enough: an in-person
# podcast with two heads sharing one camera will satisfy #1 but
# not #2, and applying the seam clamp there would push a centered
# face to the crop edge.
@@ -389,7 +390,7 @@ def extract_face_frame(
# Center horizontally on face, then clamp to keep the seam outside
# the crop window on true split-screen sources. When the winner
# face sits very close to the seam, the clamp will push it toward
- # the crop's inner edge — that's intentional and a strictly better
+ # the crop's inner edge: that's intentional and a strictly better
# failure mode than showing the other speaker's tile bleed.
crop_x = best_face_cx - crop_w // 2
if is_split_screen:
@@ -466,7 +467,7 @@ def generate_thumbnail(
guest_photo_path: Optional guest photo (fills background)
logo_path: Optional logo (top corner)
config: Override config dict (merged with defaults)
- variation: Variation index (0, 1, 2) — changes layout slightly
+ variation: Variation index (0, 1, 2) that changes layout slightly
Returns:
Path to generated thumbnail
@@ -529,8 +530,8 @@ def generate_thumbnail(
photo = photo.filter(ImageFilter.GaussianBlur(blur))
img.paste(photo, (x_offset, y_offset))
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("thumbnail", "photo layer skipped", error=exc)
# ── Layer 3: Gradient overlays ──
img = _draw_gradients(img, bottom=cfg.get("gradient_bottom", 0.8), top=cfg.get("gradient_top", 0.0))
@@ -594,7 +595,7 @@ def generate_thumbnail(
l2_block_h = sum(s[1] + hl_pad_y * 2 for s in l2_sizes) if line2_style == "highlight" else sum(s[1] for s in l2_sizes)
total_content_h = l1_block_h + block_gap + l2_block_h
- # Max width for box sizing — clamp to image bounds
+ # Max width for box sizing: clamp to image bounds
all_widths = [s[0] for s in l1_sizes] + [s[0] + hl_pad_x * 2 for s in l2_sizes]
max_content_w = min(max(all_widths) if all_widths else 400, max_text_w)
@@ -630,7 +631,7 @@ def generate_thumbnail(
except TypeError:
draw.rectangle([box_l, box_t, box_r, box_b], fill=fill_rgba)
- # Draw Line 1 — white text, no background
+ # Draw Line 1: white text, no background
y = content_top
for i, line in enumerate(l1_lines):
tw, th = l1_sizes[i]
@@ -641,7 +642,7 @@ def generate_thumbnail(
# Gap between blocks
y = content_top + l1_block_h + block_gap
- # Draw Line 2 — dark text on accent highlight, or accent text
+ # Draw Line 2: dark text on accent highlight, or accent text
dark_text = _hex_to_rgb(cfg.get("bg_color", "#0D0D0D"))
for i, line in enumerate(l2_lines):
tw, th = l2_sizes[i]
@@ -691,8 +692,8 @@ def generate_thumbnail(
lx, ly = margin, margin
img.paste(logo, (lx, ly), logo)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("thumbnail", "logo layer skipped", error=exc)
# ── Layer 6: Frame border around entire image ──
if frame_border > 0:
@@ -744,7 +745,7 @@ def generate_variations(
if result:
guest_photo_path = result["path"]
- # Split title into two lines (smart split — try to balance)
+ # Split title into two lines (smart split: try to balance)
words = title.split()
if len(words) <= 2:
line1 = words[0] if words else ""
diff --git a/backend/services/thumbnail_html.py b/backend/services/thumbnail_html.py
index c8de9a7..cc79174 100644
--- a/backend/services/thumbnail_html.py
+++ b/backend/services/thumbnail_html.py
@@ -4,12 +4,14 @@ Thumbnail generator using HTML/CSS + headless browser screenshot.
Renders thumbnails via a headless browser for pixel-perfect CSS control
over fonts, letter-spacing, line-height, and highlight styling.
-EVERY visual property is driven by config. The defaults here are generic —
+EVERY visual property is driven by config. The defaults here are generic;
brand-specific values live in .podcli/thumbnail-config.json.
"""
import json
import os
+from html import escape as html_escape
+from utils.log import warn as log_warn
from pathlib import Path
import re
import shutil
@@ -30,7 +32,7 @@ _THUMBNAIL_LINE_STOPWORDS = {
"a", "an", "and", "as", "at", "for", "from", "in", "into", "of", "on",
"or", "that", "the", "to", "with",
}
-_THUMBNAIL_SPLIT_SEPARATORS = (" / ", " — ", " – ", " - ", ": ", "; ", ", ")
+_THUMBNAIL_SPLIT_SEPARATORS = (" / ", " \u2014 ", " \u2013 ", " - ", ": ", "; ", ", ")
def _load_config() -> dict:
@@ -55,17 +57,17 @@ def _load_config() -> dict:
"frame_border_color": None, # None = accent
# Text box
- "box_x": "40px", # CSS left — near edge with safe area
+ "box_x": "40px", # CSS left, near edge with safe area
"box_y": "73%", # CSS top (no photo)
"box_y_with_photo": "76%",
- "box_width": "1000px", # CSS width — max width with safe areas
+ "box_width": "1000px", # CSS width, max width with safe areas
"box_min_height": "180px",
"box_border_width": 3,
"box_border_color": None, # None = accent
"box_fill_color": "rgba(255,255,255,0.92)",
"box_padding": "24px 32px",
- # Line 1 (top line — typically white text)
+ # Line 1 (top line: typically white text)
"line1_font_size": "56px",
"line1_font_weight": "600",
"line1_letter_spacing": "1px",
@@ -75,7 +77,7 @@ def _load_config() -> dict:
"line1_color": "#000000",
"line1_nowrap": True,
- # Line 2 (bottom line — highlighted)
+ # Line 2 (bottom line: highlighted)
"line2_font_size": "52px",
"line2_font_weight": "400",
"line2_font_style": "italic",
@@ -134,8 +136,8 @@ def _load_config() -> dict:
with open(config_path, encoding="utf-8") as f:
user = json.load(f)
defaults.update(user)
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("thumbnail", "thumbnail config is corrupt, using defaults", error=exc)
return defaults
@@ -256,9 +258,9 @@ def _compact_thumbnail_title(title: str, max_words: int = 7, max_chars: int = 42
if len(words) > max_words:
words = words[:max_words]
- compact = " ".join(words).strip(" -—–,:;.!?")
+ compact = " ".join(words).strip(" -\u2014\u2013,:;.!?")
if len(compact) > max_chars:
- compact = compact[:max_chars].rsplit(" ", 1)[0].strip(" -—–,:;.!?")
+ compact = compact[:max_chars].rsplit(" ", 1)[0].strip(" -\u2014\u2013,:;.!?")
return compact
@@ -498,7 +500,7 @@ def _build_html(
face_info: Optional[dict] = None,
people: Optional[list[dict]] = None,
) -> str:
- """Build the HTML for a single thumbnail — all values from config.
+ """Build the HTML for a single thumbnail: all values from config.
Args:
face_info: Dict with face_y_pct, face_h_pct etc. from frame extraction.
@@ -585,7 +587,7 @@ def _build_html(
box_fill = cfg.get("box_fill_color", f"rgba(26,26,46,0.90)")
box_padding = cfg.get("box_padding", "28px 36px")
- # Base font sizes from config — extract int from "64px", "1.5rem", or bare "64"
+ # Base font sizes from config: extract int from "64px", "1.5rem", or bare "64"
def _px(val, default):
import re
m = re.search(r"(\d+)", str(val))
@@ -760,8 +762,8 @@ body {{
<div class="gradient-top"></div>
<div class="gradient-bottom"></div>
<div class="text-box">
- <div class="line1">{l1}</div>
- <div class="line2"><span>{l2}</span></div>
+ <div class="line1">{html_escape(l1)}</div>
+ <div class="line2"><span>{html_escape(l2)}</span></div>
</div>
{logo_html}
{layers_html}
@@ -883,8 +885,8 @@ def generate_variations(
if result:
photo_path = result["path"]
face_info = result
- except Exception:
- pass
+ except Exception as exc:
+ log_warn("thumbnail", "face frame extraction failed", error=exc)
line1, line2 = _prepare_thumbnail_lines(title)
@@ -909,7 +911,7 @@ def thumbnail_to_video_frame(
"""Convert thumbnail PNG to a short video clip for appending.
Includes a silent audio track so concat_outro's acrossfade filter
- works correctly. No baked-in fades — the crossfade transition
+ works correctly. No baked-in fades: the crossfade transition
handles the visual blend.
"""
cmd = [
diff --git a/backend/services/transcript_packer.py b/backend/services/transcript_packer.py
index 31a8f35..4ddb8f7 100644
--- a/backend/services/transcript_packer.py
+++ b/backend/services/transcript_packer.py
@@ -271,7 +271,7 @@ def _normalize_speakers(speakers_block) -> dict[str, dict]:
def _speaker_short_map(speakers_block) -> dict[str, str]:
"""Map speaker IDs AND labels to short codes (S0, S1, ...) sorted by talk time.
- Accepts either key — transcribe output uses SPEAKER_00 everywhere, but
+ Accepts either key: transcribe output uses SPEAKER_00 everywhere, but
parse_transcript uses labels ("Host") in word.speaker/segment.speaker
while keeping SPEAKER_0 as the canonical id. Mapping both avoids S? holes.
"""
@@ -312,7 +312,7 @@ def _build_phrases(
) -> list[dict]:
"""Group words into phrases by speaker + silence gaps.
- Uses speaker_segments as authoritative for speaker attribution — per-word
+ Uses speaker_segments as authoritative for speaker attribution, because per-word
speaker fields are often noisy at segment boundaries, causing single-word
fragments that make the transcript unreadable.
@@ -483,7 +483,7 @@ def pack_transcript(
lines.append(f"[{_fmt_ts(t)}] {rms:.1f}dB{snippet}")
lines.append("")
- # Laughter & reactions (optional) — the moment BEFORE a laugh is usually the
+ # Laughter & reactions (optional): the moment BEFORE a laugh is usually the
# clippable one, so these timestamps flag where to look for the setup.
if events_data:
def level(e):
diff --git a/backend/services/transcription.py b/backend/services/transcription.py
index fc13cb8..5bac4e3 100644
--- a/backend/services/transcription.py
+++ b/backend/services/transcription.py
@@ -696,7 +696,7 @@ def transcribe_file(
Transcribe a video/audio file with word-level timestamps and speaker detection.
wav_path: optional pre-extracted 16 kHz mono WAV shared across analysis
- stages — used by whisper.cpp and diarization instead of re-decoding.
+ stages: used by whisper.cpp and diarization instead of re-decoding.
start_seconds/duration_seconds: sample mode, transcribe only a window of
the source (e.g. to test a language on 40s before committing to a full
@@ -807,8 +807,8 @@ def _transcribe_file_inner(
)
# Native installs ship whisper.cpp, not openai-whisper. Fall back to it
- # automatically — whether whisper is missing OR a broken install fails to
- # load/run — unless the user explicitly asked for the whisper-py engine.
+ # automatically: whether whisper is missing OR a broken install fails to
+ # load/run: unless the user explicitly asked for the whisper-py engine.
if not use_cpp:
if progress_callback:
progress_callback(5, "Loading Whisper model...")
diff --git a/backend/services/transcription_whispercpp.py b/backend/services/transcription_whispercpp.py
index 7c3b025..c9af547 100644
--- a/backend/services/transcription_whispercpp.py
+++ b/backend/services/transcription_whispercpp.py
@@ -2,7 +2,7 @@
Tokens carry a leading-space convention (" and", continuations have none); we
merge on that boundary and strip word text. The strip must match the rest of the
-pipeline exactly — apply_corrections() and caption spacing key on stripped text.
+pipeline exactly: apply_corrections() and caption spacing key on stripped text.
"""
import json
diff --git a/backend/services/video_cut.py b/backend/services/video_cut.py
index e2211a5..db8024a 100644
--- a/backend/services/video_cut.py
+++ b/backend/services/video_cut.py
@@ -1,4 +1,4 @@
-"""Video cutting helpers — extract time ranges and stitch them together.
+"""Video cutting helpers: extract time ranges and stitch them together.
Extracted from video_processor.py. These are the two entry points used
by the clip generator to slice the source video before any cropping or
diff --git a/backend/services/video_processor.py b/backend/services/video_processor.py
index 378db37..b5f57eb 100644
--- a/backend/services/video_processor.py
+++ b/backend/services/video_processor.py
@@ -64,7 +64,7 @@ import sys
def _manual_crop_x_expr(keyframes: list, crop_w: int, width: int) -> str:
"""Build an FFmpeg x-expression that HOLDS each manual keyframe's position
- until the next keyframe, then snaps (step function — no glide).
+ until the next keyframe, then snaps (step function, no glide).
keyframes: [(t_seconds, center_x_pct 0-100), ...] in clip-relative time.
Returns crop x (top-left) as a function of t, clamped to the frame.
@@ -1200,7 +1200,7 @@ def _face_sample_indices(total_frames: int, fps: float) -> list[int]:
# Memory ceiling for one batch of decoded frames awaiting detection. Sized so
-# a 1080p clip batches ~40 frames and a 4K clip ~10 — enough to keep the pool
+# a 1080p clip batches ~40 frames and a 4K clip ~10, enough to keep the pool
# busy without holding a whole clip of decoded frames in RAM.
_FACE_BATCH_BYTES = 256 * 1024 * 1024
@@ -1218,7 +1218,7 @@ def _face_detect_workers(sample_count: int = 0) -> int:
PODCLI_FACE_WORKERS overrides and is taken literally; 1 disables the pool
entirely, which is the first thing to try when bisecting a framing
regression. Otherwise the count is capped both by cores and by how many
- frames there are to share out — a 2s clip stays serial.
+ frames there are to share out, so a 2s clip stays serial.
"""
raw = os.environ.get("PODCLI_FACE_WORKERS", "").strip()
if raw:
@@ -1235,7 +1235,7 @@ def _detect_batch(batch: list, detectors: list, width: int, height: int, executo
"""Detect faces across a batch of (time, frame) pairs, input order preserved.
Each worker owns one detector and walks its own stride of the batch, so no
- cv2.FaceDetectorYN instance is ever touched by two threads — they carry
+ cv2.FaceDetectorYN instance is ever touched by two threads: they carry
per-instance input-size state and are not thread-safe. Striding (rather
than a shared work queue) also makes the assignment deterministic.
"""
@@ -1279,7 +1279,7 @@ def _dump_crop_path(
No-op unless the env var is set, and never raises: this is diagnostics and
must not be able to fail a render. Frame-level detections are summarised
- rather than dumped whole — the camera path is what a regression would move.
+ rather than dumped whole: the camera path is what a regression would move.
"""
dump_dir = os.environ.get("PODCLI_CROP_DUMP")
if not dump_dir:
@@ -1295,7 +1295,7 @@ def _dump_crop_path(
"detection_frames": len(detections),
"frames_with_faces": sum(1 for _, faces in detections if faces),
"segment_tracks": [
- # (start, end, speaker, track_id, ...) — keep the framing-
+ # (start, end, speaker, track_id, ...): keep the framing-
# relevant fields, drop anything unhashable/verbose.
{"start": round(s[0], 3), "end": round(s[1], 3),
"speaker": s[2], "track_id": s[3]}
@@ -1391,7 +1391,7 @@ def _track_and_crop_inner(
return None
# ── Dense face sampling (~10 fps, 2× at clip start) ──────────
- # grab() advances cheaply, retrieve() decodes only sampled frames — far
+ # grab() advances cheaply, retrieve() decodes only sampled frames, far
# cheaper than a cap.set() seek (keyframe re-decode) per sample.
sample_indices = _face_sample_indices(total_frames, fps)
detections = [] # [(time, faces), ...]
@@ -1509,7 +1509,7 @@ def _track_and_crop_inner(
seg_start = t
if cur_sp:
segments.append((seg_start, duration, cur_sp))
- # Merge short segments (<2s) — brief interjections ("yeah",
+ # Merge short segments (<2s): brief interjections ("yeah",
# "right") shouldn't trigger camera moves. Absorb them into
# the previous speaker's turn so the camera holds steady.
merged = []
@@ -1661,7 +1661,7 @@ def _track_and_crop_inner(
runs = merged_runs
if len(runs) <= 1:
- # Single layout — static crop, no transitions needed
+ # Single layout: static crop, no transitions needed
crop_x = _crop_for(runs[0][2]) if runs else max(0, (width - crop_w) // 2)
vf = f"crop={crop_w}:{crop_h}:{crop_x}:{crop_y},scale={target_w}:{target_h}"
return _run_ffmpeg_with_fallback(
@@ -1729,7 +1729,7 @@ def _track_and_crop_inner(
log_event("crop", "fallback", reason="mixed_steps_failed",
to="dissolve")
- # Multiple layouts — crop each segment separately, join
+ # Multiple layouts: crop each segment separately, join
# with cross-dissolve so transitions feel editorial.
work_dir = os.path.dirname(output_path) or "."
xfade_dur = 0.18 # Short dissolve
@@ -1953,7 +1953,7 @@ def _track_and_crop_inner(
# find the first real face detection and start there instead.
# This catches cases where face_map anchors are stale or wrong.
if segment_targets[0][0] > 0.5:
- # First segment starts late — face detection failed at clip start.
+ # First segment starts late: face detection failed at clip start.
# Find the earliest actual face position to validate default_x.
first_face_cx = None
for _t, _faces in tracked_detections:
@@ -2044,7 +2044,7 @@ def _track_and_crop_inner(
):
target_x = float(speaker_anchor_x[speaker])
else:
- # Hold position — picking the largest random face often grabs the
+ # Hold position: picking the largest random face often grabs the
# wrong speaker and causes a jump.
target_x = None
@@ -2082,7 +2082,7 @@ def _track_and_crop_inner(
crop_right = kf_x + crop_w
margin = crop_w * 0.15 # face should be at least 15% inside
if face_cx < crop_left + margin or face_cx > crop_right - margin:
- # Face not in window — recompute crop to center on face
+ # Face not in window: recompute crop to center on face
new_x = max(0, min(int(face_cx - crop_w // 2), max_crop_x))
validated.append((kf_t, new_x))
continue
@@ -2163,7 +2163,7 @@ def _crop_split_screen(
) -> Optional[str]:
"""
Split-screen crop: cut each speaker segment with a static crop on their
- camera half. No complex expressions — just separate FFmpeg calls + concat.
+ camera half. No complex expressions: just separate FFmpeg calls + concat.
This is how production tools (Opus Clip, Descript, etc.) handle it:
static crop per speaker, hard cut between segments.
@@ -2194,7 +2194,7 @@ def _crop_split_screen(
# to distinguish split-screen frames from single-person frames
left_faces = [] # (cx_in_half, cy)
right_faces = [] # (cx_in_half, cy)
- single_faces = [] # (cx_in_full, cy) — faces from single-person frames
+ single_faces = [] # (cx_in_full, cy): faces from single-person frames
sample_count = min(40, max(10, int(duration * 2)))
split_frame_count = 0
@@ -2239,7 +2239,7 @@ def _crop_split_screen(
adj_h = int(height * 0.75)
adj_w = int(adj_h * target_ratio)
if adj_w > half_w:
- # Zoomed crop wider than half — fall back to full height
+ # Zoomed crop wider than half: fall back to full height
adj_h = height
adj_w = int(height * target_ratio)
@@ -2291,7 +2291,7 @@ def _crop_split_screen(
speakers = sorted(set(w.get("speaker") for w in transcript_words if w.get("speaker")))
if len(speakers) < 2:
- # Single speaker — if mixed layout, prefer fullscreen crop; else use best half
+ # Single speaker: if mixed layout, prefer fullscreen crop; else use best half
if is_mixed and single_faces:
vf = f"crop={single_w}:{single_h}:{single_crop_x}:{single_crop_y},scale={target_w}:{target_h}"
elif len(left_faces) >= len(right_faces):
@@ -2393,7 +2393,7 @@ def _crop_split_screen(
else:
cw, ch, cx, cy = right_w, right_h, right_crop_x, right_crop_y
else:
- # Single-person fullscreen — use full-frame crop (no vertical zoom)
+ # Single-person fullscreen: use full-frame crop (no vertical zoom)
cw, ch, cx, cy = single_w, single_h, single_crop_x, single_crop_y
part_path = os.path.join(work_dir, f"_speaker_part_{i}.mp4")
@@ -2527,7 +2527,7 @@ def _use_face_map(
return None
if len(speakers_in_clip) < 2 or len(clusters) < 2:
- # Single speaker — use their cluster or the dominant one
+ # Single speaker: use their cluster or the dominant one
for sp in speakers_in_clip:
ci = speaker_mappings.get(sp)
if ci is not None and ci < len(clusters):
@@ -2575,7 +2575,7 @@ def _use_face_map(
default_ci = speaker_mappings.get(dominant, 0)
default_x = clusters[min(default_ci, len(clusters) - 1)]["crop_x"]
- # Build keyframes — instant cut for split-screen/hard-cut, smooth pan otherwise
+ # Build keyframes: instant cut for split-screen/hard-cut, smooth pan otherwise
pan_duration = 0.0 if hard_cut or is_split_screen else 0.4
duration = segments[-1][1] if segments else 1.0
keyframes = []
@@ -2590,7 +2590,7 @@ def _use_face_map(
keyframes.append((start_t, prev_x))
keyframes.append((start_t + pan_duration, target_x))
else:
- # Instant snap — single keyframe at new position, no transition frames
+ # Instant snap: single keyframe at new position, no transition frames
keyframes.append((start_t, target_x))
prev_x = target_x
@@ -2717,7 +2717,7 @@ def _build_speaker_aware_crop(
# TRUE split-screen requires presence on both halves AND a real
# horizontal gap between the leftmost and rightmost face (median
# gap > 20% of source width). This filters out in-person podcasts
- # where two heads share one camera near the middle — applying the
+ # where two heads share one camera near the middle, because applying the
# seam clamp there would push centered crops to the edge.
true_split = False
if has_split:
@@ -2748,7 +2748,7 @@ def _build_speaker_aware_crop(
segments.append((seg_start, duration, current_speaker))
if not segments:
- # No speaker data — use median of all faces
+ # No speaker data: use median of all faces
all_cx = [cx for _, faces in frame_data for cx, cy, fw, conf in faces]
all_cy = [cy for _, faces in frame_data for cx, cy, fw, conf in faces]
if all_cx:
@@ -2840,7 +2840,7 @@ def _build_speaker_aware_crop(
"""Compute crop_x and crop_y for a face at (cx, cy).
On TRUE split-screen sources (faces on both halves with a real
- gap between them — Riverside/Squadcast tiles, not in-person
+ gap between them: Riverside/Squadcast tiles, not in-person
shots), clamp crop_x so the frame seam stays outside the 9:16
window. Otherwise the other speaker bleeds into the crop and
the median across frames can land on the gap.
@@ -2849,7 +2849,7 @@ def _build_speaker_aware_crop(
than the winner's half, the clamp falls through (seam_limit < 0
or seam_floor + adj_w > width) and the crop will still include
the seam. That case requires shrinking adj_w upstream, which
- this per-frame helper can't do — leave it to the thumbnail
+ this per-frame helper can't do: leave it to the thumbnail
path, which can resize.
"""
crop_x = cx - adj_w // 2
@@ -3295,7 +3295,7 @@ def concat_outro(
# (keeps playback natural even when xfade is unavailable/fails).
#
# Both audio streams MUST be normalized to the same sample rate,
- # channel layout, and sample format before `concat` — otherwise
+ # channel layout, and sample format before `concat`, otherwise
# ffmpeg fails with rc=234 ("at least one of its streams received
# no packets"), which the old code silently swallowed and then
# cascaded into the pure-concat fallback.
@@ -3462,7 +3462,7 @@ def _detect_face_center(
crop_h: int = None,
) -> Optional[tuple]:
"""
- Simple static face detection — finds the dominant face and returns a
+ Simple static face detection: finds the dominant face and returns a
STATIC crop position that centers the face horizontally. No tracking,
no panning. The face stays centered for the entire clip.
@@ -3532,7 +3532,7 @@ def _detect_face_center(
right_count = np.sum(positions >= mid_x)
if left_count >= 3 and right_count >= 3:
- # Split-screen — pick the side with the most detections,
+ # Split-screen: pick the side with the most detections,
# clamp crop to that half with margin away from seam.
seam_margin = 20
if left_count >= right_count:
@@ -3565,7 +3565,7 @@ def _detect_face_offset(
crop_h: int = None,
) -> Optional[tuple]:
"""
- Continuous face tracking — detects face position over time and returns
+ Continuous face tracking: detects face position over time and returns
an FFmpeg expression that smoothly follows the dominant face.
Samples frames throughout the clip, picks the dominant face cluster,
@@ -3658,7 +3658,7 @@ def _detect_face_offset(
# Filter to only dominant face detections
tracked = [(t, cx) for i, (t, cx) in enumerate(timed_positions) if i in dominant_indices]
if len(tracked) < 3:
- # Too few points — use static median
+ # Too few points: use static median
median_x = int(np.median([cx for _, cx in tracked]))
crop_x = max(0, min(median_x - crop_w // 2, width - crop_w))
return (str(crop_x), median_cy)
@@ -3674,7 +3674,7 @@ def _detect_face_offset(
], dtype=float)
# 2) Fill gaps: if face wasn't detected for some frames, the tracked
- # array has gaps. That's fine — we interpolate between known points.
+ # array has gaps. That's fine: we interpolate between known points.
# 3) Heavy smoothing to prevent jitter. Use a 2.5-second rolling average
# so only sustained movement (leaning, shifting) affects the crop.
@@ -3694,7 +3694,7 @@ def _detect_face_offset(
# --- Check if tracking is even needed ---
# If the face barely moves (range < 20% of crop width), just use static.
- # Most podcast clips have speakers sitting still — tracking should be rare.
+ # Most podcast clips have speakers sitting still. Tracking should be rare.
movement_range = int(smoothed.max() - smoothed.min())
if movement_range < crop_w * 0.20:
return (str(int(np.median(smoothed))), median_cy)
@@ -3732,7 +3732,7 @@ def _detect_face_offset(
t1, x1 = keyframes[i + 1]
dt = max(0.01, t1 - t0)
if x0 == x1:
- # No movement in this segment — constant
+ # No movement in this segment: constant
expr_parts.append(f"if(lt(t\\,{t1:.2f})\\,{x0}\\,")
else:
# Linear interpolation
@@ -3743,7 +3743,7 @@ def _detect_face_offset(
# Cap nesting depth
if len(expr_parts) > 40:
- # Too many keyframes — subsample
+ # Too many keyframes: subsample
step = len(keyframes) // 20
keyframes = keyframes[::step] + [keyframes[-1]]
# Rebuild (recursive call would be cleaner but let's just return static)
diff --git a/backend/utils/log.py b/backend/utils/log.py
index d43758b..5e94a63 100644
--- a/backend/utils/log.py
+++ b/backend/utils/log.py
@@ -2,7 +2,7 @@
The render pipeline previously scattered `print(..., file=sys.stderr)` calls
with inconsistent prefixes, which made it hard to answer the most common
-question — "why was this clip framed/encoded this way?". Routing those through
+question: "why was this clip framed/encoded this way?". Routing those through
`log_event` gives every line a `[category]` prefix and `key=value` fields so the
chosen path is always visible (and easy to grep) without a debugger.
"""
@@ -51,7 +51,7 @@ def timed(category: str, stage: str, **fields):
"""Time a block and emit `[category] timing stage=... ms=...` on exit.
Debug level, so stage timings stay silent unless PODCLI_LOG_VERBOSE is set.
- Emits on failure too — a stage that blows up after 40s is exactly the one
+ Emits on failure too: a stage that blows up after 40s is exactly the one
worth seeing. Yields a dict the caller can add fields to before the line is
written, for counts that are only known once the block has run.
"""
diff --git a/backend/utils/prompt_files.py b/backend/utils/prompt_files.py
index e57ea7b..3efeb26 100644
--- a/backend/utils/prompt_files.py
+++ b/backend/utils/prompt_files.py
@@ -4,7 +4,7 @@ The Claude/Codex CLIs need a file they can read for the prompt. Writing
these to the repo root (as several call sites used to do via
`tempfile.NamedTemporaryFile(dir=project_dir)`) litters the working
directory with `tmp*.txt` files whenever a process crashes before the
-cleanup block runs — which is how we accumulated 150+ stale files.
+cleanup block runs: which is how we accumulated 150+ stale files.
Route them through `<podcli_home>/tmp/` instead:
- Under the gitignored config home, so no risk of accidental commits.
diff --git a/backend/utils/text.py b/backend/utils/text.py
index 9d481c0..8984811 100644
--- a/backend/utils/text.py
+++ b/backend/utils/text.py
@@ -28,7 +28,7 @@ def safe_upper(text: str) -> str:
return text.upper() if text else text
return "".join(c if _is_caseless_script_char(c) else c.upper() for c in text)
-_TRAILING_PUNCT = " ,;:-–—"
+_TRAILING_PUNCT = " ,;:-\u2013\u2014"
# Windows refuses these as a filename stem whatever the extension, so "CON.fcpxml"
# fails just as "CON" does.
diff --git a/cli/internal/backend/embed.go b/cli/internal/backend/embed.go
index eb14867..1bdc540 100644
--- a/cli/internal/backend/embed.go
+++ b/cli/internal/backend/embed.go
@@ -1,7 +1,7 @@
// Package backend ships the Python processing backend inside the launcher
// binary so an installed podcli runs without the source repo. The files/ tree is
// synced from the repo backend/ at build time (`go generate ./...` or CI) and is
-// gitignored — never edit files/ by hand.
+// gitignored: never edit files/ by hand.
package backend
import (
diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go
index 09103cd..6fcc181 100644
--- a/cli/internal/config/config.go
+++ b/cli/internal/config/config.go
@@ -18,6 +18,7 @@ type Config struct {
Latest string `json:"latest,omitempty"`
CheckedAt string `json:"checkedAt,omitempty"`
} `json:"update"`
+ Engine string `json:"engine,omitempty"`
}
func Load() Config {
@@ -76,6 +77,12 @@ func RecordUpdateCheck(latest string) {
c.Save()
}
+// DefaultEngine is the transcription engine used when neither --engine nor
+// PODCLI_ENGINE is set. Empty means the launcher picks one.
+func DefaultEngine() string {
+ return Load().Engine
+}
+
func Get(key string) (string, error) {
switch key {
case "update.auto":
@@ -83,8 +90,10 @@ func Get(key string) (string, error) {
return "off", nil
}
return "on", nil
+ case "engine":
+ return Load().Engine, nil
}
- return "", fmt.Errorf("unknown config key %q (known: update.auto)", key)
+ return "", fmt.Errorf("unknown config key %q (known: update.auto, engine)", key)
}
func Set(key, val string) error {
@@ -94,8 +103,12 @@ func Set(key, val string) error {
c := Load()
c.Update.Auto = &on
return c.Save()
+ case "engine":
+ c := Load()
+ c.Engine = strings.ToLower(strings.TrimSpace(val))
+ return c.Save()
}
- return fmt.Errorf("unknown config key %q (known: update.auto)", key)
+ return fmt.Errorf("unknown config key %q (known: update.auto, engine)", key)
}
func offValue(s string) bool {
diff --git a/cli/internal/engine/engine.go b/cli/internal/engine/engine.go
index 4e8a5a5..dc41c7e 100644
--- a/cli/internal/engine/engine.go
+++ b/cli/internal/engine/engine.go
@@ -168,7 +168,7 @@ func SyncScript() string {
func RunSync() (int, error) {
node, script := Node(), SyncScript()
if node == "" || script == "" {
- return 1, fmt.Errorf("sync not provisioned — run `podcli setup`")
+ return 1, fmt.Errorf("sync not provisioned: run `podcli setup`")
}
cmd := exec.Command(node, script)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
@@ -209,7 +209,7 @@ func nodeEnv() []string {
func RunMCP() (int, error) {
node, server := Node(), MCPServer()
if node == "" || server == "" {
- return 1, fmt.Errorf("MCP server not provisioned — run `podcli setup`")
+ return 1, fmt.Errorf("MCP server not provisioned: run `podcli setup`")
}
cmd := exec.Command(node, server)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
@@ -254,7 +254,7 @@ func DataEnv() []string {
func Run(args []string) (int, error) {
root, ok := BackendRoot()
if !ok {
- return 1, fmt.Errorf("python backend not found — set PODCLI_BACKEND or run inside the repo")
+ return 1, fmt.Errorf("python backend not found: set PODCLI_BACKEND or run inside the repo")
}
cli := filepath.Join(root, "cli.py")
full := append([]string{"-W", "ignore::UserWarning", cli}, args...)
diff --git a/cli/internal/podstack/podstack.go b/cli/internal/podstack/podstack.go
index 16e008d..a789384 100644
--- a/cli/internal/podstack/podstack.go
+++ b/cli/internal/podstack/podstack.go
@@ -375,7 +375,7 @@ func Run(cmd string, args []string) int {
switch engine {
case "auto", "claude", "codex":
default:
- fmt.Fprintf(os.Stderr, " %sInvalid AI engine:%s %s — use --claude, --codex, or --ai auto\n", colBold, colReset, engine)
+ fmt.Fprintf(os.Stderr, " %sInvalid AI engine:%s %s: use --claude, --codex, or --ai auto\n", colBold, colReset, engine)
return 1
}
diff --git a/cli/internal/provision/provision.go b/cli/internal/provision/provision.go
index 143fd95..8b6ab9d 100644
--- a/cli/internal/provision/provision.go
+++ b/cli/internal/provision/provision.go
@@ -649,7 +649,7 @@ func downloadOnce(url, tmp, label string, client *http.Client) (bool, error) {
case http.StatusRequestedRangeNotSatisfiable:
return true, nil // already complete on disk
case http.StatusOK:
- if start > 0 { // server ignored Range or the file changed — restart cleanly
+ if start > 0 { // server ignored Range or the file changed: restart cleanly
os.Truncate(tmp, 0)
start = 0
}
@@ -716,7 +716,7 @@ func (g *stallGuard) stop() { g.timer.Stop() }
// symlinkTargetInside reports whether a symlink at linkPath pointing to linkname
// resolves within root (root has a trailing separator). Absolute targets and
-// any path that escapes via .. are rejected — this is the symlink half of the
+// any path that escapes via .. are rejected. This is the symlink half of the
// zip-slip defense, since the path guard alone only validates the link's own
// location, not where it points.
func symlinkTargetInside(linkPath, linkname, root string) bool {
@@ -783,21 +783,9 @@ type ffArchive struct {
}
// Pinned, versioned upstream archives, verified by SHA-256 before extraction.
-// darwin/arm64 is absent on purpose: evermeet.cx only builds x86_64, so Apple
-// Silicon is served by our own release asset (see releaseFFmpeg).
+// darwin is absent on purpose: Intel Macs are unsupported and Apple Silicon is
+// served by our own release asset (see releaseFFmpeg).
var ffmpegSpecs = map[string][]ffArchive{
- "darwin/amd64": {
- {
- URL: "https://evermeet.cx/ffmpeg/ffmpeg-8.1.2.zip",
- SHA256: "e91df72a1ee7c26606f90dd2dd4dcccc6a75140ff9ea6fdd50faae828b82ba69",
- Bins: []string{"ffmpeg"},
- },
- {
- URL: "https://evermeet.cx/ffmpeg/ffprobe-8.1.2.zip",
- SHA256: "399b93f0b9862f69767afa343e90c2f48d7e7958cadbb6deb76a012d0e3b7ce3",
- Bins: []string{"ffprobe"},
- },
- },
"linux/amd64": {
{
URL: "https://johnvansickle.com/ffmpeg/old-releases/ffmpeg-6.0.1-amd64-static.tar.xz",
@@ -1274,9 +1262,12 @@ func pythonRoot(bin string) string {
}
// pythonAssetURL resolves a python-build-standalone install_only tarball for
-// this platform via the GitHub latest-release API, so it tracks upstream
-// without a hardcoded version that rots.
-var pythonReleasesAPI = "https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest"
+// this platform from one pinned release tag, so every install gets the same
+// interpreter. Bump pythonReleaseTag deliberately; its SHA256SUMS asset
+// supplies the checksum.
+const pythonReleaseTag = "20261026"
+
+var pythonReleasesAPI = "https://api.github.com/repos/astral-sh/python-build-standalone/releases/tags/" + pythonReleaseTag
func pythonAssetURL() (url, name, sumsURL string, err error) {
triple, ok := pyTriples[runtime.GOOS+"/"+runtime.GOARCH]
@@ -1416,15 +1407,16 @@ func ensurePip(pybin string) error {
}
// EnsureSpeakerDeps installs the speaker-diarization stack (pyannote.audio pulls
-// torch) into the hermetic Python. Opt-in because it's a large download (~2GB)
-// most users don't need.
+// torch) plus openai-whisper into the hermetic Python. whisper.cpp skips
+// diarization, so the openai-whisper engine has to come with it. Opt-in
+// because it's a large download (~2GB) most users don't need.
func EnsureSpeakerDeps() error {
bin := PythonBin()
if !have(bin) {
return fmt.Errorf("python not provisioned - run `podcli setup` first")
}
- fmt.Fprintln(os.Stderr, " installing speaker deps (pyannote.audio + torch) - large download (~2GB), several minutes")
- cmd := exec.Command(bin, "-m", "pip", "install", "--disable-pip-version-check", "--progress-bar=on", "pyannote.audio>=3.1.0", "speechbrain")
+ fmt.Fprintln(os.Stderr, " installing speaker deps (openai-whisper + pyannote.audio + torch) - large download (~2GB), several minutes")
+ cmd := exec.Command(bin, "-m", "pip", "install", "--disable-pip-version-check", "--progress-bar=on", "openai-whisper", "pyannote.audio>=3.1.0", "speechbrain")
cmd.Stdout, cmd.Stderr = os.Stderr, os.Stderr
cmd.Env = append(os.Environ(), "PYTHONUNBUFFERED=1")
return cmd.Run()
diff --git a/cli/main.go b/cli/main.go
index 739cdb7..4ba4ea8 100644
--- a/cli/main.go
+++ b/cli/main.go
@@ -360,6 +360,9 @@ func transcribeEngine(args []string) string {
sel = strings.ToLower(strings.TrimPrefix(a, "--engine="))
}
}
+ if sel == "" {
+ sel = config.DefaultEngine()
+ }
if sel == "" && engine.IsHermeticPython() {
sel = "whispercpp"
}
@@ -408,7 +411,7 @@ func setup(args []string) int {
return 1
}
backendDir = fallback
- fmt.Fprintf(os.Stderr, " backend: using fallback %s (may be stale — run `podcli doctor`)\n", backendDir)
+ fmt.Fprintf(os.Stderr, " backend: using fallback %s (may be stale: run `podcli doctor`)\n", backendDir)
} else {
fmt.Printf(" backend: %s\n", backendDir)
}
@@ -449,7 +452,11 @@ func setup(args []string) int {
fmt.Fprintf(os.Stderr, " speakers: failed (%v)\n", err)
return 1
}
- fmt.Printf(" speakers: pyannote.audio installed (set HF_TOKEN to use)\n")
+ if err := config.Set("engine", "whisper-py"); err != nil {
+ fmt.Fprintf(os.Stderr, " speakers: could not save engine setting (%v)\n", err)
+ return 1
+ }
+ fmt.Printf(" speakers: openai-whisper + pyannote.audio installed, default engine set to whisper-py (set HF_TOKEN to use; `podcli config set engine whispercpp` reverts)\n")
}
if wc, err := provision.EnsureWhisperCpp(); err != nil {
fmt.Fprintf(os.Stderr, " whisper: skipped (%v) - backend will use PATH whisper-cli\n", err)
@@ -1200,7 +1207,7 @@ Launcher commands:
update Check for and apply a newer release
uninstall Remove podcli app files (keeps user data unless --purge)
setup [--model base] [--vad] [--speakers]
- Provision runtimes + models (--speakers adds pyannote+torch, ~2GB)
+ Provision runtimes + models (--speakers adds openai-whisper, pyannote, torch, ~2GB)
setup --refresh Re-provision runtimes for this launcher version, skipping models
mcp Run the MCP server (stdio) for Claude/Codex
mcp install Register the MCP server with Claude Code and Codex
@@ -1209,7 +1216,7 @@ Launcher commands:
process --json --yes writes one JSON object to stdout and skips prompts.
--help and --version never download. First run of process, studio, transcribe,
-or multicam provisions the engine. podcli mcp does not — stdout is JSON-RPC —
+or multicam provisions the engine. podcli mcp does not, because stdout is JSON-RPC.
so run podcli setup first.
Exit codes: 0 success, 1 runtime or processing error, 2 usage, 130 interrupted.
diff --git a/docs/clips-schema.md b/docs/clips-schema.md
index 7ad2a75..cb759b5 100644
--- a/docs/clips-schema.md
+++ b/docs/clips-schema.md
@@ -2,9 +2,9 @@
`clips.json` is a flat JSON array of clip records, shared on disk by two writers:
-- **TypeScript** — `src/services/clips-history.ts` (`ClipsHistory`), writes one entry per render
+- **TypeScript**: `src/services/clips-history.ts` (`ClipsHistory`), writes one entry per render
from the web server and MCP server.
-- **Python** — `backend/services/clips_history.py`, the CLI writer (`clips edit`/`reopen`) and the
+- **Python**: `backend/services/clips_history.py`, the CLI writer (`clips edit`/`reopen`) and the
Phase 2 analytics writer.
The TS type is `ClipHistoryEntry` in `src/models/index.ts`. Keep both languages in sync with this table.
@@ -25,13 +25,13 @@ The TS type is `ClipHistoryEntry` in `src/models/index.ts`. Keep both languages
| `duration` | number | TS render | |
| `created_at` | string (ISO) | TS render | |
| `content_type` | string? | TS render | Carried from the suggestion (`guest_story`, `hot_take`, …). Undefined when no suggestion was used. |
-| `transcript_slice` | string? | TS render | Plain text the clip says. The session transcript is overwritten, so this is the **only durable** copy — never reconstruct it later. |
+| `transcript_slice` | string? | TS render | Plain text the clip says. The session transcript is overwritten, so this is the **only durable** copy: never reconstruct it later. |
| `payoff` | string? | TS render | Carried from the suggestion. The clip's payoff line; grounds thumbnail headline copy. |
| `context_line` | string? | TS render | Carried from the suggestion. The question the clip answers, if any. |
| `preview_text` | string? | TS render | Carried from the suggestion. The clip's verbatim opening line. |
| `thumbnail_config` | object? | TS render / edit | Per-clip thumbnail settings (`line1`, `line2`, `image_path`, `timestamp`, `preview_path`, `variations`). |
| `youtube_video_id` | string? | Phase 2 | Set when a published video is linked. |
-| `metrics` | object? | Phase 2 | `{ views?, retention?, ctr?, impressions?, fetched_at? }`. retention/ctr are 0–100. |
+| `metrics` | object? | Phase 2 | `{ views?, retention?, ctr?, impressions?, fetched_at? }`. retention/ctr are 0-100. |
## Writer contract
@@ -39,5 +39,5 @@ The TS type is `ClipHistoryEntry` in `src/models/index.ts`. Keep both languages
- **Read-modify-write, preserve unknown keys.** A writer in one language must never drop fields it
doesn't know about (e.g. the CLI editing a title must not clobber a Phase 2 `metrics` block).
`update_clip` applies only non-`None` fields onto the loaded entry.
-- **No file locking.** Single-user localhost tool; TS writes on render, Python writes on edit — not
+- **No file locking.** Single-user localhost tool; TS writes on render, Python writes on edit, not
concurrent in practice. Do not add locking.
diff --git a/docs/configuration.md b/docs/configuration.md
index f72a629..15cd737 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -12,13 +12,14 @@ Copy `.env.example` to `.env`, or export these in your shell. `setup.sh` copies
| `PODCLI_QUALITY` | `high` | Render quality profile |
| `PODCLI_NO_UPDATE` | unset | Set to `1` to skip the update check. Same as `podcli config set update.auto off` |
| `PODCLI_LOG_LEVEL` | `info` | Logging verbosity |
+| `PODCLI_CLOUD_SYNC` | unset (off) | Set to `1` to upload each rendered clip video and transcript slice to your podcli Pro workspace. Applies only when signed in |
| `PODCLI_PORT` | `3847` | Web studio port. `PORT` also works. Set it in the MCP client's env too, or the MCP tools render without live studio progress |
| `HF_TOKEN` | unset | Hugging Face token, required for speaker diarization |
| `PODCLI_ENV_FILE` | `./.env` | Path to an alternate `.env` |
| `PODCLI_BACKEND` | resolved | Override the Python backend directory |
| `PODCLI_PYTHON` | resolved | Override the Python interpreter. The launcher exports the resolved path as `PYTHON_PATH` for internal use |
| `PODCLI_TRANSITION_AUTOFIX_PASSES` | auto | Transition QA/autofix passes. Runs only on reframes that can produce hard cuts. Set a number to force it, `0` disables; the renderer caps it at 2 |
-| `PODCLI_FACE_WORKERS` | auto | Threads used for face detection during reframing. Auto sizes by core count (max 12) and by clip length, so short clips stay serial rather than paying to build detectors they cannot amortize. Set `1` to force serial — the first thing to try when bisecting a framing regression, since it changes speed only, never the result |
+| `PODCLI_FACE_WORKERS` | auto | Threads used for face detection during reframing. Auto sizes by core count (max 12) and by clip length, so short clips stay serial rather than paying to build detectors they cannot amortize. Set `1` to force serial, the first thing to try when bisecting a framing regression, since it changes speed only, never the result |
| `PODCLI_CROP_DUMP` | unset | Directory to write each clip's computed camera path to as `<clip>.crop.json`. Diagnostics only; use it to diff framing decisions before and after a change |
| `FFMPEG_PATH` / `FFPROBE_PATH` | `ffmpeg` / `ffprobe` | Override the FFmpeg binaries |
diff --git a/docs/limitations.md b/docs/limitations.md
index d640dd4..f1a5a0f 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -9,9 +9,9 @@ behavior, not a roadmap.
fine GCC-PHAT match with linear clock-drift correction
(`backend/services/multicam_signal.py`). There is no timecode-based sync;
embedded timecode is read as session metadata only
- (`backend/services/multicam.py:278-282`).
+ (`_timecode_seconds` in `backend/services/multicam.py`).
- A camera with no audio track cannot be synced automatically. Its offset
- must be set by hand (`backend/services/multicam.py:1082`).
+ must be set by hand (`update_mapping` in `backend/services/multicam.py`).
- Remote call recordings (Zoom, Riverside, one file per person) are assumed
to start together, since there's no shared audio to cross-correlate
against.
@@ -41,7 +41,7 @@ behavior, not a roadmap.
`compare_transcription_engines`.
- Speaker diarization runs on the `whisper-py` and `assemblyai` paths.
`whispercpp` and `omnilingual` never produce speaker labels. Every word comes back with
- `speaker: null` (`backend/services/transcription_whispercpp.py:67,215`).
+ `speaker: null` (`_tokens_to_words` and `transcribe_file` in `backend/services/transcription_whispercpp.py`).
- Diarization needs `HF_TOKEN` set (see `docs/configuration.md`). Without
it, or if diarization fails for any other reason, transcription still
completes. It just comes back with no speaker labels, degrading
diff --git a/docs/thumbnail-config.example.json b/docs/thumbnail-config.example.json
index f0ed77b..0bcec37 100644
--- a/docs/thumbnail-config.example.json
+++ b/docs/thumbnail-config.example.json
@@ -81,6 +81,6 @@
"variation_offset_up": "3%",
"variation_offset_down": "2%",
- "_comment_pre_clip_thumbnail": "How long the still thumbnail plays at the start of the rendered short before the live video begins. 0.5–1.0s is the sweet spot.",
+ "_comment_pre_clip_thumbnail": "How long the still thumbnail plays at the start of the rendered short before the live video begins. 0.5-1.0s is the sweet spot.",
"intro_duration": 0.8
}
diff --git a/llms.txt b/llms.txt
index e727f09..06c96ca 100644
--- a/llms.txt
+++ b/llms.txt
@@ -21,7 +21,7 @@ Clip scoring uses Claude Code or Codex login, or an Anthropic API key; without t
## First run
`podcli process episode.mp4` (or studio / transcribe / multicam) provisions the engine on first run.
-`podcli mcp` does not — stdout is JSON-RPC. Run `podcli setup` once before pointing an agent at it.
+`podcli mcp` does not: stdout is JSON-RPC. Run `podcli setup` once before pointing an agent at it.
`--help` and `--version` never download anything.
## Agent CLI
diff --git a/package-lock.json b/package-lock.json
index bdef6be..5d041a8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,9 +11,9 @@
"dependencies": {
"@fontsource/dm-sans": "^5.3.0",
"@modelcontextprotocol/sdk": "^1.30.0",
- "@remotion/bundler": "^4.0.508",
- "@remotion/cli": "^4.0.508",
- "@remotion/renderer": "^4.0.490",
+ "@remotion/bundler": "4.0.508",
+ "@remotion/cli": "4.0.508",
+ "@remotion/renderer": "4.0.508",
"dotenv": "^17.4.2",
"express": "^5.2.1",
"lucide-react": "^1.31.0",
@@ -21,12 +21,13 @@
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.2",
- "remotion": "^4.0.490",
+ "remotion": "4.0.508",
"uuid": "^14.0.1",
"winston": "^3.17.0",
"zod": "^4.4.3"
},
"devDependencies": {
+ "@oxlint/plugins": "1.78.0",
"@types/express": "^5.0.0",
"@types/multer": "^2.2.0",
"@types/node": "^26.2.0",
@@ -34,6 +35,7 @@
"@types/react-dom": "^19.2.4",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.7.0",
+ "oxlint": "1.78.0",
"tsx": "^4.23.12",
"typescript": "^7.0.2",
"vite": "^5.4.21",
@@ -1096,6 +1098,366 @@
"url": "https://github.com/sponsors/Boshen"
}
},
+ "node_modules/@oxlint/binding-android-arm-eabi": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.78.0.tgz",
+ "integrity": "sha512-Bu819lmAfZMUHErrpe0cEWj3iaefuUODHSU8+UbXy67V/r7/7f4K3FL0NmbD85E+wiFLDYuhP8Zlv0XnVeXshw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm64": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.78.0.tgz",
+ "integrity": "sha512-CDfxZgB61B7buRdY2FJoAYYPPXCZ1EoC1LKscnC5dg3kjobdxiconvAvvN1BmHyW4PyFT3jRLDag/BY/roSNBQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-arm64": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.78.0.tgz",
+ "integrity": "sha512-2Y2U9Ahrz+OO0Ej88f9SJYq51/jUBp1Mc7iZu0ukrbeeZ3gpRGfzIFnoqfHDY96xr0GEfNrPUBFEy0nN5aD7HA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-x64": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.78.0.tgz",
+ "integrity": "sha512-rpych6eJq6m9jDRypTEaPD1xysaEW5h9+xuxhGK/QhOg+/xaqPZrCrTNoIl/f3nEjuJeCEmstNDlrE9rJi/3/g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-freebsd-x64": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.78.0.tgz",
+ "integrity": "sha512-IcMGrQT3QizkOESUJd5et+rOhVqSkNDfNik1cvrKDqIbzqx9KMtRswpFgkCuNTSwylCFLKhGUu8KmqY1ZnC0Dg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-gnueabihf": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.78.0.tgz",
+ "integrity": "sha512-/uLdoJ0IXE6vo/0f0LKjinQAp+re+VMaCWaNT8ENIv2EOCkSsc8SGaflXAuW0Jua2dq5+GLVWm1NQK7P3UFSNQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-musleabihf": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.78.0.tgz",
+ "integrity": "sha512-7xi4Wb/O8NRJhLoUXmDJMUVpNYvB5kefdhFU1Jb8rtae4QoXlTiLwI14X4YvAXVZLNZChP8m5qO9SQAlWQTbkQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-gnu": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.78.0.tgz",
+ "integrity": "sha512-4hFW0+fVXa3OIh1Y4A5SPkmvI4wuuBSrCVKzOyE7PTjhc7yEqZ1pmvEEeS5Lj/MaqvegFxXyF33N+6jkehxdyg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-musl": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.78.0.tgz",
+ "integrity": "sha512-oC0mvsgBJjlMijSDEhx9KuvR9zYeHXceA9MjbuXB1F8NSR78Yj2unOBrstEvTVaq+pko+kuue6DajC00eqvTdg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-ppc64-gnu": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.78.0.tgz",
+ "integrity": "sha512-XAllT5SUZS+ohjuZ3/5S0cwe0r7eboiuigeStCZ5DXRYx/2KVM2UvQXvAfyzXEimtQjAB7cDQ2YxDe2Zl2WNQQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-gnu": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.78.0.tgz",
+ "integrity": "sha512-trucMER/0QtecoXvc1y/UVqE3kwJipDwrx4oHfj+nNm3dq2zjP44WT0CfHNDPM3G1DXIkx/gY6lAD21NSCZVhA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-musl": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.78.0.tgz",
+ "integrity": "sha512-cm3O4F/HQbdzOUX5mKHqG5KDL6E5w0pnlZ+fbBy2rmLryPOowkuLagFHTopQsEIpjcaZoPOrL+BmmAytAG9HFg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-s390x-gnu": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.78.0.tgz",
+ "integrity": "sha512-33wRf6HqGNsybJ3qX4cGaQN2ODPxNmc1rMa0mrTmx3eFq1VzOnvQooi9bIGVYakW8a/wmqVx1mgsUm8R2xfTiw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-gnu": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.78.0.tgz",
+ "integrity": "sha512-rRdISSYegj6VganMZ9tjRjijowfHJ09IZU01i0toBAqr6n5LEtwHq2IeS4FjW2RoskOHlb6efB26H5izYb3GEQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-musl": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.78.0.tgz",
+ "integrity": "sha512-GmsP4rW0xTL6u5CVdcDsaN5Fbc7hBc382Wmar1kttbnwSEviM+rSINKOMQ+UQ6iH+AGwC+8gaAiwu134Tgh6Lg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-openharmony-arm64": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.78.0.tgz",
+ "integrity": "sha512-sy9yeYuADc8a+n4TLBayzMCZiHPW78DcIFVpOXTmdKHWQeM9xe5uzkqIIZmi326D5hY9XVwacipEB1p7tQjPAg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-arm64-msvc": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.78.0.tgz",
+ "integrity": "sha512-rjc2hF1KfMi8fZj1X/m3AmnHbdsF3rL0v6KQg0Uc880Yb2khjz+3U14sfdZ7jWTpRnN1m1NQa/TT7uU9lJWPrA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-ia32-msvc": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.78.0.tgz",
+ "integrity": "sha512-zcuXFVrEFHIafRfkCQT8w/Xe41o07ozl/vwHq7p94vB29xVzsB0sZGYORU1jhcYKv3Lr0J3HbJ2T4fHH5rWmvA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-x64-msvc": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.78.0.tgz",
+ "integrity": "sha512-Sb5ocmLSuYeOuXd+CFOToGKp/gjXUEWDnvIGwhnh8aq8wY4TMmEnKnvbogSW7RdMZv77JSARduS7/gv+khYEjA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/plugins": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/plugins/-/plugins-1.78.0.tgz",
+ "integrity": "sha512-Ypt8KeRYw+4jUtlPirfcHWMrn5ms12VrrFPD+Mds477/7tJxG1Kcz2Yrg2nVcTQEUx/GdlhS+BUg1kmxNm04Ug==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ }
+ },
"node_modules/@remotion/bundler": {
"version": "4.0.508",
"resolved": "https://registry.npmjs.org/@remotion/bundler/-/bundler-4.0.508.tgz",
@@ -5693,6 +6055,55 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/oxlint": {
+ "version": "1.78.0",
+ "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.78.0.tgz",
+ "integrity": "sha512-QgQePuxIqKOzo1KSjG2EnITEeWvWnKAm77eq8nrMtf6AGoA+zyGc4PFYtDNJSD25g/ibOwfQ851hZ4/SPkMVoA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "oxlint": "bin/oxlint"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxlint/binding-android-arm-eabi": "1.78.0",
+ "@oxlint/binding-android-arm64": "1.78.0",
+ "@oxlint/binding-darwin-arm64": "1.78.0",
+ "@oxlint/binding-darwin-x64": "1.78.0",
+ "@oxlint/binding-freebsd-x64": "1.78.0",
+ "@oxlint/binding-linux-arm-gnueabihf": "1.78.0",
+ "@oxlint/binding-linux-arm-musleabihf": "1.78.0",
+ "@oxlint/binding-linux-arm64-gnu": "1.78.0",
+ "@oxlint/binding-linux-arm64-musl": "1.78.0",
+ "@oxlint/binding-linux-ppc64-gnu": "1.78.0",
+ "@oxlint/binding-linux-riscv64-gnu": "1.78.0",
+ "@oxlint/binding-linux-riscv64-musl": "1.78.0",
+ "@oxlint/binding-linux-s390x-gnu": "1.78.0",
+ "@oxlint/binding-linux-x64-gnu": "1.78.0",
+ "@oxlint/binding-linux-x64-musl": "1.78.0",
+ "@oxlint/binding-openharmony-arm64": "1.78.0",
+ "@oxlint/binding-win32-arm64-msvc": "1.78.0",
+ "@oxlint/binding-win32-ia32-msvc": "1.78.0",
+ "@oxlint/binding-win32-x64-msvc": "1.78.0"
+ },
+ "peerDependencies": {
+ "oxlint-tsgolint": ">=7.0.2001",
+ "vite-plus": "*"
+ },
+ "peerDependenciesMeta": {
+ "oxlint-tsgolint": {
+ "optional": true
+ },
+ "vite-plus": {
+ "optional": true
+ }
+ }
+ },
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
diff --git a/package.json b/package.json
index 80d2d34..d0d9b54 100644
--- a/package.json
+++ b/package.json
@@ -32,14 +32,15 @@
"remotion:prebundle": "node remotion/render.mjs --prebundle",
"remotion:studio": "npx remotion studio remotion/src/index.ts",
"test": "vitest run",
- "test:watch": "vitest"
+ "test:watch": "vitest",
+ "lint": "oxlint"
},
"dependencies": {
"@fontsource/dm-sans": "^5.3.0",
"@modelcontextprotocol/sdk": "^1.30.0",
- "@remotion/bundler": "^4.0.508",
- "@remotion/cli": "^4.0.508",
- "@remotion/renderer": "^4.0.490",
+ "@remotion/bundler": "4.0.508",
+ "@remotion/cli": "4.0.508",
+ "@remotion/renderer": "4.0.508",
"dotenv": "^17.4.2",
"express": "^5.2.1",
"lucide-react": "^1.31.0",
@@ -47,12 +48,13 @@
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.2",
- "remotion": "^4.0.490",
+ "remotion": "4.0.508",
"uuid": "^14.0.1",
"winston": "^3.17.0",
"zod": "^4.4.3"
},
"devDependencies": {
+ "@oxlint/plugins": "1.78.0",
"@types/express": "^5.0.0",
"@types/multer": "^2.2.0",
"@types/node": "^26.2.0",
@@ -60,6 +62,7 @@
"@types/react-dom": "^19.2.4",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.7.0",
+ "oxlint": "1.78.0",
"tsx": "^4.23.12",
"typescript": "^7.0.2",
"vite": "^5.4.21",
diff --git a/plans/horizontal-clips.md b/plans/horizontal-clips.md
index 9cdacac..90d079f 100644
--- a/plans/horizontal-clips.md
+++ b/plans/horizontal-clips.md
@@ -34,16 +34,16 @@ So the work splits in two: **selection** (a second scoring profile + a dialogue-
## Verified coupling inventory
-An adversarial audit (7 parallel readers + 8 refutation passes + synthesis) found the real surface is **~31 distinct aspect-ratio coupling sites (~56 raw literals, ~66 edit points including format threading + duration caps)**, not the 8 originally mapped. The audit **refuted 4 design assumptions** — those corrections are baked into the phases below:
+An adversarial audit (7 parallel readers + 8 refutation passes + synthesis) found the real surface is **~31 distinct aspect-ratio coupling sites (~56 raw literals, ~66 edit points including format threading + duration caps)**, not the 8 originally mapped. The audit **refuted 4 design assumptions**. Those corrections are baked into the phases below:
1. **Captions are NOT relative.** `HormoziCaptions`/`SubtleCaptions`/`KaraokeCaptions` read only `fps` from `useVideoConfig()`; `BrandedCaptions` also reads `height` (only for a face-avoid nudge), never `width`. All font sizes/margins/logo box/side insets are absolute pixels in `remotion/src/types.ts` STYLES tuned for 1080x1920. Changing composition dims alone leaves captions ~1.8x oversized floating mid-frame. **Caption geometry is the biggest blind spot** and is net-new plumbing across 4 layers (Python cmd → `render.mjs` CLI flag → `inputProps` → `CaptionedClip` prop), plus the ASS fallback (`captions_burn.py`, `caption_renderer.py` PlayRes, `caption_styles.py` margins).
-2. **The MCP "two schemas" was wrong.** The handler `inputSchema` objects (`create-clip.handler.ts:33`, `batch-clips.handler.ts`) are **dead code** (`server.tool()` uses only `.name`/`.description`). The real gates are (a) the inline Zod shape in `src/server.ts` (MCP, strips unknown keys), and (b) `src/ui/web-server.ts` — the **primary** path — which manually destructures `req.body` and builds the Python payload with an explicit allowlist (`styledClips` whitelist ~`2671`, `/api/create-clip`, `/api/batch-clips`). A `format` param must be added at ~10 hops or it silently reverts to vertical with no error.
+2. **The MCP "two schemas" was wrong.** The handler `inputSchema` objects (`create-clip.handler.ts:33`, `batch-clips.handler.ts`) are **dead code** (`server.tool()` uses only `.name`/`.description`). The real gates are (a) the inline Zod shape in `src/server.ts` (MCP, strips unknown keys), and (b) `src/ui/web-server.ts`, the **primary** path, which manually destructures `req.body` and builds the Python payload with an explicit allowlist (`styledClips` whitelist ~`2671`, `/api/create-clip`, `/api/batch-clips`). A `format` param must be added at ~10 hops or it silently reverts to vertical with no error.
3. **`fit_to_frame` is NOT redundant** with `crop_to_vertical`'s center branch. That branch blur-pillarboxes wider-than-target sources and crops top/bottom off narrower ones; only pixel-exact 16:9 passes through. Real-world near-16:9 inputs (1920x1088, 2.39:1, 4:3 inserts) are mishandled. Keep `fit_to_frame` as a distinct scale+pad/letterbox path.
4. **Render canvas dims are already dynamic.** `render.mjs:170-238` ffprobes the cropped clip and overrides Remotion composition width/height at `renderMedia` time, so a 1920x1080 source auto-produces a 1920x1080 overlay (DaVinci ProRes overlay too). `Root.tsx:38-39` literals govern only Remotion Studio preview. So horizontal render is *dimension*-correct for free; it is *caption-layout*-broken until profile work lands.
### Two hard caps that block horizontal from functioning
-- `backend/services/clip_generator.py:711` — `if duration > MAX_CLIP_DURATION: raise ValueError` (45s). A 60-300s clip crashes here. Must become `spec.dur_max`-aware.
-- `src/ui/web-server.ts` — 180s HTTP duration cap on `/api/create-clip` and `/api/batch-clips`. Rejects horizontal at the boundary before Python.
+- `backend/services/clip_generator.py:711`: `if duration > MAX_CLIP_DURATION: raise ValueError` (45s). A 60-300s clip crashes here. Must become `spec.dur_max`-aware.
+- `src/ui/web-server.ts`: 180s HTTP duration cap on `/api/create-clip` and `/api/batch-clips`. Rejects horizontal at the boundary before Python.
### Deferred / do-not-touch
- **Thumbnails** are a separate ~4-file / ~12-literal 9:16 track (`thumbnail_ai.py`, `thumbnail_generator.py`, `thumbnail_html.py`, `ThumbnailTemplate.tsx`). Not part of clip FormatSpec. Horizontal clips get portrait thumbnails until Phase 5.
@@ -54,37 +54,37 @@ An adversarial audit (7 parallel readers + 8 refutation passes + synthesis) foun
## Phases
-### Phase 1 — Parameterize rendering (SAFE, no behavior change) ✅ DONE
+### Phase 1: Parameterize rendering (SAFE, no behavior change) ✅ DONE
Verified **byte-identical for the vertical default** (341/341 backend tests pass; smoke-checked that duration aliases hold 20/45/20/35, affected importers load, and `crop_to_vertical`'s `target_dims` default is `(1080,1920)`). Two guardrails were mandatory and applied:
-- **Guardrail A — keep duration constants as aliases.** `cli.py:70,398`, `clip_generator.py:31`, `claude_suggest.py:21`, and `DEFAULT_PRESET` itself import `MIN/MAX/TARGET_CLIP_DURATION` by name; deleting them ImportError-crashes all four. They now derive from `FORMATS["vertical"]` but keep the exact module-level names.
-- **Guardrail B — change only the crop-path literal.** Only `video_processor.py:103` was touched. Thumbnails, caption PlayRes, `clip_studio.py`, `render.mjs` fallback, and `Root.tsx` were left alone — they resolve to vertical anyway and rewriting them adds risk with no behavior benefit.
+- **Guardrail A: keep duration constants as aliases.** `cli.py:70,398`, `clip_generator.py:31`, `claude_suggest.py:21`, and `DEFAULT_PRESET` itself import `MIN/MAX/TARGET_CLIP_DURATION` by name; deleting them ImportError-crashes all four. They now derive from `FORMATS["vertical"]` but keep the exact module-level names.
+- **Guardrail B: change only the crop-path literal.** Only `video_processor.py:103` was touched. Thumbnails, caption PlayRes, `clip_studio.py`, `render.mjs` fallback, and `Root.tsx` were left alone because they resolve to vertical anyway, and rewriting them adds risk with no behavior benefit.
Edits shipped:
-1. **NEW** `backend/services/formats.py` — `FormatSpec` (frozen dataclass) + `FORMATS` {vertical, horizontal, square} + `get_format()`. Imports nothing from `presets` (avoids cycle; `presets` imports from it).
-2. `backend/presets.py` — duration constants now alias `FORMATS["vertical"].{dur_min,dur_max,target_min,target_max}`; added `"format": "vertical"` to `DEFAULT_PRESET` (inert; the `{**DEFAULT_PRESET, **saved}` merge back-fills old presets).
-3. `backend/services/video_processor.py` — `crop_to_vertical(...)` gained `target_dims: tuple = (1080, 1920)`; line 103 is now `target_w, target_h = target_dims`.
+1. **NEW** `backend/services/formats.py`: `FormatSpec` (frozen dataclass) + `FORMATS` {vertical, horizontal, square} + `get_format()`. Imports nothing from `presets` (avoids cycle; `presets` imports from it).
+2. `backend/presets.py`: duration constants now alias `FORMATS["vertical"].{dur_min,dur_max,target_min,target_max}`; added `"format": "vertical"` to `DEFAULT_PRESET` (inert; the `{**DEFAULT_PRESET, **saved}` merge back-fills old presets).
+3. `backend/services/video_processor.py`: `crop_to_vertical(...)` gained `target_dims: tuple = (1080, 1920)`; line 103 is now `target_w, target_h = target_dims`.
-### Phase 2 — Render horizontal (still defaults vertical) ✅ DONE
+### Phase 2: Render horizontal (still defaults vertical) ✅ DONE
Verified end to end: a 1280x720 source rendered `format="horizontal"` → **1920x1080** via `chose=fit-letterbox` (face analysis skipped), and `format="vertical"` → **1080x1920** unchanged. 341 Python + 47 TS tests pass, `tsc` clean.
- **Render fork** in `clip_generator.py` step 2: `spec.reframe ? crop_to_vertical(..., target_dims=spec.dims) : fit_to_frame(..., spec.dims)`. New `fit_to_frame` in `video_processor.py` = `scale=…:force_original_aspect_ratio=decrease` + centered `pad` + `setsar=1` (letterbox, collapses to plain scale for exact-ratio), skips all face analysis. `spec = get_format(format)` resolved once and reused for the dur cap, progress label, and fork. (Kept the `crop_to_vertical` name for now; rename deferred.)
-- **Caps relaxed:** `clip_generator.py` uses `spec.dur_max` (vertical still 45); the two web-server 180s HTTP caps use a format-keyed ceiling (horizontal→300, else 180 — *not* `spec.dur_max`, which would tighten vertical).
+- **Caps relaxed:** `clip_generator.py` uses `spec.dur_max` (vertical still 45); the two web-server 180s HTTP caps use a format-keyed ceiling (horizontal→300, else 180, *not* `spec.dur_max`, which would tighten vertical).
- **`format` threaded end to end**, defaulting vertical at every hop: `generate_clip` signature + result dict; `main.py` create/batch; **6** `cli.py` `generate_clip` call sites + `--format` flag + `_selection_signature` cache key; `server.ts` create/batch Zod + primary clip literal + export-selected/clip-numbers maps + `findDuplicate`/`record`; `web-server.ts` create-clip destructure/validation/payload/history/recipe + MCP-export resolver + `styledClips` whitelist + batch per-clip cap + `createBatchHistoryRecorder`; `models/index.ts` types; `clips-history.ts` `findDuplicate` (backward-compatible, missing→vertical, so a horizontal re-clip of a vertical range is no longer a false duplicate).
- `Root.tsx`/`render.mjs` untouched (ffprobe already sizes the canvas). Output is dimension-correct; **captions still use vertical geometry** until Phase 3 (conscious deferral, not a silent bug).
-### Phase 3 — Correct captions per format (the real blind spot)
+### Phase 3: Correct captions per format (the real blind spot)
- Add a `caption_profile` carrying per-format geometry (fontSize, margins, logo box, side insets). Wire a `--format`/`--caption-profile` flag through `render.mjs` → `inputProps` → `CaptionedClipProps`, and add a `lower_third` profile to `types.ts` STYLES + the 4 Remotion caption components (make absolute pixels profile-driven).
- Mirror in the **ASS fallback** (default path, `allow_ass_fallback=True`): thread real dims into `captions_burn.py:27`, `caption_renderer.py` PlayRes (`17`,`501`), `caption_styles.py:73` margins; wire up the already-parameterized-but-dead `_calibrate_libass_y`.
-### Phase 4 — Iterate the AI for horizontal viral moments (the product)
+### Phase 4: Iterate the AI for horizontal viral moments (the product)
- **Second scoring profile.** Keep `standalone/hook/relevance/quotability` as `vertical_score`; add `arc/tension/depth/payoff` as `horizontal_score` in `claude_suggest.py:_build_prompt`. New KB file `.podcli/knowledge/04b-longform-creation-guide.md` loaded alongside `04-shorts-creation-guide.md`. Moment schema (`suggest-clips.handler.ts`) gains both scores (keep `score` alias). Detect once, rank twice.
- **Dialogue-tension signal** (highest-leverage new AI): a function in `audio_analyzer.py` next to `compute_energy_scores` combining speaker-turn frequency (from diarization labels) + sustained energy → catches debate/back-and-forth that vertical spike-scoring misses. Feeds `horizontal_score`.
- Make the LLM duration window format-aware (`claude_suggest.py:241-311,433` currently bake 20-45s into the prompt).
-### Phase 5 — UI + learning loop + more renderers
+### Phase 5: UI + learning loop + more renderers
- ContentStudio format selector + "render both"; 16:9 preview variants in `styles.css` (+ `dist` copies) and `EpisodeWorkspace.jsx:77` (`PROD_TO_PCT` hardcodes 1920).
- Feed both format performance streams into the YouTube learning loop ([studio-phase-1] roadmap) → learn format × moment-type winners → back into scoring.
- Horizontal thumbnails (16:9 / 1280x720) as a deliverable. Then the cheap renderers off the same spine: audiograms, quote cards (reuse `thumbnail_ai.py`), show notes / X threads (LLM over the transcript).
diff --git a/plans/moment-detection.md b/plans/moment-detection.md
index 23f7aec..abdb423 100644
--- a/plans/moment-detection.md
+++ b/plans/moment-detection.md
@@ -1,6 +1,6 @@
# podcli → Generalized moment detection (multi-signal saliency engine)
-> Goal: one detector that works across content types. The podcast clip selector and a new "auto-cut the funny/interesting moments" highlighter (party videos, vlogs, action, streams) become **two profiles of one engine**, not two features. Anchor use case that surfaced the need: a folder of party clips, "cut me the funny bits" — any language, no labels. Podcast selection is preserved as the default profile.
+> Goal: one detector that works across content types. The podcast clip selector and a new "auto-cut the funny/interesting moments" highlighter (party videos, vlogs, action, streams) become **two profiles of one engine**, not two features. Anchor use case that surfaced the need: a folder of party clips, "cut me the funny bits", any language, no labels. Podcast selection is preserved as the default profile.
## North star
@@ -15,13 +15,13 @@ one long video (any content, any language)
## The one decision everything hangs on
-**Content profile is orthogonal to output format.** `FormatSpec` (9:16 / 16:9 / 1:1) is a *render-time* aspect-ratio decision. A **`ContentProfile`** (podcast / party / action / auto) is a *detection-time* decision about **which signals matter and how candidates are generated**. A moment is detected under a profile, then rendered to one or more formats. Do not overload `FormatSpec.score_key` for this — mirror its pattern in a separate `ContentProfile` spec.
+**Content profile is orthogonal to output format.** `FormatSpec` (9:16 / 16:9 / 1:1) is a *render-time* aspect-ratio decision. A **`ContentProfile`** (podcast / party / action / auto) is a *detection-time* decision about **which signals matter and how candidates are generated**. A moment is detected under a profile, then rendered to one or more formats. Do not overload `FormatSpec.score_key` for this, mirror its pattern in a separate `ContentProfile` spec.
The existing transcript-LLM selector is **one channel** in this engine (the `transcript_semantic` channel), not the whole thing. That is the reframe: today the LLM *is* selection; tomorrow it is the dominant channel for the podcast profile and near-zero for party.
## Why this generalizes (research-backed)
-Multi-signal highlight detection is a solved shape: compute a per-modality saliency curve, normalize **per-video** (never global), fuse (weighted sum with soft-OR bias, audio weighted heaviest for human-centric video), peak-pick, and for reaction-driven content extend **backwards from the reaction** to the cause. FunnyNet-W: a funny moment is "an n-second clip *followed by* laughter," audio carries >50% of the decision, optimal look-back ≈ 8s. Cai/Lu/Cai built laughter+applause+cheer detection *for home videos* at ~93% recall. All of it is unsupervised — no labeled data, only pretrained off-the-shelf models. See the audio-model and fusion research threads (this session) for citations.
+Multi-signal highlight detection is a solved shape: compute a per-modality saliency curve, normalize **per-video** (never global), fuse (weighted sum with soft-OR bias, audio weighted heaviest for human-centric video), peak-pick, and for reaction-driven content extend **backwards from the reaction** to the cause. FunnyNet-W: a funny moment is "an n-second clip *followed by* laughter," audio carries >50% of the decision, optimal look-back ≈ 8s. Cai/Lu/Cai built laughter+applause+cheer detection *for home videos* at ~93% recall. All of it is unsupervised, no labeled data, only pretrained off-the-shelf models. See the audio-model and fusion research threads (this session) for citations.
## Profiles as concrete weight vectors
@@ -35,76 +35,76 @@ Channels each emit a per-video-normalized 0..1 curve; a profile is a weight vect
| `energy` (RMS, peak-weighted) | 0.1 | 0.2 | 0.2 | REUSE `audio_analyzer.py` |
| `motion` (optical flow + scene-cut density) | 0.0 | 0.1 | **0.2** | PARTIAL (cuts exist; flow NEW) |
| `face_reaction` (mouth activity / smile proxy) | 0.05 | 0.1 | 0.0 | REUSE `face_analysis.py` (crude) |
-| **candidate source** | `llm` | `saliency` | `saliency` | — |
+| **candidate source** | `llm` | `saliency` | `saliency` | n/a |
Weights are starting points, tuned later. `auto` = a cheap first pass picks the profile: clean speech + 1-2 stable faces → podcast; sparse speech + high motion + crowd/laughter audio → party; sustained high motion → action.
## Two candidate-generation modes (the key to not regressing podcast)
- **`llm` (podcast):** the existing `claude_suggest` flow generates candidates over the whole transcript, exactly as today. The fused signal score blends in at the ranking seam. **When party channels have weight 0, output is byte-for-byte the current behavior.** This is the safety property.
-- **`saliency` (party / action):** the fused curve drives candidate generation directly — `find_peaks` → reaction-expand → boundary-snap → candidate windows. Works with **no usable transcript**. The LLM is optional here, used only to title/caption the already-chosen windows.
+- **`saliency` (party / action):** the fused curve drives candidate generation directly: `find_peaks` → reaction-expand → boundary-snap → candidate windows. Works with **no usable transcript**. The LLM is optional here, used only to title/caption the already-chosen windows.
-## Architecture — new modules
+## Architecture: new modules
1. **`backend/services/audio_events.py`** (NEW, no-torch)
- YAMNet exported to a **self-contained ONNX graph** (raw 16 kHz waveform in, log-mel baked into the graph → **no librosa needed**). ~15 MB, Apache-2.0. AudioSet classes `Laughter`, `Cheering`, `Applause`, `Screaming` are native outputs (+ Giggle/Belly-laugh/Whoop children).
- Reuse `transcription_whispercpp._extract_wav` (`-ar 16000 -ac 1`) for audio; **do not import `speaker_detection`** (drags in torch).
- Returns per-window (≈1 Hz, matching energy) class probabilities → one 0..1 curve per trigger class.
- - Runtime: `onnxruntime`. **First test whether `cv2.dnn` (already loads YuNet `.onnx`) can run yamnet.onnx** — if yes, zero new deps.
+ - Runtime: `onnxruntime`. **First test whether `cv2.dnn` (already loads YuNet `.onnx`) can run yamnet.onnx**, if yes, zero new deps.
- Ship `backend/models/yamnet.onnx` + a **dev-only** `scripts/export_yamnet.py` (uses tf2onnx; never shipped or imported at runtime).
2. **`backend/services/saliency.py`** (NEW)
- - `normalize_per_video(curve)` — robust z-score via numpy median/MAD, or percentile-rank. **Never global.**
- - `fuse(channels, profile)` — weighted sum with soft-OR bias.
- - `pick_peaks(curve, profile)` — **numpy reimplementation of `find_peaks`** (~40 lines: height floor `mean + kσ`, min-distance NMS by descending height, prominence filter, min-width). Avoids adding scipy. Keep peaks above the top ~10-15th percentile of the video's **own** prominence distribution (adaptive count).
- - `reaction_expand(peak, events)` — if the peak's driver is an `audio_event` class, move anchor to reaction onset, extend ~8 s back, keep 1-3 s of payoff.
- - `snap_boundaries(window)` — snap start/end to nearest {Whisper sentence-end, silence gap >300 ms, scene cut, motion-quiet local min} within ±500 ms.
+ - `normalize_per_video(curve)`: robust z-score via numpy median/MAD, or percentile-rank. **Never global.**
+ - `fuse(channels, profile)`: weighted sum with soft-OR bias.
+ - `pick_peaks(curve, profile)`: **numpy reimplementation of `find_peaks`** (~40 lines: height floor `mean + kσ`, min-distance NMS by descending height, prominence filter, min-width). Avoids adding scipy. Keep peaks above the top ~10-15th percentile of the video's **own** prominence distribution (adaptive count).
+ - `reaction_expand(peak, events)`: if the peak's driver is an `audio_event` class, move anchor to reaction onset, extend ~8 s back, keep 1-3 s of payoff.
+ - `snap_boundaries(window)`: snap start/end to nearest {Whisper sentence-end, silence gap >300 ms, scene cut, motion-quiet local min} within ±500 ms.
-3. **`backend/services/profiles.py`** (NEW) — `ContentProfile` dataclass (name, `channel_weights`, `candidate_source`, peak params, reaction-expand params, boundary sources) mirroring `FormatSpec`; `get_profile(name)`; `auto_detect(signals)`.
+3. **`backend/services/profiles.py`** (NEW): `ContentProfile` dataclass (name, `channel_weights`, `candidate_source`, peak params, reaction-expand params, boundary sources) mirroring `FormatSpec`; `get_profile(name)`; `auto_detect(signals)`.
-4. **`motion` channel** (Phase 3) — `cv2.calcOpticalFlowFarneback` on sampled frames (**OpenCV already present**) + reuse `local_reframe.count_scene_cuts` / `clip_generator._detect_scene_cuts`.
+4. **`motion` channel** (Phase 3): `cv2.calcOpticalFlowFarneback` on sampled frames (**OpenCV already present**) + reuse `local_reframe.count_scene_cuts` / `clip_generator._detect_scene_cuts`.
-5. **`prosody` channel** (Phase 2/3) — numpy F0 (autocorrelation) + short-term energy + speech-rate vs speaker baseline. No librosa.
+5. **`prosody` channel** (Phase 2/3): numpy F0 (autocorrelation) + short-term energy + speech-rate vs speaker baseline. No librosa.
## Dependency deltas (no-torch native path)
-- **ADD** `onnxruntime` to `requirements-runtime.txt` — the only new hard dep. **Settled by spike:** OpenCV-DNN *cannot* run the YAMNet graph (rejects the dynamic-shape mel front-end: `dynamic 'zero' shapes are not supported`), so the zero-new-dep route is out. `onnxruntime` still pulls in no torch/TF.
+- **ADD** `onnxruntime` to `requirements-runtime.txt`: the only new hard dep. **Settled by spike:** OpenCV-DNN *cannot* run the YAMNet graph (rejects the dynamic-shape mel front-end: `dynamic 'zero' shapes are not supported`), so the zero-new-dep route is out. `onnxruntime` still pulls in no torch/TF.
- **NO** librosa (self-contained waveform-in graph, confirmed), **NO** torch/TF at runtime.
-- `scipy` is present in the dev venv (so `find_peaks` works there) but is **not** in `requirements-runtime.txt` — either add it or keep the numpy peak-pick reimpl for the hermetic runtime. Decide at Phase 2.
+- `scipy` is present in the dev venv (so `find_peaks` works there) but is **not** in `requirements-runtime.txt`: either add it or keep the numpy peak-pick reimpl for the hermetic runtime. Decide at Phase 2.
- Optical flow + face already covered by `opencv-python-headless`.
-- `yamnet.onnx` weight (~16 MB) committed to `backend/models/`; no export step needed — a self-contained waveform-in export already exists at HF `zeropointnine/yamnet-onnx` (input `waveform` [dynamic], outputs `[frames,521]` scores + `[frames,1024]` embeddings + `[frames,64]` mel). Verify its license before committing; keep a dev-only `scripts/export_yamnet.py` (tf2onnx) as the reproducible fallback.
+- `yamnet.onnx` weight (~16 MB) committed to `backend/models/`; no export step is needed because a self-contained waveform-in export already exists at HF `zeropointnine/yamnet-onnx` (input `waveform` [dynamic], outputs `[frames,521]` scores + `[frames,1024]` embeddings + `[frames,64]` mel). Verify its license before committing; keep a dev-only `scripts/export_yamnet.py` (tf2onnx) as the reproducible fallback.
## Spike results (validated this session)
Ran the self-contained YAMNet ONNX on real podcli audio (a 38 s Deeptech Decoded clip, extracted with podcli's exact `-ar 16000 -ac 1`):
- **No-torch confirmed:** `torch`/`tensorflow` absent from the process before and after inference (onnxruntime only).
-- **Correct classification:** Speech 0.774 (dominant, correct for a talking clip), Silence 0.186, and Laughter/Cheering/Applause/Screaming all exactly 0.000 — correct negative control (serious monologue, no laughter). Mel front-end baked in the graph → featurization provably correct, no code to own.
+- **Correct classification:** Speech 0.774 (dominant, correct for a talking clip), Silence 0.186, and Laughter/Cheering/Applause/Screaming all exactly 0.000, which is a correct negative control (serious monologue, no laughter). Mel front-end baked in the graph → featurization provably correct, no code to own.
- **Negligible cost:** 98 ms for 38 s of audio (~380× realtime); a 3 h video ≈ 28 s of audio-event analysis.
-- **Positive reaction detection confirmed on podcast content.** Swept 32 real clips: the detector ranked the one comedic show + two chuckle moments above the dry technical majority (which scored exactly 0.00). Zooming in, laughter fires as a **sharp 1-2 frame spike anti-correlated with Speech** (e.g. laugh=0.23 while speech drops 1.00→0.11 at 13.5s, then back to speech) — the exact reaction signature the 8s-backward-expansion relies on. Absolute values are modest (0.23-0.25 for brief chuckles in pre-cut clips) but that is a non-issue: a spike on a 0.00 baseline is trivially caught by **prominence-based peak-picking**, which is why per-video normalization (not absolute thresholds) is mandated above.
-- **Still worth a check (needs real party footage):** amplitude/robustness on noisy handheld party audio with music and overlapping speech — YAMNet's known soft spot. If weak, AST ONNX (`onnx-community`, pre-exported, mAP 0.485) is the drop-in fallback; needs a 128-bin log-mel numpy front-end.
+- **Positive reaction detection confirmed on podcast content.** Swept 32 real clips: the detector ranked the one comedic show + two chuckle moments above the dry technical majority (which scored exactly 0.00). Zooming in, laughter fires as a **sharp 1-2 frame spike anti-correlated with Speech** (e.g. laugh=0.23 while speech drops 1.00→0.11 at 13.5s, then back to speech), the exact reaction signature the 8s-backward-expansion relies on. Absolute values are modest (0.23-0.25 for brief chuckles in pre-cut clips) but that is a non-issue: a spike on a 0.00 baseline is trivially caught by **prominence-based peak-picking**, which is why per-video normalization (not absolute thresholds) is mandated above.
+- **Still worth a check (needs real party footage):** amplitude/robustness on noisy handheld party audio with music and overlapping speech. YAMNet's known soft spot. If weak, AST ONNX (`onnx-community`, pre-exported, mAP 0.485) is the drop-in fallback; needs a 128-bin log-mel numpy front-end.
## Integration seams (from the code map)
-1. **Detect-once hub** — `backend/cli.py` ~658-720 (and MCP twin `backend/main.py:handle_suggest_clips` ~358). Energy is *already* computed once here (`get_energy_profile`) and `face_map` extracted. All new channels compute here; fusion produces the saliency curve.
-2. **Scoring merge** — `claude_suggest.suggest_with_claude` normalization (~999) + `_select_top_by_score` (~687). Blend the LLM score in as the `transcript_semantic` channel; key the weights off the active `ContentProfile`.
-3. **Transcript-packer co-location** — `transcript_packer.pack_transcript` (~274) already flags top-RMS moments for the in-chat MCP agent. Add laughter/event/motion flags so the conversational path also sees them.
+1. **Detect-once hub**: `backend/cli.py` ~658-720 (and MCP twin `backend/main.py:handle_suggest_clips` ~358). Energy is *already* computed once here (`get_energy_profile`) and `face_map` extracted. All new channels compute here; fusion produces the saliency curve.
+2. **Scoring merge**: `claude_suggest.suggest_with_claude` normalization (~999) + `_select_top_by_score` (~687). Blend the LLM score in as the `transcript_semantic` channel; key the weights off the active `ContentProfile`.
+3. **Transcript-packer co-location**: `transcript_packer.pack_transcript` (~274) already flags top-RMS moments for the in-chat MCP agent. Add laughter/event/motion flags so the conversational path also sees them.
## Contract-change tax
-A new `profile` param threads the **same ~12 hops the `format` field did**: `suggest-clips.handler.ts` inputSchema, `src/models/index.ts` types, `src/server.ts` Zod (dual-declaration), `src/ui/web-server.ts` `styledClips` whitelist, `python-executor` stdin, `main.py` params, and `cli.py`'s `generate_clip` call sites — or it silently reverts to the default. Follow the `format` precedent exactly.
+A new `profile` param threads the **same ~12 hops the `format` field did**: `suggest-clips.handler.ts` inputSchema, `src/models/index.ts` types, `src/server.ts` Zod (dual-declaration), `src/ui/web-server.ts` `styledClips` whitelist, `python-executor` stdin, `main.py` params, and `cli.py`'s `generate_clip` call sites, or it silently reverts to the default. Follow the `format` precedent exactly.
## Phasing
-- **Phase 0 — profile scaffolding, zero behavior change.** [DONE, PR #43 / Phase 2 branch] `ContentProfile` abstraction added (`profiles.py`); `profile` param threaded through the CLI (`--profile`, config, selection signature). Python-side default `podcast` reproduces current selection. TS-side threading (MCP/web `profile` param) still open — see below.
-- **Phase 1 — audio-event channel (the isolated valuable core).** [DONE, PR #43] YAMNet-ONNX laughter/cheer/applause/scream (`audio_events.py`) computed in the detect-once hub; surfaced in the packed transcript and CLI heuristic. Podcast output unchanged unless the channel is weighted. Validated on 32 real clips.
-- **Phase 2 — fusion engine + saliency candidate source + party profile (audio-only).** [DONE, this branch] `saliency.py`: per-video robust-z normalization, weighted fusion, numpy peak-pick (NMS), reaction dilation, reaction-first candidate generation, 8 s backward expansion, quiet-point boundary snap. Wired to `--profile party|action` in `podcli process`. Deterministic on clean input; reactions detected with correct run-up windows. **Gate remaining: tune thresholds/weights on real party footage (synthetic podcast-clip concat is not representative).**
-- **Phase 3 — visual channels + action profile + multi-file pooling.** Optical flow (OpenCV) + face-reaction channels; action profile; pool peaks across a *folder* of clips and rank globally ("best 15 bits from tonight" across 80 phone videos). **Gate: catches a silent visual gag; folder-level ranking works.**
-- **Phase 4 (optional) — highlight reel renderer.** Ordering, pacing, optional music-bed ducking, transitions — a thin renderer atop the detected moments, reusing the clip-render stack.
+- **Phase 0: profile scaffolding, zero behavior change.** [DONE, PR #43 / Phase 2 branch] `ContentProfile` abstraction added (`profiles.py`); `profile` param threaded through the CLI (`--profile`, config, selection signature). Python-side default `podcast` reproduces current selection. TS-side threading (MCP/web `profile` param) still open: see below.
+- **Phase 1: audio-event channel (the isolated valuable core).** [DONE, PR #43] YAMNet-ONNX laughter/cheer/applause/scream (`audio_events.py`) computed in the detect-once hub; surfaced in the packed transcript and CLI heuristic. Podcast output unchanged unless the channel is weighted. Validated on 32 real clips.
+- **Phase 2: fusion engine + saliency candidate source + party profile (audio-only).** [DONE, this branch] `saliency.py`: per-video robust-z normalization, weighted fusion, numpy peak-pick (NMS), reaction dilation, reaction-first candidate generation, 8 s backward expansion, quiet-point boundary snap. Wired to `--profile party|action` in `podcli process`. Deterministic on clean input; reactions detected with correct run-up windows. **Gate remaining: tune thresholds/weights on real party footage (synthetic podcast-clip concat is not representative).**
+- **Phase 3: visual channels + action profile + multi-file pooling.** Optical flow (OpenCV) + face-reaction channels; action profile; pool peaks across a *folder* of clips and rank globally ("best 15 bits from tonight" across 80 phone videos). **Gate: catches a silent visual gag; folder-level ranking works.**
+- **Phase 4 (optional): highlight reel renderer.** Ordering, pacing, optional music-bed ducking, transitions: a thin renderer atop the detected moments, reusing the clip-render stack.
## Guardrails
-- **Per-video normalization is mandatory** — party clips vary wildly in level/room/camera; global normalization is wrong.
+- **Per-video normalization is mandatory**: party clips vary wildly in level/room/camera; global normalization is wrong.
- **Podcast profile must reproduce current behavior** when party channels are weight 0. Ship behind the profile param; default is safe. This is the non-regression contract.
-- **`find_peaks` `distance` param is the NMS / min-gap** — it deletes lower peaks within the gap automatically. Adaptive clip count = top percentile of the video's own prominence distribution, not an absolute N.
+- **`find_peaks` `distance` param is the NMS / min-gap**. It deletes lower peaks within the gap automatically. Adaptive clip count = top percentile of the video's own prominence distribution, not an absolute N.
- **YAMNet ONNX must never import torch/TF at runtime.** The export step is dev/CI only; the native runtime installs `onnxruntime` (or reuses OpenCV-DNN) and feeds raw 16 kHz samples.
-- **Reaction-expansion only fires for saliency candidates** whose trigger is an audio-event class — never rewrite LLM-chosen podcast windows.
+- **Reaction-expansion only fires for saliency candidates** whose trigger is an audio-event class: never rewrite LLM-chosen podcast windows.
diff --git a/plans/native-cli.md b/plans/native-cli.md
index e405cf1..15a909e 100644
--- a/plans/native-cli.md
+++ b/plans/native-cli.md
@@ -18,7 +18,7 @@ No `setup.sh`. No venv. No `pip`. No `npm install` of the engine. No "is the rig
## Why this is hard (the core tension)
-codex is a single static Rust binary with **zero** runtime deps. podcli is the opposite — a **three-runtime hybrid**:
+codex is a single static Rust binary with **zero** runtime deps. podcli is the opposite: a **three-runtime hybrid**:
- **Python engine** (`backend/cli.py`, ~188KB): Whisper (→ PyTorch ~2GB), OpenCV face-crop, Pillow, FFmpeg, Google API.
- **Node/TS**: MCP server (`src/server.ts`), React web UI, Remotion → headless **Chromium** (studio bookends).
@@ -37,13 +37,13 @@ You can't fold PyTorch + Chromium + FFmpeg into one static binary. So we **packa
| **Runtimes** | **Fully hermetic.** Launcher downloads pinned standalone CPython, static FFmpeg, whisper.cpp (+ Node/Chromium later). System python/node/ffmpeg ignored. |
| **Transcription** | **whisper.cpp** replaces `openai-whisper`/PyTorch. GGUF models. Metal on Apple Silicon, CUDA/CPU elsewhere. ~145MB vs ~2GB. |
| **Bundle model** | Tiny launcher; **first run provisions the full core stack** (download-once, like today's `setup.sh` but automatic + cross-platform). |
-| **Storage** | **Global** managed dir for runtimes + model cache (`%LOCALAPPDATA%\podcli` / `~/Library/Application Support/podcli` / `~/.local/share/podcli`). **Per-project** `.podcli/` (knowledge, output, history) stays in cwd — podcli stays project-scoped like git. |
+| **Storage** | **Global** managed dir for runtimes + model cache (`%LOCALAPPDATA%\podcli` / `~/Library/Application Support/podcli` / `~/.local/share/podcli`). **Per-project** `.podcli/` (knowledge, output, history) stays in cwd, so podcli stays project-scoped like git. |
| **Distribution** | **Install script** (`curl -fsSL https://podcli.com/install.sh \| sh`, `irm https://podcli.com/install.ps1 \| iex`) fetching the platform binary from GitHub Releases. npm is out: the unscoped `podcli` name is blocked (see RELEASE.md). Code signing is not in place yet. |
| **Auto-update** | On launch: fast (~250ms, short-timeout) check against GitHub Releases, cached for 24h. Newer → update then load. Offline/slow → proceed on current version (never blocks). Self-replace the managed binary in the managed `bin/`; if that's impossible, print the matching install-script command. |
| **Update opt-out** | Persistent off switch: `podcli config set update.auto off` + `PODCLI_NO_UPDATE=1`. When off: no checks, runs installed version. `podcli update` still works on demand. |
| **AI features** | API key preferred → AI-CLI fallback → core works without. If a key is set, call the Claude/OpenAI API directly (self-contained); else shell to installed Claude/Codex CLI (today's behavior); else the video pipeline still works and AI features print how to enable them. |
| **Platforms** | macOS arm64, macOS x64, Linux x64, Linux arm64, Windows x64. |
-| **First milestone** | **Thin vertical slice** — `process` pipeline only, fully hermetic, whisper.cpp, npm/bun, self-update, all 5 platforms. Studio / AI-API / MCP come after. |
+| **First milestone** | **Thin vertical slice**: `process` pipeline only, fully hermetic, whisper.cpp, npm/bun, self-update, all 5 platforms. Studio / AI-API / MCP come after. |
---
@@ -86,35 +86,35 @@ Clean seam: `backend/services/transcription.py::transcribe_file()` returns a fix
## Roadmap
-### Phase 0 — Foundation spike (de-risk everything)
+### Phase 0: Foundation spike (de-risk everything)
- Go launcher skeleton: arg parse, subcommand passthrough to a hand-placed python.
- Managed-dir layout + OS-appropriate paths.
- Hermetic provisioning: download pinned **CPython standalone**, **static FFmpeg**, **whisper.cpp** binary + base-q5 model for the **current** platform; create hermetic venv; `pip install` backend deps into it.
- Prove `go run . process sample.mp4` produces a clip using **only** hermetic components (rename/hide system python+ffmpeg to verify).
-### Phase 1 — whisper.cpp engine swap
+### Phase 1: whisper.cpp engine swap
- Reimplement `transcribe_file()` on whisper.cpp behind the existing dict contract.
- Word-timestamp parity test vs `openai-whisper` on a fixture; tune `--max-len`/token-timestamp flags.
- Remove `openai-whisper` from `requirements.txt`; confirm captions (karaoke/Hormozi/subtle) still render correctly.
-### Phase 2 — Distribution + self-update (→ first installable release)
+### Phase 2: Distribution + self-update (→ first installable release)
- CI matrix builds the Go launcher for all **4 targets** (darwin-arm64, linux-amd64, linux-arm64, windows-amd64).
- **Install script** resolves the latest release and drops the platform binary into the managed `bin/`, adding it to PATH.
- GitHub Release per version carries: the 4 launchers, the runtime assets (whisper-cli, ffmpeg, studio and remotion bundles), and `checksums.txt` covering every asset.
- Self-update: fast on-launch check, atomic self-replace of the managed binary, install-script fallback message, `PODCLI_NO_UPDATE` + `config set update.auto off`, `podcli update`, keep-previous-binary for `podcli rollback`.
- **Ship.** Install script → `podcli process` works hermetic on all 4 platforms and auto-updates. ← *this is the MVP gate.*
-### Phase 3 — Lazy tiers + studio
-- Demote OpenCV face-crop to lazy (center-crop default offline; fetch opencv on first smart crop — the center-crop fallback already exists at `cli.py:621`).
+### Phase 3: Lazy tiers + studio
+- Demote OpenCV face-crop to lazy (center-crop default offline; fetch opencv on first smart crop; the center-crop fallback already exists at `cli.py:621`).
- Lazy bigger Whisper models.
- **Studio**: provision hermetic **Node + Remotion + Chromium** on first `studio` use; route `studio` render through it.
-### Phase 4 — AI goes native
+### Phase 4: AI goes native
- Port PodStack prompt files (`.claude/commands/*.md`) into the engine as direct **Claude API** calls.
- `podcli config set api-key …`; precedence: API key → installed Claude/Codex CLI → "enable AI" hint.
- Keep core pipeline fully functional without any AI.
-### Phase 5 — MCP / web UI (or deprecate)
+### Phase 5: MCP / web UI (or deprecate)
- Decide whether the MCP server still matters once AI is native via API, or it's only for "use podcli from inside Claude/Codex."
- If kept: `podcli serve` (MCP stdio) + `podcli ui` (web dashboard) provisioned on demand via hermetic Node.
@@ -122,13 +122,13 @@ Clean seam: `backend/services/transcription.py::transcribe_file()` returns a fix
## Risks / open questions
-- **whisper.cpp timestamp quality** for word-highlight captions — *prove in Phase 1 before deleting PyTorch path.*
-- **Hermetic Node + Chromium on Windows** for studio (Phase 3) — Remotion's Chromium download + headless render is the heaviest non-ML surface; expect platform-specific pain.
-- **First-run download size/time** — set expectations with a clear progress UI; cache aggressively in the global dir.
-- **npm self-update vs package-manager ownership** — managed-binary-in-`~/.podcli/bin` sidesteps it; fallback message covers the rest.
-- **GPU acceleration** — whisper.cpp Metal (mac) is automatic; CUDA (linux/win) needs the right prebuilt — decide CPU-only baseline + optional CUDA fetch.
-- **Versioning** — single version for launcher + manifest of pinned runtime versions; SemVer; changelog drives the "update available" line.
-- **MCP/web UI fate** — genuinely open; resolve at Phase 5.
+- **whisper.cpp timestamp quality** for word-highlight captions: *prove in Phase 1 before deleting PyTorch path.*
+- **Hermetic Node + Chromium on Windows** for studio (Phase 3). Remotion's Chromium download + headless render is the heaviest non-ML surface; expect platform-specific pain.
+- **First-run download size/time**: set expectations with a clear progress UI; cache aggressively in the global dir.
+- **npm self-update vs package-manager ownership**: managed-binary-in-`~/.podcli/bin` sidesteps it; fallback message covers the rest.
+- **GPU acceleration**: whisper.cpp Metal (mac) is automatic; CUDA (linux/win) needs the right prebuilt; decide CPU-only baseline + optional CUDA fetch.
+- **Versioning**: single version for launcher + manifest of pinned runtime versions; SemVer; changelog drives the "update available" line.
+- **MCP/web UI fate**: genuinely open; resolve at Phase 5.
---
diff --git a/plans/studio-phase-1.md b/plans/studio-phase-1.md
index f6446d7..263613f 100644
--- a/plans/studio-phase-1.md
+++ b/plans/studio-phase-1.md
@@ -1,4 +1,4 @@
-# podcli Studio — Phase 1 Implementation Plan
+# podcli Studio: Phase 1 Implementation Plan
> Major release groundwork. Full design (13 decisions) lives in the session memory file
> `project_studio_dashboard_design.md`. This plan covers **Phase 1 only**: the studio
@@ -12,20 +12,20 @@ shared on-disk contract; Python is the engine + history writer, web/MCP are thin
---
-## Phase 0 — Discovery (DONE — facts to build on)
+## Phase 0: Discovery (DONE, facts to build on)
**UI / build**
- No bundler today. `src/ui/public/index.html` (~1880 lines) loads React 18.2 + ReactDOM + babel-standalone via CDN, all app code in one `<script type="text/babel">`. CSS: `public/css/styles.css`. Other pages: `config.html`, `integrations.html`, `knowledge.html`.
-- Express serves statics: `app.use(express.static(join(__dirname, "public")))` — `src/ui/web-server.ts:197`. Port **3847** (`web-server.ts:52`). **No SPA fallback route today.**
+- Express serves statics: `app.use(express.static(join(__dirname, "public")))`, `src/ui/web-server.ts:197`. Port **3847** (`web-server.ts:52`). **No SPA fallback route today.**
- Build: `"build": "tsc && cp -r src/ui/public dist/ui/"` (`package.json`). `"type":"module"`, target ES2022, module ESNext, `rootDir ./src`, `outDir ./dist`, **no `jsx` configured** (public/ is not part of tsc build).
-- Stable API surface the new UI consumes: `/api/history`, `/api/outputs`, `/api/ui-state` (GET/POST — MCP↔UI bridge), `/api/events` (SSE), `/api/preview/:f`, `/api/stream-source`, plus the full upload→transcribe→suggest→create/batch flow.
+- Stable API surface the new UI consumes: `/api/history`, `/api/outputs`, `/api/ui-state` (GET/POST, MCP↔UI bridge), `/api/events` (SSE), `/api/preview/:f`, `/api/stream-source`, plus the full upload→transcribe→suggest→create/batch flow.
**Data layer**
- `ClipHistoryEntry` (`src/models/index.ts:200-213`): `id, source_video, start_second, end_second, caption_style, crop_strategy, logo_path?, title, output_path, file_size_mb, duration, created_at`. **No** `content_type`, `score`, transcript, or youtube fields.
- `src/services/clips-history.ts`: `load / save / record / findDuplicate / list / getBySource`. `record(entry: Omit<ClipHistoryEntry,"id"|"created_at">)`. Writes `paths.clipsHistory` = `${home}/history/clips.json`.
- **5 `record()` call sites**: `web-server.ts:600` (create-clip), `:729` (batch-clips), `:1804` (davinci export); `server.ts:666` (MCP create_clip), `:908` (MCP batch_create_clips).
-- `content_type` originates in `suggest-clips.handler.ts:123`; the suggestion (with `content_type`) is resolved at `create-clip.handler.ts:128-137`; transcript words available at `create-clip.handler.ts:152` — but neither is threaded into `record()`.
-- **Python does NOT read/write clips.json today** — `backend/config/paths.py:59` knows the path; nothing uses it. No Python history module exists.
+- `content_type` originates in `suggest-clips.handler.ts:123`; the suggestion (with `content_type`) is resolved at `create-clip.handler.ts:128-137`; transcript words available at `create-clip.handler.ts:152`, but neither is threaded into `record()`.
+- **Python does NOT read/write clips.json today.** `backend/config/paths.py:59` knows the path; nothing uses it. No Python history module exists.
- Paths agree across `src/config/paths.ts` and `backend/config/paths.py`.
**CLI / Python**
@@ -35,11 +35,11 @@ shared on-disk contract; Python is the engine + history writer, web/MCP are thin
- **CLI = human ANSI text, no `--json`.** The JSON task-runner is separate (`backend/main.py` `emit_result` + `TASK_HANDLERS`), used by `PythonExecutor`. The `clips` CLI commands use the ANSI/human contract.
- `PythonExecutor.execute(taskType, params)` (`src/services/python-executor.ts`) spawns `backend/main.py`, JSON over stdin/stdout. (Relevant to Phase 2; Phase 1 CLI runs cli.py directly.)
-**Concurrency note (accepted constraint):** clips.json has no file locking. Single-user localhost tool; TS writes on render, Python writes on `clips edit` — not concurrent in practice. Do **not** add locking (over-engineering). Both writers must preserve unknown fields on rewrite (read-modify-write, never reconstruct).
+**Concurrency note (accepted constraint):** clips.json has no file locking. Single-user localhost tool; TS writes on render, Python writes on `clips edit`, not concurrent in practice. Do **not** add locking (over-engineering). Both writers must preserve unknown fields on rewrite (read-modify-write, never reconstruct).
---
-## Phase 1A — Data foundation (schema + Python history writer)
+## Phase 1A: Data foundation (schema + Python history writer)
Lowest risk, no UI. Establishes the shared contract everything else builds on.
@@ -48,8 +48,8 @@ Lowest risk, no UI. Establishes the shared contract everything else builds on.
```ts
content_type?: string; // carried from SuggestedClip at record time
transcript_slice?: string; // packed/plain text of the clip's words, captured at render time
- youtube_video_id?: string; // Phase 2 — declared now so the schema is stable
- metrics?: { // Phase 2 — declared now, never written in Phase 1
+ youtube_video_id?: string; // Phase 2, declared now so the schema is stable
+ metrics?: { // Phase 2: declared now, never written in Phase 1
views?: number;
retention?: number; // averageViewPercentage 0-100
ctr?: number; // impressionsClickThroughRate 0-100
@@ -59,7 +59,7 @@ Lowest risk, no UI. Establishes the shared contract everything else builds on.
```
2. **Thread `content_type` + `transcript_slice` into the TS record calls** where they are in scope:
- In `create-clip.handler.ts`, the resolved `suggestion` (has `content_type`) and `transcriptWords` (line 152) are both available. Build a `transcript_slice` string (join the words whose timestamps fall in `[start_second, end_second]`) and surface both on the handler's return so the web/MCP record sites can pass them.
- - Update the **5 record() sites** to pass `content_type` and `transcript_slice` when available (omit otherwise — they're optional). Batch/davinci sites: thread per-clip `content_type` if the batch spec carries it; otherwise leave undefined. **Do not invent data** — only pass what is genuinely in scope.
+ - Update the **5 record() sites** to pass `content_type` and `transcript_slice` when available (omit otherwise; they're optional). Batch/davinci sites: thread per-clip `content_type` if the batch spec carries it; otherwise leave undefined. **Do not invent data**: only pass what is genuinely in scope.
3. **Create `backend/services/clips_history.py`** mirroring `corrections.py` structure. Functions:
```python
load_clips_history() -> list[dict] # read paths["clipsHistory"], [] if missing/bad
@@ -85,14 +85,14 @@ Lowest risk, no UI. Establishes the shared contract everything else builds on.
- [ ] Python `update_clip` then TS `load()` → unknown fields survive both round-trips (write a `metrics` stub by hand, edit title in Python, confirm `metrics` still present).
### Anti-pattern guards
-- ❌ No new entities/tables, no migration script — fields are optional, old entries stay valid.
+- ❌ No new entities/tables, no migration script. Fields are optional, so old entries stay valid.
- ❌ Do not rewrite clips.json by reconstructing objects field-by-field (drops unknown keys). Read-modify-write only.
- ❌ Do not add file locking.
-- ❌ Do not fabricate `content_type`/`transcript_slice` where the source data isn't actually in scope — leave undefined.
+- ❌ Do not fabricate `content_type`/`transcript_slice` where the source data isn't actually in scope: leave undefined.
---
-## Phase 1B — CLI `clips` subcommands
+## Phase 1B: CLI `clips` subcommands
Delivers CLI parity for history + re-iteration entry point. Depends on 1A's Python service.
@@ -100,13 +100,13 @@ Delivers CLI parity for history + re-iteration entry point. Depends on 1A's Pyth
1. **Register the `clips` subparser** in `cli.py main()` (beside `knowledge`), following the existing `add_parser`/`add_subparsers` pattern:
- `clips list [-n/--limit N]`
- `clips edit <clip_id> [--title T] [--caption-style S] [--notes ...]` (metadata-only edits per design: edit → save → latest)
- - `clips reopen <clip_id>` — hydrate `.podcli/ui-state.json` from the history entry so the web Workspace opens with that clip loaded (see below).
+ - `clips reopen <clip_id>`: hydrate `.podcli/ui-state.json` from the history entry so the web Workspace opens with that clip loaded (see below).
- Add `elif args.command == "clips": cmd_clips(args)` to dispatch.
2. **Implement `cmd_clips(args)`** using the `cmd_assets`/`cmd_knowledge` ANSI template:
- `list`: print id (8-char), title, source basename, created_at, duration; show `content_type` if present.
- `edit`: `find_clip` → apply provided fields → `update_clip`. Error + `sys.exit(1)` if not found.
- - `reopen`: read the entry; write a single-suggestion `ui-state.json` — `videoPath = source_video`, a one-item `suggestions` array reconstructed from the entry (`title, start_second, end_second, duration, content_type, preview_text = transcript_slice`), `phase = "reviewing"`. This is the CLI→UI bridge over the shared `.podcli/` contract. Print confirmation + the URL `http://localhost:3847/episode?...` (or instruct to open the studio).
-3. **`reopen` semantics are metadata-only in Phase 1** — it loads the clip back into the editing surface; it does not auto-re-render. (Re-render is a save action in the UI / a future flag.)
+ - `reopen`: read the entry; write a single-suggestion `ui-state.json`, `videoPath = source_video`, a one-item `suggestions` array reconstructed from the entry (`title, start_second, end_second, duration, content_type, preview_text = transcript_slice`), `phase = "reviewing"`. This is the CLI→UI bridge over the shared `.podcli/` contract. Print confirmation + the URL `http://localhost:3847/episode?...` (or instruct to open the studio).
+3. **`reopen` semantics are metadata-only in Phase 1**: it loads the clip back into the editing surface; it does not auto-re-render. (Re-render is a save action in the UI / a future flag.)
### Documentation references
- Subparser + dispatch: `cli.py main()` (~2862-3044).
@@ -120,13 +120,13 @@ Delivers CLI parity for history + re-iteration entry point. Depends on 1A's Pyth
- [ ] Editing a clip in Python preserves its `metrics`/unknown fields (re-run the 1A round-trip check).
### Anti-pattern guards
-- ❌ Don't emit JSON from the CLI (human ANSI contract) — match existing subcommands.
+- ❌ Don't emit JSON from the CLI (human ANSI contract), match existing subcommands.
- ❌ Don't reach into TS to record; write clips.json via the Python service from 1A.
- ❌ `reopen` must not trigger a render in Phase 1.
---
-## Phase 1C — Vite + React Router scaffold (parity with current UI)
+## Phase 1C: Vite + React Router scaffold (parity with current UI)
Stand up the build app and **port the existing editor** into a route, preserving all working functionality before adding new pages.
@@ -140,7 +140,7 @@ Stand up the build app and **port the existing editor** into a route, preserving
- `/episode` (and `/episode/:source?`) → `EpisodeWorkspace` (the ported existing editor)
- `/clip/:id` → `ClipDetail` (Phase 1D)
6. **Port the existing editor** from `public/index.html` into `routes/EpisodeWorkspace.tsx` + extracted components (`LivePhonePreview`, `TikTokWireframe`, `PhoneCaptionBody`, `SpecRecap`, `McpHints`). Mostly mechanical: move JSX out of the babel `<script>`, replace CDN globals (`const {useState}=React`) with real imports, keep the `api()` fetch helper and the `STYLE_CONFIGS` map. Reuse `public/css/styles.css` (import it).
-7. **Express: serve the built SPA + add a fallback route.** Keep `express.static` at `web-server.ts:197` (now serving Vite output in `dist/ui/public`). After all `/api` routes, add an SPA fallback: `app.get("*", (req,res)=> res.sendFile(join(__dirname,"public","index.html")))` — guard so it never shadows `/api/*` or static assets.
+7. **Express: serve the built SPA + add a fallback route.** Keep `express.static` at `web-server.ts:197` (now serving Vite output in `dist/ui/public`). After all `/api` routes, add an SPA fallback: `app.get("*", (req,res)=> res.sendFile(join(__dirname,"public","index.html")))`, guard so it never shadows `/api/*` or static assets.
8. **Update build/dev scripts** in `package.json`:
- `"build": "vite build --config src/ui/client/vite.config.ts && tsc && cp -r src/ui/public/css dist/ui/public/css && cp src/ui/public/*.png dist/ui/public/"` (Vite emits HTML/JS to `dist/ui/public`; still copy non-bundled css/images, or import CSS through Vite and drop the copy).
- `"ui:dev": "vite --config src/ui/client/vite.config.ts"` (client) alongside existing `"ui": "tsx src/ui/web-server.ts"` (server). Document running both in dev.
@@ -158,23 +158,23 @@ Stand up the build app and **port the existing editor** into a route, preserving
- [ ] `git grep babel-standalone` returns nothing in the new client.
### Anti-pattern guards
-- ❌ Don't rewrite editor logic — **port** it (move + swap imports). Behavior parity first, cleanup later.
+- ❌ Don't rewrite editor logic: **port** it (move + swap imports). Behavior parity first, cleanup later.
- ❌ Don't let `tsc` try to compile the client (must be in root tsconfig `exclude`).
- ❌ SPA fallback must be registered AFTER api routes and must not intercept `/api/*`.
-- ❌ Don't break the `/api/ui-state` MCP↔UI bridge — the Workspace must still read/write it (this is how `clips reopen` hands off).
+- ❌ Don't break the `/api/ui-state` MCP↔UI bridge: the Workspace must still read/write it (this is how `clips reopen` hands off).
---
-## Phase 1D — Studio Home (library) + Clip Detail (edit page)
+## Phase 1D: Studio Home (library) + Clip Detail (edit page)
The new surfaces. Depends on 1A (fields), 1B (edit path), 1C (router/shell).
### What to implement
-1. **`StudioHome` (`/`)** — the library:
- - Fetch `/api/history` (and `/api/outputs` for file existence). Group into **episodes by `source_video` basename** (mirror `getBySource` logic client-side, or add a thin `/api/episodes` endpoint that calls `clips-history.getBySource` grouping — prefer reusing existing `/api/history` to keep code minimal).
- - Episode cards: source name, clip count, created range, status. Recent-clips rail. An **action rail** up top driven by clip state ("N clips rendered", "Episode X in review") — derive from existing data, no new backend.
+1. **`StudioHome` (`/`)**: the library:
+ - Fetch `/api/history` (and `/api/outputs` for file existence). Group into **episodes by `source_video` basename** (mirror `getBySource` logic client-side, or add a thin `/api/episodes` endpoint that calls `clips-history.getBySource` grouping; prefer reusing existing `/api/history` to keep code minimal).
+ - Episode cards: source name, clip count, created range, status. Recent-clips rail. An **action rail** up top driven by clip state ("N clips rendered", "Episode X in review"), derive from existing data with no new backend.
- "+ New Episode" → `/episode` (fresh editor).
-2. **`ClipDetail` (`/clip/:id`)** — the per-clip edit page (design decision: edit → save → latest, no version stacks):
+2. **`ClipDetail` (`/clip/:id`)**: the per-clip edit page (design decision: edit → save → latest, no version stacks):
- Load the clip (from `/api/history` by id, or a small `/api/clip/:id` that calls `find_clip`). Show preview (`/api/preview/:filename` from `output_path`), transcript_slice, content_type, settings.
- Editable fields: **title, caption style, thumbnail, cut timing**. Save:
- Metadata-only edits (title) → POST to a thin endpoint that calls the **same Python `update_clip`** (via `PythonExecutor` or a small route) so TS and CLI share one writer. (Minimal: add `update_clip` task to `backend/main.py` TASK_HANDLERS reusing 1A's service, exposed as `/api/clip/:id` PATCH.)
@@ -196,13 +196,13 @@ The new surfaces. Depends on 1A (fields), 1B (edit path), 1C (router/shell).
- [ ] "Reopen in editor" loads the clip into the Workspace (same result as `clips reopen`).
### Anti-pattern guards
-- ❌ No version stacks/trays — one current state per clip.
-- ❌ Don't add a second history writer in TS for edits — route edits through the Python `update_clip` so there is one source of truth.
-- ❌ No YouTube/metrics UI (Phase 2) — `metrics`/`youtube_video_id` exist in the schema but are not surfaced or written here.
+- ❌ No version stacks/trays: one current state per clip.
+- ❌ Don't add a second history writer in TS for edits: route edits through the Python `update_clip` so there is one source of truth.
+- ❌ No YouTube/metrics UI (Phase 2), `metrics`/`youtube_video_id` exist in the schema but are not surfaced or written here.
---
-## Final Phase — Verification
+## Final Phase: Verification
1. **Build & run:** `npm run build` clean (tsc + vite); `npm run ui:prod` serves the SPA on 3847; deep links + refresh work.
2. **Parity:** full upload→transcribe→suggest→create/batch flow works in the new UI identically to the removed `index.html`.
diff --git a/remotion/bundle-cache.mjs b/remotion/bundle-cache.mjs
index e8b9dff..617a6b2 100644
--- a/remotion/bundle-cache.mjs
+++ b/remotion/bundle-cache.mjs
@@ -10,6 +10,7 @@ const require = createRequire(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = path.resolve(__dirname, "..");
+
const CACHE_ROOT = process.env.PODCLI_CACHE_DIR
? path.resolve(process.env.PODCLI_CACHE_DIR)
: path.join(PROJECT_ROOT, "data", "cache");
@@ -34,17 +35,20 @@ function currentHash() {
function walk(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
+
if (entry.isDirectory()) walk(full);
else if (entry.isFile()) hash.update(fs.readFileSync(full));
}
}
walk(path.join(__dirname, "src"));
+
if (fs.existsSync(PUBLIC_DIR)) walk(PUBLIC_DIR);
hash.update(fs.readFileSync(path.join(__dirname, "webpack-override.mjs")));
hash.update(fs.readFileSync(fileURLToPath(import.meta.url)));
hash.update(`remotion@${require("remotion/package.json").version}`);
hash.update(`@remotion/bundler@${require("@remotion/bundler/package.json").version}`);
+
return hash.digest("hex");
}
@@ -64,22 +68,28 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function removeStaleLock() {
try {
const entries = fs.readdirSync(LOCK_DIR, { withFileTypes: true });
+
if (entries.length === 0) {
if (Date.now() - fs.statSync(LOCK_DIR).mtimeMs > LOCK_STALE_MS) {
fs.rmdirSync(LOCK_DIR);
+
return true;
}
+
return false;
}
for (const entry of entries) {
if (!entry.isFile()) continue;
const tokenPath = path.join(LOCK_DIR, entry.name);
+
if (Date.now() - fs.statSync(tokenPath).mtimeMs > LOCK_STALE_MS) {
fs.rmSync(tokenPath, { force: true });
}
}
+
fs.rmdirSync(LOCK_DIR);
+
return true;
} catch {
return false;
@@ -88,18 +98,22 @@ function removeStaleLock() {
async function acquireLock() {
const token = `${process.pid}-${crypto.randomUUID()}`;
+
for (;;) {
try {
fs.mkdirSync(LOCK_DIR);
const tokenPath = path.join(LOCK_DIR, token);
+
try {
fs.writeFileSync(tokenPath, token, { flag: "wx" });
} catch (err) {
try {
fs.rmdirSync(LOCK_DIR);
} catch {}
+
throw err;
}
+
const lock = { token, tokenPath, heartbeat: undefined };
lock.heartbeat = setInterval(() => {
try {
@@ -110,10 +124,12 @@ async function acquireLock() {
}
}, LOCK_HEARTBEAT_MS);
lock.heartbeat.unref();
+
return lock;
} catch (err) {
if (err.code !== "EEXIST") throw err;
}
+
if (removeStaleLock()) continue;
await sleep(500);
}
@@ -121,9 +137,11 @@ async function acquireLock() {
function releaseLock(lock) {
clearInterval(lock.heartbeat);
+
try {
fs.rmSync(lock.tokenPath, { force: true });
} catch {}
+
try {
fs.rmdirSync(LOCK_DIR);
} catch {}
@@ -133,12 +151,14 @@ function ownsLock(lock) {
return fs.existsSync(lock.tokenPath);
}
-export async function getCachedBundle({ onBundle } = {}) {
+export async function getCachedBundle({ onBundle, bundler = bundle } = {}) {
const want = currentHash();
+
if (cacheIsValid(want)) return CACHE_DIR;
fs.mkdirSync(CACHE_ROOT, { recursive: true });
const lock = await acquireLock();
+
try {
if (cacheIsValid(want)) return CACHE_DIR;
@@ -147,22 +167,26 @@ export async function getCachedBundle({ onBundle } = {}) {
// never leaves CACHE_DIR half-written.
const staging = `${CACHE_DIR}.tmp-${lock.token}`;
fs.rmSync(staging, { recursive: true, force: true });
+
try {
- await bundle({
+ await bundler({
entryPoint: ENTRY_POINT,
outDir: staging,
publicDir: PUBLIC_DIR,
webpackOverride,
});
+
if (!ownsLock(lock)) {
throw new Error("Bundle cache lock ownership lost");
}
+
fs.writeFileSync(path.join(staging, ".hash"), want);
fs.rmSync(CACHE_DIR, { recursive: true, force: true });
fs.renameSync(staging, CACHE_DIR);
} finally {
fs.rmSync(staging, { recursive: true, force: true });
}
+
return CACHE_DIR;
} finally {
releaseLock(lock);
diff --git a/remotion/bundle-cache.test.mjs b/remotion/bundle-cache.test.mjs
index ec2ea39..43379b8 100644
--- a/remotion/bundle-cache.test.mjs
+++ b/remotion/bundle-cache.test.mjs
@@ -3,9 +3,8 @@ import os from "os";
import path from "path";
import { fileURLToPath } from "url";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { bundle } from "@remotion/bundler";
-vi.mock("@remotion/bundler", () => ({ bundle: vi.fn() }));
+const bundle = vi.fn();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -14,17 +13,21 @@ const temporaryDirectories = [];
function deferred() {
let resolve;
+
const promise = new Promise((resolvePromise) => {
resolve = resolvePromise;
});
+
return { promise, resolve };
}
afterEach(() => {
- vi.mocked(bundle).mockReset();
+ bundle.mockReset();
vi.resetModules();
+
if (savedCacheDir === undefined) delete process.env.PODCLI_CACHE_DIR;
else process.env.PODCLI_CACHE_DIR = savedCacheDir;
+
for (const directory of temporaryDirectories.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
@@ -36,25 +39,27 @@ describe("bundle cache hash", () => {
temporaryDirectories.push(cacheRoot);
process.env.PODCLI_CACHE_DIR = cacheRoot;
- vi.mocked(bundle).mockImplementation(async ({ outDir }) => {
+ bundle.mockImplementation(async ({ outDir }) => {
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, "index.html"), "");
+
return outDir;
});
const { getCachedBundle } = await import("./bundle-cache.mjs");
- await getCachedBundle();
+ await getCachedBundle({ bundler: bundle });
expect(bundle).toHaveBeenCalledTimes(1);
- await getCachedBundle();
+ await getCachedBundle({ bundler: bundle });
expect(bundle).toHaveBeenCalledTimes(1);
const publicDir = path.join(__dirname, "public");
fs.mkdirSync(publicDir, { recursive: true });
const marker = path.join(publicDir, `.bundle-cache-test-${process.pid}`);
fs.writeFileSync(marker, "new texture");
+
try {
- await getCachedBundle();
+ await getCachedBundle({ bundler: bundle });
expect(bundle).toHaveBeenCalledTimes(2);
} finally {
fs.rmSync(marker, { force: true });
@@ -69,27 +74,30 @@ describe("bundle cache lock", () => {
process.env.PODCLI_CACHE_DIR = cacheRoot;
const pendingBundles = [];
- vi.mocked(bundle).mockImplementation(async ({ outDir }) => {
+ bundle.mockImplementation(async ({ outDir }) => {
const completion = deferred();
pendingBundles.push(completion);
await completion.promise;
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, "index.html"), "");
+
return outDir;
});
const { CACHE_DIR, getCachedBundle } = await import("./bundle-cache.mjs");
const lockDir = `${CACHE_DIR}.lock`;
- const first = getCachedBundle();
+ const first = getCachedBundle({ bundler: bundle });
await vi.waitFor(() => expect(pendingBundles).toHaveLength(1));
const staleTime = new Date(Date.now() - 10 * 60 * 1000);
+
for (const entry of fs.readdirSync(lockDir)) {
fs.utimesSync(path.join(lockDir, entry), staleTime, staleTime);
}
+
fs.utimesSync(lockDir, staleTime, staleTime);
- const second = getCachedBundle();
+ const second = getCachedBundle({ bundler: bundle });
await vi.waitFor(() => expect(pendingBundles).toHaveLength(2));
const replacementTokens = fs.readdirSync(lockDir);
expect(replacementTokens).toHaveLength(1);
diff --git a/remotion/package-lock.json b/remotion/package-lock.json
index 0029e5d..a583f59 100644
--- a/remotion/package-lock.json
+++ b/remotion/package-lock.json
@@ -11,11 +11,11 @@
"@fontsource/dm-sans": "5.2.8",
"@fontsource/noto-sans-georgian": "5.3.0",
"@fontsource/playfair-display": "5.3.0",
- "@remotion/bundler": "4.0.488",
- "@remotion/renderer": "4.0.488",
+ "@remotion/bundler": "4.0.508",
+ "@remotion/renderer": "4.0.508",
"react": "19.2.7",
"react-dom": "19.2.7",
- "remotion": "4.0.488"
+ "remotion": "4.0.508"
}
},
"node_modules/@emnapi/core": {
@@ -660,21 +660,21 @@
}
},
"node_modules/@remotion/bundler": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/bundler/-/bundler-4.0.488.tgz",
- "integrity": "sha512-HBBH+IRRSuGjgc23e4uujOJffKvPcMhDiMrl9X3TJJXCO/qc9CqUQzW4yH4m04yecUBEZjogmrXLBoSVNYhZcw==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/bundler/-/bundler-4.0.508.tgz",
+ "integrity": "sha512-hFOIXXHK/W3Ue7V/Y+lbFJ6dGWYFKUWy1RrOwteEcLvU5OQmmTkNB2fSA7dy0Semii25F9TML8rpXGNQENhAbg==",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
- "@remotion/media-parser": "4.0.488",
- "@remotion/studio": "4.0.488",
- "@remotion/studio-shared": "4.0.488",
- "@remotion/timeline-utils": "4.0.488",
+ "@remotion/media-parser": "4.0.508",
+ "@remotion/studio": "4.0.508",
+ "@remotion/studio-shared": "4.0.508",
+ "@remotion/timeline-utils": "4.0.508",
"@rspack/core": "1.7.11",
"@rspack/plugin-react-refresh": "1.6.1",
"css-loader": "7.1.4",
"esbuild": "0.28.1",
"react-refresh": "0.18.0",
- "remotion": "4.0.488",
+ "remotion": "4.0.508",
"style-loader": "4.0.0",
"webpack": "5.105.0"
},
@@ -683,24 +683,16 @@
"react-dom": ">=16.8.0"
}
},
- "node_modules/@remotion/canvas-capture": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/canvas-capture/-/canvas-capture-4.0.488.tgz",
- "integrity": "sha512-K5unf3W3yRlzoERZ1Kd+3k6NZJZdKupSEb1O0oPf5VEkct9PI5DpuK1b/AGPULwSop14GHb7GoYlRFse9rAiDA==",
- "license": "Remotion License",
- "dependencies": {
- "mediabunny": "1.50.8",
- "remotion": "4.0.488"
- },
- "peerDependencies": {
- "react": ">=16.8.0",
- "react-dom": ">=16.8.0"
- }
+ "node_modules/@remotion/captions": {
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/captions/-/captions-4.0.508.tgz",
+ "integrity": "sha512-0IX2QTfzN/7mHzztYDwHKv06i+nP+lO2HDeJ4eKsl4yoVd6tvQ9IX4budwnwMR+yy/2wxj9L7iCW/8rnlFdGrw==",
+ "license": "MIT"
},
"node_modules/@remotion/compositor-darwin-arm64": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-arm64/-/compositor-darwin-arm64-4.0.488.tgz",
- "integrity": "sha512-FP4FY4zPEMQ/EQYBfs20TYfs2kyHlwpypaR+BRk2zYV29r3klNi+vzrlxk0P480g3QiX0sxKZ8AFDeBZdbP6UA==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-arm64/-/compositor-darwin-arm64-4.0.508.tgz",
+ "integrity": "sha512-xg05WFTGjTQnC8U8HsDYFuxpP+5CMdmZx2fMAri+7CckpDrlNkPdflbRqWVjQgksL2dzbzdEb7ZkVf9qSBpOjQ==",
"cpu": [
"arm64"
],
@@ -710,9 +702,9 @@
]
},
"node_modules/@remotion/compositor-darwin-x64": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-x64/-/compositor-darwin-x64-4.0.488.tgz",
- "integrity": "sha512-5GBn7Oqx2eAMJfXikrRAGcdjtJwT2/zHpguLuoNzbepuc7AAb1Sj7iqzj+kMLQU7Dc4/iiVdvN7SOVc4adFbgA==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-x64/-/compositor-darwin-x64-4.0.508.tgz",
+ "integrity": "sha512-ma9ZAgBQ9VWpqKCUaK3T2H7ZThGq/IWLOTs+Reqioyu67o7UWF1KJdQMO9AuLjtRXnWJm7eVRmcF0+2pPcCdsQ==",
"cpu": [
"x64"
],
@@ -722,57 +714,69 @@
]
},
"node_modules/@remotion/compositor-linux-arm64-gnu": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-gnu/-/compositor-linux-arm64-gnu-4.0.488.tgz",
- "integrity": "sha512-kHfWTF3W/N6q1ZTCXiFhJGcDZB4GB2ZnglbK90k/b3os0IyJvz8n44qFNz0PS3HKCerG9vO8aYLTRNg41g56Og==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-gnu/-/compositor-linux-arm64-gnu-4.0.508.tgz",
+ "integrity": "sha512-ryC1lU1EmBENhRA8PV1hQbJYd1SOuEfSftib34mqZCJyo2CmkJ8gzJALw+RQHQ7+OQ2yybNQULwOCahmQZ2sEQ==",
"cpu": [
"arm64"
],
+ "libc": [
+ "glibc"
+ ],
"optional": true,
"os": [
"linux"
]
},
"node_modules/@remotion/compositor-linux-arm64-musl": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-musl/-/compositor-linux-arm64-musl-4.0.488.tgz",
- "integrity": "sha512-ySrF9LfJDjc+yqenfWMGvPVoINJe7grxlT0i9DjcPX6XS+yfDSQQSFnDfNB0jdHiuD8NJjjaJ0AGhOozKIQLlg==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-musl/-/compositor-linux-arm64-musl-4.0.508.tgz",
+ "integrity": "sha512-+CjqbOcoEyCa8VzzhtyRpynWINCUvvg8cAP+2bQLPeDX7Sceca1greJ8K4+y1YqmCcjtRiwb0V0cFYR0Ys4E+g==",
"cpu": [
"arm64"
],
+ "libc": [
+ "musl"
+ ],
"optional": true,
"os": [
"linux"
]
},
"node_modules/@remotion/compositor-linux-x64-gnu": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-gnu/-/compositor-linux-x64-gnu-4.0.488.tgz",
- "integrity": "sha512-xXzFkWAjWVJNl9/lYuEgqVYJQd+yNaxM03gLaG2CYEK3yq03+PHwdDrs9W2gTHs1l8P1XkMuiOGXmtlAO6W9Zg==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-gnu/-/compositor-linux-x64-gnu-4.0.508.tgz",
+ "integrity": "sha512-17KSBgA2bF/kXezB8FqywdK3a99SM1BZ3ErPXxtJiLDYR0EG6bg9CySL87iPJ7fYsk5Enj5Rm+A5o+AnkdKZlQ==",
"cpu": [
"x64"
],
+ "libc": [
+ "glibc"
+ ],
"optional": true,
"os": [
"linux"
]
},
"node_modules/@remotion/compositor-linux-x64-musl": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-musl/-/compositor-linux-x64-musl-4.0.488.tgz",
- "integrity": "sha512-bu2JPr0UTufzYpMzt8jBmC93RxKI9iqOVSzISW7bUDDZzuUMdcUJNDeauWuI9b6B17bn3j3VoDbOrZ/kKeb4/w==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-musl/-/compositor-linux-x64-musl-4.0.508.tgz",
+ "integrity": "sha512-XJumh4s8VNh8BHAy+sV8KoSGWBNsiNRcrpyQat3nQw7ddvP+5vJJMBnkFP3+wGt/56eL8im5HA131iKII8pXYw==",
"cpu": [
"x64"
],
+ "libc": [
+ "musl"
+ ],
"optional": true,
"os": [
"linux"
]
},
"node_modules/@remotion/compositor-win32-x64-msvc": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/compositor-win32-x64-msvc/-/compositor-win32-x64-msvc-4.0.488.tgz",
- "integrity": "sha512-iljgUki6NBoTIfxRyOEhMhyVBbo0Yot2sb6El8qeUBDrNc3Ctl3ixBT2lZZJmdq3gaY46gKH9lYENvE2kGQALA==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/compositor-win32-x64-msvc/-/compositor-win32-x64-msvc-4.0.508.tgz",
+ "integrity": "sha512-odYJig/S3MVgbRPKrdf8ew2bswVXloPNWw7G3zfFH8eu5BrA9uBTfYwtcbQcLrR2/RUQpcWd2v66bpbaShIOWA==",
"cpu": [
"x64"
],
@@ -782,25 +786,25 @@
]
},
"node_modules/@remotion/licensing": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.488.tgz",
- "integrity": "sha512-5jVmxoOzpeZMnLX7qLQUteOA0vbj+uPYHH8G3nuD87xnPPWDGMy/t8bA8GuImfLn55aM6jaNLP4ngi3IorlvgA==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.508.tgz",
+ "integrity": "sha512-S9w6lckixF0tYc3wcnh1zLACPl0AgG9v/QGOYqkkaZX/p+F86202+YMWKAHdMiCQPEYntTfCgIfnqucGuLoWeA==",
"license": "MIT"
},
"node_modules/@remotion/media-parser": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/media-parser/-/media-parser-4.0.488.tgz",
- "integrity": "sha512-g4Q2S/Iso87h/ZMWniv3QyZEV45iVg6wwlPSd2ukXAVCh3Gz5e333/y4exNT/MZ2l45WPaNN9CA4EV3qsLu8bw==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/media-parser/-/media-parser-4.0.508.tgz",
+ "integrity": "sha512-kJrY/pnhBxVEM1xBVbT+vrsPmrDQERFepHhOD7XG/XCj/WgR71FIeoBMvn0YnYs6URkGBycIV6V2vlPsN8kYXg==",
"license": "Remotion License https://remotion.dev/license"
},
"node_modules/@remotion/media-utils": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.488.tgz",
- "integrity": "sha512-Q5Q02PtGmGLIb2pjUiAQt/2dZDHezpjF57hNmV/XMzM7RBw+RiaPJMMRtuJ5hSgOWSJouGMUvtNnlKO/H0L6CA==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.508.tgz",
+ "integrity": "sha512-hNNpE9OH9Sb3xKF33mQiAFQoL4+k14k50RylSfOWXVZYWn9vcIA7dgcqLy2SqFbtQP8AJAlT1BXe6kBMmQgnNQ==",
"license": "MIT",
"dependencies": {
"mediabunny": "1.50.8",
- "remotion": "4.0.488"
+ "remotion": "4.0.508"
},
"peerDependencies": {
"react": ">=16.8.0",
@@ -808,12 +812,12 @@
}
},
"node_modules/@remotion/player": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.488.tgz",
- "integrity": "sha512-bP9y6PFHtP79ikR2zxFiMwR11Cc5BoN9+PEP1YEdMXhkf4o+zDj6PzNw/Va2SjWhozrOTgVshgs1QZfQYleEkg==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.508.tgz",
+ "integrity": "sha512-1PRmoz39abpF3Br9FPSpJrCb7X+/JpYHr66AzE+qNsiRQ5HssRqgUwVvF/F1zLKgjmT+NQlJDADbCGswcO/K2A==",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
- "remotion": "4.0.488"
+ "remotion": "4.0.508"
},
"peerDependencies": {
"react": ">=16.8.0",
@@ -821,26 +825,26 @@
}
},
"node_modules/@remotion/renderer": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/renderer/-/renderer-4.0.488.tgz",
- "integrity": "sha512-gChcGkdrp4/0hmJDUU75bmvOk6RSO+xbzpQM82DvGbBEKHd/PmfEObsPXW9biMvJ2PG9IUAbfNhCBLJZMOTL6A==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/renderer/-/renderer-4.0.508.tgz",
+ "integrity": "sha512-zOjyc2JTLq4r7FnMPGqN4GdP0gt6roKk+RLPpNMV22A0bvd2zH9xc4V3FDxk7Mna+YDv/cD494BR4HxbtPS4hA==",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
- "@remotion/licensing": "4.0.488",
- "@remotion/streaming": "4.0.488",
+ "@remotion/licensing": "4.0.508",
+ "@remotion/streaming": "4.0.508",
"execa": "5.1.1",
- "remotion": "4.0.488",
- "source-map": "0.8.0-beta.0",
+ "remotion": "4.0.508",
+ "source-map": "0.8.0",
"ws": "8.21.0"
},
"optionalDependencies": {
- "@remotion/compositor-darwin-arm64": "4.0.488",
- "@remotion/compositor-darwin-x64": "4.0.488",
- "@remotion/compositor-linux-arm64-gnu": "4.0.488",
- "@remotion/compositor-linux-arm64-musl": "4.0.488",
- "@remotion/compositor-linux-x64-gnu": "4.0.488",
- "@remotion/compositor-linux-x64-musl": "4.0.488",
- "@remotion/compositor-win32-x64-msvc": "4.0.488"
+ "@remotion/compositor-darwin-arm64": "4.0.508",
+ "@remotion/compositor-darwin-x64": "4.0.508",
+ "@remotion/compositor-linux-arm64-gnu": "4.0.508",
+ "@remotion/compositor-linux-arm64-musl": "4.0.508",
+ "@remotion/compositor-linux-x64-gnu": "4.0.508",
+ "@remotion/compositor-linux-x64-musl": "4.0.508",
+ "@remotion/compositor-win32-x64-msvc": "4.0.508"
},
"peerDependencies": {
"react": ">=16.8.0",
@@ -848,68 +852,76 @@
}
},
"node_modules/@remotion/streaming": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/streaming/-/streaming-4.0.488.tgz",
- "integrity": "sha512-/l+drcbhtg6ot4y6ApPolkBjsO0cZx20KtFBnCrzxufnNHRKOp7RzeOHxLXNVLMP/Bz2cf31sQYXbalXk16sjQ==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/streaming/-/streaming-4.0.508.tgz",
+ "integrity": "sha512-0RGjgFXkOwBAgPl/z4fO5eTWIMlWfbUFV747TETUpjSO2z6wSTpTJr6WGn9tOSi6OSjdtsqXcBEUpt1XvMuMhA==",
"license": "MIT"
},
"node_modules/@remotion/studio": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/studio/-/studio-4.0.488.tgz",
- "integrity": "sha512-LVuW1usvzqz3GRVf0jL9jYT0XzYglS/TGuyW5ee5o3hmz47ksiwCUYYt6zv9x0DzlyZtK6dzfYzbvPVwSIQkiQ==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/studio/-/studio-4.0.508.tgz",
+ "integrity": "sha512-5dkFn9wttOJsx1NobBU2TowXhPCyHasffI9usfN2sMLbX1l7r7I91FaVXm7JCeBs7Wor9XdZJjvcqDrjuIZh3w==",
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "0.3.31",
- "@remotion/canvas-capture": "4.0.488",
- "@remotion/media-utils": "4.0.488",
- "@remotion/player": "4.0.488",
- "@remotion/renderer": "4.0.488",
- "@remotion/studio-shared": "4.0.488",
- "@remotion/timeline-utils": "4.0.488",
- "@remotion/web-renderer": "4.0.488",
- "@remotion/zod-types": "4.0.488",
+ "@remotion/captions": "4.0.508",
+ "@remotion/media-utils": "4.0.508",
+ "@remotion/player": "4.0.508",
+ "@remotion/renderer": "4.0.508",
+ "@remotion/studio-protocol": "4.0.508",
+ "@remotion/studio-shared": "4.0.508",
+ "@remotion/timeline-utils": "4.0.508",
+ "@remotion/web-renderer": "4.0.508",
+ "@remotion/zod-types": "4.0.508",
"mediabunny": "1.50.8",
"memfs": "3.4.3",
"open": "8.4.2",
- "remotion": "4.0.488",
+ "remotion": "4.0.508",
"semver": "7.5.3",
- "zod": "4.3.6"
+ "zod": "4.4.3"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
+ "node_modules/@remotion/studio-protocol": {
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/studio-protocol/-/studio-protocol-4.0.508.tgz",
+ "integrity": "sha512-oQ4WwFMNuoS5AhwBLJ4kb/fb3bCtQx9lBIDmQRD5eOON0quRLmVvsckyggNEeAYh8sdFsWrxLsrir2OwBzPftQ==",
+ "license": "Remotion License"
+ },
"node_modules/@remotion/studio-shared": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/studio-shared/-/studio-shared-4.0.488.tgz",
- "integrity": "sha512-QPLJEteenroRRPJ3z9gxffycGJanYNC/XvGJbpSlcELYMyZBkE/+LYq6bNV2Xso5FoGO50GUd9lt/fCKJR3F0A==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/studio-shared/-/studio-shared-4.0.508.tgz",
+ "integrity": "sha512-l+mbQWucqxGdm5xMImUFpQggxnlZpl27AR0Pf07ljuCSNr0NKpkGjc++HAGilayrOaHGwPkdIWJfPgv8cBrBQw==",
"license": "MIT",
"dependencies": {
- "remotion": "4.0.488"
+ "@remotion/studio-protocol": "4.0.508",
+ "remotion": "4.0.508"
}
},
"node_modules/@remotion/timeline-utils": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/timeline-utils/-/timeline-utils-4.0.488.tgz",
- "integrity": "sha512-TwC4bPkJHm9hwtzI2pVjERKCmcsw82FoGSecc7c7Bwo9az+1l0KenTg1HznMVhqJRtMTTyDSZvkiD7Lat1TFdg==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/timeline-utils/-/timeline-utils-4.0.508.tgz",
+ "integrity": "sha512-AF3Nwyse5xmb51kRwpqGDhCW02KsHCjjwwIuJ7dcVm3s7H9G8uAxyC7shxvzvxzvxFl/Z168cf4Tlfh1FdBrwA==",
"license": "MIT",
"dependencies": {
"mediabunny": "1.50.8"
}
},
"node_modules/@remotion/web-renderer": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/web-renderer/-/web-renderer-4.0.488.tgz",
- "integrity": "sha512-9hzmwPGRUvlXs0pjdlI4kIS3nogVOa6Wheoob+S7PxaFLK2wobxbNtTAKNidoLJXfv/chCo65v1ThPJFsyb5qw==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/web-renderer/-/web-renderer-4.0.508.tgz",
+ "integrity": "sha512-knl+/1s7C5ZYnm9kL51Bphs+iqMRv3LQzw2uoMRSlDWR0FGBUNceDMxozyuBnS53mIiDE3zUpKweI+AJtSy+Lw==",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
"@mediabunny/aac-encoder": "1.50.8",
"@mediabunny/flac-encoder": "1.50.8",
"@mediabunny/mp3-encoder": "1.50.8",
- "@remotion/licensing": "4.0.488",
+ "@remotion/licensing": "4.0.508",
"mediabunny": "1.50.8",
- "remotion": "4.0.488"
+ "remotion": "4.0.508"
},
"peerDependencies": {
"react": ">=18.0.0",
@@ -917,12 +929,12 @@
}
},
"node_modules/@remotion/zod-types": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/@remotion/zod-types/-/zod-types-4.0.488.tgz",
- "integrity": "sha512-2XdHInhWUX5DhaMNxVaOsv/T6po4siPOJ8EcU0AA8nBbwIgTpFSE/R6XwMRQGwEtCknY3EOJBORhVfWh0tXOCQ==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/@remotion/zod-types/-/zod-types-4.0.508.tgz",
+ "integrity": "sha512-rXEvoe07Yid/1beu51ShQyuo6L4QI8viKVI46e2DhuUauhzL1PTjSEbUsmsUlT//zFQO9nki7+nycNOR4xRe0w==",
"license": "MIT",
"dependencies": {
- "remotion": "4.0.488"
+ "remotion": "4.0.508"
}
},
"node_modules/@rspack/binding": {
@@ -1922,12 +1934,6 @@
"url": "https://opencollective.com/webpack"
}
},
- "node_modules/lodash.sortby": {
- "version": "4.7.0",
- "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz",
- "integrity": "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==",
- "license": "MIT"
- },
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
@@ -2204,15 +2210,6 @@
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"license": "MIT"
},
- "node_modules/punycode": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
- "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/react": {
"version": "19.2.7",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
@@ -2244,9 +2241,9 @@
}
},
"node_modules/remotion": {
- "version": "4.0.488",
- "resolved": "https://registry.npmjs.org/remotion/-/remotion-4.0.488.tgz",
- "integrity": "sha512-V+2GQChZQkrBWrT2+bqpvu9Q/8mAri08vdZEdWsl5hy5j8/3z2DAr+Fw81K4RHmLKgKbZY21AJv7hUD+DKOdhA==",
+ "version": "4.0.508",
+ "resolved": "https://registry.npmjs.org/remotion/-/remotion-4.0.508.tgz",
+ "integrity": "sha512-HEL3zBa6XEoGtqTKs6PiMI8tsZ9c731xFpBtsd8fGa04FjdRdXAybDUEWNLp08UhvNY9YUM+LACLvKu+NWog2w==",
"license": "SEE LICENSE IN LICENSE.md",
"peerDependencies": {
"react": ">=16.8.0",
@@ -2330,16 +2327,12 @@
"license": "ISC"
},
"node_modules/source-map": {
- "version": "0.8.0-beta.0",
- "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0-beta.0.tgz",
- "integrity": "sha512-2ymg6oRBpebeZi9UUNsgQ89bhx01TcTkmNTGnNO88imTmbSgy4nfujrgVEFKWpMTEGA11EDkTt7mqObTPdigIA==",
- "deprecated": "The work that was done in this beta branch won't be included in future versions",
+ "version": "0.8.0",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0.tgz",
+ "integrity": "sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ==",
"license": "BSD-3-Clause",
- "dependencies": {
- "whatwg-url": "^7.0.0"
- },
"engines": {
- "node": ">= 8"
+ "node": ">= 12"
}
},
"node_modules/source-map-js": {
@@ -2507,15 +2500,6 @@
}
}
},
- "node_modules/tr46": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz",
- "integrity": "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA==",
- "license": "MIT",
- "dependencies": {
- "punycode": "^2.1.0"
- }
- },
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -2577,12 +2561,6 @@
"node": ">=10.13.0"
}
},
- "node_modules/webidl-conversions": {
- "version": "4.0.2",
- "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz",
- "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==",
- "license": "BSD-2-Clause"
- },
"node_modules/webpack": {
"version": "5.105.0",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.105.0.tgz",
@@ -2640,17 +2618,6 @@
"node": ">=10.13.0"
}
},
- "node_modules/whatwg-url": {
- "version": "7.1.0",
- "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.1.0.tgz",
- "integrity": "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==",
- "license": "MIT",
- "dependencies": {
- "lodash.sortby": "^4.7.0",
- "tr46": "^1.0.1",
- "webidl-conversions": "^4.0.2"
- }
- },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -2694,9 +2661,9 @@
"license": "ISC"
},
"node_modules/zod": {
- "version": "4.3.6",
- "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
- "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
diff --git a/remotion/package.json b/remotion/package.json
index 52ca62a..56b5dc1 100644
--- a/remotion/package.json
+++ b/remotion/package.json
@@ -8,10 +8,10 @@
"@fontsource/dm-sans": "5.2.8",
"@fontsource/noto-sans-georgian": "5.3.0",
"@fontsource/playfair-display": "5.3.0",
- "@remotion/bundler": "4.0.488",
- "@remotion/renderer": "4.0.488",
+ "@remotion/bundler": "4.0.508",
+ "@remotion/renderer": "4.0.508",
"react": "19.2.7",
"react-dom": "19.2.7",
- "remotion": "4.0.488"
+ "remotion": "4.0.508"
}
}
diff --git a/remotion/remotion.config.ts b/remotion/remotion.config.ts
index c46219f..eb20713 100644
--- a/remotion/remotion.config.ts
+++ b/remotion/remotion.config.ts
@@ -2,5 +2,7 @@ import { Config } from "@remotion/cli/config";
import { webpackOverride } from "./webpack-override.mjs";
Config.setVideoImageFormat("jpeg");
+
Config.setOverwriteOutput(true);
+
Config.overrideWebpackConfig(webpackOverride);
diff --git a/remotion/render-audiogram.mjs b/remotion/render-audiogram.mjs
index b62c4ab..18d654a 100644
--- a/remotion/render-audiogram.mjs
+++ b/remotion/render-audiogram.mjs
@@ -26,6 +26,7 @@ import { renderMedia, selectComposition } from "@remotion/renderer";
// Same reason as remotion/render.mjs: the 30s default is measured against
// the font delayRender competing with the whole bundle.
const DELAY_RENDER_TIMEOUT_MS = 120_000;
+
import { getCachedBundle } from "./bundle-cache.mjs";
import path from "path";
import fs from "fs";
@@ -36,17 +37,20 @@ import { spawnSync } from "child_process";
function parseArgs() {
const args = process.argv.slice(2);
const opts = {};
+
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith("--") && i + 1 < args.length) {
opts[args[i].replace(/^--/, "")] = args[i + 1];
i++;
}
}
+
return opts;
}
async function main() {
const opts = parseArgs();
+
if (!opts.props || !opts.output || !opts.audio) {
console.error(
"Usage: render-audiogram.mjs --props <json> --audio <file> --start <s> --end <s> --output <path>",
@@ -83,6 +87,7 @@ async function main() {
const bundleLocation = await getCachedBundle({
onBundle: () => console.log(" Remotion: bundling (first run, or src/config changed)..."),
});
+
const composition = await selectComposition({
timeoutInMilliseconds: DELAY_RENDER_TIMEOUT_MS,
serveUrl: bundleLocation,
@@ -111,6 +116,7 @@ async function main() {
});
const ffmpeg = process.env.PODCLI_FFMPEG || "ffmpeg";
+
const mux = spawnSync(
ffmpeg,
[
@@ -132,11 +138,13 @@ async function main() {
],
{ encoding: "utf-8" },
);
+
try {
fs.unlinkSync(silentVideo);
} catch {
// A leftover temp file is not worth failing a finished render over.
}
+
if (mux.status !== 0 || !fs.existsSync(opts.output)) {
console.error(`Audio mux failed:\n${(mux.stderr || "").slice(-800)}`);
process.exit(1);
diff --git a/remotion/render-bookend.mjs b/remotion/render-bookend.mjs
index 0d76530..8368876 100644
--- a/remotion/render-bookend.mjs
+++ b/remotion/render-bookend.mjs
@@ -26,18 +26,21 @@ import { spawnSync } from "child_process";
function parseArgs() {
const args = process.argv.slice(2);
const opts = {};
+
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith("--") && i + 1 < args.length) {
opts[args[i].replace(/^--/, "")] = args[i + 1];
i++;
}
}
+
return opts;
}
async function main() {
const opts = parseArgs();
+
if (!opts.mode || !opts.output) {
console.error("Usage: render-bookend.mjs --mode intro|outro --title <t> --output <path> [--handle --platforms --seconds --bg --accent]");
process.exit(1);
@@ -48,6 +51,7 @@ async function main() {
const height = parseInt(opts.height || "1920", 10);
const seconds = parseFloat(opts.seconds || "3");
const durationInFrames = Math.round(seconds * fps);
+
const platforms = (opts.platforms || "tiktok,instagram,youtube,x")
.split(",").map((s) => s.trim()).filter(Boolean);
@@ -63,6 +67,7 @@ async function main() {
const bundleLocation = await getCachedBundle({
onBundle: () => console.log(" Remotion: bundling (first run, or src/config changed)..."),
});
+
const composition = await selectComposition({ serveUrl: bundleLocation, id: "Bookend", inputProps });
const seed = `${path.resolve(opts.output)}:${process.pid}`;
@@ -101,9 +106,11 @@ async function main() {
],
{ stdio: "ignore", timeout: 60000 }
);
+
if (mux.status !== 0) {
throw new Error(`ffmpeg failed to add silent audio track (exit ${mux.status})`);
}
+
try { fs.unlinkSync(silentVideo); } catch {}
console.log(`OK ${opts.output}`);
diff --git a/remotion/render-full-episode.mjs b/remotion/render-full-episode.mjs
index fb3fa7d..06568b5 100644
--- a/remotion/render-full-episode.mjs
+++ b/remotion/render-full-episode.mjs
@@ -20,11 +20,14 @@ import path from "node:path";
const parseArgs = () => {
const out = {};
+
for (let i = 2; i < process.argv.length; i += 2) {
const key = process.argv[i]?.replace(/^--/, "");
const value = process.argv[i + 1];
+
if (key && value) out[key] = value;
}
+
return out;
};
@@ -39,17 +42,22 @@ const run = (command, args) => {
stdio: ["ignore", "pipe", "pipe"],
timeout: STEP_TIMEOUT_MS,
});
+
const name = path.basename(command);
+
if (result.error) {
const reason = result.error.code === "ETIMEDOUT"
? `timed out after ${STEP_TIMEOUT_MS / 60000} minutes`
: result.error.message;
+
throw new Error(`${name} failed: ${reason}`);
}
+
if (result.status !== 0) {
const detail = (result.stderr || result.stdout || "unknown error").trim().slice(-3000);
throw new Error(`${name} failed (${result.status}): ${detail}`);
}
+
return (result.stdout || "").trim();
};
@@ -59,10 +67,12 @@ const progress = (percent, message) => {
const quoteConcatPath = (filePath) => {
const normalized = filePath.replaceAll("\\", "/");
+
return `'${normalized.replaceAll("'", "'\\''")}'`;
};
const args = parseArgs();
+
for (const required of ["video", "words", "output", "ffmpeg", "ffprobe"]) {
if (!args[required]) throw new Error(`Missing --${required}`);
}
@@ -74,49 +84,66 @@ const partialOutput = `${output}.partial.mp4`;
const logo = args.logo ? path.resolve(args.logo) : null;
const styleName = args.style || "branded";
const captionPosition = args["caption-position"] || "auto";
+
// Mirrors the 60-160 clamp in backend/services/caption_renderer.py so the ASS
// and Remotion caption paths render the same size for a given request.
const rawFontScale = Number(args["caption-font-scale"]);
+
const captionFontScale = Number.isFinite(rawFontScale)
? Math.min(160, Math.max(60, rawFontScale))
: 100;
+
const logoPosition = args["logo-position"] || "top-left";
const fps = Number(args.fps || 30);
const chunkSeconds = Number(args["chunk-seconds"] || 15);
if (fs.existsSync(output)) throw new Error(`Refusing to overwrite existing output: ${output}`);
+
if (!fs.existsSync(video)) throw new Error(`Video not found: ${video}`);
+
if (!fs.existsSync(wordsPath)) throw new Error(`Words JSON not found: ${wordsPath}`);
+
if (logo && !fs.existsSync(logo)) throw new Error(`Logo not found: ${logo}`);
+
if (!(fps > 0) || !(chunkSeconds > 0)) throw new Error("fps and chunk-seconds must be positive");
const wordsData = JSON.parse(fs.readFileSync(wordsPath, "utf8"));
const words = Array.isArray(wordsData) ? wordsData : wordsData.words || [];
const faceY = Array.isArray(wordsData) ? null : wordsData.faceY ?? null;
+
const dimensions = run(args.ffprobe, [
"-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=s=x:p=0", video,
]);
+
const [width, height] = dimensions.split("x").map(Number);
+
const duration = Number(run(args.ffprobe, [
"-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", video,
]));
+
if (!(width > 0 && height > 0 && duration > 0)) throw new Error("Could not probe video");
const durationInFrames = Math.ceil(duration * fps);
const framesPerChunk = Math.max(1, Math.round(chunkSeconds * fps));
const outputDir = path.dirname(output);
+
fs.mkdirSync(outputDir, { recursive: true });
+
const workDir = fs.mkdtempSync(path.join(outputDir, ".podcli-full-caption-work-"));
let server;
const cleanup = () => {
try { server?.close(); } catch {}
+
try { fs.rmSync(workDir, { recursive: true, force: true }); } catch {}
+
try { fs.rmSync(partialOutput, { force: true }); } catch {}
};
+
process.on("SIGINT", () => { cleanup(); process.exit(130); });
+
process.on("SIGTERM", () => { cleanup(); process.exit(143); });
try {
@@ -124,8 +151,10 @@ try {
if (request.url !== "/logo.png" || !logo) {
response.writeHead(404);
response.end();
+
return;
}
+
const stat = fs.statSync(logo);
response.writeHead(200, {
"Content-Type": "image/png",
@@ -139,6 +168,7 @@ try {
progress(2, "Preparing caption renderer");
const bundle = await getCachedBundle({ onBundle: () => progress(3, "Preparing caption renderer") });
+
const inputProps = {
videoSrc: "",
words,
@@ -152,16 +182,19 @@ try {
logoPosition,
singleLine: true,
};
+
const composition = await selectComposition({
serveUrl: bundle,
id: "CaptionedClip",
inputProps,
timeoutInMilliseconds: 120000,
});
+
const renderComposition = { ...composition, durationInFrames, fps, width, height };
const chunks = [];
const chunkCount = Math.ceil(durationInFrames / framesPerChunk);
const requestedConcurrency = Number.parseInt(process.env.PODCLI_REMOTION_CONCURRENCY || "", 10);
+
const concurrency = Number.isFinite(requestedConcurrency)
? Math.max(1, Math.min(os.cpus().length, requestedConcurrency))
: Math.max(2, Math.min(os.cpus().length, 8));
@@ -190,6 +223,7 @@ try {
timeoutInMilliseconds: 120000,
onProgress: ({ progress: chunkProgress }) => {
const percent = Math.floor(chunkProgress * 100);
+
if (percent >= lastPercent + 10) {
lastPercent = percent;
const overall = 5 + ((index + chunkProgress) / chunkCount) * 80;
diff --git a/remotion/render.mjs b/remotion/render.mjs
index 7851e37..a371df7 100644
--- a/remotion/render.mjs
+++ b/remotion/render.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
- * Remotion render script — called by Python backend.
+ * Remotion render script: called by Python backend.
*
* Caches the bundle under PODCLI_CACHE_DIR/remotion-bundle/ (default data/cache/)
* so subsequent renders skip the ~15-20s bundling step.
@@ -36,17 +36,21 @@ const BOOLEAN_FLAGS = new Set(["prebundle", "keep-overlay", "progress"]);
function parseArgs() {
const args = process.argv.slice(2);
const opts = {};
+
for (let i = 0; i < args.length; i++) {
const key = args[i].replace(/^--/, "");
+
if (BOOLEAN_FLAGS.has(key)) {
opts[key] = true;
continue;
}
+
if (args[i].startsWith("--") && i + 1 < args.length) {
opts[key] = args[i + 1];
i++;
}
}
+
return opts;
}
@@ -54,11 +58,13 @@ function parseArgs() {
// and Remotion caption paths render the same size for a given request.
function clampCaptionFontScale(raw) {
const value = Number(raw);
+
return Number.isFinite(value) ? Math.min(160, Math.max(60, value)) : 100;
}
function clampLogoScale(raw) {
const value = Number(raw);
+
return Number.isFinite(value) ? Math.min(1.5, Math.max(0.5, value)) : 1;
}
@@ -68,24 +74,29 @@ function clampLogoScale(raw) {
// compositions now, and the slowest CI runner does not finish inside 30s.
const timeoutFor = (durationSec) => {
const override = parseInt(process.env.PODCLI_REMOTION_TIMEOUT_MS ?? "", 10);
+
if (Number.isFinite(override)) return Math.max(1, override);
+
return Math.round(Math.min(50 * 60_000, Math.max(120_000, 90_000 + durationSec * 15_000)));
};
const videoCacheBytes = () => {
const mb = parseInt(process.env.PODCLI_REMOTION_VIDEO_CACHE_MB ?? "", 10);
+
return (Number.isFinite(mb) && mb > 0 ? mb : 512) * 1024 * 1024;
};
+
const offthreadVideoCacheSizeInBytes = videoCacheBytes();
async function main() {
const opts = parseArgs();
- // Prebundle mode — just bundle and exit
+ // Prebundle mode: just bundle and exit
if (opts.prebundle) {
const t0 = Date.now();
const loc = await getCachedBundle({ onBundle: () => console.log(" Remotion: bundling (first run, or src/config changed)...") });
console.log(`Remotion bundle ready at ${loc} (${Date.now() - t0}ms)`);
+
return;
}
@@ -107,6 +118,7 @@ async function main() {
const t0 = Date.now();
const bundleLocation = await getCachedBundle({ onBundle: () => console.log(" Remotion: bundling (first run, or src/config changed)...") });
const bundleMs = Date.now() - t0;
+
if (bundleMs > 1000) {
console.log(` bundled in ${(bundleMs / 1000).toFixed(1)}s`);
}
@@ -114,8 +126,10 @@ async function main() {
// Serve video and logo via a tiny local HTTP server
// (Remotion's bundled server can't serve dynamically added files)
const http = await import("http");
+
const assetServer = http.createServer((req, res) => {
let filePath = null;
+
if (req.url === "/clip.mp4") filePath = path.resolve(opts.video);
else if (req.url === "/logo.png" && opts.logo) filePath = path.resolve(opts.logo);
@@ -130,19 +144,24 @@ async function main() {
res.end();
}
});
+
await new Promise((resolve) => assetServer.listen(0, "127.0.0.1", resolve));
const assetPort = assetServer.address().port;
// Ensure the asset server is closed and the overlay temp file removed on any exit path
let captionOverlay;
const closeAssetServer = () => { try { assetServer.close(); } catch {} };
+
const cleanupOnSignal = () => {
closeAssetServer();
+
if (captionOverlay && !opts["keep-overlay"]) {
try { fs.unlinkSync(captionOverlay); } catch {}
}
+
process.exit(1);
};
+
process.on("SIGINT", cleanupOnSignal);
process.on("SIGTERM", cleanupOnSignal);
@@ -165,13 +184,16 @@ async function main() {
*/
const { spawnSync } = await import("child_process");
const ffprobe = process.env.PODCLI_FFPROBE || "ffprobe";
+
const probeFor = (...entries) => {
const r = spawnSync(
ffprobe,
["-v", "error", ...entries, path.resolve(opts.video)],
{ encoding: "utf-8", timeout: 5000 },
);
+
if (r.error || r.status !== 0) return null;
+
return String(r.stdout ?? "").trim();
};
@@ -179,8 +201,10 @@ async function main() {
"-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=s=x:p=0",
);
+
if (size) {
const [w, h] = size.split("x").map(Number);
+
if (w > 0 && h > 0) {
renderW = w;
renderH = h;
@@ -197,9 +221,11 @@ async function main() {
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
);
+
// Same silence as the shape, and the same cost: an overlay cut to the last
// word rather than to the file stops before the clip does.
const measured = Number.parseFloat(durStr ?? "");
+
if (Number.isFinite(measured) && measured > 0) {
videoDuration = measured;
} else {
@@ -228,6 +254,7 @@ async function main() {
// How each part arrives and leaves. A JSON object rather than a flag per
// property: it is one value in a template, and it travels as one.
let motion = null;
+
if (opts.motion) {
try {
motion = JSON.parse(opts.motion);
@@ -246,10 +273,12 @@ async function main() {
*/
const json = (name) => {
if (!opts[name]) return null;
+
try {
return JSON.parse(opts[name]);
} catch {
console.error(`Ignoring --${name}: not valid JSON`);
+
return null;
}
};
@@ -257,16 +286,18 @@ async function main() {
const cards = json("cards");
const brand = json("brand");
const theme = json("theme");
+
const topic = opts.topic
? {
label: opts.topic,
position: opts["topic-position"] || "top-left",
- ...(opts["topic-color"] ? { color: opts["topic-color"] } : {}),
- ...(opts["topic-background"] ? { background: opts["topic-background"] } : {}),
+ ...(opts["topic-color"] && { color: opts["topic-color"] }),
+ ...(opts["topic-background"] && { background: opts["topic-background"] }),
}
: null;
+
const progress = opts.progress
- ? { ...(opts["progress-color"] ? { color: opts["progress-color"] } : {}) }
+ ? (opts["progress-color"] ? { color: opts["progress-color"] } : {})
: null;
const inputProps = {
@@ -286,8 +317,8 @@ async function main() {
topic,
progress,
cards: Array.isArray(cards) ? cards : null,
- brand: brand && typeof brand === "object" ? brand : null,
- theme: theme && typeof theme === "object" && !Array.isArray(theme) ? theme : null,
+ brand: brand instanceof Object ? brand : null,
+ theme: theme instanceof Object && !Array.isArray(theme) ? theme : null,
fontFamily: opts["font-family"] || null,
};
@@ -324,9 +355,11 @@ async function main() {
});
const cpus = os.cpus().length;
+
const concurrency = process.env.PODCLI_REMOTION_CONCURRENCY
? Math.max(1, parseInt(process.env.PODCLI_REMOTION_CONCURRENCY, 10))
: Math.max(2, Math.min(cpus, 8));
+
if (opts["keep-overlay"]) {
const outBase = opts.output.replace(/\.[^.]+$/, "");
captionOverlay = `${outBase}_captions.mov`;
@@ -359,6 +392,7 @@ async function main() {
offthreadVideoCacheSizeInBytes,
onProgress: ({ progress }) => {
const pct = Math.round(progress * 100);
+
if (pct > lastPct + 9) {
lastPct = pct;
process.stderr.write(` captions: ${pct}%\n`);
@@ -379,6 +413,7 @@ async function main() {
// one with a space in it broke the quoting instead of the render.
process.stderr.write(" compositing...\n");
const ffmpeg = process.env.PODCLI_FFMPEG || "ffmpeg";
+
const composite = spawnSync(
ffmpeg,
[
@@ -392,10 +427,12 @@ async function main() {
],
{ stdio: ["pipe", "pipe", "pipe"], timeout: 300000, encoding: "utf8" }
);
+
if (composite.error || composite.status !== 0) {
const why = composite.error
? `${composite.error.code === "ENOENT" ? `${ffmpeg} not found` : composite.error.message}`
: `exit ${composite.status}: ${(composite.stderr || "").trim().slice(-500)}`;
+
throw new Error(`compositing the captions failed (${why})`);
}
@@ -404,6 +441,7 @@ async function main() {
} else {
try { fs.unlinkSync(captionOverlay); } catch {}
}
+
console.log(`Done: ${opts.output}`);
} finally {
closeAssetServer();
diff --git a/remotion/src/Audiogram.tsx b/remotion/src/Audiogram.tsx
index 1c909f3..d33cc8f 100644
--- a/remotion/src/Audiogram.tsx
+++ b/remotion/src/Audiogram.tsx
@@ -36,6 +36,7 @@ export interface AudiogramProps {
const smooth = (levels: number[][], frame: number, bar: number): number => {
const now = levels[Math.min(frame, levels.length - 1)]?.[bar] ?? 0;
const before = levels[Math.max(0, Math.min(frame, levels.length - 1) - 1)]?.[bar] ?? 0;
+
return now >= before ? now : before * 0.6 + now * 0.4;
};
@@ -120,6 +121,7 @@ export const Audiogram: React.FC<AudiogramProps> = ({
>
{Array.from({ length: bars }, (_, bar) => {
const level = smooth(levels, frame, bar);
+
return (
<div
key={bar}
diff --git a/remotion/src/Bookend.tsx b/remotion/src/Bookend.tsx
index 4ae4702..f1d7315 100644
--- a/remotion/src/Bookend.tsx
+++ b/remotion/src/Bookend.tsx
@@ -15,6 +15,7 @@ const FONT = "'DM Sans', sans-serif";
// --- Recognizable social glyphs as inline SVG (monochrome, fill=currentColor) ---
const Glyph: React.FC<{ name: string; size: number; color: string }> = ({ name, size, color }) => {
const common = { width: size, height: size, viewBox: "0 0 24 24", fill: color } as const;
+
switch (name) {
case "tiktok":
return (
@@ -45,12 +46,12 @@ const Glyph: React.FC<{ name: string; size: number; color: string }> = ({ name,
}
};
-const PLATFORM_LABEL: Record<string, string> = {
- tiktok: "TikTok",
- instagram: "Instagram",
- youtube: "YouTube",
- x: "X",
-};
+const PLATFORM_LABEL = new Map([
+ ["tiktok", "TikTok"],
+ ["instagram", "Instagram"],
+ ["youtube", "YouTube"],
+ ["x", "X"],
+]);
export const Bookend: React.FC<BookendProps> = ({
mode,
@@ -142,6 +143,7 @@ export const Bookend: React.FC<BookendProps> = ({
const pop = spring({ frame: Math.max(0, f), fps, config: { damping: 12, mass: 0.6 }, durationInFrames: Math.round(fps * 0.5) });
const scale = interpolate(pop, [0, 1], [0.2, 1]);
const op = interpolate(pop, [0, 1], [0, 1]);
+
return (
<div
key={p}
@@ -168,7 +170,7 @@ export const Bookend: React.FC<BookendProps> = ({
<Glyph name={p} size={iconSize} color="#FFFFFF" />
</div>
<div style={{ color: "rgba(255,255,255,0.7)", fontSize: width * 0.028, fontWeight: 700 }}>
- {PLATFORM_LABEL[p] || p}
+ {PLATFORM_LABEL.get(p) || p}
</div>
</div>
);
diff --git a/remotion/src/CaptionedClip.tsx b/remotion/src/CaptionedClip.tsx
index 71900c0..fb5a5b1 100644
--- a/remotion/src/CaptionedClip.tsx
+++ b/remotion/src/CaptionedClip.tsx
@@ -14,10 +14,10 @@ import type { ProgressBarProps } from "./components/ProgressBar";
import { Cards } from "./components/Cards";
import type { Card } from "./cards";
import type { Brand } from "./components/Cards";
-import { MOTION } from "./motion";
+import { MOTION, motionForVoice } from "./motion";
import type { Motion } from "./motion";
import {
- brandCaptions, captionScale, captionZone, STYLES, LOGO_CAPTION_GAP, LOGO_HEIGHT, LOGO_INSET, safeFor,
+ brandCaptions, captionScale, captionZone, styleNamed, LOGO_CAPTION_GAP, LOGO_HEIGHT, LOGO_INSET, safeFor,
} from "./types";
import type { Word, CaptionStyle, CaptionPosition, LogoPosition } from "./types";
import { resolveTheme } from "./style/theme";
@@ -79,14 +79,16 @@ export const CaptionedClip: React.FC<CaptionedClipProps> = ({
theme: themeInput,
}) => {
const theme = resolveTheme(withDefaultTextures(themeInput ?? null));
- const preset = theme ? STYLES[theme.captions] : undefined;
+ const preset = theme ? styleNamed(theme.captions) : undefined;
+
const voice: CaptionStyle = preset && preset.name !== style.name
? {
...preset,
fontFamily: style.fontFamily,
- fontSize: preset.fontSize * (style.fontSize / (STYLES[style.name]?.fontSize ?? style.fontSize)),
+ fontSize: preset.fontSize * (style.fontSize / (styleNamed(style.name)?.fontSize ?? style.fontSize)),
}
: style;
+
const { fps, height, width } = useVideoConfig();
const SAFE = safeFor(width, height);
const frame = useCurrentFrame();
@@ -94,6 +96,7 @@ export const CaptionedClip: React.FC<CaptionedClipProps> = ({
const nameCardSeconds = nameCard?.title ? (nameCard.seconds ?? 3) : 0;
const pastNameCard = frame / fps >= nameCardSeconds;
const captionShrink = cards?.length ? CARDED : 1;
+
/*
* Captions used to drop toward the bottom edge while a card held the frame,
* on the reasoning that there is no chin down there to clear. There is no
@@ -115,6 +118,7 @@ export const CaptionedClip: React.FC<CaptionedClipProps> = ({
: captionPosition === "center" ? 820
: captionPosition === "lower" ? SAFE.bottom
: width < height ? voice.marginBottom : SAFE.bottom;
+
const captionStyle: CaptionStyle = {
...brandCaptions(voice, brand),
marginBottom: Math.max(placementMargin, SAFE.bottom),
@@ -144,14 +148,19 @@ export const CaptionedClip: React.FC<CaptionedClipProps> = ({
* frame is told how much of the top is already spoken for.
*/
const logoTop = Boolean(logoSrc) && logoPosition.startsWith("top-");
+
const chipTop = Boolean(topic?.label)
&& (topic?.position ?? "top-left").startsWith("top-");
+
const chipClashes = logoTop
&& chipTop
&& (topic?.position ?? "top-left").slice(4) === logoPosition.slice(4);
+
const chipInset = LOGO_INSET
+ (chipClashes ? LOGO_HEIGHT * logoScale + LOGO_CAPTION_GAP : 0);
+
const CHIP_HEIGHT = 48;
+
const topTaken = Math.max(
SAFE.top,
logoTop ? LOGO_INSET + LOGO_HEIGHT * logoScale + LOGO_CAPTION_GAP : 0,
@@ -159,9 +168,11 @@ export const CaptionedClip: React.FC<CaptionedClipProps> = ({
);
const captionMotion: Motion = {
- ...(MOTION[voice.name] ?? MOTION.subtle), ...(motion?.captions ?? {}),
+ ...motionForVoice(voice.name), ...motion?.captions,
};
- const cardMotion: Motion = { ...MOTION.nameCard, ...(motion?.nameCard ?? {}) };
+
+ const cardMotion: Motion = { ...MOTION.nameCard, ...motion?.nameCard };
+
const CaptionComponent = {
hormozi: HormoziCaptions,
karaoke: KaraokeCaptions,
diff --git a/remotion/src/Root.tsx b/remotion/src/Root.tsx
index 24e5e5e..9f4db37 100644
--- a/remotion/src/Root.tsx
+++ b/remotion/src/Root.tsx
@@ -3,7 +3,8 @@ import { Composition, continueRender, delayRender, getInputProps } from "remotio
import { CaptionedClip } from "./CaptionedClip";
import { Bookend } from "./Bookend";
import { Audiogram } from "./Audiogram";
-import { fontStack, STYLES } from "./types";
+import { fontStack, STYLES, styleNamed } from "./types";
+import type { Motion } from "./motion";
import type { Word } from "./types";
import type { CaptionPosition, LogoPosition } from "./types";
import type { TopicChipProps } from "./components/TopicChip";
@@ -35,15 +36,15 @@ const loadFace = (source: string, weight: string, family = "DM Sans", style = "n
});
Promise.all([
- loadFace(dmSans400 as string, "400"),
- loadFace(dmSans700 as string, "700"),
- loadFace(playfair700i as string, "700", "Playfair Display", "italic"),
- loadFace(playfair900i as string, "900", "Playfair Display", "italic"),
- loadFace(barlow600 as string, "600", "Barlow Condensed"),
- loadFace(barlow700 as string, "700", "Barlow Condensed"),
- loadFace(courier400 as string, "400", "Courier Prime"),
- loadFace(georgian400 as string, "400", "Noto Sans Georgian"),
- loadFace(georgian700 as string, "700", "Noto Sans Georgian"),
+ loadFace(dmSans400, "400"),
+ loadFace(dmSans700, "700"),
+ loadFace(playfair700i, "700", "Playfair Display", "italic"),
+ loadFace(playfair900i, "900", "Playfair Display", "italic"),
+ loadFace(barlow600, "600", "Barlow Condensed"),
+ loadFace(barlow700, "700", "Barlow Condensed"),
+ loadFace(courier400, "400", "Courier Prime"),
+ loadFace(georgian400, "400", "Noto Sans Georgian"),
+ loadFace(georgian700, "700", "Noto Sans Georgian"),
])
.then(() => continueRender(fontsReady))
.catch((err) => {
@@ -51,6 +52,7 @@ Promise.all([
continueRender(fontsReady);
});
+// SAFETY: render.mjs assembles these input props from its CLI options and hands them to the composition.
const inputProps = getInputProps() as {
videoSrc?: string;
words?: Word[];
@@ -84,8 +86,8 @@ const inputProps = getInputProps() as {
accent?: string;
} | null;
motion?: {
- captions?: Record<string, unknown>;
- nameCard?: Record<string, unknown>;
+ captions?: Partial<Motion>;
+ nameCard?: Partial<Motion>;
} | null;
/**
* The parts a show's template switches on, and the colours it draws them in.
@@ -106,14 +108,17 @@ const inputProps = getInputProps() as {
export const RemotionRoot: React.FC = () => {
const fps = inputProps.fps || 30;
const durationInFrames = inputProps.durationInFrames || 900;
- const baseStyle = STYLES[inputProps.styleName || "branded"];
+ const baseStyle = styleNamed(inputProps.styleName || "branded") ?? STYLES.branded;
+
const positionMargins: Partial<Record<CaptionPosition, number>> = {
upper: 760,
center: 480,
lower: 220,
};
+
const captionPosition = inputProps.captionPosition || "auto";
const fontScale = Math.max(0.6, Math.min(1.6, (inputProps.captionFontScale || 100) / 100));
+
const style = {
...baseStyle,
fontSize: baseStyle.fontSize * fontScale,
diff --git a/remotion/src/cards.ts b/remotion/src/cards.ts
index 1ca087a..8a87b27 100644
--- a/remotion/src/cards.ts
+++ b/remotion/src/cards.ts
@@ -181,10 +181,12 @@ export type Card =
*/
export const cardAt = (cards: Card[], seconds: number): Card | null => {
let found: Card | null = null;
+
for (const card of cards) {
if (seconds >= card.start && seconds < card.end) {
if (!found || card.start >= found.start) found = card;
}
}
+
return found;
};
diff --git a/remotion/src/chunks.ts b/remotion/src/chunks.ts
index e1b1280..e69ef1c 100644
--- a/remotion/src/chunks.ts
+++ b/remotion/src/chunks.ts
@@ -17,6 +17,7 @@ export interface ChunkOptions {
}
const BREAK_GAP_SECONDS = 0.8;
+
// Mirrors CAPTION_GAP_FILL_MAX in backend/services/caption_renderer.py: both
// renderers must burn the same caption timings.
const GAP_FILL_MAX_SECONDS = 0.4;
@@ -35,6 +36,7 @@ function hasBreakBetween(words: Word[], from: number, to: number): boolean {
for (let i = from; i < to; i++) {
if (breaksAfter(words[i], words[i + 1])) return true;
}
+
return false;
}
@@ -48,11 +50,14 @@ export function buildChunks(words: Word[], opts: ChunkOptions): Chunk[] {
while (end < words.length && end - i < opts.perChunk) {
if (breaksAfter(words[end - 1], words[end])) break;
+
if (opts.maxChars != null) {
const nextChars = charCount + 1 + words[end].word.trim().length;
+
if (nextChars > opts.maxChars) break;
charCount = nextChars;
}
+
end += 1;
}
@@ -64,6 +69,7 @@ export function buildChunks(words: Word[], opts: ChunkOptions): Chunk[] {
) {
end = words.length;
}
+
if (opts.splitTail && words.length - end === 1 && end - i > 2) {
end -= 1;
}
@@ -85,9 +91,11 @@ export function buildChunks(words: Word[], opts: ChunkOptions): Chunk[] {
// for the whole pause.
for (let k = 0; k < chunks.length; k++) {
const next = chunks[k + 1];
+
const hold = next
? Math.min(next.start, chunks[k].end + GAP_FILL_MAX_SECONDS)
: chunks[k].end + LAST_CHUNK_HOLD_SECONDS;
+
const capped = opts.clipEnd != null ? Math.min(hold, opts.clipEnd) : hold;
chunks[k].displayEnd = Math.max(chunks[k].end, capped);
}
@@ -105,5 +113,6 @@ export function splitCaptionLines<T>(
singleLine = false,
): [T[], T[]] {
if (singleLine || items.length <= splitIndex) return [items, []];
+
return [items.slice(0, splitIndex), items.slice(splitIndex)];
}
diff --git a/remotion/src/components/BrandedCaptions.tsx b/remotion/src/components/BrandedCaptions.tsx
index 5ecb836..21943c5 100644
--- a/remotion/src/components/BrandedCaptions.tsx
+++ b/remotion/src/components/BrandedCaptions.tsx
@@ -54,7 +54,7 @@ const WordWithPill: React.FC<{
return (
<span style={{ position: "relative", display: "inline" }}>
- {/* Pill background — absolutely positioned, doesn't affect layout */}
+ {/* Pill background: absolutely positioned, doesn't affect layout */}
<span
style={{
position: "absolute",
@@ -69,12 +69,12 @@ const WordWithPill: React.FC<{
pointerEvents: "none",
}}
/>
- {/* Word text — always inline, never shifts */}
+ {/* Word text: always inline, never shifts */}
<span
style={{
position: "relative",
zIndex: 1,
- ...(word.emphasis && emphasisColor ? { color: emphasisColor } : {}),
+ ...(word.emphasis && emphasisColor && { color: emphasisColor }),
}}
>
{word.word}
@@ -151,6 +151,7 @@ export const BrandedCaptions: React.FC<Props> = ({
splitTail: true,
clipEnd: durationInFrames / fps,
});
+
const activeChunk = activeChunkAt(chunks, currentTime);
// Dynamic margin: if face is in the lower portion, push captions further down
@@ -158,13 +159,15 @@ export const BrandedCaptions: React.FC<Props> = ({
// Default margin is style.marginBottom. If face center is below 0.55, reduce margin.
const baseMargin = style.marginBottom * s;
let dynamicMargin = baseMargin;
+
if (captionPosition === "auto" && faceY != null && faceY > 0.55) {
- // Face is low — push captions to the very bottom
+ // Face is low: push captions to the very bottom
dynamicMargin = Math.max(80 * s, baseMargin - Math.round((faceY - 0.55) * height * 0.6));
} else if (captionPosition === "auto" && faceY != null && faceY < 0.35) {
- // Face is high — can bring captions up a bit
+ // Face is high: can bring captions up a bit
dynamicMargin = baseMargin + 60 * s;
}
+
// A bottom-anchored logo spans 180-306 scaled units. Captions sitting inside
// that band (captionPosition "lower" starts at 220) would render over it.
if (hasLogo && logoPosition.startsWith("bottom-")) {
diff --git a/remotion/src/components/Cards.tsx b/remotion/src/components/Cards.tsx
index 7282649..9919448 100644
--- a/remotion/src/components/Cards.tsx
+++ b/remotion/src/components/Cards.tsx
@@ -30,6 +30,7 @@ import type { Block } from "../scene";
*/
export type { Brand } from "./brand";
+
export { DEFAULT_BRAND } from "./brand";
/**
@@ -89,7 +90,7 @@ const SHOWS_A_FILE = new Set(["image", "video"]);
* Two, because the API cuts a caption at ninety characters and ninety
* characters of label type do not fit on one line of this frame. Reserving one
* was reserving for the caption that happens to be short, and the second line
- * of a long one came out of the band below it — which is the caption pill.
+ * of a long one came out of the band below it, which is the caption pill.
*/
const CAPTION_LINES_MEDIA = 2;
@@ -238,10 +239,12 @@ const BleedMedia: React.FC<{
const SAFE = safeFor(width, height);
const src = card.src.startsWith("http") ? card.src : staticFile(card.src);
const fit = card.fit === "fit" ? "contain" : "cover";
+
const box: React.CSSProperties = {
position: "absolute", inset: 0, width: "100%", height: "100%",
objectFit: fit, backgroundColor: card.fit === "fit" ? brand.surface : "#000",
};
+
const Frame = getRemotionEnvironment().isRendering ? OffthreadVideo : Video;
return (
@@ -445,6 +448,7 @@ const CardBody: React.FC<{
if (card.kind === "compare") {
const top = Math.max(...card.rows.map((r) => r.value)) || 1;
+
return (
<>
{card.eyebrow && <Label text={card.eyebrow} scale={s} tone={MUTED} />}
@@ -511,6 +515,7 @@ const CardBody: React.FC<{
if (card.kind === "share") {
const pct = Math.max(0, Math.min(1, card.value));
+
return (
<>
{card.eyebrow && <Label text={card.eyebrow} scale={s} tone={MUTED} />}
@@ -654,6 +659,7 @@ const CardBody: React.FC<{
// The same split as the speaker above it: the player seeks a <video> per
// frame, and a render has no seekable player to drive.
const Frame = getRemotionEnvironment().isRendering ? OffthreadVideo : Video;
+
return (
<>
<Frame
@@ -742,6 +748,7 @@ const SpeakerBand: React.FC<{ src: string; startFrom: number; faceY?: number | n
src, startFrom, faceY,
}) => {
const Frame = getRemotionEnvironment().isRendering ? OffthreadVideo : Video;
+
return (
<Frame
src={src}
@@ -782,22 +789,25 @@ const KNOWN_KINDS = new Set([
* which is the two that show a file and the scene itself, return null and keep
* the arithmetic they have.
*/
+const smallText = (text: string): Block => ({ type: "text", text, size: "sm" });
+
const presetBlocks = (card: Card): Block[] | null => {
const eyebrow: Block[] = "eyebrow" in card && card.eyebrow
? [{ type: "text", text: card.eyebrow, size: "xs" }]
: [];
+
switch (card.kind) {
case "stat":
return [
...eyebrow,
{ type: "text", text: card.value, size: "xxl" },
- ...(card.caption ? [{ type: "text", text: card.caption, size: "sm" } as Block] : []),
+ ...(card.caption ? [smallText(card.caption)] : []),
];
case "headline":
return [
...eyebrow,
{ type: "text", text: card.lead, emphasis: card.emphasis, size: "xl" },
- ...(card.sub ? [{ type: "text", text: card.sub, size: "sm" } as Block] : []),
+ ...(card.sub ? [smallText(card.sub)] : []),
];
case "bullets":
return [...eyebrow, { type: "list", items: card.items, size: "md" }];
@@ -809,7 +819,7 @@ const presetBlocks = (card: Card): Block[] | null => {
return [
...eyebrow,
{ type: "meter", value: card.value, display: card.display },
- ...(card.caption ? [{ type: "text", text: card.caption, size: "sm" } as Block] : []),
+ ...(card.caption ? [smallText(card.caption)] : []),
];
case "entity":
return [...eyebrow, { type: "chip", name: card.name, note: card.note, src: card.src }];
@@ -839,7 +849,7 @@ export const Cards: React.FC<{
}> = ({
cards, videoSrc, startFrom = 0, style, faceY, faceH, brand, topInset,
}) => {
- const colours = { ...DEFAULT_BRAND, ...(brand ?? {}) };
+ const colours = { ...DEFAULT_BRAND, ...brand };
const frame = useCurrentFrame();
const { fps, height, width } = useVideoConfig();
const SAFE = safeFor(width, height);
@@ -857,11 +867,16 @@ export const Cards: React.FC<{
*/
const usable = cards.filter((c) => {
if (!KNOWN_KINDS.has(c.kind)) return false;
+
if (c.kind === "image" || c.kind === "video") return Boolean(c.src);
+
if (c.kind === "scene") return c.blocks.some(drawsSomething);
+
return true;
});
+
const card = cardAt(usable, frame / fps);
+
if (!card) return null;
const { opacity } = motionAt({
@@ -870,6 +885,7 @@ export const Cards: React.FC<{
end: card.end,
motion: card.motion ?? MOTION.card,
});
+
if (opacity <= 0) return null;
/*
@@ -914,7 +930,7 @@ export const Cards: React.FC<{
* same call whether the arrangement was named by somebody or arrived as
* blocks.
*/
- const shape = presetBlocks(card);
+ const presetLayout = presetBlocks(card);
/*
* The measure a preset is actually set to, rather than the scene's.
*
@@ -925,9 +941,11 @@ export const Cards: React.FC<{
* same number, so nothing moves there.
*/
const contentWidth = width / s - SAFE.left - SAFE.right;
- const wanted = shape ? sceneHeight(shape, "stack", "tight", contentWidth) : 0;
+ const wanted = presetLayout ? sceneHeight(presetLayout, "stack", "tight", contentWidth) : 0;
+
const fitFor = (available: number) =>
wanted > 0 ? Math.max(MIN_FIT, Math.min(1, available / s / wanted)) : 1;
+
/** How far this card would have to shrink to sit in a room of this height. */
const fitsIn = (available: number) =>
(card.kind === "scene"
@@ -935,6 +953,7 @@ export const Cards: React.FC<{
layout: card.layout, gap: card.gap, room: available / s,
}).fit
: fitFor(available));
+
const bodyShares = fitsIn(bodyRoom(room - speakerTakes)) > MIN_FIT;
/*
* How far down a card written into the shot has to start.
@@ -949,10 +968,12 @@ export const Cards: React.FC<{
*/
const HEAD_BELOW_EYES = 0.13;
const faceFloor = ((faceY ?? 0.4) + HEAD_BELOW_EYES) * height;
+
const overRoom = Math.min(
bodyRoom(room),
Math.max(0, height - faceFloor - (captionZone(style) + GAP.section) * s),
);
+
/*
* Written into the shot rather than laid over it, when the shot has the room.
*
@@ -968,6 +989,7 @@ export const Cards: React.FC<{
* makes its own.
*/
const over = card.place === "over" && fitsIn(overRoom) > MIN_FIT;
+
const withSpeaker = !over
&& card.speaker !== null
&& Boolean(videoSrc)
@@ -976,6 +998,7 @@ export const Cards: React.FC<{
&& (!SHOWS_A_FILE.has(card.kind)
|| mediaBand(card.kind, bodyRoom(room - speakerTakes), s, hasCaption)
>= MEDIA_MIN * s);
+
/*
* How far the type has to come down to sit inside the band.
*
@@ -989,7 +1012,9 @@ export const Cards: React.FC<{
const bodyAvailable = over
? overRoom
: bodyRoom(withSpeaker ? room - speakerTakes : room);
+
const bodyFit = fitFor(bodyAvailable);
+
/*
* A file takes the whole frame when it was asked to, or when a band would
* be too short to be worth one.
@@ -1006,6 +1031,7 @@ export const Cards: React.FC<{
const bandWouldBe = SHOWS_A_FILE.has(card.kind)
? mediaBand(card.kind, bodyRoom(withSpeaker ? room - speakerTakes : room), s, hasCaption)
: 0;
+
const bleeds = SHOWS_A_FILE.has(card.kind)
&& !withSpeaker
&& (("bleed" in card && card.bleed === true) || bandWouldBe < MEDIA_MIN * s);
diff --git a/remotion/src/components/HormoziCaptions.tsx b/remotion/src/components/HormoziCaptions.tsx
index b36206f..76e529d 100644
--- a/remotion/src/components/HormoziCaptions.tsx
+++ b/remotion/src/components/HormoziCaptions.tsx
@@ -30,6 +30,7 @@ export const HormoziCaptions: React.FC<Props> = ({
absorbTail: 1,
clipEnd: durationInFrames / fps,
});
+
const activeChunk = activeChunkAt(chunks, currentTime);
if (!activeChunk) return null;
@@ -73,9 +74,11 @@ export const HormoziCaptions: React.FC<Props> = ({
>
{activeChunk.words.map((word, i) => {
const isActive = currentTime >= word.start && currentTime < word.end;
+
const text = style.uppercase
? safeUpper(word.word)
: word.word;
+
// The word being spoken still wins: the sweep is what this style is.
// Emphasis colours it for the rest of the chunk, which is the part
// somebody reads with the sound off.
diff --git a/remotion/src/components/KaraokeCaptions.tsx b/remotion/src/components/KaraokeCaptions.tsx
index 1f76e9c..81f1aac 100644
--- a/remotion/src/components/KaraokeCaptions.tsx
+++ b/remotion/src/components/KaraokeCaptions.tsx
@@ -32,6 +32,7 @@ const KaraokeLine: React.FC<{
>
{words.map((word, i) => {
const isSpoken = currentTime >= word.start;
+
const progress = isSpoken
? Math.min(1, (currentTime - word.start) / Math.max(0.05, word.end - word.start))
: 0;
@@ -83,6 +84,7 @@ export const KaraokeCaptions: React.FC<Props> = ({ words, style, singleLine = fa
absorbTail: 1,
clipEnd: durationInFrames / fps,
});
+
const activeChunk = activeChunkAt(chunks, currentTime);
if (!activeChunk) return null;
@@ -92,6 +94,7 @@ export const KaraokeCaptions: React.FC<Props> = ({ words, style, singleLine = fa
Math.ceil(activeChunk.words.length / 2),
singleLine,
);
+
const scaledStyle = { ...style, fontSize: style.fontSize * s };
return (
diff --git a/remotion/src/components/NameCard.tsx b/remotion/src/components/NameCard.tsx
index c0b6704..3a48ccc 100644
--- a/remotion/src/components/NameCard.tsx
+++ b/remotion/src/components/NameCard.tsx
@@ -49,6 +49,7 @@ export const NameCard: React.FC<NameCardProps> = ({
motion: motion ?? MOTION.nameCard,
scale: 12 * s,
});
+
if (opacity <= 0) return null;
return (
diff --git a/remotion/src/components/Scene.tsx b/remotion/src/components/Scene.tsx
index a370732..a8d2470 100644
--- a/remotion/src/components/Scene.tsx
+++ b/remotion/src/components/Scene.tsx
@@ -85,6 +85,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (block.type === "text") {
const size = sizeOf(block);
+
return (
<div
style={{
@@ -111,6 +112,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (block.type === "quote") {
const size = sizeOf(block);
+
return (
<>
<div
@@ -154,6 +156,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (block.type === "list") {
const size = sizeOf(block);
+
return (
<>
{block.items.map((item, i) => (
@@ -207,6 +210,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (block.type === "bars") {
const top = Math.max(...block.rows.map((row) => row.value)) || 1;
+
return (
<>
{block.rows.map((row, i) => (
@@ -251,6 +255,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (block.type === "meter") {
const share = Math.max(0, Math.min(1, block.value));
+
return (
<>
<div
@@ -284,6 +289,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (block.type === "steps" && stepsStacked(block.points)) {
const last = block.points.length - 1;
const type = stepType(block.points, paint.width / unit);
+
return (
<div style={{ display: "flex", flexDirection: "column", alignItems: "stretch" }}>
{block.points.map((point, i) => (
@@ -330,6 +336,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (block.type === "steps") {
const last = block.points.length - 1;
const type = stepType(block.points, paint.width / unit);
+
return (
<div style={{ display: "flex", alignItems: "center" }}>
{block.points.map((point, i) => (
@@ -436,6 +443,7 @@ const Piece: React.FC<{ block: Block; paint: Paint }> = ({ block, paint }) => {
if (!block.src) return null;
const Frame = getRemotionEnvironment().isRendering ? OffthreadVideo : Video;
+
return (
<>
{block.media === "video" ? (
@@ -487,10 +495,12 @@ const Stack: React.FC<{
paint: Paint;
}> = ({ blocks, layout = "stack", gap = "group", paint }) => {
const drawn = blocks.filter((block) => block.type !== "group" || block.blocks.length);
+
if (!drawn.length) return null;
const gutter = GAP_SIZE[gap] * paint.unit;
const columns = layout === "grid" ? 2 : drawn.length;
+
const share = layout === "stack"
? paint.width
: Math.max(1, (paint.width - gutter * (columns - 1)) / columns);
@@ -515,12 +525,10 @@ const Stack: React.FC<{
flexDirection: "column",
minWidth: 0,
alignItems: block.align ? FLEX[block.align] : undefined,
- ...(layout === "stack"
- ? {}
- : {
- flexGrow: block.grow ?? 1,
- flexBasis: layout === "grid" ? `calc(50% - ${gutter / 2}px)` : 0,
- }),
+ ...(layout !== "stack" && {
+ flexGrow: block.grow ?? 1,
+ flexBasis: layout === "grid" ? `calc(50% - ${gutter / 2}px)` : 0,
+ }),
}}
>
<Piece block={block} paint={{ ...paint, width: layout === "stack" ? paint.width : share }} />
@@ -539,21 +547,29 @@ const Stack: React.FC<{
* So the media band gives up its room first, down to the height below which
* it stops saying anything, and only then does the type scale.
*/
+interface SceneFit {
+ fit: number;
+ mediaHeight: number;
+}
+
export function fitScene(
blocks: Block[],
{ layout = "stack", gap = "group", room, width = SCENE_WIDTH }: {
layout?: Layout; gap?: Gap; room: number; width?: number;
},
-): { fit: number; mediaHeight: number } {
+): SceneFit {
const asked = MEDIA_HEIGHT.max;
+
const at = (height: number) =>
sceneHeight(withMediaHeight(blocks, height), layout, gap, width);
const wanted = at(asked);
+
if (!(room > 0) || wanted <= room) return { fit: 1, mediaHeight: asked };
const mediaHeight = Math.max(MEDIA_HEIGHT.min, asked - (wanted - room));
const left = at(mediaHeight);
+
return {
fit: left <= room ? 1 : Math.max(MIN_FIT, room / left),
mediaHeight,
@@ -563,9 +579,11 @@ export function fitScene(
const withMediaHeight = (blocks: Block[], height: number): Block[] =>
blocks.map((block) => {
if (block.type === "media") return { ...block, height };
+
if (block.type === "group") {
return { ...block, blocks: withMediaHeight(block.blocks, height) };
}
+
return block;
});
diff --git a/remotion/src/components/SubtleCaptions.tsx b/remotion/src/components/SubtleCaptions.tsx
index 12e6f60..8ad3496 100644
--- a/remotion/src/components/SubtleCaptions.tsx
+++ b/remotion/src/components/SubtleCaptions.tsx
@@ -80,6 +80,7 @@ export const SubtleCaptions: React.FC<Props> = ({
absorbTail: 2,
clipEnd: durationInFrames / fps,
});
+
const activeChunk = activeChunkAt(chunks, currentTime);
if (!activeChunk) return null;
@@ -97,6 +98,7 @@ export const SubtleCaptions: React.FC<Props> = ({
Math.ceil(activeChunk.words.length / 2),
singleLine,
);
+
return (
<div
style={{
diff --git a/remotion/src/motion.ts b/remotion/src/motion.ts
index 531733c..202bf67 100644
--- a/remotion/src/motion.ts
+++ b/remotion/src/motion.ts
@@ -26,8 +26,8 @@ const FEEL: Record<Motion["feel"], { damping: number; stiffness: number; mass: n
linear: { damping: 200, stiffness: 100, mass: 1 },
};
-export const MOTION: Record<string, Motion> = {
- /** Word-by-word: springs up to size, no exit — the cut is the style. */
+export const MOTION = {
+ /** Word-by-word: springs up to size, no exit; the cut is the style. */
hormozi: { enter: "pop", exit: "none", duration: 3, feel: "snap" },
/** A line that is meant to be read, so it arrives and leaves quietly. */
subtle: { enter: "rise", exit: "fade", duration: 5, feel: "soft" },
@@ -52,7 +52,18 @@ export const MOTION: Record<string, Motion> = {
card: { enter: "fade", exit: "fade", duration: 6, feel: "soft" },
/** Always there, so it neither arrives nor leaves. */
watermark: { enter: "none", exit: "none", duration: 0, feel: "linear" },
-};
+} satisfies Record<string, Motion>;
+
+/** The motion a caption voice ships with, or the subtle one for a voice with none of its own. */
+export const motionForVoice = (name: string): Motion =>
+ new Map<string, Motion>(Object.entries(MOTION)).get(name) ?? MOTION.subtle;
+
+export interface MotionFrame {
+ opacity: number;
+ scale: number;
+ shift: number;
+ slide: number;
+}
/**
* Fade a thing in when it arrives and out before it leaves.
@@ -87,6 +98,7 @@ export function fadeInOut({
: 1;
const held = endFrame - startFrame;
+
if (!outFrames || held < inFrames + outFrames + 2) return rising;
const falling = interpolate(frame, [endFrame - outFrames, endFrame], [1, 0], {
@@ -113,7 +125,7 @@ export function motionAt({
motion: Motion;
/** How far a rise or a sink travels, already scaled to the canvas. */
scale?: number;
-}): { opacity: number; scale: number; shift: number; slide: number } {
+}): MotionFrame {
const startFrame = Math.round(start * fps);
const since = frame - startFrame;
@@ -135,6 +147,7 @@ export function motionAt({
: 0;
const endFrame = Math.round(end * fps);
+
const leaving = motion.exit === "sink"
? interpolate(frame, [endFrame - motion.duration, endFrame], [0, rise], {
extrapolateLeft: "clamp",
diff --git a/remotion/src/scene.test.ts b/remotion/src/scene.test.ts
index fee8ff7..bde09a8 100644
--- a/remotion/src/scene.test.ts
+++ b/remotion/src/scene.test.ts
@@ -33,21 +33,25 @@ describe("fitting a scene into the room it was given", () => {
it("measures a wrapped line as taller than one that fits across", () => {
const short = blockHeight(text("Short"), 888);
+
const long = blockHeight(
text("A sentence long enough to wrap across more than one line of this frame"),
888,
);
+
expect(long).toBeGreaterThan(short);
});
it("gives a row the width it actually has rather than the whole frame", () => {
const words = "A sentence long enough to wrap when it only has half the frame";
const alone = sceneHeight([text(words)], "stack", "group");
+
const beside = sceneHeight(
[{ type: "group", layout: "row", blocks: [text(words), text(words)] }],
"stack",
"group",
);
+
expect(beside).toBeGreaterThan(alone);
});
});
@@ -75,6 +79,7 @@ describe("the card in front at a moment", () => {
{ kind: "quote", start: 0, end: 3, text: "first" },
{ kind: "scene", start: 3, end: 6, blocks: [text("second")] },
];
+
expect(cardAt(cards, 1)?.kind).toBe("quote");
expect(cardAt(cards, 4)?.kind).toBe("scene");
// Half-open, so a card ending where the next begins is a cut.
@@ -85,7 +90,9 @@ describe("the card in front at a moment", () => {
describe("a stacked timeline of steps", () => {
- const steps = (note: string) => [{ type: "steps", points: [{ value: "Product", note }, { value: "Distribution", note }] }] as Block[];
+ const steps = (note: string): Block[] => [
+ { type: "steps", points: [{ value: "Product", note }, { value: "Distribution", note }] },
+ ];
it("grows when a note wraps", () => {
const short = sceneHeight(steps("First-time founders"), "stack", "group");
diff --git a/remotion/src/scene.ts b/remotion/src/scene.ts
index 730496a..6ee3097 100644
--- a/remotion/src/scene.ts
+++ b/remotion/src/scene.ts
@@ -1,4 +1,5 @@
import { SAFE } from "./types";
+
export type Tone = "ink" | "accent" | "muted" | "context";
export type Size = "xs" | "sm" | "md" | "lg" | "xl" | "xxl";
@@ -105,6 +106,7 @@ export function emphasisRuns(text: string, emphasis?: string | string[]): Run[]
const phrases = (Array.isArray(emphasis) ? emphasis : emphasis ? [emphasis] : [])
.map((phrase) => phrase.trim())
.filter(Boolean);
+
if (!phrases.length) return [{ text, mark: false }];
const runs: Run[] = [{ text, mark: false }];
@@ -112,20 +114,26 @@ export function emphasisRuns(text: string, emphasis?: string | string[]): Run[]
for (const phrase of phrases) {
let placed = false;
+
for (let i = 0; i < runs.length && !placed; i++) {
const run = runs[i]!;
+
if (run.mark) continue;
const at = run.text.toLowerCase().indexOf(phrase.toLowerCase());
+
if (at < 0) continue;
const before = run.text.slice(0, at);
const after = run.text.slice(at + phrase.length);
const parts: Run[] = [];
+
if (before) parts.push({ text: before, mark: false });
parts.push({ text: run.text.slice(at, at + phrase.length), mark: true });
+
if (after) parts.push({ text: after, mark: false });
runs.splice(i, 1, ...parts);
placed = true;
}
+
/*
* Appended only when the line does not contain it at all. A phrase that is
* in the line but already sits inside another mark has been said: adding
@@ -139,6 +147,7 @@ export function emphasisRuns(text: string, emphasis?: string | string[]): Run[]
for (const phrase of appended) {
runs.push({ text: " ", mark: false }, { text: phrase, mark: true });
}
+
return runs;
}
@@ -163,6 +172,7 @@ const LINE = 1.25;
const lines = (text: string, size: number, width: number, advance = ADVANCE) => {
const perLine = Math.max(1, Math.floor(width / (size * advance)));
+
return Math.max(1, Math.ceil(text.length / perLine));
};
@@ -176,21 +186,28 @@ export const stepsStacked = (points: StepPoint[]) => points.length <= 3;
export const stepType = (points: StepPoint[], width = SCENE_WIDTH) => {
const stacked = stepsStacked(points);
+
const slot = stacked
? width - 56
: (width - Math.max(0, points.length - 1) * 120) / Math.max(1, points.length);
+
const fits = (text: string | undefined, size: number) => !text || text.length * size * CHAR_WIDTH <= slot;
+
const value = [TYPE_SIZE.xl, TYPE_SIZE.lg, TYPE_SIZE.md, TYPE_SIZE.sm]
.find((size) => points.every((point) => fits(point.value, size))) ?? TYPE_SIZE.xs;
+
const note = (stacked ? [TYPE_SIZE.md, TYPE_SIZE.sm, TYPE_SIZE.xs] : [TYPE_SIZE.sm, TYPE_SIZE.xs])
.find((size) => points.every((point) => fits(point.note, size))) ?? TYPE_SIZE.xs;
+
return { value, note };
};
const stepRow = (points: StepPoint[], width: number) => {
const type = stepType(points, width);
+
if (!stepsStacked(points)) return 26 + type.value + type.note * 2.6 + 24;
const text = width - 56;
+
return points.reduce((sum, point, i) =>
sum + (i ? STEP_RISE : 0)
+ lines(point.value, type.value, text, CHAR_WIDTH) * type.value * 1.05
@@ -221,22 +238,28 @@ export function blockHeight(block: Block, width: number): number {
case "text": {
const size = TYPE_SIZE[sizeOf(block)];
const text = emphasised(block.text, block.emphasis);
+
return lines(text, size, width, block.caps ? CAPS_ADVANCE : ADVANCE) * size * LINE;
}
+
case "quote": {
const size = TYPE_SIZE[sizeOf(block)];
const body = lines(block.text, size, width) * size * LINE;
+
return body + (block.attribution ? GAP_SIZE.group + TYPE_SIZE.xs * LINE : 0);
}
+
case "list": {
const size = TYPE_SIZE[sizeOf(block)];
const marker = 46;
+
return block.items.reduce(
(total, item, i) =>
total + (i ? GAP_SIZE.tight : 0) + lines(item, size, width - marker) * size * LINE,
0,
);
}
+
case "bars":
return block.rows.length * BAR_ROW + Math.max(0, block.rows.length - 1) * 30;
case "meter":
@@ -262,6 +285,7 @@ function groupHeight(
block: Extract<Block, { type: "group" }>, width: number,
): number {
const kids = listOf(block);
+
if (!kids.length) return 0;
const gap = gapOf(block);
const layout = block.layout ?? "stack";
@@ -275,6 +299,7 @@ function groupHeight(
const columns = layout === "grid" ? 2 : kids.length;
const share = Math.max(1, (width - gap * (columns - 1)) / columns);
+
if (layout === "row") {
return Math.max(...kids.map((kid) => blockHeight(kid, share)));
}
@@ -283,11 +308,13 @@ function groupHeight(
let total = 0;
kids.forEach((kid, i) => {
tallest = Math.max(tallest, blockHeight(kid, share));
+
if (i % columns === columns - 1 || i === kids.length - 1) {
total += (total ? gap : 0) + tallest;
tallest = 0;
}
});
+
return total;
}
@@ -312,7 +339,9 @@ export function fitScale(
): number {
if (!(room > 0)) return 1;
const wanted = sceneHeight(blocks, layout, gap, width);
+
if (wanted <= room) return 1;
+
return Math.max(MIN_FIT, room / wanted);
}
diff --git a/remotion/src/style/materials.tsx b/remotion/src/style/materials.tsx
index 3915359..1605688 100644
--- a/remotion/src/style/materials.tsx
+++ b/remotion/src/style/materials.tsx
@@ -5,10 +5,12 @@ import type { Theme } from "./theme";
const random = (seed: number) => {
let t = (seed * 2654435761) >>> 0;
+
return () => {
t = (t + 0x6d2b79f5) >>> 0;
let r = Math.imul(t ^ (t >>> 15), 1 | t);
r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r;
+
return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
};
};
@@ -19,15 +21,19 @@ export const fibrous = (seed: number, wave: number, fiber: number, sides: Sides
const r = random(seed);
const { top = true, right = true, bottom = true, left = true } = sides;
const points: string[] = [];
+
const edge = (on: boolean, point: (t: number, d: number) => string) => {
if (!on) {
points.push(point(0, 0));
+
return;
}
+
const p1 = r() * 6.28;
const p2 = r() * 6.28;
const f1 = 2 + r() * 2.5;
const f2 = 9 + r() * 6;
+
for (let i = 0; i < steps; i++) {
const t = (i / steps) * 100;
const u = i / steps;
@@ -36,10 +42,12 @@ export const fibrous = (seed: number, wave: number, fiber: number, sides: Sides
points.push(point(t, 1 + wave * smooth + fiber * r() + spike));
}
};
+
edge(top, (t, d) => `${t.toFixed(2)}% ${d.toFixed(1)}px`);
edge(right, (t, d) => `calc(100% - ${d.toFixed(1)}px) ${t.toFixed(2)}%`);
edge(bottom, (t, d) => `${(100 - t).toFixed(2)}% calc(100% - ${d.toFixed(1)}px)`);
edge(left, (t, d) => `${d.toFixed(1)}px ${(100 - t).toFixed(2)}%`);
+
return `polygon(${points.join(",")})`;
};
@@ -120,6 +128,7 @@ export const Label: React.FC<{
children: React.ReactNode;
}> = ({ theme, seed, scale: s, size: base, color, ink, pad = 0.28, style, children }) => {
const size = base * (theme.type.label.size ?? 1);
+
if (theme.surface === "none") {
return (
<div style={{ display: "inline-block", ...fontOf({ ...theme.type.label, size: 1 }, size), fontWeight: 700, lineHeight: 1,
@@ -128,6 +137,7 @@ export const Label: React.FC<{
</div>
);
}
+
return (
<Paper
theme={theme}
@@ -157,7 +167,9 @@ export const Tape: React.FC<{
style?: React.CSSProperties;
}> = ({ theme, seed, scale: s, width, style }) => {
const tapes = theme.textures.tape ?? [];
+
if (!theme.tape || !tapes.length) return null;
+
return (
<Img
src={tapes[seed % tapes.length]}
diff --git a/remotion/src/style/overlay.tsx b/remotion/src/style/overlay.tsx
index 9f455ec..6038715 100644
--- a/remotion/src/style/overlay.tsx
+++ b/remotion/src/style/overlay.tsx
@@ -42,6 +42,7 @@ const StatBody: React.FC<Props<"stat">> = ({ card, theme, s, f, fps }) => {
const eyebrowAt = card.eyebrow ? next("label") : 0;
const figureAt = next("figure", card.value);
const captionAt = next("strip");
+
return (
<>
<Eyebrow theme={theme} s={s} f={f} fps={fps} at={eyebrowAt} text={card.eyebrow} />
@@ -62,6 +63,7 @@ const HeadlineBody: React.FC<Props<"headline">> = ({ card, theme, s, f, fps }) =
const markAt = leadAt + roleFrames(theme, "title", card.lead) + 2;
const subAt = next("strip");
const mark = Array.isArray(card.emphasis) ? card.emphasis[0] : card.emphasis;
+
return (
<>
<Eyebrow theme={theme} s={s} f={f} fps={fps} at={eyebrowAt} text={card.eyebrow} />
@@ -80,6 +82,7 @@ const EntityBody: React.FC<Props<"entity">> = ({ card, theme, s, f, fps }) => {
const mediaAt = card.src ? next("media") : 0;
const nameAt = next("figure", card.name);
const noteAt = next("strip");
+
return (
<div style={{ display: "flex", alignItems: "center", gap: 32 * s }}>
{card.src && (
@@ -105,6 +108,7 @@ const BulletsBody: React.FC<Props<"bullets">> = ({ card, theme, s, f, fps }) =>
const eyebrowAt = card.eyebrow ? next("title", card.eyebrow) : 0;
const items = card.items.slice(0, 3);
const ats = items.map(() => next("item"));
+
return (
<>
<Eyebrow theme={theme} s={s} f={f} fps={fps} at={eyebrowAt} text={card.eyebrow} />
@@ -126,6 +130,7 @@ const QuoteBody: React.FC<Props<"quote">> = ({ card, theme, s, f, fps }) => {
const next = planner(theme);
const textAt = next("title", card.text);
const byAt = next("label");
+
return (
<>
<Reveal theme={theme} role="title" f={f} at={textAt} fps={fps} style={{ position: "relative" }}>
@@ -145,6 +150,7 @@ const CompareBody: React.FC<Props<"compare">> = ({ card, theme, s, f, fps }) =>
const rows = card.rows.slice(0, 3);
const ats = rows.map(() => next("item"));
const top = Math.max(...rows.map((row) => row.value), 1);
+
return (
<>
<Eyebrow theme={theme} s={s} f={f} fps={fps} at={eyebrowAt} text={card.eyebrow} />
@@ -169,6 +175,7 @@ const ChangeBody: React.FC<Props<"change">> = ({ card, theme, s, f, fps }) => {
const eyebrowAt = title ? next("label") : 0;
const fromAt = next("item");
const toAt = next("figure", card.to.value) + 4;
+
return (
<>
<Eyebrow theme={theme} s={s} f={f} fps={fps} at={eyebrowAt} text={title} />
@@ -199,6 +206,7 @@ const ShareBody: React.FC<Props<"share">> = ({ card, theme, s, f, fps }) => {
const figureAt = next("figure", display);
const barAt = next("item");
const fill = progress(theme.motion, f, barAt, Math.max(12, theme.motion.frames * 2));
+
return (
<>
<Eyebrow theme={theme} s={s} f={f} fps={fps} at={eyebrowAt} text={card.eyebrow} />
@@ -219,13 +227,21 @@ const ShareBody: React.FC<Props<"share">> = ({ card, theme, s, f, fps }) => {
const Body: React.FC<{ card: Card; theme: Theme; s: number; f: number; fps: number }> = ({ card, ...rest }) => {
if (card.kind === "stat") return <StatBody card={card} {...rest} />;
+
if (card.kind === "headline") return <HeadlineBody card={card} {...rest} />;
+
if (card.kind === "entity") return <EntityBody card={card} {...rest} />;
+
if (card.kind === "bullets") return <BulletsBody card={card} {...rest} />;
+
if (card.kind === "quote") return <QuoteBody card={card} {...rest} />;
+
if (card.kind === "compare") return <CompareBody card={card} {...rest} />;
+
if (card.kind === "change") return <ChangeBody card={card} {...rest} />;
+
if (card.kind === "share") return <ShareBody card={card} {...rest} />;
+
return null;
};
@@ -236,16 +252,20 @@ export const OverlayCard: React.FC<{
const k = tempo(fitted, card, length);
const f = Math.floor((useCurrentFrame() - start) * k);
const { fps } = useVideoConfig();
+
const out = interpolate(f, [length * k - EXIT_FRAMES * k, length * k], [1, 0], {
extrapolateLeft: "clamp", extrapolateRight: "clamp",
});
+
const panelIn = progress(fitted.motion, f, 0, 6);
const paper = fitted.surface === "paper";
+
const inner = (
<div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 16 * s, padding: `${34 * s}px ${44 * s}px ${40 * s}px` }}>
<Body card={card} theme={fitted} s={s} f={f} fps={fps} />
</div>
);
+
return (
<div style={{
position: "absolute", left: 48 * s, right: 48 * s, top, opacity: out * panelIn,
diff --git a/remotion/src/style/pages.tsx b/remotion/src/style/pages.tsx
index 8878a8d..0b8934e 100644
--- a/remotion/src/style/pages.tsx
+++ b/remotion/src/style/pages.tsx
@@ -4,7 +4,7 @@ import {
useVideoConfig, Video,
} from "remotion";
import type { Card } from "../cards";
-import { fontOf } from "./theme";
+import { fontOf, isString } from "./theme";
import type { Role, Theme } from "./theme";
import { Label, Paper, Tape } from "./materials";
import { camera, progress, Reveal, RevealText, roleFrames, TEXT_ENTRANCES } from "./reveal";
@@ -24,10 +24,12 @@ type PageProps<K extends Card["kind"]> = {
export const planner = (theme: Theme, start = 2) => {
let cursor = start;
+
return (role: Role, text?: string) => {
const at = cursor;
const spoken = TEXT_ENTRANCES.has(theme.motion.roles[role]);
cursor = at + (spoken ? roleFrames(theme, role, text) : 0) + Math.max(2, theme.motion.stagger);
+
return at;
};
};
@@ -51,9 +53,11 @@ const Page: React.FC<{
const shift = Math.max(0, inset - CONTENT_TOP + 20);
const squeeze = (CONTENT_BOTTOM - CONTENT_TOP - shift) / (CONTENT_BOTTOM - CONTENT_TOP);
const lens = (shot: Shot) => ({ ...shot, x: shot.x * s, y: shot.y * s });
+
const fade = theme.motion.exit === "fade"
? interpolate(f, [length - EXIT_FRAMES * k, length], [1, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" })
: 1;
+
return (
<AbsoluteFill style={{ overflow: "hidden", opacity: fade, backgroundColor: theme.color.ground }}>
<div style={{
@@ -81,13 +85,16 @@ export const Circle: React.FC<{ theme: Theme; f: number; at: number; s: number;
theme, f, at, s, inset,
}) => {
const p = progress(theme.motion, f, at, 10);
+
if (p <= 0) return null;
+
const ring = (dx: string, dy: string, rot: number) => (
<ellipse cx={dx} cy={dy} rx="55%" ry="70%" transform={`rotate(${rot})`} pathLength={1}
style={{ transformOrigin: "center", transformBox: "fill-box" }}
fill="none" stroke={theme.color.accent} strokeWidth={6 * s} strokeLinecap="round"
strokeDasharray="1" strokeDashoffset={1 - p} />
);
+
return (
<svg style={{ position: "absolute", inset: -inset * s, width: `calc(100% + ${2 * inset * s}px)`,
height: `calc(100% + ${2 * inset * s}px)`, overflow: "visible" }}>
@@ -99,6 +106,7 @@ export const Circle: React.FC<{ theme: Theme; f: number; at: number; s: number;
const figureSize = (value: string) => {
const length = Array.from(value).length;
+
return length > 9 ? 150 : length > 6 ? 200 : 280;
};
@@ -106,8 +114,11 @@ export const tilt = (theme: Theme, k: number) => ({ transform: `rotate(${theme.t
export const titleSize = (text: string, base: number) => {
const length = Array.from(text).length;
+
if (length > 22) return base * 0.66;
+
if (length > 14) return base * 0.8;
+
return base;
};
@@ -139,6 +150,7 @@ const StatPage: React.FC<PageProps<"stat"> & { length: number }> = ({ card, them
const sheetAt = next("media");
const figureAt = next("figure", card.value) + 4;
const circleAt = figureAt + 8;
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k}
punch={{ at: figureAt, zoom: 1.12, x: 540, y: 820 }}
@@ -192,6 +204,7 @@ const HeadlinePage: React.FC<PageProps<"headline"> & { length: number }> = ({ ca
const markAt = leadAt + roleFrames(theme, "title", card.lead) + 2;
const subAt = next("strip") + 6;
const mark = Array.isArray(card.emphasis) ? card.emphasis[0] : card.emphasis;
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k}
punch={{ at: markAt, zoom: 1.1, x: 540, y: 640 }}
@@ -231,6 +244,7 @@ const EntityPage: React.FC<PageProps<"entity"> & { length: number }> = ({ card,
const nameAt = next("figure", card.name) + 10;
const noteAt = next("strip") + 10;
const src = card.src && (theme.media === "halftone" ? theme.textures.halftone?.[card.src] ?? card.src : card.src);
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k}
punch={{ at: nameAt, zoom: 1.1, x: 300, y: 1090 }}
@@ -268,6 +282,7 @@ const BulletsPage: React.FC<PageProps<"bullets"> & { length: number }> = ({ card
const lift = title ? 0 : 220;
const stocks = [theme.color.sheet, theme.color.stripAlt, theme.color.strip];
const lefts = theme.surface === "paper" ? [50, 110, 70] : [50, 50, 50];
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k}
punch={{ at: items[0] ?? 0, zoom: 1.08, x: 480, y: 600 }}
@@ -306,6 +321,7 @@ const QuotePage: React.FC<PageProps<"quote"> & { length: number }> = ({ card, th
const next = planner(theme);
const textAt = next("title", card.text);
const byAt = next("label") + 4;
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k}
punch={{ at: byAt, zoom: 1.06, x: 540, y: 700 }}
@@ -355,6 +371,7 @@ const CompareRows: React.FC<PageProps<"compare"> & { length: number }> = ({ card
const rows = card.rows.slice(0, 5);
const ats = rows.map(() => next("item"));
const top = Math.max(...rows.map((r) => r.value), 1);
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k} punch={{ at: ats[0] ?? 0, zoom: 1.06, x: 540, y: 700 }}
shots={[{ at: 0, zoom: 1.3, x: 380, y: 290 }, { at: ats[0] ?? 0, zoom: 1.3, x: 380, y: 290 }, { at: (ats[0] ?? 0) + 12, zoom: 1, x: 540, y: 960 }]}>
@@ -387,6 +404,7 @@ const ChangePage: React.FC<PageProps<"change"> & { length: number }> = ({ card,
const arrowAt = fromAt + 6;
const toAt = next("figure", card.to.value) + 8;
const p = progress(theme.motion, f, arrowAt, 10);
+
const end = (value: string, note: string | undefined, at: number, role: "item" | "figure", top: number, seed: number, strong: boolean) => (
<Reveal theme={theme} role={role} f={f} at={at} fps={fps} style={{ left: 0, right: 0, top: top * s, display: "flex", flexDirection: "column", alignItems: "center", gap: 14 * s }}>
<Label theme={theme} seed={seed} scale={s} size={(strong ? 200 : 120) * s} pad={0.16}
@@ -396,6 +414,7 @@ const ChangePage: React.FC<PageProps<"change"> & { length: number }> = ({ card,
{note && <div style={{ ...fontOf(theme.type.label, 54 * s), color: theme.color.muted }}>{note}</div>}
</Reveal>
);
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k} punch={{ at: toAt, zoom: 1.1, x: 540, y: 1000 }}
shots={[{ at: 0, zoom: 1.25, x: 540, y: 560 }, { at: arrowAt, zoom: 1.25, x: 540, y: 560 }, { at: toAt + 8, zoom: 1, x: 540, y: 960 }]}>
@@ -422,6 +441,7 @@ const SharePage: React.FC<PageProps<"share"> & { length: number }> = ({ card, th
const figureAt = next("figure", display) + 4;
const barAt = next("item");
const fill = progress(theme.motion, f, barAt, Math.max(12, theme.motion.frames * 2));
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k} punch={{ at: figureAt, zoom: 1.1, x: 540, y: 700 }}
shots={[{ at: 0, zoom: 1.3, x: 380, y: 290 }, { at: figureAt, zoom: 1.3, x: 380, y: 290 }, { at: figureAt + 12, zoom: 1, x: 540, y: 960 }]}>
@@ -454,9 +474,11 @@ const MediaPage: React.FC<PageProps<"image" | "video"> & { length: number }> = (
const captionAt = next("strip") + 6;
const bleed = theme.surface === "none";
const fit: React.CSSProperties = { width: "100%", height: "100%", display: "block", objectFit: card.fit === "fit" ? "contain" : "cover" };
+
const body = card.kind === "video"
? <Frame src={src} muted startFrom={Math.max(0, Math.round((card.startAt ?? 0) * fps))} style={fit} />
: <Img src={shown} style={fit} />;
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k} punch={null}
shots={[{ at: 0, zoom: 1.12, x: 540, y: 800 }, { at: 30, zoom: 1, x: 540, y: 960 }]}>
@@ -483,10 +505,13 @@ const ScenePage: React.FC<PageProps<"scene"> & { length: number }> = ({ card, th
const sheetAt = next("media");
const bodyAt = next("item");
const surface = theme.surface === "none" ? theme.color.ground : theme.color.sheet;
+
const room = hasMedia(card.blocks)
? 940
: Math.min(940, Math.max(360, sceneHeight(card.blocks, card.layout ?? "stack", card.gap ?? "group") * 920 / SCENE_WIDTH + 80));
+
const top = 250 + (940 - room) / 2;
+
return (
<Page theme={theme} s={s} f={f} length={length} inset={inset} k={k} punch={null}
shots={[{ at: 0, zoom: 1.12, x: 540, y: 700 }, { at: bodyAt + 14, zoom: 1, x: 540, y: 960 }]}>
@@ -506,8 +531,11 @@ const ScenePage: React.FC<PageProps<"scene"> & { length: number }> = ({ card, th
const cardTexts = (card: Card): string[] => Object.entries(card).flatMap(([key, value]) => {
if (key === "kind") return [];
- if (typeof value === "string") return [value];
- if (Array.isArray(value)) return value.filter((item): item is string => typeof item === "string");
+
+ if (Array.isArray(value)) return value.filter(isString);
+
+ if (isString(value)) return [value];
+
return [];
});
@@ -516,18 +544,24 @@ export const paced = (theme: Theme, card: Card, length: number): Theme => {
const hold = Math.max(1, theme.motion.holdEvery);
const longest = Math.max(0, ...cardTexts(card).map((text) => Array.from(text).length));
const words = Math.max(0, ...cardTexts(card).map((text) => text.split(/\s+/).filter(Boolean).length));
+
if (theme.motion.textUnit === "word") {
if (words * hold <= budget) return theme;
+
return { ...theme, motion: { ...theme.motion, textUnit: "char", charsPerPose: Math.ceil((longest * hold) / budget) } };
}
+
const poses = Math.ceil(longest / theme.motion.charsPerPose);
+
if (poses * hold <= budget) return theme;
+
return { ...theme, motion: { ...theme.motion, charsPerPose: Math.ceil((longest * hold) / budget) } };
};
export const buildFrames = (theme: Theme, card: Card) => {
const texts = cardTexts(card);
const typed = texts.reduce((sum, text) => sum + roleFrames(theme, "title", text), 0);
+
return typed + texts.length * (Math.max(2, theme.motion.stagger) + theme.motion.frames) + 24;
};
@@ -542,15 +576,26 @@ export const TakeoverPage: React.FC<{
const f = Math.floor((useCurrentFrame() - start) * k);
const { fps } = useVideoConfig();
const props = { theme: fitted, s, f, fps, length: length * k, inset, k };
+
if (card.kind === "stat") return <StatPage card={card} {...props} />;
+
if (card.kind === "headline") return <HeadlinePage card={card} {...props} />;
+
if (card.kind === "entity") return <EntityPage card={card} {...props} />;
+
if (card.kind === "bullets") return <BulletsPage card={card} {...props} />;
+
if (card.kind === "quote") return <QuotePage card={card} {...props} />;
+
if (card.kind === "compare") return <CompareRows card={card} {...props} />;
+
if (card.kind === "change") return <ChangePage card={card} {...props} />;
+
if (card.kind === "share") return <SharePage card={card} {...props} />;
+
if (card.kind === "image" || card.kind === "video") return <MediaPage card={card} {...props} />;
+
if (card.kind === "scene") return <ScenePage card={card} {...props} />;
+
return null;
};
diff --git a/remotion/src/style/reveal.test.ts b/remotion/src/style/reveal.test.ts
index 3eb76df..d29bd0a 100644
--- a/remotion/src/style/reveal.test.ts
+++ b/remotion/src/style/reveal.test.ts
@@ -19,13 +19,17 @@ describe("settle", () => {
const crossings = (bounces: number) => {
let count = 0;
let above = false;
+
for (let i = 1; i < 200; i++) {
const now = settle(i / 200, bounces) > 1;
+
if (now !== above) count++;
above = now;
}
+
return count;
};
+
expect(crossings(1)).toBe(1);
expect(crossings(2)).toBe(2);
});
diff --git a/remotion/src/style/reveal.tsx b/remotion/src/style/reveal.tsx
index 9db71f3..f702275 100644
--- a/remotion/src/style/reveal.tsx
+++ b/remotion/src/style/reveal.tsx
@@ -14,6 +14,7 @@ export const progress = (motion: Motion, frame: number, at: number, frames = mot
export const wipe = (p: number, from: "left" | "bottom" = "left") => {
const hidden = `${(1 - p) * 100}%`;
+
return from === "bottom" ? `inset(${hidden} 0 0 0)` : `inset(-20% ${hidden} -20% -5%)`;
};
@@ -21,6 +22,7 @@ export const TEXT_ENTRANCES = new Set<Entrance>(["type", "typed", "scramble", "c
export const settle = (t: number, bounces: number) => {
const k = Math.min(1, Math.max(0, t));
+
return 1 - (1 - k) ** 2 * Math.cos((Math.PI * (2 * bounces + 1) * k) / 2);
};
@@ -32,25 +34,34 @@ const unitCount = (text: string, unit: Motion["textUnit"]) =>
export const entranceFrames = (motion: Motion, entrance: Entrance, text?: string) => {
if (entrance === "pop") return 1;
+
if (entrance === "count") return Math.round(motion.frames * 1.8);
+
if (TEXT_ENTRANCES.has(entrance) && text) {
const perPose = motion.textUnit === "word" ? 1 : motion.charsPerPose;
+
return Math.ceil(unitCount(text, motion.textUnit) / perPose) * Math.max(1, motion.holdEvery);
}
+
return motion.frames;
};
const offset = (from: Side, distance: number) => {
if (from === "left") return `translateX(${-distance}px)`;
+
if (from === "right") return `translateX(${distance}px)`;
+
if (from === "top") return `translateY(${-distance}px)`;
+
return `translateY(${distance}px)`;
};
const mask = (entrance: Entrance, p: number) => {
if (entrance === "mask-circle") return `circle(${p * 75}% at 50% 50%)`;
+
if (entrance === "mask-split") return `inset(-10% ${(1 - p) * 50}% -10% ${(1 - p) * 50}%)`;
const x = p * 220 - 10;
+
return `polygon(-10% -10%, ${x}% -10%, ${x - 100}% 110%, -10% 110%)`;
};
@@ -63,6 +74,7 @@ const DIGITS = "0123456789";
const scrambled = (char: string, n: number) => {
const pool = /[A-Z]/.test(char) ? UPPER : /[a-z]/.test(char) ? LOWER : /[0-9]/.test(char) ? DIGITS : "";
+
return pool ? pool[n % pool.length] : char;
};
@@ -71,6 +83,7 @@ const NUMBER = /^(.*?)([-−]?)(\d{1,3}(?:,\d{3})+|\d+)(?:\.(\d+))?(.*)$/s;
export const countedTo = (text: string, p: number) => {
if (p >= 1) return text;
const found = NUMBER.exec(text);
+
if (!found) return text;
const [, before, sign, whole, decimals = "", after] = found;
const target = Number(`${whole.replace(/,/g, "")}.${decimals || "0"}`);
@@ -78,6 +91,7 @@ export const countedTo = (text: string, p: number) => {
const fixed = now.toFixed(decimals.length);
const [int, frac] = fixed.split(".");
const grouped = whole.includes(",") ? int.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : int;
+
return `${before}${sign}${grouped}${frac ? `.${frac}` : ""}${after}`;
};
@@ -93,11 +107,14 @@ export const Reveal: React.FC<{
const { motion } = theme;
const entrance = motion.roles[role];
const base: React.CSSProperties = { position: "absolute", ...style };
+
if (f < at) return null;
+
if (entrance === "pop" || TEXT_ENTRANCES.has(entrance)) return <div style={base}>{children}</div>;
if (entrance === "wipe" || entrance === "wipe-up") {
const p = progress(motion, f, at);
+
return <div style={{ ...base, clipPath: p < 1 ? wipe(p, entrance === "wipe-up" ? "bottom" : "left") : undefined }}>{children}</div>;
}
@@ -107,7 +124,9 @@ export const Reveal: React.FC<{
config: { damping: 10 + (1 - motion.overshoot) * 30, stiffness: 180, mass: 0.6 },
durationInFrames: motion.frames * 2,
});
+
const opacity = interpolate(held(motion, f) - at, [0, 2], [0, 1], { extrapolateRight: "clamp" });
+
return (
<div style={{ ...base, opacity, transform: `${base.transform ?? ""} scale(${0.82 + 0.18 * k})` }}>{children}</div>
);
@@ -119,7 +138,9 @@ export const Reveal: React.FC<{
config: { stiffness: 220, damping: 14, mass: 0.6 },
durationInFrames: motion.frames * 2,
});
+
const opacity = interpolate(held(motion, f) - at, [0, 1], [0, 1], { extrapolateRight: "clamp" });
+
return (
<div style={{ ...base, opacity, transform: `${base.transform ?? ""} scale(${1.35 - 0.35 * k})` }}>{children}</div>
);
@@ -128,6 +149,7 @@ export const Reveal: React.FC<{
if (entrance === "drop") {
const p = progress(motion, f, at);
const turn = (at % 2 ? 4 : -4) * (1 - p);
+
return (
<div style={{ ...base, opacity: Math.min(1, p * 3), transform: `${base.transform ?? ""} rotate(${turn}deg) scale(${1 + 0.08 * (1 - p)})` }}>
{children}
@@ -139,6 +161,7 @@ export const Reveal: React.FC<{
const p = progress(motion, f, at);
const dx = 4 + 10 * (1 - p);
const dy = -(3 + 6 * (1 - p));
+
return (
<div style={{ ...base, opacity: p, filter: `drop-shadow(${dx}px ${dy}px 0 ${theme.color.accent})` }}>{children}</div>
);
@@ -147,6 +170,7 @@ export const Reveal: React.FC<{
const t = interpolate(held(motion, f), [at, at + Math.max(1, motion.frames)], [0, 1], {
extrapolateLeft: "clamp", extrapolateRight: "clamp",
});
+
const moved = motion.bounces > 0 ? settle(t, motion.bounces) : progress(motion, f, at);
const shown = interpolate(held(motion, f) - at, [0, 3], [0, 1], { extrapolateRight: "clamp" });
@@ -166,16 +190,19 @@ export const Reveal: React.FC<{
if (entrance === "blur") {
const p = progress(motion, f, at);
+
return <div style={{ ...base, opacity: p, filter: p < 1 ? `blur(${(1 - p) * 18}px)` : undefined }}>{children}</div>;
}
if (entrance === "mask-circle" || entrance === "mask-diagonal" || entrance === "mask-split") {
const p = progress(motion, f, at);
+
return <div style={{ ...base, clipPath: p < 1 ? mask(entrance, p) : undefined }}>{children}</div>;
}
const p = progress(motion, f, at);
const rise = entrance === "rise" ? offset("bottom", (1 - (motion.bounces > 0 ? moved : p)) * 40) : "";
+
return <div style={{ ...base, opacity: p, transform: `${base.transform ?? ""} ${rise}` }}>{children}</div>;
};
@@ -191,10 +218,13 @@ export const RevealText: React.FC<{
}> = ({ theme, role, f, at, text, mark, markAt, s }) => {
const { motion } = theme;
const entrance = motion.roles[role];
+
if (entrance === "count") {
const p = progress(motion, f, at, entranceFrames(motion, "count"));
+
return <span style={{ fontVariantNumeric: "tabular-nums" }}>{countedTo(text, p)}</span>;
}
+
const typing = TEXT_ENTRANCES.has(entrance);
const pieces = units(text, motion.textUnit);
const perPose = motion.textUnit === "word" ? 1 : motion.charsPerPose;
@@ -210,8 +240,10 @@ export const RevealText: React.FC<{
let cursor = 0;
const finished = at + entranceFrames(motion, entrance, text);
const since = held(motion, f) - finished;
+
const caretOn = entrance === "typed"
&& (count < total || (since < 30 && Math.floor(since / 15) % 2 === 0));
+
const spans: { text: string; from: number; visible: boolean; fresh: boolean; cover?: string; caret?: boolean }[] = pieces.map((piece) => {
const word = piece.trim().length > 0;
const index = word ? seen++ : seen - 1;
@@ -219,9 +251,11 @@ export const RevealText: React.FC<{
cursor += piece.length;
const settled = index < count;
const shown = entrance === "scramble" ? f >= at : settled || (!word && index < count);
+
const cover = entrance === "scramble" && !settled && word
? Array.from(piece).map((char, i) => scrambled(char, (from + i) * 7 + seed * 13)).join("")
: undefined;
+
return {
text: piece, from, visible: shown, cover,
fresh: entrance === "type" && word && index === count - 1 && count < total,
@@ -230,7 +264,7 @@ export const RevealText: React.FC<{
});
const render = (lo: number, hi: number) => spans
- .filter((span) => span.from >= lo && span.from < hi)
+ .flatMap((span) => (span.from >= lo && span.from < hi ? [span] : []))
.map((span) => (
span.cover ? (
<span key={span.from} style={{ opacity: span.visible ? 1 : 0 }}>
@@ -262,6 +296,7 @@ export const RevealText: React.FC<{
if (markStart < 0 || motion.textUnit === "word" && !spans.some((span) => span.from === markStart)) {
return <>{render(0, text.length)}</>;
}
+
if (theme.mark === "color") {
return (
<>
@@ -271,6 +306,7 @@ export const RevealText: React.FC<{
</>
);
}
+
return (
<>
{render(0, markStart)}
@@ -302,18 +338,21 @@ export const camera = (
let zoom = 1;
let x = width / 2;
let y = height / 2;
+
if (motion.camera === "push") {
zoom = 1 + 0.045 * Math.min(1, h / Math.max(1, length));
} else if (motion.camera === "punch" && punch) {
const k = interpolate(h, [punch.at, punch.at + 1, punch.at + 14], [0, 1, 0.35], {
extrapolateLeft: "clamp", extrapolateRight: "clamp", easing: Easing.out(Easing.cubic),
});
+
zoom = 1 + (punch.zoom - 1) * k;
x = width / 2 + (punch.x - width / 2) * k;
y = height / 2 + (punch.y - height / 2) * k;
} else if (motion.camera === "track" && shots.length) {
const next = shots.findIndex((shot) => shot.at > h);
const last = shots[shots.length - 1];
+
if (next === -1) {
zoom = last.zoom * (1 + 0.02 * Math.min(1, (h - last.at) / 120));
({ x, y } = last);
@@ -328,8 +367,10 @@ export const camera = (
y = a.y + (b.y - a.y) * k;
}
}
+
if (zoom === 1) return "none";
const tx = Math.min(0, Math.max(width - width * zoom, width / 2 - x * zoom));
const ty = Math.min(0, Math.max(height - height * zoom, height / 2 - y * zoom));
+
return `translate(${tx}px, ${ty}px) scale(${zoom})`;
};
diff --git a/remotion/src/style/styled.tsx b/remotion/src/style/styled.tsx
index 9d12880..5a37cff 100644
--- a/remotion/src/style/styled.tsx
+++ b/remotion/src/style/styled.tsx
@@ -16,14 +16,17 @@ export const StyledCards: React.FC<{ cards: Card[]; theme: Theme; topInset?: num
const frame = useCurrentFrame();
const { fps, height } = useVideoConfig();
const card = cardAt(cards.filter((c) => theme.layout[c.kind] === "takeover"), frame / fps);
+
if (!card) return null;
const start = Math.round(card.start * fps);
+
if (theme.placement === "overlay" && OVERLAY_KINDS.has(card.kind)) {
return (
<OverlayCard card={card} theme={theme} s={captionScale(height)} start={start}
length={Math.round(card.end * fps) - start} top={(topInset + 12) * captionScale(height)} />
);
}
+
return (
<TakeoverPage card={card} theme={theme} s={captionScale(height)} start={start}
length={Math.round(card.end * fps) - start} inset={topInset} />
@@ -42,7 +45,9 @@ export const StyledNameCard: React.FC<{
const s = captionScale(height);
const end = Math.round(seconds * fps);
const out = progress(theme.motion, frame, end - 6, 6);
+
if (frame < 8 || out >= 1) return null;
+
return (
<Reveal theme={theme} role="name" f={frame} at={8} fps={fps} style={{
left: 60 * s, top, display: "flex", flexDirection: "column",
@@ -75,10 +80,13 @@ export const StyledCaptions: React.FC<{
const { fps, height, durationInFrames } = useVideoConfig();
const s = captionScale(height);
const now = frame / fps;
+
const chunks = buildChunks(words, {
perChunk: style.wordsPerChunk, absorbTail: 1, clipEnd: durationInFrames / fps,
});
+
const chunk = activeChunkAt(chunks, now);
+
if (!chunk) return null;
const seed = Math.round(chunk.start * 31);
const size = theme.type.caption * s;
@@ -95,6 +103,7 @@ export const StyledCaptions: React.FC<{
textShadow: bare ? `0 ${2 * s}px ${12 * s}px rgba(0,0,0,0.85), 0 0 ${3 * s}px rgba(0,0,0,0.6)` : undefined }}>
{chunk.words.map((w, i) => {
const on = now >= w.start && now < w.end;
+
return (
<React.Fragment key={i}>
{i > 0 ? " " : ""}
diff --git a/remotion/src/style/textures.ts b/remotion/src/style/textures.ts
index da99bbf..904fab3 100644
--- a/remotion/src/style/textures.ts
+++ b/remotion/src/style/textures.ts
@@ -13,6 +13,8 @@ export const DEFAULT_PACK_TEXTURES: NonNullable<ThemeInput["textures"]> = {
export const withDefaultTextures = (theme: ThemeInput | null): ThemeInput | null => {
if (!theme) return null;
+
if (theme.textures && Object.keys(theme.textures).length > 0) return theme;
+
return { ...theme, textures: DEFAULT_PACK_TEXTURES };
};
diff --git a/remotion/src/style/theme.test.ts b/remotion/src/style/theme.test.ts
index 036a6bc..8463f27 100644
--- a/remotion/src/style/theme.test.ts
+++ b/remotion/src/style/theme.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
-import { ENTRANCES, FONT_IDS, MOTIONS, PACKS, PLACEMENTS, ROLES, resolveTheme } from "./theme";
+import { ENTRANCES, FONT_IDS, MOTIONS, PACKS, ROLES, resolveTheme } from "./theme";
+import type { PackId, ThemeInput } from "./theme";
+
+const isPackId = (id: string): id is PackId => id in PACKS;
+const isMotionId = (id: string): id is keyof typeof MOTIONS => id in MOTIONS;
+const packIds = Object.keys(PACKS).filter(isPackId);
+const motionIds = Object.keys(MOTIONS).filter(isMotionId);
describe("resolveTheme", () => {
it("returns null without a style", () => {
@@ -29,6 +35,7 @@ describe("resolveTheme", () => {
pack: "clean",
overrides: { color: { ground: "linear-gradient(red, blue)", accent: "url(x.png)", ink: "#FFFFFF" } },
});
+
expect(theme?.color.ground).toBe(PACKS.clean.color.ground);
expect(theme?.color.accent).toBe(PACKS.clean.color.accent);
expect(theme?.color.ink).toBe("#FFFFFF");
@@ -58,14 +65,15 @@ describe("motion presets", () => {
it("name an entrance for every role and leave by fading", () => {
for (const [id, motion] of Object.entries(MOTIONS)) {
expect(Object.keys(motion.roles).sort(), id).toEqual([...ROLES].sort());
+
for (const entrance of Object.values(motion.roles)) expect(ENTRANCES, id).toContain(entrance);
expect(motion.exit, id).toBe("fade");
}
});
it("resolve on every pack", () => {
- for (const pack of Object.keys(PACKS) as (keyof typeof PACKS)[]) {
- for (const motion of Object.keys(MOTIONS) as (keyof typeof MOTIONS)[]) {
+ for (const pack of packIds) {
+ for (const motion of motionIds) {
expect(resolveTheme({ pack, motion })?.motion).toEqual(MOTIONS[motion]);
}
}
@@ -93,7 +101,7 @@ describe("fonts picked to match a reference", () => {
describe("card placement", () => {
it("draws cards as full pages unless a style asks otherwise", () => {
- for (const pack of Object.keys(PACKS) as (keyof typeof PACKS)[]) {
+ for (const pack of packIds) {
expect(resolveTheme({ pack })?.placement).toBe("page");
}
});
@@ -107,7 +115,9 @@ describe("card placement", () => {
});
it("ignores a placement the renderer does not know", () => {
- const theme = resolveTheme({ pack: "poster", placement: "corner" as (typeof PLACEMENTS)[number] });
+ // A template arrives as JSON, so an unknown placement is a value the types cannot rule out.
+ const input: ThemeInput = JSON.parse('{ "pack": "poster", "placement": "corner" }');
+ const theme = resolveTheme(input);
expect(theme?.placement).toBe("page");
});
});
diff --git a/remotion/src/style/theme.ts b/remotion/src/style/theme.ts
index 274b47b..babe961 100644
--- a/remotion/src/style/theme.ts
+++ b/remotion/src/style/theme.ts
@@ -1,29 +1,42 @@
import type React from "react";
export type EdgeKind = "straight" | "torn";
+
export type Layout = "takeover";
+
export type Placement = "page" | "overlay";
+
export const PLACEMENTS: Placement[] = ["page", "overlay"];
+
export type Role = "title" | "figure" | "item" | "media" | "label" | "strip" | "caption" | "name";
+
export type Entrance =
| "type" | "scramble" | "wipe" | "wipe-up" | "pop" | "rise" | "fade" | "spring"
| "slide" | "scale" | "blur" | "mask-circle" | "mask-diagonal" | "mask-split"
| "count" | "slam" | "drop" | "register" | "typed";
+
export type Side = "left" | "right" | "top" | "bottom";
+
export type TextUnit = "char" | "word";
+
export type Ease = "out" | "in-out" | "linear";
+
export type CameraMove = "none" | "track" | "push" | "punch";
+
export type Exit = "cut" | "fade";
+
export type CaptionChoice = "pack" | "template" | "hormozi" | "karaoke" | "subtle" | "branded" | "outline";
export const CAPTION_CHOICES: CaptionChoice[] = ["pack", "template", "hormozi", "karaoke", "subtle", "branded", "outline"];
export const ROLES: Role[] = ["title", "figure", "item", "media", "label", "strip", "caption", "name"];
+
export const ENTRANCES: Entrance[] = [
"type", "scramble", "wipe", "wipe-up", "pop", "rise", "fade", "spring",
"slide", "scale", "blur", "mask-circle", "mask-diagonal", "mask-split",
"count", "slam", "drop", "register", "typed",
];
+
export const SIDES: Side[] = ["left", "right", "top", "bottom"];
export interface Face {
@@ -221,10 +234,10 @@ const face = (family: string, weight: number, extra: Partial<Face> = {}): Face =
...extra,
});
-const TAKEOVER: Record<string, Layout> = {
+const TAKEOVER = {
stat: "takeover", headline: "takeover", entity: "takeover", bullets: "takeover", quote: "takeover",
compare: "takeover", change: "takeover", share: "takeover", image: "takeover", video: "takeover", scene: "takeover",
-};
+} satisfies Record<string, Layout>;
const collage: Theme = {
pack: "collage",
@@ -434,19 +447,24 @@ export const PACKS = { clean, collage, editorial, swiss, poster, terminal, riso
export type PackId = keyof typeof PACKS;
-const isObject = (v: unknown): v is Record<string, unknown> =>
- typeof v === "object" && v !== null && !Array.isArray(v);
+/** A string primitive. String(value) only equals value when value is already that string. */
+export const isString = <V>(value: V): value is V & string => String(value) === value;
+
+const isPlainObject = <V>(value: V): value is V & object => value instanceof Object && !Array.isArray(value);
const FORBIDDEN = /gradient|url\(|image-set|filter/i;
-const deepMerge = <T>(base: T, patch: unknown): T => {
- if (!isObject(base) || !isObject(patch)) return (patch ?? base) as T;
- const out: Record<string, unknown> = { ...base };
+const deepMerge = <T extends object>(base: T, patch: DeepPartial<T>): T => {
+ const out = new Map(Object.entries(base));
+
for (const [key, value] of Object.entries(patch)) {
- if (value === undefined || (typeof value === "string" && FORBIDDEN.test(value))) continue;
- out[key] = isObject(value) && isObject(out[key]) ? deepMerge(out[key], value) : value;
+ if (value === undefined || (isString(value) && FORBIDDEN.test(value))) continue;
+ const current = out.get(key);
+ out.set(key, isPlainObject(value) && isPlainObject(current) ? deepMerge(current, value) : value);
}
- return out as T;
+
+ // SAFETY: out holds every key of base, each replaced only by a patch value of the same DeepPartial shape.
+ return Object.fromEntries(out) as T;
};
const FONTS: Record<FontId, { display: Face; label: Face }> = {
@@ -471,8 +489,10 @@ const FONTS: Record<FontId, { display: Face; label: Face }> = {
const withFonts = (theme: Theme, fonts: ThemeInput["fonts"]): Theme => {
const display = fonts?.display && FONTS[fonts.display]?.display;
const label = fonts?.label && FONTS[fonts.label]?.label;
+
if (!display && !label) return theme;
- return { ...theme, type: { ...theme.type, ...(display ? { display } : {}), ...(label ? { label } : {}) } };
+
+ return { ...theme, type: { ...theme.type, ...(display && { display }), ...(label && { label }) } };
};
export const resolveTheme = (input?: ThemeInput | null): Theme | null => {
@@ -482,7 +502,8 @@ export const resolveTheme = (input?: ThemeInput | null): Theme | null => {
const overridden = deepMerge(base, input.overrides ?? {});
const wanted = input.placement ?? overridden.placement;
const merged = { ...overridden, placement: PLACEMENTS.includes(wanted) ? wanted : base.placement };
- return { ...merged, textures: { ...merged.textures, ...(input.textures ?? {}) } };
+
+ return { ...merged, textures: { ...merged.textures, ...input.textures } };
};
export const fontOf = (f: Face, size: number): React.CSSProperties => ({
diff --git a/remotion/src/text.ts b/remotion/src/text.ts
index 8dae0a8..9ab9338 100644
--- a/remotion/src/text.ts
+++ b/remotion/src/text.ts
@@ -11,6 +11,7 @@ const CASELESS_SCRIPT_RANGES: Array<[number, number]> = [
function isCaselessScriptChar(ch: string): boolean {
const cp = ch.codePointAt(0) ?? 0;
+
return CASELESS_SCRIPT_RANGES.some(([lo, hi]) => cp >= lo && cp <= hi);
}
@@ -21,13 +22,16 @@ function isCaselessScriptChar(ch: string): boolean {
export function safeUpper(text: string): string {
if (!text) return text;
let hasCaseless = false;
+
for (const ch of text) {
if (isCaselessScriptChar(ch)) {
hasCaseless = true;
break;
}
}
+
if (!hasCaseless) return text.toUpperCase();
+
return Array.from(text)
.map((ch) => (isCaselessScriptChar(ch) ? ch : ch.toUpperCase()))
.join("");
diff --git a/remotion/src/types.ts b/remotion/src/types.ts
index f66f5f6..8730ce1 100644
--- a/remotion/src/types.ts
+++ b/remotion/src/types.ts
@@ -50,6 +50,7 @@ export interface CaptionStyle {
}
export type CaptionPosition = "auto" | "upper" | "center" | "lower";
+
export type LogoPosition =
| "top-left"
| "top-center"
@@ -177,7 +178,7 @@ export const CAPTION_LINES = 3;
export const captionZone = (style: CaptionStyle) =>
style.marginBottom + style.fontSize * CAPTION_LINES * 1.2 + 36;
-export const STYLES: Record<string, CaptionStyle> = {
+export const STYLES = {
hormozi: {
name: "hormozi",
fontSize: 90,
@@ -242,7 +243,10 @@ export const STYLES: Record<string, CaptionStyle> = {
wordsPerChunk: 7,
marginBottom: 460,
},
-};
+} satisfies Record<string, CaptionStyle>;
+
+export const styleNamed = (name: string): CaptionStyle | undefined =>
+ new Map<string, CaptionStyle>(Object.entries(STYLES)).get(name);
/**
* The caption styles, in the show's own colours.
@@ -263,6 +267,7 @@ export const brandCaptions = (
brand?: { accent: string; ink: string; surface: string } | null,
): CaptionStyle => {
if (!brand) return style;
+
return {
...style,
color: style.name === "karaoke"
@@ -272,6 +277,6 @@ export const brandCaptions = (
emphasisColor: brand.accent,
background: `color-mix(in oklab, ${brand.surface} 85%, transparent)`,
// Opaque, unlike the pill: a stroke at 85% is a grey halo, not an edge.
- ...(style.stroke ? { stroke: brand.surface } : {}),
+ ...(style.stroke && { stroke: brand.surface }),
};
};
diff --git a/remotion/test-render.mjs b/remotion/test-render.mjs
index 61f31ab..a972917 100644
--- a/remotion/test-render.mjs
+++ b/remotion/test-render.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
- * Quick test render — generates a captioned clip to ~/Downloads/
+ * Quick test render: generates a captioned clip to ~/Downloads/
* Uses the same caching as production.
*
* Usage:
@@ -39,6 +39,7 @@ const words = [
const fps = 30;
const durationInFrames = Math.ceil(5.5 * fps);
+
const outputPath = path.join(
process.env.HOME,
"Downloads",
@@ -47,22 +48,24 @@ const outputPath = path.join(
// Try to load logo from podcli asset registry
let logoPath = "";
+
try {
const home = process.env.PODCLI_HOME
? path.resolve(process.env.PODCLI_HOME)
: path.join(PROJECT_ROOT, ".podcli");
+
const registryPath = path.join(home, "assets", "registry.json");
+
if (!fs.existsSync(registryPath)) {
console.warn("No assets registry at", registryPath);
} else {
const registry = JSON.parse(fs.readFileSync(registryPath, "utf-8"));
const logo = registry.assets?.find((a) => a.type === "logo");
+
if (logo?.path && fs.existsSync(logo.path)) logoPath = logo.path;
}
} catch {}
-let logoSrc;
-
const inputProps = {
videoSrc: "",
words,
diff --git a/remotion/webpack-override.mjs b/remotion/webpack-override.mjs
index 0f119f1..bde76a1 100644
--- a/remotion/webpack-override.mjs
+++ b/remotion/webpack-override.mjs
@@ -1,10 +1,8 @@
const TSCONFIG_RAW = { compilerOptions: {} };
const pinTsconfig = (entry) =>
- entry &&
- typeof entry === "object" &&
- typeof entry.loader === "string" &&
- entry.loader.includes("esbuild-loader")
+ entry instanceof Object &&
+ String(entry.loader).includes("esbuild-loader")
? { ...entry, options: { ...entry.options, tsconfigRaw: TSCONFIG_RAW } }
: entry;
@@ -22,6 +20,7 @@ export const webpackOverride = (config) => ({
if (isFontAssetRule(rule)) {
return { ...rule, type: "asset/inline" };
}
+
return Array.isArray(rule?.use) ? { ...rule, use: rule.use.map(pinTsconfig) } : rule;
}),
},
diff --git a/remotion/webpack-override.test.mjs b/remotion/webpack-override.test.mjs
index ea8cec5..9323fc8 100644
--- a/remotion/webpack-override.test.mjs
+++ b/remotion/webpack-override.test.mjs
@@ -32,6 +32,7 @@ describe("webpackOverride", () => {
it("pins tsconfigRaw on every esbuild-loader rule", () => {
const entries = esbuildEntries(webpackOverride(remotionLikeConfig()));
expect(entries).toHaveLength(1);
+
for (const entry of entries) {
expect(entry.options.tsconfigRaw).toBeDefined();
}
@@ -63,6 +64,7 @@ describe("webpackOverride", () => {
],
},
});
+
expect(config.module.rules[0].type).toBe("asset/inline");
expect(config.module.rules[1].type).toBe("asset/resource");
});
diff --git a/scripts/build-remotion.sh b/scripts/build-remotion.sh
index 55c5da2..907f61e 100644
--- a/scripts/build-remotion.sh
+++ b/scripts/build-remotion.sh
@@ -2,7 +2,7 @@
# Build the Remotion render bundle: the remotion/ project plus a production
# node_modules with only the render deps. Native bindings (@rspack, the Remotion
# compositor) are per-platform, so this MUST run on each target platform/arch in
-# CI — the produced bundle is not portable across os/arch.
+# CI: the produced bundle is not portable across os/arch.
#
# Layout (extracted to the runtime dir): remotion/ + node_modules/ as siblings of
# backend/, so render.mjs resolves node_modules and the Python backend resolves
diff --git a/scripts/build-studio.sh b/scripts/build-studio.sh
index 1f6507a..343ec7d 100644
--- a/scripts/build-studio.sh
+++ b/scripts/build-studio.sh
@@ -1,7 +1,7 @@
#!/bin/sh
# Build the studio web-UI bundle: a single self-contained server (esbuild) plus
# the built SPA. Rendering is delegated to the Python backend at runtime, so the
-# bundle needs no node_modules — only a Node runtime to execute it.
+# bundle needs no node_modules: only a Node runtime to execute it.
#
# Usage: scripts/build-studio.sh [out-dir] (default: dist/studio)
set -e
@@ -9,7 +9,7 @@ here="$(cd "$(dirname "$0")/.." && pwd)"
out="${1:-$here/dist/studio}"
cd "$here"
-# Type-check the SPA — vite/esbuild don't, so undefined-var bugs in the client
+# Type-check the SPA: vite/esbuild don't, so undefined-var bugs in the client
# would otherwise ship silently (blank pages at runtime).
npx tsc --noEmit -p src/ui/client/tsconfig.json
npm run build # tsc + vite -> dist/ui/web-server.js + dist/ui/public
@@ -22,6 +22,6 @@ node -e "require('esbuild').buildSync({entryPoints:['dist/ui/web-server.js'],bun
cp -r dist/ui/public "$out/public"
# MCP stdio server (the mcp__podcli__* tools Claude/Codex drive).
node -e "require('esbuild').buildSync({entryPoints:['dist/index.js'],bundle:true,platform:'node',format:'esm',outfile:'$out/mcp-server.mjs',banner:{js:\"$banner\"},logLevel:'error'})"
-# `podcli sync` — reconciles clips, assets, and knowledge with a Pro workspace.
+# `podcli sync`: reconciles clips, assets, and knowledge with a Pro workspace.
node -e "require('esbuild').buildSync({entryPoints:['dist/sync.js'],bundle:true,platform:'node',format:'esm',outfile:'$out/sync.mjs',banner:{js:\"$banner\"},logLevel:'error'})"
echo "studio + mcp + sync bundle -> $out"
diff --git a/scripts/check-docs-drift.mjs b/scripts/check-docs-drift.mjs
index db7f921..0c11c50 100644
--- a/scripts/check-docs-drift.mjs
+++ b/scripts/check-docs-drift.mjs
@@ -6,6 +6,7 @@ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const read = (p) => readFileSync(join(root, p), "utf8");
let manifest;
+
try {
manifest = JSON.parse(read("docs-manifest.json"));
} catch {
@@ -20,17 +21,22 @@ const warnings = [];
try {
const llms = read("llms.txt");
const llmsCount = [...llms.matchAll(/(\d+) tools/g)].map((m) => Number(m[1]));
+
for (const claim of llmsCount) {
if (claim !== manifest.mcpToolCount) {
errors.push(`llms.txt mentions "${claim} tools" but src registers ${manifest.mcpToolCount}. Re-run: node scripts/gen-docs-manifest.mjs`);
}
}
+
const listed = [...llms.matchAll(/^- ([a-z][a-z0-9_]+)$/gm)].map((m) => m[1]).sort();
+
if (Array.isArray(manifest.mcpToolNames) && listed.length) {
const registered = [...manifest.mcpToolNames].sort();
const missing = registered.filter((t) => !listed.includes(t));
const stale = listed.filter((t) => !registered.includes(t));
+
if (missing.length) errors.push(`llms.txt is missing tools: ${missing.join(", ")}`);
+
if (stale.length) errors.push(`llms.txt lists unregistered tools: ${stale.join(", ")}`);
}
} catch {
@@ -42,6 +48,7 @@ if (/single-page/i.test(readme) && manifest.studioRouteCount > 1) {
}
const toolClaims = [...new Set([...readme.matchAll(/(\d+)\s+(?:MCP\s+)?tools/gi)].map((m) => Number(m[1])))];
+
for (const claim of toolClaims) {
if (claim !== manifest.mcpToolCount) {
warnings.push(`README mentions "${claim} tools" but src registers ${manifest.mcpToolCount} (server.tool calls).`);
@@ -51,16 +58,22 @@ for (const claim of toolClaims) {
const claudeMd = read("CLAUDE.md");
const toolSection = claudeMd.split(/^## MCP tools/m)[1]?.split(/^## /m)[0] ?? "";
const documentedTools = [...toolSection.matchAll(/^\| `([a-z0-9_]+)` \|/gm)].map((m) => m[1]).sort();
+
if (Array.isArray(manifest.mcpToolNames)) {
const registered = [...manifest.mcpToolNames].sort();
const missing = registered.filter((t) => !documentedTools.includes(t));
const stale = documentedTools.filter((t) => !registered.includes(t));
+
if (missing.length) errors.push(`CLAUDE.md MCP tool table is missing: ${missing.join(", ")}`);
+
if (stale.length) errors.push(`CLAUDE.md MCP tool table lists unregistered tools: ${stale.join(", ")}`);
+
if (documentedTools.length !== registered.length) {
errors.push(`CLAUDE.md documents ${documentedTools.length} MCP tools but src registers ${registered.length}.`);
}
+
const claudeClaims = [...new Set([...claudeMd.matchAll(/All (\d+) tools/g)].map((m) => Number(m[1])))];
+
for (const claim of claudeClaims) {
if (claim !== registered.length) {
errors.push(`CLAUDE.md claims "${claim} tools" but src registers ${registered.length}.`);
@@ -78,6 +91,7 @@ for (const w of warnings) console.warn("warning:", w);
if (errors.length) {
console.error("Docs drift detected:");
+
for (const e of errors) console.error(" -", e);
process.exit(1);
}
diff --git a/scripts/gen-docs-manifest.mjs b/scripts/gen-docs-manifest.mjs
index 09603bf..475ff3b 100644
--- a/scripts/gen-docs-manifest.mjs
+++ b/scripts/gen-docs-manifest.mjs
@@ -9,9 +9,11 @@ const read = (p) => readFileSync(join(root, p), "utf8");
function tsSources(dir, acc = []) {
for (const entry of readdirSync(join(root, dir), { withFileTypes: true })) {
const rel = join(dir, entry.name);
+
if (entry.isDirectory()) tsSources(rel, acc);
else if (entry.name.endsWith(".ts")) acc.push(read(rel));
}
+
return acc;
}
@@ -19,34 +21,41 @@ function collectToolNames(sources) {
const defs = new Map();
const names = [];
let registrations = 0;
+
for (const src of sources) {
for (const m of src.matchAll(/const\s+(\w+)\s*=\s*\{\s*name:\s*"([^"]+)"/g)) {
defs.set(m[1], m[2]);
}
}
+
for (const src of sources) {
// server.registerTool (the non-deprecated API, needed for a strict
// input schema that server.tool's raw-shape shorthand can't express)
// takes its name the same way: as the first positional argument.
for (const m of src.matchAll(/server\.(?:registerTool|tool)\(\s*(?:"([^"]+)"|(\w+)\.name)/g)) {
registrations += 1;
+
if (m[1]) names.push(m[1]);
else if (defs.has(m[2])) names.push(defs.get(m[2]));
}
}
+
if (names.length !== registrations) {
console.error(`resolved ${names.length} tool names for ${registrations} server.tool(/server.registerTool( registrations`);
process.exit(1);
}
+
return names.sort();
}
const mainTsx = read("src/ui/client/main.tsx");
-const studioRoutes = [...mainTsx.matchAll(/<Route\s+path="([^"]+)"\s+element=\{<(\w+)/g)]
- .filter((m) => !/Navigate/.test(m[0]))
- .map((m) => ({ path: m[1], component: m[2] }));
+
+const studioRoutes = [...mainTsx.matchAll(/<Route\s+path="([^"]+)"\s+element=\{<(\w+)/g)].flatMap((m) =>
+ /Navigate/.test(m[0]) ? [] : [{ path: m[1], component: m[2] }],
+);
let version = "";
+
try {
version = execSync("git describe --tags --abbrev=0", { cwd: root }).toString().trim();
} catch {
@@ -65,9 +74,11 @@ const manifest = {
};
writeFileSync(join(root, "docs-manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
+
console.log("wrote docs-manifest.json:", JSON.stringify(manifest));
const toolList = mcpToolNames.map((n) => `- ${n}`).join("\n");
+
const llms = `# podcli
Open-source AI podcast clipper. Turn a long episode into short clips with face tracking and burned-in captions. Drive it from the CLI, a web studio, or your coding agent.
@@ -91,7 +102,7 @@ Clip scoring uses Claude Code or Codex login, or an Anthropic API key; without t
## First run
\`podcli process episode.mp4\` (or studio / transcribe / multicam) provisions the engine on first run.
-\`podcli mcp\` does not — stdout is JSON-RPC. Run \`podcli setup\` once before pointing an agent at it.
+\`podcli mcp\` does not: stdout is JSON-RPC. Run \`podcli setup\` once before pointing an agent at it.
\`--help\` and \`--version\` never download anything.
## Agent CLI
@@ -118,5 +129,7 @@ ${toolList}
Clips (9:16 / 16:9 / 1:1) and full-episode multicam edit. Knowledge base at .podcli/knowledge/. PodStack slash commands in .claude/commands/.
`;
+
writeFileSync(join(root, "llms.txt"), llms);
+
console.log("wrote llms.txt");
diff --git a/scripts/release-hygiene.mjs b/scripts/release-hygiene.mjs
index 6d84fe8..60ee503 100644
--- a/scripts/release-hygiene.mjs
+++ b/scripts/release-hygiene.mjs
@@ -60,18 +60,22 @@ export function checkMediaFiles(files) {
function checkLargeFiles(files) {
const errors = [];
+
for (const f of files) {
if (LARGE_FILE_ALLOWLIST.has(f)) continue;
let size;
+
try {
size = statSync(join(root, f)).size;
} catch {
continue; // deleted-but-staged path, or a submodule gitlink; not our concern here
}
+
if (size > MAX_SIZE_BYTES) {
errors.push(`file over 1MB, not on the allowlist: ${f} (${(size / 1024 / 1024).toFixed(2)}MB)`);
}
}
+
return errors;
}
@@ -89,7 +93,7 @@ const TEXT_EXTENSIONS = new Set([
]);
export function matchSecretPatterns(content) {
- return SECRET_PATTERNS.filter(({ re }) => re.test(content)).map(({ name }) => name);
+ return SECRET_PATTERNS.flatMap(({ re, name }) => (re.test(content) ? [name] : []));
}
// Known fixture files that intentionally contain fake secrets shaped like
@@ -99,19 +103,24 @@ const SECRET_SCAN_ALLOWLIST = new Set(["scripts/release-hygiene.test.mjs"]);
function checkSecretPatterns(files) {
const errors = [];
+
for (const f of files) {
if (SECRET_SCAN_ALLOWLIST.has(f)) continue;
+
if (!TEXT_EXTENSIONS.has(extname(f).toLowerCase())) continue;
let content;
+
try {
content = readFileSync(join(root, f), "utf8");
} catch {
continue;
}
+
for (const name of matchSecretPatterns(content)) {
errors.push(`possible ${name} in ${f}`);
}
}
+
return errors;
}
@@ -119,6 +128,7 @@ function checkSecretPatterns(files) {
// above without running the whole CLI (and without a stray process.exit).
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const files = trackedFiles();
+
const errors = [
...checkMediaFiles(files),
...checkLargeFiles(files),
@@ -128,6 +138,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
if (errors.length) {
console.error("Release hygiene check failed:");
+
for (const e of errors) console.error(" -", e);
process.exit(1);
}
diff --git a/scripts/release-hygiene.test.mjs b/scripts/release-hygiene.test.mjs
index 24dcadd..9f2abc1 100644
--- a/scripts/release-hygiene.test.mjs
+++ b/scripts/release-hygiene.test.mjs
@@ -31,11 +31,13 @@ describe("release-hygiene: trackedFiles", () => {
execSync("git init -q", { cwd: dir });
execSync('git config user.email "[email protected]"', { cwd: dir });
execSync('git config user.name "Test"', { cwd: dir });
+
return dir;
}
it("lists a file whose name has a non-ASCII character", () => {
const dir = initRepo();
+
try {
const name = "文字.txt"; // CJK characters, non-ASCII bytes in the path
writeFileSync(join(dir, name), "content");
@@ -51,6 +53,7 @@ describe("release-hygiene: trackedFiles", () => {
it("lists plain-ASCII filenames alongside the non-ASCII one", () => {
const dir = initRepo();
+
try {
writeFileSync(join(dir, "école.txt"), "content"); // accented e
writeFileSync(join(dir, "plain.txt"), "content");
diff --git a/setup.ps1 b/setup.ps1
index 28a8ffc..8c19852 100644
--- a/setup.ps1
+++ b/setup.ps1
@@ -86,23 +86,6 @@ function Invoke-Install {
Write-Host " ok $clipperHome (internal)"
Write-Host " ok $dataDir (output & cache)"
- $modelDir = Join-Path $ScriptDir "backend\models"
- New-Item -ItemType Directory -Force -Path $modelDir | Out-Null
- $caffeModel = Join-Path $modelDir "res10_300x300_ssd_iter_140000.caffemodel"
- if (-not (Test-Path $caffeModel)) {
- Write-Host " .. Downloading face detection model..."
- $oldProgress = $ProgressPreference
- $ProgressPreference = "SilentlyContinue"
- Invoke-WebRequest -Uri "https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt" `
- -OutFile (Join-Path $modelDir "deploy.prototxt")
- Invoke-WebRequest -Uri "https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20170830/res10_300x300_ssd_iter_140000.caffemodel" `
- -OutFile $caffeModel
- $ProgressPreference = $oldProgress
- Write-Host " ok Face detection model ready"
- } else {
- Write-Host " ok Face detection model exists"
- }
-
Write-Host ""
Write-Host "--- [3/6] Python virtual environment ---"
if (-not (Test-Path $VenvPython)) {
diff --git a/setup.sh b/setup.sh
index 6b9cb0e..48a0f57 100755
--- a/setup.sh
+++ b/setup.sh
@@ -16,7 +16,7 @@ case "$(uname -s 2>/dev/null)" in
esac
# ============================================================
-# podcli — Install & Launch
+# podcli: Install & Launch
# Usage:
# ./setup.sh # Install everything + open UI
# ./setup.sh --install # Install only (no launch)
@@ -77,20 +77,6 @@ install() {
echo " ✓ $CLIPPER_HOME (internal)"
echo " ✓ $DATA_DIR (output & cache)"
- # Download DNN face detection model if missing
- MODEL_DIR="$SCRIPT_DIR/backend/models"
- mkdir -p "$MODEL_DIR"
- if [ ! -f "$MODEL_DIR/res10_300x300_ssd_iter_140000.caffemodel" ]; then
- echo " ↓ Downloading face detection model..."
- curl -sL -o "$MODEL_DIR/deploy.prototxt" \
- "https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt"
- curl -sL -o "$MODEL_DIR/res10_300x300_ssd_iter_140000.caffemodel" \
- "https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20170830/res10_300x300_ssd_iter_140000.caffemodel"
- echo " ✓ Face detection model ready"
- else
- echo " ✓ Face detection model exists"
- fi
-
echo ""
echo "━━━ [3/6] Python virtual environment ━━━"
if [ ! -d "venv" ]; then
@@ -172,7 +158,7 @@ launch_ui() {
# The studio is a Vite + React Router SPA; build it before serving.
if [ ! -f dist/ui/public/index.html ]; then
echo " Building the studio UI..."
- npm run build || { echo " Build failed — run ./setup.sh --install first."; exit 1; }
+ npm run build || { echo " Build failed: run ./setup.sh --install first."; exit 1; }
fi
echo " Studio: http://localhost:${PORT:-3847}"
diff --git a/src/config/paths.test.ts b/src/config/paths.test.ts
index 26e65a6..b916be3 100644
--- a/src/config/paths.test.ts
+++ b/src/config/paths.test.ts
@@ -18,6 +18,7 @@ beforeAll(async () => {
afterAll(() => {
if (savedHome === undefined) delete process.env.PODCLI_HOME;
else process.env.PODCLI_HOME = savedHome;
+
if (savedData === undefined) delete process.env.PODCLI_DATA;
else process.env.PODCLI_DATA = savedData;
rmSync(tmp, { recursive: true, force: true });
diff --git a/src/config/paths.ts b/src/config/paths.ts
index ce4e98e..c83b5e5 100644
--- a/src/config/paths.ts
+++ b/src/config/paths.ts
@@ -13,16 +13,19 @@ function resolveHome(): string {
if (process.env.PODCLI_HOME) {
return resolve(process.env.PODCLI_HOME);
}
+
if (existsSync(homeMarker)) {
try {
const marker = readFileSync(homeMarker, "utf-8").trim();
+
if (marker) {
return isAbsolute(marker) ? resolve(marker) : resolve(projectRoot, marker);
}
} catch {
- // Unreadable marker — fall through to the default home.
+ // Unreadable marker: fall through to the default home.
}
}
+
return resolve(projectRoot, ".podcli");
}
@@ -36,11 +39,13 @@ function resolveBackendDir(): string {
}
const sourceBackend = join(projectRoot, "backend");
+
if (existsSync(join(sourceBackend, "cli.py"))) {
return sourceBackend;
}
const runtimeBackend = join(projectRoot, "runtime", "backend");
+
if (existsSync(join(runtimeBackend, "cli.py"))) {
return runtimeBackend;
}
@@ -53,13 +58,16 @@ const backendDir = resolveBackendDir();
function detectPython(): string {
if (process.env.PYTHON_PATH) return process.env.PYTHON_PATH;
const isWindows = process.platform === "win32";
+
const venvPython = join(
projectRoot,
"venv",
isWindows ? "Scripts" : "bin",
isWindows ? "python.exe" : "python3"
);
+
if (existsSync(venvPython)) return venvPython;
+
return isWindows ? "python" : "python3";
}
diff --git a/src/config/server.ts b/src/config/server.ts
index dc75d0c..4b353e3 100644
--- a/src/config/server.ts
+++ b/src/config/server.ts
@@ -1,6 +1,7 @@
export function resolveWebServerPort(env: NodeJS.ProcessEnv = process.env): number {
const raw = env.PODCLI_PORT || env.PORT;
const parsed = raw ? parseInt(raw, 10) : NaN;
+
return Number.isInteger(parsed) && parsed > 0 && parsed <= 65535 ? parsed : 3847;
}
diff --git a/src/create-clip-offline-identity.test.ts b/src/create-clip-offline-identity.test.ts
index 4052bb7..72c73e3 100644
--- a/src/create-clip-offline-identity.test.ts
+++ b/src/create-clip-offline-identity.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { callTool, type ToolArgs } from "./test-support/mcp-client.js";
// create_clip/batch_create_clips fill transcript_words from session state
// when the caller omits it (e.g. clip_number-only calls). handleCreateClip
@@ -36,19 +37,16 @@ beforeAll(async () => {
afterAll(() => {
if (savedHome === undefined) delete process.env.PODCLI_HOME;
else process.env.PODCLI_HOME = savedHome;
+
if (savedData === undefined) delete process.env.PODCLI_DATA;
else process.env.PODCLI_DATA = savedData;
+
if (savedPort === undefined) delete process.env.PODCLI_PORT;
else process.env.PODCLI_PORT = savedPort;
rmSync(tmp, { recursive: true, force: true });
});
-function getHandler(name: string) {
- const server = createServer() as unknown as {
- _registeredTools: Record<string, { handler: (args: unknown, extra: unknown) => Promise<{ content: { text: string }[]; isError?: boolean }> }>;
- };
- return server._registeredTools[name].handler;
-}
+const callServerTool = (name: string, args: ToolArgs) => callTool(createServer(), name, args);
function writeMismatchedState() {
writeFileSync(
@@ -68,17 +66,15 @@ function writeMismatchedState() {
describe("create_clip offline identity guard", () => {
it("rejects clip_number-only calls when the session transcript doesn't match the video", async () => {
writeMismatchedState();
- const handler = getHandler("create_clip");
- const result = await handler({ clip_number: 1 }, {});
- expect(result.content[0].text).toContain("belongs to a different video");
+ const result = await callServerTool("create_clip", { clip_number: 1 });
+ expect(result.text).toContain("belongs to a different video");
});
});
describe("batch_create_clips offline identity guard", () => {
it("rejects export_selected calls when the session transcript doesn't match the video", async () => {
writeMismatchedState();
- const handler = getHandler("batch_create_clips");
- const result = await handler({ export_selected: true }, {});
- expect(result.content[0].text).toContain("belongs to a different video");
+ const result = await callServerTool("batch_create_clips", { export_selected: true });
+ expect(result.text).toContain("belongs to a different video");
});
});
diff --git a/src/handlers/batch-clips.handler.ts b/src/handlers/batch-clips.handler.ts
index 1c191e4..f162ae1 100644
--- a/src/handlers/batch-clips.handler.ts
+++ b/src/handlers/batch-clips.handler.ts
@@ -1,6 +1,7 @@
-import { readFileSync } from "fs";
+import { z } from "zod";
import { PythonExecutor } from "../services/python-executor.js";
import { FileManager } from "../services/file-manager.js";
+import { readUIStateFile } from "../services/ui-state-file.js";
import { ClipsHistory } from "../services/clips-history.js";
import { paths } from "../config/paths.js";
import { webServerUrl } from "../config/server.js";
@@ -22,12 +23,15 @@ const executor = new PythonExecutor();
const fileManager = new FileManager();
const history = new ClipsHistory();
+const jobStartedSchema = z.object({ job_id: z.string(), status: z.string() });
+
/** Load UI state from disk. Returns null if unavailable. */
function loadState(): UIState | null {
try {
- return JSON.parse(readFileSync(paths.uiState, "utf-8")) as UIState;
+ return readUIStateFile();
} catch (err) {
log.debug("UI state unavailable", { err: err instanceof Error ? err.message : err });
+
return null;
}
}
@@ -35,7 +39,7 @@ function loadState(): UIState | null {
export const batchClipsToolDef = {
name: "batch_create_clips",
description:
- "STEP 3 — Export multiple clips at once as finished vertical shorts.\n\n" +
+ "STEP 3: Export multiple clips at once as finished vertical shorts.\n\n" +
"EASIEST: pass export_selected=true to export all selected clips in one go.\n" +
"Alternative: pass clip_numbers=[1, 3, 5] for specific ones.\n" +
"Everything (video, timestamps, settings) auto-loads from session state.\n\n" +
@@ -157,6 +161,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
// Auto-resolve video path
const videoPath = input.video_path || state?.videoPath || "";
+
if (!videoPath) {
return JSON.stringify({ error: "video_path is required (no video in session state)" });
}
@@ -166,6 +171,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
// swapped in after that transcript was generated.
if (input.transcript_words == null && transcript) {
const mismatch = transcriptVideoMismatch(state?.transcriptVideoIdentity, videoPath);
+
if (mismatch) {
return JSON.stringify({ error: mismatch });
}
@@ -199,11 +205,13 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
if (input.export_selected) {
// Export all selected (non-deselected) clips
clips = [];
+
for (let i = 0; i < suggestions.length; i++) {
if (!deselected.includes(i)) {
clips.push(buildClipFromSuggestion(suggestions[i], i + 1));
}
}
+
if (clips.length === 0) {
return JSON.stringify({
error: `No selected clips to export. ${suggestions.length} total, all deselected.`,
@@ -215,10 +223,12 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
for (const num of input.clip_numbers) {
const idx = num - 1;
+
if (idx < 0 || idx >= suggestions.length) {
errors.push(`Clip #${num} not found`);
continue;
}
+
clips.push(buildClipFromSuggestion(suggestions[idx], num));
}
@@ -238,6 +248,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
if (input.keep_caption_overlay === true) {
clips = clips.map((c) => ({ ...c, keep_caption_overlay: c.keep_caption_overlay ?? true }));
}
+
if (input.write_clean_variant === true) {
clips = clips.map((c) => ({ ...c, write_clean_variant: c.write_clean_variant ?? true }));
}
@@ -248,21 +259,24 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
clips[i].end_second,
clips[i].format || batchFormat,
);
+
if (rangeError) {
return JSON.stringify({ error: `Clip ${i + 1}: ${rangeError}` });
}
+
const hookError = validateHook(
clips[i].hook,
clips[i].start_second,
clips[i].end_second,
clips[i].keep_segments,
);
+
if (hookError) {
return JSON.stringify({ error: `Clip ${i + 1}: ${hookError}` });
}
}
- // Async path — route through Web UI so caller can poll job_status for
+ // Async path: route through Web UI so caller can poll job_status for
// live progress during a multi-minute render. Falls back to sync if the
// UI isn't running.
if (input.async_mode) {
@@ -283,16 +297,19 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
write_clean_variant: input.write_clean_variant === true,
}),
});
+
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
- const data = (await res.json()) as { job_id: string; status: string };
+ const data = jobStartedSchema.parse(await res.json());
+
return JSON.stringify({
job_id: data.job_id,
status: data.status,
clip_count: clips.length,
- next_step: `Poll job_status("${data.job_id}", wait_seconds: 30) in a loop, emitting one terse progress line to the user between polls (e.g. "Rendering 3/7 — clip #3"). Stop when done=true.`,
+ next_step: `Poll job_status("${data.job_id}", wait_seconds: 30) in a loop, emitting one terse progress line to the user between polls (e.g. "Rendering 3/7, clip #3"). Stop when done=true.`,
});
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
log.warn("Web UI unavailable, falling back to sync batch render", { err: msg });
// fall through to sync path
@@ -320,6 +337,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
if (!result.data) {
throw new Error("Batch clip creation returned no data");
}
+
const data = result.data;
const recorded = await history.recordBatchResults(data.results, {
@@ -331,6 +349,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
contentTypeFor: (s, e) => findContentType(suggestions, s, e),
suggestions,
});
+
await history.persistBatchRecipes(data.results, recorded, {
transcriptWords: transcriptWords,
clipSpecs: clips,
diff --git a/src/handlers/compare-engines.handler.test.ts b/src/handlers/compare-engines.handler.test.ts
index 2e1a001..1eb09c2 100644
--- a/src/handlers/compare-engines.handler.test.ts
+++ b/src/handlers/compare-engines.handler.test.ts
@@ -1,14 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
+import { handleCompareEngines } from "./compare-engines.handler.js";
const executeMock = vi.fn();
-vi.mock("../services/python-executor.js", () => ({
- PythonExecutor: class {
- execute = executeMock;
- },
-}));
-
-const { handleCompareEngines } = await import("./compare-engines.handler.js");
+const executor = { execute: executeMock };
describe("handleCompareEngines", () => {
beforeEach(() => {
@@ -30,7 +25,7 @@ describe("handleCompareEngines", () => {
model_size: "base",
language: "ka",
output_dir: "/tmp/cmp",
- });
+ }, executor);
expect(executeMock).toHaveBeenCalledWith("compare_engines", {
file_path: "/video.mp4",
@@ -54,7 +49,8 @@ describe("handleCompareEngines", () => {
file_path: "/video.mp4",
engine_a: "whispercpp",
engine_b: "whisper-py",
- });
+ }, executor);
+
const parsed = JSON.parse(text);
expect(parsed.overall_disagreement).toBe(0.35);
@@ -65,7 +61,7 @@ describe("handleCompareEngines", () => {
it("throws when the backend returns no data", async () => {
executeMock.mockResolvedValue({ data: undefined });
await expect(
- handleCompareEngines({ file_path: "/video.mp4", engine_a: "whispercpp", engine_b: "whisper-py" }),
+ handleCompareEngines({ file_path: "/video.mp4", engine_a: "whispercpp", engine_b: "whisper-py" }, executor),
).rejects.toThrow(/no data/i);
});
});
diff --git a/src/handlers/compare-engines.handler.ts b/src/handlers/compare-engines.handler.ts
index 560c2a3..2cf8262 100644
--- a/src/handlers/compare-engines.handler.ts
+++ b/src/handlers/compare-engines.handler.ts
@@ -1,4 +1,4 @@
-import { PythonExecutor } from "../services/python-executor.js";
+import { PythonExecutor, type TaskExecutor } from "../services/python-executor.js";
const executor = new PythonExecutor();
@@ -66,8 +66,11 @@ export const compareEnginesToolDef = {
},
};
-export async function handleCompareEngines(input: CompareEnginesInput): Promise<string> {
- const result = await executor.execute<{
+export async function handleCompareEngines(
+ input: CompareEnginesInput,
+ taskExecutor: TaskExecutor = executor,
+): Promise<string> {
+ const result = await taskExecutor.execute<{
overall_disagreement: number;
both_empty_window_count: number;
json_path?: string;
diff --git a/src/handlers/create-clip.handler.ts b/src/handlers/create-clip.handler.ts
index c1d2420..0b13a2a 100644
--- a/src/handlers/create-clip.handler.ts
+++ b/src/handlers/create-clip.handler.ts
@@ -1,6 +1,6 @@
-import { readFileSync } from "fs";
import { PythonExecutor } from "../services/python-executor.js";
import { FileManager } from "../services/file-manager.js";
+import { readUIStateFile } from "../services/ui-state-file.js";
import { paths } from "../config/paths.js";
import type { ClipResult, CreateClipInput, SuggestedClip, UIState } from "../models/index.js";
import { childLogger } from "../utils/logger.js";
@@ -16,9 +16,10 @@ const fileManager = new FileManager();
/** Load UI state from disk. Returns null if unavailable. */
function loadState(): UIState | null {
try {
- return JSON.parse(readFileSync(paths.uiState, "utf-8")) as UIState;
+ return readUIStateFile();
} catch (err) {
log.debug("UI state unavailable", { err: err instanceof Error ? err.message : err });
+
return null;
}
}
@@ -26,8 +27,8 @@ function loadState(): UIState | null {
export const createClipToolDef = {
name: "create_clip",
description:
- "STEP 3 — Export a single clip as a finished vertical short (1080x1920, 9:16).\n\n" +
- "EASIEST: just pass clip_number (e.g. 3) — everything else auto-loads from session state.\n" +
+ "STEP 3: Export a single clip as a finished vertical short (1080x1920, 9:16).\n\n" +
+ "EASIEST: just pass clip_number (e.g. 3); everything else auto-loads from session state.\n" +
"Output: H.264 MP4 with burned-in captions, normalized audio (-14 LUFS).\n\n" +
"For batch export, use batch_create_clips instead.\n" +
"Caption styles: branded (professional), hormozi (bold/yellow), karaoke (progressive highlight), subtle (minimal).\n" +
@@ -164,13 +165,16 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>
// Resolve clip from suggestion number
let suggestion: SuggestedClip | null = null;
+
if (input.clip_number != null) {
const idx = input.clip_number - 1;
+
if (idx < 0 || idx >= suggestions.length) {
return JSON.stringify({
error: `Clip #${input.clip_number} not found. Available: 1-${suggestions.length}`,
});
}
+
suggestion = suggestions[idx];
}
@@ -179,11 +183,13 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>
const startSecond = input.start_second ?? suggestion?.start_second;
const endSecond = input.end_second ?? suggestion?.end_second;
const title = input.title || suggestion?.title || "clip";
+
const captionStyle =
input.caption_style ||
suggestion?.suggested_caption_style ||
settings.captionStyle ||
"hormozi";
+
const cropStrategy = input.crop_strategy || settings.cropStrategy || "speaker";
const format = input.format || settings.format || "vertical";
const logoPath = input.logo_path || settings.logoPath || null;
@@ -202,6 +208,7 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>
// still carry a mismatched one.
if (input.transcript_words == null && transcript) {
const mismatch = transcriptVideoMismatch(state?.transcriptVideoIdentity, videoPath);
+
if (mismatch) {
return JSON.stringify({ error: mismatch });
}
@@ -211,16 +218,21 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>
if (!videoPath) {
return JSON.stringify({ error: "video_path is required (no video in session state)" });
}
+
if (startSecond == null || endSecond == null) {
return JSON.stringify({
error: "start_second and end_second are required (use clip_number to reference a suggestion)",
});
}
+
const rangeError = validateClipRange(startSecond, endSecond, format);
+
if (rangeError) {
return JSON.stringify({ error: rangeError });
}
+
const hookError = validateHook(hook, startSecond, endSecond, keepSegments);
+
if (hookError) {
return JSON.stringify({ error: hookError });
}
@@ -242,8 +254,8 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>
logo_path: logoPath,
outro_path: outroPath,
intro_path: introPath,
- ...(input.name_card ? { name_card: input.name_card } : {}),
- ...(input.motion ? { motion: input.motion } : {}),
+ ...(input.name_card && { name_card: input.name_card }),
+ ...(input.motion && { motion: input.motion }),
...(keepSegments && { keep_segments: keepSegments }),
...(hook && { hook }),
});
@@ -251,6 +263,7 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>
if (!result.data) {
throw new Error("Clip creation returned no data");
}
+
const data = result.data;
return JSON.stringify({
diff --git a/src/handlers/integrations.handler.ts b/src/handlers/integrations.handler.ts
index ecb6474..90b4cc1 100644
--- a/src/handlers/integrations.handler.ts
+++ b/src/handlers/integrations.handler.ts
@@ -20,6 +20,7 @@ interface IntegrationDescriptor {
}
interface ListResult { integrations: IntegrationDescriptor[] }
+
interface SetResult { name: string; enabled: boolean }
export const manageIntegrationsToolDef = {
@@ -27,9 +28,9 @@ export const manageIntegrationsToolDef = {
description:
"List, enable, or disable podcli integrations (editor exporters, platform uploads, productivity tools, AI helpers).\n\n" +
"Actions:\n" +
- " • list — return all installed integrations with their enabled state (default)\n" +
- " • enable — turn an integration on (its tools become callable)\n" +
- " • disable — turn an integration off (calls return a disabled error)\n\n" +
+ " • list: return all installed integrations with their enabled state (default)\n" +
+ " • enable: turn an integration on (its tools become callable)\n" +
+ " • disable: turn an integration off (calls return a disabled error)\n\n" +
"State persists at the active config home (integrations.json, gitignored).",
};
@@ -38,11 +39,14 @@ export async function handleManageIntegrations(input: {
name?: string;
}): Promise<string> {
const action = input.action ?? "list";
+
const result = await executor.execute<ListResult | SetResult>("manage_integrations", {
action,
name: input.name ?? "",
});
+
if (!result.data) throw new Error(`manage_integrations returned no data (action=${action})`);
+
return JSON.stringify(result.data, null, 2);
}
@@ -66,18 +70,20 @@ export const exportToDaVinciResolveToolDef = {
name: "export_to_davinci_resolve",
description:
"Export podcli shorts as a DaVinci Resolve FCPXML project.\n\n" +
- "Each short becomes a compound clip with V1 source + V2 ProRes 4444 alpha caption overlay — " +
+ "Each short becomes a compound clip with V1 source + V2 ProRes 4444 alpha caption overlay, " +
"fully editable in free or Studio Resolve 20.x.\n\n" +
"Requires the davinci_resolve integration to be enabled (manage_integrations action=enable name=davinci_resolve).",
};
export async function handleExportToDaVinciResolve(input: DvExportInput): Promise<string> {
- const result = await executor.execute<Record<string, unknown>>("run_integration_tool", {
+ const result = await executor.execute<object>("run_integration_tool", {
integration: "davinci_resolve",
tool: "export_to_davinci_resolve",
params: input,
});
+
if (!result.data) throw new Error("export_to_davinci_resolve returned no data");
+
return JSON.stringify(result.data, null, 2);
}
@@ -86,11 +92,11 @@ export const manageConfigToolDef = {
description:
"Manage portable config profiles and legacy path migration.\n\n" +
"Actions:\n" +
- " • status — active config home, cache dir, migration state (default)\n" +
- " • migrate — move legacy project/.podcli/cache into data/cache (idempotent)\n" +
- " • export — zip the active config home (knowledge, presets, assets, settings)\n" +
- " • import — restore a bundle; backs up existing config before overwrite\n" +
- " • use — activate a config home path (writes .podcli-home marker)",
+ " • status: active config home, cache dir, migration state (default)\n" +
+ " • migrate: move legacy project/.podcli/cache into data/cache (idempotent)\n" +
+ " • export: zip the active config home (knowledge, presets, assets, settings)\n" +
+ " • import: restore a bundle; backs up existing config before overwrite\n" +
+ " • use: activate a config home path (writes .podcli-home marker)",
};
export async function handleManageConfig(input: {
@@ -101,14 +107,17 @@ export async function handleManageConfig(input: {
dry_run?: boolean;
}): Promise<string> {
const action = input.action ?? "status";
- const result = await executor.execute<Record<string, unknown>>("manage_config", {
+
+ const result = await executor.execute<object>("manage_config", {
action,
bundle_path: input.bundle_path,
home: input.home,
activate: input.activate,
dry_run: input.dry_run,
});
+
if (!result.data) throw new Error(`manage_config returned no data (action=${action})`);
+
return JSON.stringify(result.data, null, 2);
}
@@ -134,13 +143,13 @@ export const manageEnvToolDef = {
description:
"List, set, or unset global podcli settings stored in .env.\n\n" +
"Keys:\n" +
- " • HF_TOKEN — HuggingFace token for speaker detection\n" +
- " • PODCLI_CLAUDE_PATH — manual path to Claude Code CLI when auto-discovery fails\n" +
- " • PODCLI_CODEX_PATH — manual path to Codex CLI when auto-discovery fails\n\n" +
+ " • HF_TOKEN: HuggingFace token for speaker detection\n" +
+ " • PODCLI_CLAUDE_PATH: manual path to Claude Code CLI when auto-discovery fails\n" +
+ " • PODCLI_CODEX_PATH: manual path to Codex CLI when auto-discovery fails\n\n" +
"Actions:\n" +
- " • list — show all settings, configured values, and AI CLI detection (default)\n" +
- " • set — set a key (path must exist for PODCLI_*_PATH keys)\n" +
- " • unset — remove a key (falls back to auto-discovery)",
+ " • list: show all settings, configured values, and AI CLI detection (default)\n" +
+ " • set: set a key (path must exist for PODCLI_*_PATH keys)\n" +
+ " • unset: remove a key (falls back to auto-discovery)",
};
export async function handleManageEnv(input: {
@@ -149,6 +158,7 @@ export async function handleManageEnv(input: {
value?: string;
}): Promise<string> {
const action = input.action ?? "list";
+
const result = await executor.execute<{
settings?: EnvSettingRow[];
path?: string;
@@ -160,7 +170,9 @@ export async function handleManageEnv(input: {
key: input.key ?? "",
value: input.value ?? "",
});
+
if (!result.data) throw new Error(`manage_env returned no data (action=${action})`);
+
return JSON.stringify(result.data, null, 2);
}
@@ -174,14 +186,16 @@ export const aiCliStatusToolDef = {
export async function handleAiCliStatus(): Promise<string> {
const result = await executor.execute<AiCliStatus>("ai_cli_status", {});
+
if (!result.data) throw new Error("ai_cli_status returned no data");
+
return JSON.stringify(result.data, null, 2);
}
function mcpText(text: string, isError = false) {
return {
content: [{ type: "text" as const, text }],
- ...(isError ? { isError: true as const } : {}),
+ ...(isError && { isError: true as const }),
};
}
@@ -198,7 +212,9 @@ export function registerIntegrationMcpTools(server: McpServer): void {
if ((action === "enable" || action === "disable") && !name?.trim()) {
return mcpText("`name` is required when action is enable or disable.", true);
}
+
const text = await handleManageIntegrations({ action, name });
+
return mcpText(text);
} catch (err) {
return mcpText(err instanceof Error ? err.message : String(err), true);
@@ -229,6 +245,7 @@ export function registerIntegrationMcpTools(server: McpServer): void {
async (params) => {
try {
const text = await handleExportToDaVinciResolve(params);
+
return mcpText(text);
} catch (err) {
return mcpText(err instanceof Error ? err.message : String(err), true);
@@ -252,6 +269,7 @@ export function registerIntegrationMcpTools(server: McpServer): void {
async (params) => {
try {
const text = await handleManageConfig(params);
+
return mcpText(text);
} catch (err) {
return mcpText(err instanceof Error ? err.message : String(err), true);
@@ -272,13 +290,17 @@ export function registerIntegrationMcpTools(server: McpServer): void {
if (action === "set" && !key?.trim()) {
return mcpText("`key` is required when action is set.", true);
}
+
if (action === "set" && !value?.trim()) {
return mcpText("`value` is required when action is set.", true);
}
+
if (action === "unset" && !key?.trim()) {
return mcpText("`key` is required when action is unset.", true);
}
+
const text = await handleManageEnv({ action, key, value });
+
return mcpText(text);
} catch (err) {
return mcpText(err instanceof Error ? err.message : String(err), true);
@@ -293,6 +315,7 @@ export function registerIntegrationMcpTools(server: McpServer): void {
async () => {
try {
const text = await handleAiCliStatus();
+
return mcpText(text);
} catch (err) {
return mcpText(err instanceof Error ? err.message : String(err), true);
diff --git a/src/handlers/integrations.routes.ts b/src/handlers/integrations.routes.ts
index 44949b8..2f1deb5 100644
--- a/src/handlers/integrations.routes.ts
+++ b/src/handlers/integrations.routes.ts
@@ -4,15 +4,15 @@ import { existsSync } from "fs";
import { mkdir, unlink } from "fs/promises";
import { join, extname } from "path";
import { v4 as uuidv4 } from "uuid";
-import type { PythonExecutor } from "../services/python-executor.js";
+import type { TaskExecutor } from "../services/python-executor.js";
import { paths } from "../config/paths.js";
-function routeError(err: unknown): string {
- return err instanceof Error ? err.message : String(err);
+function routeError(cause: unknown): string {
+ return cause instanceof Error ? cause.message : String(cause);
}
export interface ConfigIntegrationRouteDeps {
- executor: PythonExecutor;
+ executor: TaskExecutor;
uploadDir: string;
}
@@ -25,7 +25,7 @@ export function registerConfigIntegrationRoutes(
app.get("/api/config/status", async (_req, res) => {
try {
- const result = await executor.execute<Record<string, unknown>>("manage_config", { action: "status" });
+ const result = await executor.execute<object>("manage_config", { action: "status" });
res.json(result.data ?? {});
} catch (err) {
res.status(500).json({ error: routeError(err) });
@@ -34,7 +34,7 @@ export function registerConfigIntegrationRoutes(
app.post("/api/config/migrate", async (_req, res) => {
try {
- const result = await executor.execute<Record<string, unknown>>("manage_config", { action: "migrate" });
+ const result = await executor.execute<object>("manage_config", { action: "migrate" });
res.json(result.data ?? {});
} catch (err) {
res.status(500).json({ error: routeError(err) });
@@ -45,15 +45,20 @@ export function registerConfigIntegrationRoutes(
try {
const bundlePath = join(paths.working, `profile-export-${uuidv4()}.zip`);
await mkdir(paths.working, { recursive: true });
+
const result = await executor.execute<{ bundle: string }>("manage_config", {
action: "export",
bundle_path: bundlePath,
});
+
const file = result.data?.bundle ?? bundlePath;
+
if (!existsSync(file)) {
res.status(500).json({ error: "Export failed: bundle not created" });
+
return;
}
+
res.download(file, "podcli-profile.zip", () => {
void unlink(file).catch(() => {});
});
@@ -75,6 +80,7 @@ export function registerConfigIntegrationRoutes(
limits: { fileSize: 512 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
const ext = extname(file.originalname).toLowerCase();
+
if (ext === ".zip") cb(null, true);
else cb(new Error("Profile import must be a .zip file"));
},
@@ -84,14 +90,18 @@ export function registerConfigIntegrationRoutes(
try {
if (!req.file?.path) {
res.status(400).json({ error: "Missing bundle file" });
+
return;
}
+
const activate = req.body?.activate === "1" || req.body?.activate === true;
- const result = await executor.execute<Record<string, unknown>>("manage_config", {
+
+ const result = await executor.execute<object>("manage_config", {
action: "import",
bundle_path: req.file.path,
activate,
});
+
res.json(result.data ?? {});
} catch (err) {
res.status(500).json({ error: routeError(err) });
@@ -105,6 +115,7 @@ export function registerConfigIntegrationRoutes(
const result = await executor.execute<{ integrations: unknown[] }>("manage_integrations", {
action: "list",
});
+
res.json(result.data ?? { integrations: [] });
} catch (err) {
res.status(500).json({ error: routeError(err) });
@@ -114,11 +125,13 @@ export function registerConfigIntegrationRoutes(
app.post("/api/integrations/:name", async (req, res) => {
const name = req.params.name;
const enabled = !!req.body?.enabled;
+
try {
const result = await executor.execute<{ name: string; enabled: boolean }>("manage_integrations", {
action: enabled ? "enable" : "disable",
name,
});
+
res.json(result.data ?? { name, enabled });
} catch (err) {
res.status(500).json({ error: routeError(err) });
@@ -128,11 +141,13 @@ export function registerConfigIntegrationRoutes(
app.get("/api/integration-info", (_req, res) => {
const packagedMcpPath = join(projectRoot, "runtime", "studio", "mcp-server.mjs");
const sourceMcpPath = join(projectRoot, "dist", "index.js");
+
const mcpPath = process.env.PODCLI_STUDIO
? join(process.env.PODCLI_STUDIO, "mcp-server.mjs")
: existsSync(packagedMcpPath)
? packagedMcpPath
: sourceMcpPath;
+
res.json({
mcp_path: mcpPath,
dist_path: mcpPath,
diff --git a/src/handlers/mine-channel.handler.test.ts b/src/handlers/mine-channel.handler.test.ts
index e7a074d..0c003b9 100644
--- a/src/handlers/mine-channel.handler.test.ts
+++ b/src/handlers/mine-channel.handler.test.ts
@@ -50,14 +50,17 @@ function depsReturning(opts: {
describe("listChannelUploads", () => {
it("normalizes a bare channel root to the /videos tab before calling yt-dlp", async () => {
const seenArgs: string[][] = [];
+
const deps: MineChannelDeps = {
runYtDlp: async (args) => {
seenArgs.push(args);
+
return { stdout: FLAT_PLAYLIST_STDOUT, stderr: "", code: 0 };
},
fetchText: async () => "",
minedVideoIds: async () => new Set(),
};
+
await listChannelUploads(deps, { channel_url: "https://www.youtube.com/@deeptechdecodedai" });
expect(seenArgs[0].at(-1)).toBe("https://www.youtube.com/@deeptechdecodedai/videos");
});
@@ -67,9 +70,11 @@ describe("listChannelUploads", () => {
JSON.stringify({ title: "Shorts", _type: "playlist" }),
JSON.stringify({ id: "vid1", title: "Episode 1", duration: 3600 }),
].join("\n");
+
const uploads = await listChannelUploads(depsReturning({ stdout }), {
channel_url: "https://www.youtube.com/@example/videos",
});
+
expect(uploads).toHaveLength(1);
expect(uploads[0].video_id).toBe("vid1");
});
@@ -78,6 +83,7 @@ describe("listChannelUploads", () => {
const uploads = await listChannelUploads(depsReturning({ stdout: FLAT_PLAYLIST_STDOUT }), {
channel_url: "https://www.youtube.com/@example/videos",
});
+
expect(uploads).toHaveLength(2);
expect(uploads[0]).toMatchObject({ video_id: "vid1", title: "Episode 1", duration: 3600 });
});
@@ -86,6 +92,7 @@ describe("listChannelUploads", () => {
const uploads = await listChannelUploads(depsReturning({ stdout: FLAT_PLAYLIST_STDOUT }), {
channel_url: "https://www.youtube.com/@example/videos",
});
+
expect(uploads[1].url).toBe("https://www.youtube.com/watch?v=vid2");
});
@@ -93,6 +100,7 @@ describe("listChannelUploads", () => {
const uploads = await listChannelUploads(depsReturning({ stdout: FLAT_PLAYLIST_STDOUT, minedIds: ["vid1"] }), {
channel_url: "https://www.youtube.com/@example/videos",
});
+
expect(uploads.find((u) => u.video_id === "vid1")?.already_mined).toBe(true);
expect(uploads.find((u) => u.video_id === "vid2")?.already_mined).toBe(false);
});
@@ -112,6 +120,7 @@ describe("mineVideoCaptions", () => {
depsReturning({ stdout: VIDEO_INFO_WITH_ORIGINAL_TRACK, captionText: FIXTURE_VTT }),
{ video_url: "https://youtu.be/vid1" },
);
+
expect(result.track).toEqual({ lang: "ka-orig", kind: "auto" });
expect(result.transcript?.language).toBe("ka");
});
@@ -121,6 +130,7 @@ describe("mineVideoCaptions", () => {
depsReturning({ stdout: VIDEO_INFO_WITH_ORIGINAL_TRACK, captionText: FIXTURE_VTT }),
{ video_url: "https://youtu.be/vid1" },
);
+
expect(result.transcript?.words.map((w) => w.word)).toEqual(["Hello", "and", "welcome", "to", "the", "show"]);
expect(result.transcript?.text).toBe("Hello and welcome to the show");
});
@@ -129,6 +139,7 @@ describe("mineVideoCaptions", () => {
const result = await mineVideoCaptions(depsReturning({ stdout: VIDEO_INFO_NO_CAPTIONS }), {
video_url: "https://youtu.be/vid3",
});
+
expect(result.transcript).toBeNull();
expect(result.track).toBeNull();
expect(result.message).toMatch(/no captions/i);
@@ -139,6 +150,7 @@ describe("mineVideoCaptions", () => {
depsReturning({ stdout: VIDEO_INFO_WITH_ORIGINAL_TRACK, captionText: FIXTURE_VTT, minedIds: ["vid1"] }),
{ video_url: "https://youtu.be/vid1" },
);
+
expect(result.already_mined).toBe(true);
expect(result.message).toMatch(/already/i);
});
diff --git a/src/handlers/mine-channel.handler.ts b/src/handlers/mine-channel.handler.ts
index e448065..fc6af24 100644
--- a/src/handlers/mine-channel.handler.ts
+++ b/src/handlers/mine-channel.handler.ts
@@ -1,4 +1,6 @@
import { spawn } from "child_process";
+import { z } from "zod";
+import { absentWhenNull } from "../utils/zod-helpers.js";
import { paths, pythonEnv } from "../config/paths.js";
import { ClipsHistory } from "../services/clips-history.js";
import {
@@ -8,7 +10,7 @@ import {
isCookieBrowser,
normalizeChannelUrl,
} from "../utils/ytdlp-args.js";
-import { selectBestCaptionTrack, parseVtt, parseJson3, cuesToWords, type CaptionTrackRef } from "../utils/captions.js";
+import { selectBestCaptionTrack, parseVtt, parseJson3, cuesToWords } from "../utils/captions.js";
import type { WordTimestamp } from "../models/index.js";
const history = new ClipsHistory();
@@ -53,10 +55,30 @@ async function runYtDlp(args: string[]): Promise<RunResult> {
async function fetchText(url: string): Promise<string> {
const res = await fetch(url);
+
if (!res.ok) throw new Error(`HTTP ${res.status} fetching caption track`);
+
return res.text();
}
+const uploadEntrySchema = z.looseObject({
+ id: absentWhenNull(z.string()),
+ title: z.string().catch(""),
+ duration: absentWhenNull(z.number()),
+ upload_date: absentWhenNull(z.string()),
+ url: absentWhenNull(z.string()),
+});
+
+const captionTracksSchema = z.record(z.string(), z.array(z.object({ ext: z.string(), url: z.string() })));
+
+const videoInfoSchema = z.looseObject({
+ id: z.string(),
+ title: z.string(),
+ duration: absentWhenNull(z.number()),
+ subtitles: absentWhenNull(captionTracksSchema),
+ automatic_captions: absentWhenNull(captionTracksSchema),
+});
+
export interface ChannelUpload {
video_id: string;
title: string;
@@ -100,27 +122,37 @@ export async function listChannelUploads(
limit: input.limit,
cookiesFromBrowser: isCookieBrowser(input.cookies_from_browser) ? input.cookies_from_browser : undefined,
});
+
const { stdout, stderr, code } = await deps.runYtDlp(args);
+
if (code !== 0) {
throw new Error(stderr.trim() || "yt-dlp failed to list the channel's uploads");
}
+
const minedIds = await deps.minedVideoIds();
+
return stdout
.trim()
.split("\n")
.filter(Boolean)
- .map((line) => JSON.parse(line) as { id?: string; title: string; duration?: number; upload_date?: string; url?: string })
- // A tab or sub-playlist entry (e.g. "Shorts", "Live") has no video id of
- // its own: only real uploads do.
- .filter((u): u is { id: string; title: string; duration?: number; upload_date?: string; url?: string } => Boolean(u.id))
- .map((u) => ({
- video_id: u.id,
- title: u.title,
- duration: u.duration,
- upload_date: u.upload_date,
- url: u.url ?? `https://www.youtube.com/watch?v=${u.id}`,
- already_mined: minedIds.has(u.id),
- }));
+ .flatMap((line) => {
+ const u = uploadEntrySchema.parse(JSON.parse(line));
+
+ // A tab or sub-playlist entry (e.g. "Shorts", "Live") has no video id of
+ // its own: only real uploads do.
+ if (!u.id) return [];
+
+ return [
+ {
+ video_id: u.id,
+ title: u.title,
+ duration: u.duration,
+ upload_date: u.upload_date,
+ url: u.url ?? `https://www.youtube.com/watch?v=${u.id}`,
+ already_mined: minedIds.has(u.id),
+ },
+ ];
+ });
}
export async function mineVideoCaptions(
@@ -131,27 +163,27 @@ export async function mineVideoCaptions(
videoUrl: input.video_url,
cookiesFromBrowser: isCookieBrowser(input.cookies_from_browser) ? input.cookies_from_browser : undefined,
});
+
const { stdout, stderr, code } = await deps.runYtDlp(args);
+
if (code !== 0) {
throw new Error(stderr.trim() || "yt-dlp failed to fetch video info");
}
+
// --dump-json prints exactly one JSON object; take the last non-empty line
// defensively in case a warning slipped through on an earlier line.
const jsonLine = stdout.trim().split("\n").filter(Boolean).at(-1);
+
if (!jsonLine) throw new Error("yt-dlp returned no video info");
- const info = JSON.parse(jsonLine) as {
- id: string;
- title: string;
- duration?: number;
- subtitles?: Record<string, CaptionTrackRef[]>;
- automatic_captions?: Record<string, CaptionTrackRef[]>;
- };
+
+ const info = videoInfoSchema.parse(JSON.parse(jsonLine));
// --no-playlist stops a playlist/mix url from resolving to its first entry,
// but a url that already names one video (e.g. a stale redirect) can still
// resolve to a different id than the one asked for. Catch that here rather
// than silently returning the wrong video's captions.
const requestedId = extractYouTubeVideoId(input.video_url);
+
if (requestedId && requestedId !== info.id) {
throw new Error(
`yt-dlp resolved ${input.video_url} to video ${info.id}, not the requested ${requestedId}`,
@@ -162,6 +194,7 @@ export async function mineVideoCaptions(
const alreadyMined = minedIds.has(info.id);
const track = selectBestCaptionTrack(info.subtitles, info.automatic_captions);
+
if (!track) {
return {
video_id: info.id,
@@ -176,13 +209,16 @@ export async function mineVideoCaptions(
}
const captionText = await deps.fetchText(track.url);
+
const { words, segments } =
track.ext === "json3"
? parseJson3(captionText)
: (() => {
const cues = parseVtt(captionText);
+
return { words: cuesToWords(cues), segments: cues.map((c) => ({ text: c.text, start: c.start, end: c.end })) };
})();
+
const language = track.lang.replace(/-orig$/, "");
return {
@@ -215,18 +251,22 @@ const defaultDeps: MineChannelDeps = {
export async function handleMineChannel(input: MineChannelInput): Promise<string> {
if (input.action === "list") {
if (!input.channel_url) throw new Error("channel_url is required for action=list");
+
const uploads = await listChannelUploads(defaultDeps, {
channel_url: input.channel_url,
limit: input.limit,
cookies_from_browser: input.cookies_from_browser,
});
+
return JSON.stringify({ uploads, count: uploads.length });
}
if (!input.video_url) throw new Error("video_url is required for action=mine");
+
const result = await mineVideoCaptions(defaultDeps, {
video_url: input.video_url,
cookies_from_browser: input.cookies_from_browser,
});
+
return JSON.stringify(result);
}
diff --git a/src/handlers/suggest-clips.handler.test.ts b/src/handlers/suggest-clips.handler.test.ts
index 36e2a2e..7e3e94f 100644
--- a/src/handlers/suggest-clips.handler.test.ts
+++ b/src/handlers/suggest-clips.handler.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import { z } from "zod";
-import { handleSuggestClips, hookSchema, suggestClipsInputShape } from "./suggest-clips.handler.js";
+import { handleSuggestClips, hookSchema, suggestClipsInputFields } from "./suggest-clips.handler.js";
const base = {
title: "Why the seed round cost them pricing",
@@ -14,7 +14,7 @@ const base = {
describe("suggest_clips hook", () => {
it("accepts a hook in the tool schema and rejects an unknown mode", () => {
- const schema = z.object(suggestClipsInputShape);
+ const schema = z.object(suggestClipsInputFields);
expect(
schema.safeParse({ suggestions: [{ ...base, hook: { start: 110, end: 113, mode: "move" } }] }).success,
).toBe(true);
@@ -28,6 +28,7 @@ describe("suggest_clips hook", () => {
suggestions: [{ ...base, hook: { start: 110, end: 113, mode: "repeat" } }],
}),
);
+
expect(out.clips[0].hook).toEqual({ start: 110, end: 113, mode: "repeat" });
expect(out.clips[0].duration).toBe(33);
});
diff --git a/src/handlers/suggest-clips.handler.ts b/src/handlers/suggest-clips.handler.ts
index ba919ee..5743605 100644
--- a/src/handlers/suggest-clips.handler.ts
+++ b/src/handlers/suggest-clips.handler.ts
@@ -1,5 +1,5 @@
/**
- * suggest_clips tool — helps Claude structure its clip suggestions.
+ * suggest_clips tool: helps Claude structure its clip suggestions.
*
* This tool doesn't do heavy processing. Claude analyzes the transcript
* in conversation, then calls this tool to store/format the suggestions.
@@ -99,7 +99,7 @@ const suggestionSchema = z.object({
});
/** Single source of truth for the tool's arguments; server.ts registers this. */
-export const suggestClipsInputShape = {
+export const suggestClipsInputFields = {
suggestions: z
.array(suggestionSchema)
.describe("Array of suggested clip moments"),
@@ -108,7 +108,7 @@ export const suggestClipsInputShape = {
export const suggestClipsToolDef = {
name: "suggest_clips",
description:
- "STEP 2 — Submit your clip suggestions after analyzing the transcript.\n\n" +
+ "STEP 2: Submit your clip suggestions after analyzing the transcript.\n\n" +
"Before calling this: read the transcript via get_ui_state(include_transcript: true) " +
"and identify the best viral moments.\n\n" +
"Every suggestion must carry its own context. A clip that opens on an answer " +
@@ -130,17 +130,21 @@ export async function handleSuggestClips(input: SuggestClipsInput): Promise<stri
const suggestions = input.suggestions;
const problems: string[] = [];
+
for (let i = 0; i < suggestions.length; i++) {
const s = suggestions[i];
+
const errors = [
validateSuggestionRange(s.start_second, s.end_second),
validateSuggestionContext(s),
validateHook(s.hook, s.start_second, s.end_second, s.segments),
].filter((e): e is string => e !== null);
+
for (const error of errors) {
problems.push(`Suggestion ${i + 1} ("${s.title}"): ${error}`);
}
}
+
if (problems.length > 0) {
throw new Error(
`${problems.length} of ${suggestions.length} suggestions need work. ` +
@@ -185,6 +189,7 @@ export async function handleSuggestClips(input: SuggestClipsInput): Promise<stri
function formatTime(seconds: number): string {
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);
+
return `${m}:${s.toString().padStart(2, "0")}`;
}
@@ -203,10 +208,11 @@ export async function handleRankClipCandidates(input: {
}): Promise<string> {
const result = await rankExecutor.execute<{
count: number;
- candidates: Array<Record<string, unknown>>;
+ candidates: object[];
}>("rank_candidates", {
video_path: input.video_path,
top_n: input.top_n ?? 20,
});
+
return JSON.stringify(result.data ?? result);
}
diff --git a/src/handlers/transcribe.handler.test.ts b/src/handlers/transcribe.handler.test.ts
index 4633025..07f9a98 100644
--- a/src/handlers/transcribe.handler.test.ts
+++ b/src/handlers/transcribe.handler.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
+import { handleTranscribe, type TranscribeDeps } from "./transcribe.handler.js";
const executeMock = vi.fn();
const cacheGetMock = vi.fn();
@@ -6,29 +7,16 @@ const cacheSetMock = vi.fn();
const cacheGetPackedMock = vi.fn();
const cacheGetHashForEngineMock = vi.fn();
-vi.mock("../services/python-executor.js", () => ({
- PythonExecutor: class {
- execute = executeMock;
+const deps: TranscribeDeps = {
+ executor: { execute: executeMock },
+ cache: {
+ get: cacheGetMock,
+ set: cacheSetMock,
+ getPackedMarkdown: cacheGetPackedMock,
+ getFileHashForEngine: cacheGetHashForEngineMock,
},
-}));
-
-vi.mock("../services/transcript-cache.js", () => ({
- TranscriptCache: class {
- get = cacheGetMock;
- set = cacheSetMock;
- getPackedMarkdown = cacheGetPackedMock;
- getFileHashForEngine = cacheGetHashForEngineMock;
- },
- hasSpeakerLabels: () => true,
- needsDiarizationRetry: () => false,
-}));
-
-vi.mock("../services/engine-resolve.js", () => ({
- resolveTranscribeEngine: vi.fn().mockResolvedValue("whispercpp"),
- engineCanDiarize: () => false,
-}));
-
-const { handleTranscribe } = await import("./transcribe.handler.js");
+ resolveEngine: async () => "whispercpp",
+};
describe("handleTranscribe, sample mode", () => {
beforeEach(() => {
@@ -47,7 +35,7 @@ describe("handleTranscribe, sample mode", () => {
file_path: "/video.mp4",
start_seconds: 120,
duration_seconds: 40,
- });
+ }, deps);
expect(cacheGetMock).not.toHaveBeenCalled();
const parsed = JSON.parse(result);
@@ -73,7 +61,7 @@ describe("handleTranscribe, sample mode", () => {
file_path: "/video.mp4",
start_seconds: 120,
duration_seconds: 40,
- });
+ }, deps);
expect(cacheSetMock).not.toHaveBeenCalled();
const parsed = JSON.parse(result);
@@ -86,7 +74,7 @@ describe("handleTranscribe, sample mode", () => {
data: { transcript: "hi", segments: [], words: [], duration: 40, language: "ka", engine: "whispercpp" },
});
- await handleTranscribe({ file_path: "/video.mp4", start_seconds: 10, duration_seconds: 30 });
+ await handleTranscribe({ file_path: "/video.mp4", start_seconds: 10, duration_seconds: 30 }, deps);
expect(executeMock).toHaveBeenCalledWith(
"transcribe",
@@ -101,7 +89,7 @@ describe("handleTranscribe, sample mode", () => {
});
cacheGetPackedMock.mockResolvedValue("# packed");
- const result = await handleTranscribe({ file_path: "/video.mp4", duration_seconds: 0 });
+ const result = await handleTranscribe({ file_path: "/video.mp4", duration_seconds: 0 }, deps);
expect(cacheGetMock).toHaveBeenCalled();
expect(cacheSetMock).toHaveBeenCalled();
@@ -116,7 +104,7 @@ describe("handleTranscribe, sample mode", () => {
});
cacheGetPackedMock.mockResolvedValue("# packed");
- await handleTranscribe({ file_path: "/video.mp4" });
+ await handleTranscribe({ file_path: "/video.mp4" }, deps);
expect(cacheGetMock).toHaveBeenCalled();
expect(cacheSetMock).toHaveBeenCalled();
diff --git a/src/handlers/transcribe.handler.ts b/src/handlers/transcribe.handler.ts
index b9444b4..dd80d58 100644
--- a/src/handlers/transcribe.handler.ts
+++ b/src/handlers/transcribe.handler.ts
@@ -1,6 +1,7 @@
import { basename } from "path";
import { randomUUID } from "crypto";
-import { PythonExecutor } from "../services/python-executor.js";
+import { z } from "zod";
+import { PythonExecutor, type TaskExecutor } from "../services/python-executor.js";
import { TranscriptCache, needsDiarizationRetry } from "../services/transcript-cache.js";
import { resolveTranscribeEngine, engineCanDiarize } from "../services/engine-resolve.js";
import { webServerUrl } from "../config/server.js";
@@ -20,6 +21,15 @@ const processExecutor = new PythonExecutor();
const executor = new PythonExecutor();
const cache = new TranscriptCache();
+/** What handleTranscribe talks to. Tests pass stand-ins instead of the Python process and the disk cache. */
+export interface TranscribeDeps {
+ executor: TaskExecutor;
+ cache: Pick<TranscriptCache, "get" | "set" | "getPackedMarkdown" | "getFileHashForEngine">;
+ resolveEngine: typeof resolveTranscribeEngine;
+}
+
+const defaultDeps: TranscribeDeps = { executor, cache, resolveEngine: resolveTranscribeEngine };
+
export interface TranscribeInput {
file_path: string;
model_size?: "tiny" | "base" | "small" | "medium" | "large";
@@ -34,15 +44,15 @@ export interface TranscribeInput {
export const transcribeToolDef = {
name: "transcribe_podcast",
description:
- "STEP 1 — Transcribe a podcast video/audio file. This is typically the first tool you call.\n\n" +
+ "STEP 1: Transcribe a podcast video/audio file. This is typically the first tool you call.\n\n" +
"What it does: Uses Whisper AI for word-level timestamps, with speaker detection (who said what) on by " +
"default. Speaker labels are what let a clip tell a question from an answer, so leave them on for any " +
"interview. Pass enable_diarization=false to skip them and save time on a single-speaker recording.\n" +
- "Returns: Lightweight metadata only — duration, language, word/segment counts, speaker summary, and " +
+ "Returns: lightweight metadata only, namely duration, language, word/segment counts, speaker summary, and " +
"packed_ready flag. The actual transcript body is NOT returned here (it would be 500KB+ for a typical " +
"episode). Read the content via get_ui_state(include_transcript: true) which returns a compact " +
"phrase-grouped markdown view (~10x smaller than raw segments).\n" +
- "Caching: Results are cached by file hash — same file won't be re-transcribed.\n" +
+ "Caching: Results are cached by file hash, so the same file won't be re-transcribed.\n" +
"Supported formats: MP4, MOV, WebM, MKV, MP3, WAV.\n\n" +
"After transcription: call rank_clip_candidates(video_path) for a ~20-clip shortlist " +
"(do not read the whole transcript unless you need to rewrite a range). " +
@@ -101,7 +111,10 @@ export const transcribeToolDef = {
},
};
-export async function handleTranscribe(input: TranscribeInput): Promise<string> {
+export async function handleTranscribe(
+ input: TranscribeInput,
+ { executor, cache, resolveEngine }: TranscribeDeps = defaultDeps,
+): Promise<string> {
const filePath = input.file_path;
const modelSize = input.model_size ?? "base";
const engine = input.engine;
@@ -118,16 +131,18 @@ export async function handleTranscribe(input: TranscribeInput): Promise<string>
// Resolve before reading the cache: an unset engine is written under
// whatever transcribe_file actually ran (e.g. "whispercpp" on a native
// install), so reading with the raw unset request always misses.
- const resolvedEngine = await resolveTranscribeEngine(executor, engine, modelSize);
+ const resolvedEngine = await resolveEngine(executor, engine, modelSize);
const cacheKey = { engine: resolvedEngine, model: modelSize, language };
// A sample is a throwaway check on a slice of the file. It must never
// serve (or pollute) the main transcript cache, which is keyed by the
// whole file and assumed complete.
const cachedRaw = isSample ? null : await cache.get(filePath, cacheKey);
+
const cached = needsDiarizationRetry(cachedRaw, enableDiarization, engineCanDiarize(resolvedEngine))
? null
: cachedRaw;
+
if (cached) {
// Same combo cache.get(filePath, cacheKey) just matched: the packed
// view has to be keyed identically, or a backfill here would write it
@@ -135,6 +150,7 @@ export async function handleTranscribe(input: TranscribeInput): Promise<string>
const packedKey = { engine: cached.engine ?? resolvedEngine, model: modelSize, language };
// Backfill packed view if this cache predates auto-packing.
let packed = await cache.getPackedMarkdown(filePath, packedKey);
+
if (!packed) {
try {
const cacheHash = await cache.getFileHashForEngine(filePath, packedKey);
@@ -146,9 +162,10 @@ export async function handleTranscribe(input: TranscribeInput): Promise<string>
});
packed = await cache.getPackedMarkdown(filePath, packedKey);
} catch {
- // Non-fatal — caller still gets metadata
+ // Non-fatal: caller still gets metadata
}
}
+
return JSON.stringify({ cached: true, packed_ready: !!packed, ...formatResult(cached) });
}
@@ -167,6 +184,7 @@ export async function handleTranscribe(input: TranscribeInput): Promise<string>
if (!result.data) {
throw new Error("Transcription returned no data");
}
+
const data = result.data;
const actualEngine = data.engine ?? resolvedEngine;
@@ -186,7 +204,7 @@ export async function handleTranscribe(input: TranscribeInput): Promise<string>
}
/**
- * Returns lightweight metadata — NOT the transcript body. The full transcript
+ * Returns lightweight metadata: NOT the transcript body. The full transcript
* is available via get_ui_state(include_transcript: true), which serves the
* packed markdown view (~10x smaller than raw segments/words). Raw segments
* and words arrays stay in the on-disk cache for internal Python consumers.
@@ -201,9 +219,10 @@ function formatResult(data: TranscriptResult) {
word_count: (data.words ?? []).length,
segment_count: (data.segments ?? []).length,
speakers: data.speakers ?? { num_speakers: 0, speakers: {} },
- ...(data.complete === false
- ? { complete: false, sample_offset_seconds: data.sample_offset_seconds ?? 0 }
- : {}),
+ ...(data.complete === false && {
+ complete: false,
+ sample_offset_seconds: data.sample_offset_seconds ?? 0,
+ }),
next_step: "Read the transcript via get_ui_state(include_transcript: true), then suggest_clips.",
};
}
@@ -212,12 +231,26 @@ function formatResult(data: TranscriptResult) {
// Async transcription via Web UI job queue
// =============================================
+const jobStartSchema = z.object({
+ job_id: z.string(),
+ status: z.string(),
+ cached: z.boolean().optional(),
+});
+
+const jobPollSchema = z.object({
+ status: z.enum(["running", "done", "error"]),
+ progress: z.number(),
+ message: z.string(),
+ result: z.unknown().optional(),
+ error: z.string().optional(),
+});
+
export const transcribeStartToolDef = {
name: "transcribe_start",
description:
"Start transcription as a background job and return a job_id immediately. " +
"Use this instead of transcribe_podcast for long files so you can narrate progress " +
- "to the user while it runs (a 60-min episode takes 15–25 min).\n\n" +
+ "to the user while it runs (a 60-min episode takes 15-25 min).\n\n" +
"Flow: call transcribe_start(file_path) → emit status text to user → " +
"call job_status(job_id, wait_seconds: 30) in a loop until done → " +
"then read the packed transcript via get_ui_state(include_transcript: true).\n\n" +
@@ -269,17 +302,19 @@ export async function handleTranscribeStart(input: TranscribeInput): Promise<str
duration_seconds: input.duration_seconds,
}),
});
+
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
- const data = (await res.json()) as { job_id: string; status: string; cached?: boolean };
+ const data = jobStartSchema.parse(await res.json());
- // Rough estimate — Whisper base + diarization is roughly 1/3× audio duration on CPU.
+ // Rough estimate: Whisper base + diarization is roughly 1/3× audio duration on CPU.
// We don't know duration here; ballpark from file size.
- let estimate = "10–30 min depending on episode length";
+ let estimate = "10-30 min depending on episode length";
+
try {
const { statSync } = await import("fs");
const mb = statSync(input.file_path).size / (1024 * 1024);
const mins = Math.max(2, Math.round(mb / 50)); // very rough: ~50MB/min of processing
- estimate = data.cached ? "instant (cached)" : `~${mins}–${mins * 2} min`;
+ estimate = data.cached ? "instant (cached)" : `~${mins}-${mins * 2} min`;
} catch {
// ignore
}
@@ -290,16 +325,18 @@ export async function handleTranscribeStart(input: TranscribeInput): Promise<str
status: data.status,
estimate,
next_step: data.cached
- ? "Cached — skip polling, read via get_ui_state(include_transcript: true)."
+ ? "Cached: skip polling, read via get_ui_state(include_transcript: true)."
: `Poll job_status("${data.job_id}", wait_seconds: 30) in a loop, emitting one terse progress line to the user between polls.`,
});
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return JSON.stringify({
error: "Web UI not running. Start it with `npm run ui`, or fall back to transcribe_podcast for synchronous transcription.",
});
}
+
throw err;
}
}
@@ -308,7 +345,7 @@ export const jobStatusToolDef = {
name: "job_status",
description:
"Poll the status of any background job (transcription, clip render, batch export, process_episode). " +
- "Supports long-polling: pass wait_seconds (1–60) to block until the job changes state " +
+ "Supports long-polling: pass wait_seconds (1-60) to block until the job changes state " +
"or the timeout elapses, whichever comes first. Paces Claude's polling naturally so " +
"the spinner doesn't spam and the user sees steady progress text.\n\n" +
"Returns { status: 'running'|'done'|'error', progress, message, done, result? }.\n" +
@@ -336,15 +373,22 @@ export async function handleJobStatus(input: {
}): Promise<string> {
const wait = Math.max(0, Math.min(60, input.wait_seconds ?? 30));
const deadline = Date.now() + wait * 1000;
- let lastProgress = -1;
+ // Seeded from the first read, so the wait ends on a change after the caller
+ // asked, not on the first look.
+ let lastProgress: number | null = null;
const local = localJobs.get(input.job_id);
+
if (local) {
while (true) {
const job = localJobs.get(input.job_id);
+
if (!job) break;
const terminal = job.status === "done" || job.status === "error";
+
+ if (lastProgress === null) lastProgress = job.progress;
const progressChanged = job.progress !== lastProgress;
+
if (terminal || progressChanged || Date.now() >= deadline) {
return JSON.stringify({
status: job.status,
@@ -357,10 +401,11 @@ export async function handleJobStatus(input: {
job.status === "done"
? "Job complete. The result field lists clip paths, durations, scores, titles, and captions."
: job.status === "error"
- ? "Job failed — check the error. Retry process_episode if appropriate."
- : `Still running — call job_status("${input.job_id}", wait_seconds: 30) again.`,
+ ? "Job failed: check the error. Retry process_episode if appropriate."
+ : `Still running: call job_status("${input.job_id}", wait_seconds: 30) again.`,
});
}
+
lastProgress = job.progress;
await new Promise((r) => setTimeout(r, 2000));
}
@@ -369,18 +414,16 @@ export async function handleJobStatus(input: {
try {
while (true) {
const res = await fetch(`${webServerUrl}/api/job/${input.job_id}`);
+
if (res.status === 404) {
return JSON.stringify({ error: `Job ${input.job_id} not found` });
}
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const job = (await res.json()) as {
- status: "running" | "done" | "error";
- progress: number;
- message: string;
- result?: unknown;
- error?: string;
- };
+ const job = jobPollSchema.parse(await res.json());
+
+ if (lastProgress === null) lastProgress = job.progress;
const progressChanged = job.progress !== lastProgress;
const terminal = job.status === "done" || job.status === "error";
@@ -393,10 +436,10 @@ export async function handleJobStatus(input: {
error: job.error,
next_step:
job.status === "done"
- ? "Job complete. For transcription: get_ui_state(include_transcript: true). For renders: clips are on disk — the result field lists paths."
+ ? "Job complete. For transcription: get_ui_state(include_transcript: true). For renders: clips are on disk. The result field lists paths."
: job.status === "error"
- ? "Job failed — check the error. Retry the original start call if appropriate."
- : `Still running — call job_status("${input.job_id}", wait_seconds: 30) again and emit one terse progress line to the user between polls.`,
+ ? "Job failed: check the error. Retry the original start call if appropriate."
+ : `Still running: call job_status("${input.job_id}", wait_seconds: 30) again and emit one terse progress line to the user between polls.`,
});
}
@@ -405,9 +448,11 @@ export async function handleJobStatus(input: {
}
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return JSON.stringify({ error: "Web UI not running." });
}
+
throw err;
}
}
@@ -455,6 +500,7 @@ export async function handleProcessEpisode(input: {
fast: input.fast,
}, (event) => {
const job = localJobs.get(jobId);
+
if (!job || job.status !== "running") return;
job.progress = event.percent;
job.message = event.message;
@@ -467,14 +513,15 @@ export async function handleProcessEpisode(input: {
result: result.data,
});
})
- .catch((err: unknown) => {
+ .catch((cause: unknown) => {
localJobs.set(jobId, {
status: "error",
progress: 0,
message: "Failed",
- error: err instanceof Error ? err.message : String(err),
+ error: cause instanceof Error ? cause.message : String(cause),
});
});
+
return JSON.stringify({
job_id: jobId,
status: "running",
diff --git a/src/index.ts b/src/index.ts
index 056584e..7853deb 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,8 +1,8 @@
#!/usr/bin/env node
/**
- * podcli — MCP Server
+ * podcli: MCP Server
*
- * Entry point — starts the MCP server over stdio transport.
+ * Entry point: starts the MCP server over stdio transport.
* Connect this to Claude Desktop, Claude Code, or any MCP client.
*/
diff --git a/src/models/index.ts b/src/models/index.ts
index 933fdc2..5e20be0 100644
--- a/src/models/index.ts
+++ b/src/models/index.ts
@@ -2,6 +2,7 @@ import type { ClipHook } from "../utils/clip-hook.js";
import type { ThumbnailLayout, ThumbnailPerson } from "../utils/thumbnail-layout.js";
export type { ClipHook, HookMode } from "../utils/clip-hook.js";
+
export type { ThumbnailLayout, ThumbnailPerson } from "../utils/thumbnail-layout.js";
// === Task Communication Models ===
@@ -9,10 +10,10 @@ export type { ThumbnailLayout, ThumbnailPerson } from "../utils/thumbnail-layout
export interface TaskRequest {
task_id: string;
task_type: "transcribe" | "resolve_transcribe_engine" | "compare_engines" | "parse_transcript" | "create_clip" | "batch_clips" | "analyze_energy" | "detect_highlights" | "manage_reel" | "pack_transcript" | "detect_encoder" | "presets" | "ping" | "suggest_clips" | "rank_candidates" | "process_episode" | "find_moment" | "generate_content" | "generate_custom" | "corrections" | "manage_integrations" | "run_integration_tool" | "manage_config" | "manage_env" | "ai_cli_status" | "ai_provider_status" | "analyze_silence" | "render_silence_removed" | "manage_multicam";
- params: Record<string, unknown>;
+ params: object;
}
-export interface TaskResult<T = Record<string, unknown>> {
+export interface TaskResult<T = object> {
task_id: string;
status: "success" | "error";
data?: T;
@@ -25,7 +26,7 @@ export interface ProgressEvent {
percent: number;
message: string;
clip_result?: BatchClipsResult["results"][number];
- partial?: Record<string, unknown>;
+ partial?: object;
}
// === Transcript Models ===
@@ -87,7 +88,9 @@ export interface TranscriptResult {
// === Clip Models ===
export type CaptionStyle = "branded" | "hormozi" | "karaoke" | "subtle";
+
export type CropStrategy = "center" | "face" | "speaker";
+
export type Format = "vertical" | "horizontal" | "square";
export interface ClipRequest {
@@ -150,7 +153,7 @@ export interface UIState {
transcriptVideoIdentity?: { path: string; size: number; mtimeMs: number } | null;
rawTranscriptText?: string;
silenceOriginal?: { videoPath: string; transcript: TranscriptResult } | null;
- silencePlan?: Record<string, unknown> | null;
+ silencePlan?: object | null;
/** True when videoPath didn't exist at last check (e.g. an external drive
* is unmounted). The session is kept, not wiped, while this is set. */
videoMissing?: boolean;
diff --git a/src/podstack-commands.test.ts b/src/podstack-commands.test.ts
index bd61aa5..40a96ae 100644
--- a/src/podstack-commands.test.ts
+++ b/src/podstack-commands.test.ts
@@ -1,8 +1,9 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, beforeAll } from "vitest";
import { readFileSync, readdirSync } from "fs";
import { dirname, join, resolve } from "path";
import { fileURLToPath } from "url";
import { createServer } from "./server.js";
+import { listToolNames } from "./test-support/mcp-client.js";
// Catches the class of bug fixed alongside this test: a PodStack command
// frontmatter or body references an MCP tool name that doesn't match what
@@ -10,16 +11,22 @@ import { createServer } from "./server.js";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const commandsDir = join(repoRoot, ".claude", "commands");
-function registeredToolNames(): Set<string> {
- const server = createServer() as unknown as { _registeredTools: Record<string, unknown> };
- return new Set(Object.keys(server._registeredTools));
+function registeredToolNames(): Promise<Set<string>> {
+ return listToolNames(createServer());
}
-function parseFrontmatter(source: string): { allowedTools: string[]; body: string } {
+interface Frontmatter {
+ allowedTools: string[];
+ body: string;
+}
+
+function parseFrontmatter(source: string): Frontmatter {
const match = source.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
+
if (!match) return { allowedTools: [], body: source };
const [, frontmatter, body] = match;
const line = frontmatter.split("\n").find((l) => l.startsWith("allowed-tools:"));
+
const allowedTools = line
? line
.slice("allowed-tools:".length)
@@ -27,13 +34,18 @@ function parseFrontmatter(source: string): { allowedTools: string[]; body: strin
.map((t) => t.trim())
.filter(Boolean)
: [];
+
return { allowedTools, body };
}
const commandFiles = readdirSync(commandsDir).filter((f) => f.endsWith(".md"));
describe("PodStack command frontmatter matches registered MCP tools", () => {
- const toolNames = registeredToolNames();
+ let toolNames = new Set<string>();
+
+ beforeAll(async () => {
+ toolNames = await registeredToolNames();
+ });
it("the server registers at least one tool", () => {
expect(toolNames.size).toBeGreaterThan(0);
@@ -49,9 +61,11 @@ describe("PodStack command frontmatter matches registered MCP tools", () => {
const source = readFileSync(join(commandsDir, file), "utf-8");
const { allowedTools } = parseFrontmatter(source);
const mcpTools = allowedTools.filter((t) => t.startsWith("mcp__podcli__"));
+
const unknown = mcpTools
.map((t) => t.slice("mcp__podcli__".length))
.filter((name) => !toolNames.has(name));
+
expect(unknown, `${file} allows unknown tools: ${unknown.join(", ")}`).toEqual([]);
});
diff --git a/src/record-decisions.test.ts b/src/record-decisions.test.ts
index 7a3a20d..b672fd9 100644
--- a/src/record-decisions.test.ts
+++ b/src/record-decisions.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { callTool, type ToolArgs } from "./test-support/mcp-client.js";
// record_decisions is the MCP way to answer the per-episode open questions
// (clip count, caption style, language, ...) once instead of every run.
@@ -34,32 +35,27 @@ beforeAll(async () => {
afterAll(() => {
if (savedHome === undefined) delete process.env.PODCLI_HOME;
else process.env.PODCLI_HOME = savedHome;
+
if (savedPort === undefined) delete process.env.PODCLI_PORT;
else process.env.PODCLI_PORT = savedPort;
+
if (savedData === undefined) delete process.env.PODCLI_DATA;
else process.env.PODCLI_DATA = savedData;
rmSync(tmp, { recursive: true, force: true });
});
-function getHandler(name: string) {
- const server = createServer() as unknown as {
- _registeredTools: Record<string, { handler: (args: unknown, extra: unknown) => Promise<{ content: { text: string }[] }> }>;
- };
- return server._registeredTools[name].handler;
-}
+const recordDecisions = (args: ToolArgs) => callTool(createServer(), "record_decisions", args);
describe("record_decisions", () => {
it("records a decision and reports what's still open", async () => {
- const handler = getHandler("record_decisions");
- const result = await handler({ video_path: videoPath, clip_count: 5 }, {});
- const text = result.content[0].text;
+ const result = await recordDecisions({ video_path: videoPath, clip_count: 5 });
+ const text = result.text;
expect(text).toContain("clipCount");
expect(text).toContain("Still open");
});
it("reports every decision answered once all fields are recorded", async () => {
- const handler = getHandler("record_decisions");
- await handler(
+ await recordDecisions(
{
video_path: videoPath,
clip_count: 5,
@@ -71,16 +67,14 @@ describe("record_decisions", () => {
thumbnails_wanted: true,
delivery_target: "youtube_shorts",
},
- {},
);
- const result = await handler({ video_path: videoPath, notes: "final note" }, {});
- expect(result.content[0].text).toContain("All episode decisions answered.");
+ const result = await recordDecisions({ video_path: videoPath, notes: "final note" });
+ expect(result.text).toContain("All episode decisions answered.");
});
it("rejects a call with no fields to record", async () => {
- const handler = getHandler("record_decisions");
- const result = await handler({ video_path: videoPath }, {});
- expect(result.content[0].text).toContain("No decisions provided");
+ const result = await recordDecisions({ video_path: videoPath });
+ expect(result.text).toContain("No decisions provided");
});
it("keys decisions on the pre-silence-removal video, not its derivative", async () => {
@@ -100,8 +94,7 @@ describe("record_decisions", () => {
}),
);
- const handler = getHandler("record_decisions");
- await handler({ video_path: derivativePath, clip_count: 7 }, {});
+ await recordDecisions({ video_path: derivativePath, clip_count: 7 });
const { EpisodeState } = await import("./services/episode-state.js");
const state = new EpisodeState();
@@ -117,6 +110,7 @@ describe("recordDecisionsInputSchema", () => {
it("rejects an unknown field and names the valid fields in the error", () => {
const result = recordDecisionsInputSchema.safeParse({ video_path: videoPath, captions: true });
expect(result.success).toBe(false);
+
if (!result.success) {
const message = result.error.issues[0].message;
expect(message).toContain("captions");
@@ -136,10 +130,9 @@ describe("record_decisions duration range", () => {
const { EpisodeState } = await import("./services/episode-state.js");
const fresh = join(tmp, "fresh-episode.mp4");
writeFileSync(fresh, "another fake video");
- const handler = getHandler("record_decisions");
- await handler({ video_path: fresh, clip_duration_min: 30 }, {});
+ await recordDecisions({ video_path: fresh, clip_duration_min: 30 });
expect((await new EpisodeState().get(fresh))?.clipDurationRange).toEqual({ min: 30 });
- await handler({ video_path: fresh, clip_duration_max: 60 }, {});
+ await recordDecisions({ video_path: fresh, clip_duration_max: 60 });
expect((await new EpisodeState().get(fresh))?.clipDurationRange).toEqual({ min: 30, max: 60 });
});
});
diff --git a/src/server.ts b/src/server.ts
index f14347a..36c8ace 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -18,7 +18,7 @@ import {
} from "./handlers/compare-engines.handler.js";
import {
suggestClipsToolDef,
- suggestClipsInputShape,
+ suggestClipsInputFields,
handleSuggestClips,
rankClipCandidatesToolDef,
handleRankClipCandidates,
@@ -35,43 +35,43 @@ import {
import { registerIntegrationMcpTools } from "./handlers/integrations.handler.js";
import { mineChannelToolDef, handleMineChannel } from "./handlers/mine-channel.handler.js";
import { isHttpUrl } from "./utils/ytdlp-args.js";
-import { FileManager } from "./services/file-manager.js";
import { KnowledgeBase } from "./services/knowledge-base.js";
import { AssetManager, inferType } from "./services/asset-manager.js";
import { ClipsHistory } from "./services/clips-history.js";
import { TranscriptCache } from "./services/transcript-cache.js";
import { EpisodeState } from "./services/episode-state.js";
import { paths } from "./config/paths.js";
+import { readUIStateFile } from "./services/ui-state-file.js";
import { webServerUrl } from "./config/server.js";
import { childLogger } from "./utils/logger.js";
import { mcpError } from "./utils/errors.js";
import { transcriptVideoMismatch } from "./utils/video-identity.js";
import { podcliVersion, studioStartCommand } from "./version.js";
-import type { ClipHook, Format, SuggestedClip, UIState, WordTimestamp } from "./models/index.js";
+import type { ClipHook, SuggestedClip, UIState } from "./models/index.js";
const log = childLogger("server");
/**
* Fire-and-forget notification to the optional Web UI.
- * Never throws — the UI may not be running, which is expected.
+ * Never throws: the UI may not be running, which is expected.
*/
const transcriptCache = new TranscriptCache();
/**
* Only a studio that isn't listening may be retried inline. A render that
- * started and then failed, timed out, or went missing must surface — retrying it
+ * started and then failed, timed out, or went missing must surface: retrying it
* would render the same clips twice.
*/
-function studioUnreachable(err: unknown, label: string): boolean {
- const msg = err instanceof Error ? err.message : String(err);
+function studioUnreachable(msg: string, label: string): boolean {
if (!msg.includes("ECONNREFUSED") && !msg.includes("fetch failed")) return false;
log.warn(
`Studio not reachable at ${webServerUrl}. Running ${label} inline without live progress. If the studio listens on another port, set PODCLI_PORT for this MCP server too.`,
);
+
return true;
}
-async function uiPing(body: Record<string, unknown>): Promise<void> {
+async function uiPing(body: UIState): Promise<void> {
try {
await fetch(`${webServerUrl}/api/ui-state`, {
method: "POST",
@@ -94,9 +94,11 @@ const episodeState = new EpisodeState();
async function withKnowledge(result: string): Promise<string> {
try {
const files = await kb.listFiles();
+
if (!files.length) return result;
const listing = files.map((f) => f.filename).join(", ");
- return `[Knowledge Base: ${listing} — use knowledge_base tool to read specific files]\n\n${result}`;
+
+ return `[Knowledge Base: ${listing}. Use the knowledge_base tool to read specific files]\n\n${result}`;
} catch {
return result;
}
@@ -116,7 +118,7 @@ const TRANSCRIPT_FALLBACK_CAP = 50_000;
// captions_enabled gets no error and nothing recorded. record_decisions is
// strict on purpose: it's meant to be the durable record of a decision, so a
// typo'd key should fail loudly rather than quietly not stick.
-const recordDecisionsInputShape = {
+const recordDecisionsInputFields = {
video_path: z.string().describe("The episode's source video path (same path used with set_video/transcribe_podcast)"),
clip_count: z.number().optional().describe("How many clips to produce"),
clip_duration_min: z.number().optional().describe("Minimum target clip duration in seconds"),
@@ -129,17 +131,18 @@ const recordDecisionsInputShape = {
notes: z.string().optional().describe("Free-form notes that don't fit another field"),
};
-export const recordDecisionsInputSchema = z.strictObject(recordDecisionsInputShape, {
+export const recordDecisionsInputSchema = z.strictObject(recordDecisionsInputFields, {
// Returning undefined keeps zod's own message for every other issue.
error: (issue) =>
issue.code === "unrecognized_keys"
? `Unknown field(s): ${issue.keys.join(", ")}. Valid fields: ` +
- Object.keys(recordDecisionsInputShape).join(", ")
+ Object.keys(recordDecisionsInputFields).join(", ")
: undefined,
});
function capTranscriptText(text: string): string {
if (text.length <= TRANSCRIPT_FALLBACK_CAP) return text;
+
return (
text.slice(0, TRANSCRIPT_FALLBACK_CAP) +
`\n\n[Transcript truncated: showing the first ${TRANSCRIPT_FALLBACK_CAP} of ${text.length} characters. ` +
@@ -159,51 +162,116 @@ interface ServerUIState extends UIState {
transcriptWordCount?: number;
}
-interface WebJob {
- job_id: string;
- status: "pending" | "running" | "done" | "error";
- result?: unknown;
- error?: string;
-}
+const captionStyleSchema = z.enum(["hormozi", "karaoke", "subtle", "branded"]);
-interface OutputClip {
- filename: string;
- size_mb: number;
- created?: string;
-}
+const resultEngineSchema = z.looseObject({ engine: z.string().optional() });
-interface ApiError {
- error?: string;
-}
+const webJobSchema = z.looseObject({
+ job_id: z.string(),
+ status: z.enum(["pending", "running", "done", "error"]),
+ result: z.unknown().optional(),
+ error: z.string().optional(),
+});
-interface FileInfo {
- filename?: string;
- name?: string;
- path?: string;
- size_mb?: number;
- duration?: number;
-}
+const outputClipsSchema = z.array(
+ z.looseObject({
+ filename: z.string(),
+ size_mb: z.number(),
+ created: z.string().optional(),
+ }),
+);
+
+const apiErrorSchema = z.looseObject({ error: z.string().optional() });
+
+const apiResponseSchema = z.looseObject({
+ error: z.string().optional(),
+ job_id: z.string().optional(),
+ outputs: z
+ .looseObject({
+ validation: z.looseObject({ warnings: z.array(z.string()).optional() }).optional(),
+ })
+ .optional(),
+});
-interface PresetConfig {
- caption_style?: string;
- crop_strategy?: string;
- logo_path?: string;
- outro_path?: string;
+const cropStrategySchema = z.enum(["center", "face", "speaker"]);
+const formatSchema = z.enum(["vertical", "horizontal", "square"]);
+
+function exportClipFromSuggestion(
+ s: SuggestedClip,
+ fallbackTitle: string,
+ settings: NonNullable<UIState["settings"]>,
+) {
+ return {
+ start_second: s.start_second,
+ end_second: s.end_second,
+ title: s.title || fallbackTitle,
+ caption_style: captionStyleSchema.catch("hormozi").parse(s.suggested_caption_style || settings.captionStyle),
+ crop_strategy: cropStrategySchema.catch("speaker").parse(settings.cropStrategy),
+ format: formatSchema.catch("vertical").parse(settings.format),
+ allow_ass_fallback: false,
+ ...(s.segments && s.segments.length > 0 && { keep_segments: s.segments }),
+ hook: s.hook ?? null,
+ };
}
-interface PresetResult extends ApiError {
- presets?: Array<string | { name?: string }>;
- preset?: unknown;
- config?: PresetConfig;
-}
+type RecordedDecisions = Parameters<EpisodeState["record"]>[1];
-interface ImportTranscriptResult extends ApiError {
- data?: {
- transcript?: string;
- words?: unknown[];
- segments?: unknown[];
- duration?: number;
- };
+const fileInfoSchema = z.looseObject({
+ filename: z.string().optional(),
+ name: z.string().optional(),
+ path: z.string().optional(),
+ size_mb: z.number().optional(),
+ duration: z.number().optional(),
+});
+
+const presetResultSchema = z.looseObject({
+ error: z.string().optional(),
+ presets: z.array(z.union([z.string(), z.looseObject({ name: z.string().optional() })])).optional(),
+ preset: z.unknown().optional(),
+ config: z
+ .looseObject({
+ caption_style: z.string().optional(),
+ crop_strategy: z.string().optional(),
+ logo_path: z.string().optional(),
+ outro_path: z.string().optional(),
+ })
+ .optional(),
+});
+
+const importTranscriptResultSchema = z.looseObject({
+ error: z.string().optional(),
+ data: z
+ .looseObject({
+ transcript: z.string().optional(),
+ words: z.array(z.unknown()).optional(),
+ segments: z.array(z.unknown()).optional(),
+ duration: z.number().optional(),
+ })
+ .optional(),
+});
+
+const clipEditResultSchema = z.looseObject({
+ error: z.string().optional(),
+ index: z.number().default(0),
+ total: z.number().default(0),
+ selectedCount: z.number().default(0),
+ clip: z.looseObject({
+ title: z.string().default(""),
+ start_second: z.number().optional(),
+ end_second: z.number().optional(),
+ duration: z.number().optional(),
+ hook: z
+ .looseObject({ mode: z.string(), start: z.number(), end: z.number() })
+ .optional(),
+ }).default({ title: "" }),
+});
+
+interface SuggestionsModifyBody {
+ action: string;
+ updates?: object;
+ selected?: boolean;
+ index?: number;
+ clip_id?: string;
}
/**
@@ -215,8 +283,9 @@ interface ImportTranscriptResult extends ApiError {
function readUIStateFromDisk(): ServerUIState | null {
try {
if (!existsSync(paths.uiState)) return null;
- const raw = JSON.parse(readFileSync(paths.uiState, "utf-8")) as UIState;
+ const raw = readUIStateFile();
const words = raw.transcript?.words;
+
return {
...raw,
transcriptWordCount: Array.isArray(words) ? words.length : 0,
@@ -225,6 +294,7 @@ function readUIStateFromDisk(): ServerUIState | null {
log.debug("readUIStateFromDisk failed", {
err: err instanceof Error ? err.message : String(err),
});
+
return null;
}
}
@@ -232,12 +302,16 @@ function readUIStateFromDisk(): ServerUIState | null {
async function readUIState(): Promise<ServerUIState | null> {
try {
const res = await fetch(`${webServerUrl}/api/ui-state`);
+
if (!res.ok) return readUIStateFromDisk();
+
+ // SAFETY: /api/ui-state responds with the studio's UIState plus transcriptWordCount.
return (await res.json()) as ServerUIState;
} catch (err) {
log.debug("readUIState via Web UI failed, falling back to disk", {
err: err instanceof Error ? err.message : String(err),
});
+
return readUIStateFromDisk();
}
}
@@ -252,18 +326,21 @@ async function readUIState(): Promise<ServerUIState | null> {
async function resolveEpisodeKeyPath(videoPath: string): Promise<string> {
const state = await readUIState();
const original = state?.silenceOriginal?.videoPath;
+
if (original && (state?.videoPath === videoPath || state?.filePath === videoPath)) {
return original;
}
+
return videoPath;
}
/** Generate workflow guidance based on current state. */
async function getWorkflowGuidance(): Promise<string> {
const state = await readUIState();
+
if (!state) {
return (
- "WORKFLOW — Start from scratch:\n" +
+ "Start from scratch with this workflow:\n" +
"1. Set the video: use set_video or transcribe_podcast with a file path\n" +
"2. Get a transcript: use transcribe_podcast (auto) or import_transcript / parse_transcript\n" +
"3. Read the transcript: use get_ui_state(include_transcript: true)\n" +
@@ -295,7 +372,7 @@ async function getWorkflowGuidance(): Promise<string> {
} else if (!hasTranscript && !hasRawTranscript) {
lines.push(
`NEXT: Video is loaded but no transcript yet.\n` +
- ` → Use transcribe_podcast(file_path: \"${state.videoPath}\") to auto-transcribe with Whisper\n` +
+ ` → Use transcribe_podcast(file_path: "${state.videoPath}") to auto-transcribe with Whisper\n` +
` → Or the user can paste a transcript in the Web UI and you can read it with get_ui_state(include_transcript: true)`,
);
} else if (hasRawTranscript && !hasTranscript) {
@@ -331,12 +408,14 @@ async function getWorkflowGuidance(): Promise<string> {
}
const videoPath = state.videoPath || state.filePath;
+
if (videoPath) {
// A silence-removal pass rewrites the video to a new path with a different
// size, which would otherwise orphan decisions already recorded against the
// original. Key on the original so they carry over to its derivative.
const episodeKeyPath = state.silenceOriginal?.videoPath ?? videoPath;
const openQuestions = await episodeState.openQuestions(episodeKeyPath).catch(() => []);
+
if (openQuestions.length > 0) {
lines.push(
"\nOPEN QUESTIONS for this episode. Ask once, then call record_decisions so these never come up again:\n" +
@@ -423,17 +502,19 @@ export function createServer(): McpServer {
});
// Push FULL transcript (words[] + segments[]) to Web UI state from the
- // on-disk cache — NOT the trimmed MCP response. Without words in UI
+ // on-disk cache: NOT the trimmed MCP response. Without words in UI
// state, downstream batch_create_clips can't burn captions.
// Skipped for a sample: it's never written to this cache, and it's a
// slice of the file, not something that belongs in the UI session.
const isSample = start_seconds !== undefined || duration_seconds !== undefined;
+
try {
// handleTranscribe's result carries the engine it actually resolved
// to and cached under; the request-time `engine` can be unset while
// the write landed under "whispercpp", so reading with it misses.
const resolvedEngine =
- (JSON.parse(result) as { engine?: string }).engine ?? engine;
+ resultEngineSchema.safeParse(JSON.parse(result)).data?.engine ?? engine;
+
const cached = isSample
? null
: await transcriptCache.get(file_path, {
@@ -441,6 +522,7 @@ export function createServer(): McpServer {
model: model_size,
language,
});
+
if (cached) {
await uiPing({
videoPath: file_path,
@@ -460,6 +542,7 @@ export function createServer(): McpServer {
"Transcript is ready! Now read it with get_ui_state(include_transcript: true), " +
"analyze it for viral moments, then call suggest_clips with your findings.",
);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -487,6 +570,7 @@ export function createServer(): McpServer {
async (input) => {
try {
const text = await handleTranscribeStart(input);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -495,7 +579,7 @@ export function createServer(): McpServer {
);
// =============================================
- // Tool: job_status (generic poll — transcribe, render, batch, process_episode)
+ // Tool: job_status (generic poll: transcribe, render, batch, process_episode)
// =============================================
server.tool(
jobStatusToolDef.name,
@@ -507,6 +591,7 @@ export function createServer(): McpServer {
async (input) => {
try {
const text = await handleJobStatus(input);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -536,6 +621,7 @@ export function createServer(): McpServer {
async (input) => {
try {
const text = await handleProcessEpisode(input);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -556,6 +642,7 @@ export function createServer(): McpServer {
async (input) => {
try {
const text = await handleRankClipCandidates(input);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -569,7 +656,7 @@ export function createServer(): McpServer {
server.tool(
suggestClipsToolDef.name,
suggestClipsToolDef.description,
- suggestClipsInputShape,
+ suggestClipsInputFields,
async ({ suggestions }) => {
try {
const result = await handleSuggestClips({ suggestions });
@@ -587,14 +674,16 @@ export function createServer(): McpServer {
// Include clip history so Claude avoids duplicates
const existing = await history.list(20);
let text = await withKnowledge(result);
+
if (existing.length > 0) {
const summary = existing
.map(
(e) =>
- ` - "${e.title}" ${e.start_second}s–${e.end_second}s (${e.caption_style})`,
+ ` - "${e.title}" ${e.start_second}s-${e.end_second}s (${e.caption_style})`,
)
.join("\n");
- text += `\n\n[Previously Created Clips — avoid duplicates]\n${summary}`;
+
+ text += `\n\n[Previously Created Clips (avoid duplicates)]\n${summary}`;
}
const parsed2 = JSON.parse(result);
@@ -607,6 +696,7 @@ export function createServer(): McpServer {
" → To adjust: modify_clip(clip_number: N, updates: {start_second: ..., end_second: ...})\n" +
" → To remove one: toggle_clip(clip_number: N, selected: false)",
);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -723,12 +813,14 @@ export function createServer(): McpServer {
// Resolve asset names to paths
if (params.logo_path) {
const resolved = await assets.resolve(params.logo_path);
+
if (resolved) params.logo_path = resolved;
}
// Resolve clip_number from UI state BEFORE routing
let keepSegments: Array<{ start: number; end: number }> | null = null;
let hook: ClipHook | null = params.hook ?? null;
+
if (
params.clip_number != null &&
(params.start_second == null || params.end_second == null)
@@ -736,7 +828,8 @@ export function createServer(): McpServer {
const uiState = await readUIState();
const suggestions = uiState?.suggestions ?? [];
const settings = uiState?.settings ?? {};
- const idx = (params.clip_number as number) - 1;
+ const idx = params.clip_number - 1;
+
if (idx < 0 || idx >= suggestions.length) {
return {
content: [
@@ -747,25 +840,31 @@ export function createServer(): McpServer {
],
};
}
+
const suggestion = suggestions[idx];
+
if (params.start_second == null)
- params.start_second = suggestion.start_second as number;
+ params.start_second = suggestion.start_second;
+
if (params.end_second == null)
- params.end_second = suggestion.end_second as number;
+ params.end_second = suggestion.end_second;
+
if (!params.video_path)
- params.video_path = (uiState?.videoPath ||
- uiState?.filePath ||
- "") as string;
+ params.video_path = uiState?.videoPath || uiState?.filePath || "";
+
if (!params.title || params.title === "clip")
- params.title = (suggestion.title as string) || "clip";
+ params.title = suggestion.title || "clip";
+
if (!params.caption_style || params.caption_style === "hormozi") {
- params.caption_style =
- ((suggestion.suggested_caption_style as string) ||
- settings.captionStyle ||
- "hormozi") as typeof params.caption_style;
+ const style = suggestion.suggested_caption_style || settings.captionStyle;
+ const parsedStyle = captionStyleSchema.safeParse(style);
+
+ params.caption_style = parsedStyle.success ? parsedStyle.data : "hormozi";
}
+
if (!params.transcript_words) {
const transcript = uiState?.transcript;
+
if (transcript?.words) {
// handleCreateClip only runs this guard when transcript_words
// arrives null, so filling it from state here has to run the
@@ -773,33 +872,53 @@ export function createServer(): McpServer {
// would silently skip it.
const mismatch = transcriptVideoMismatch(
uiState?.transcriptVideoIdentity,
- params.video_path as string,
+ params.video_path ?? "",
);
+
if (mismatch) {
return { content: [{ type: "text" as const, text: mismatch }], isError: true };
}
+
params.transcript_words = transcript.words;
}
}
+
// Pull multi-cut segments from suggestion
- const segs = suggestion.segments as
- | Array<{ start: number; end: number }>
- | undefined;
+ const segs = suggestion.segments;
+
if (segs && segs.length > 0) {
keepSegments = segs;
}
+
if (params.hook === undefined && suggestion.hook) hook = suggestion.hook;
}
+ const videoPath = params.video_path;
+ const startSecond = params.start_second;
+ const endSecond = params.end_second;
+
+ if (!videoPath || startSecond === undefined || endSecond === undefined) {
+ return {
+ content: [
+ {
+ type: "text" as const,
+ text: "create_clip needs video_path, start_second, and end_second, or a clip_number from the current suggestions.",
+ },
+ ],
+ isError: true,
+ };
+ }
+
// Check for duplicates
const dup = await history.findDuplicate(
- params.video_path as string,
- params.start_second as number,
- params.end_second as number,
- (params.caption_style || "hormozi") as string,
- (params.crop_strategy || "speaker") as string,
- (params.format || "vertical") as string,
+ videoPath,
+ startSecond,
+ endSecond,
+ params.caption_style,
+ params.crop_strategy,
+ params.format,
);
+
if (dup) {
return {
content: [
@@ -814,6 +933,7 @@ export function createServer(): McpServer {
// Route through web server for real-time UI progress tracking
let usedWebServer = false;
let finalResult = "";
+
try {
const webRes = await fetch(`${webServerUrl}/api/mcp/export`, {
method: "POST",
@@ -824,7 +944,7 @@ export function createServer(): McpServer {
{
start_second: params.start_second,
end_second: params.end_second,
- title: (params.title || "clip") as string,
+ title: params.title,
caption_style: params.caption_style || "hormozi",
crop_strategy: params.crop_strategy || "speaker",
format: params.format || "vertical",
@@ -845,32 +965,40 @@ export function createServer(): McpServer {
write_clean_variant: params.write_clean_variant === true,
}),
});
+
if (webRes.ok) {
- const webData = (await webRes.json()) as WebJob;
+ const webData = webJobSchema.parse(await webRes.json());
const jobId = webData.job_id;
// Poll the job until completion (1 hour max)
const deadline = Date.now() + 3600_000;
let lostJob = false;
+
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 2000));
+
const pollRes = await fetch(
`${webServerUrl}/api/job/${jobId}`,
);
+
if (!pollRes.ok) {
lostJob = true;
break;
}
- const job = (await pollRes.json()) as WebJob;
+
+ const job = webJobSchema.parse(await pollRes.json());
+
if (job.status === "done") {
usedWebServer = true;
finalResult = JSON.stringify(job.result, null, 2);
break;
}
+
if (job.status === "error") {
throw new Error(job.error || "Job failed");
}
}
+
if (!usedWebServer) {
throw new Error(
lostJob
@@ -880,7 +1008,7 @@ export function createServer(): McpServer {
}
}
} catch (webErr: unknown) {
- if (!studioUnreachable(webErr, "create_clip")) throw webErr;
+ if (!studioUnreachable(webErr instanceof Error ? webErr.message : String(webErr), "create_clip")) throw webErr;
}
if (!usedWebServer) {
@@ -892,14 +1020,14 @@ export function createServer(): McpServer {
// Record to history
const rec = await history.record({
- source_video: params.video_path as string,
- start_second: params.start_second as number,
- end_second: params.end_second as number,
- caption_style: (params.caption_style || "hormozi") as string,
- crop_strategy: (params.crop_strategy || "speaker") as string,
- format: (params.format || "vertical") as Format,
- logo_path: params.logo_path as string | undefined,
- title: (params.title || "clip") as string,
+ source_video: videoPath,
+ start_second: startSecond,
+ end_second: endSecond,
+ caption_style: params.caption_style,
+ crop_strategy: params.crop_strategy,
+ format: params.format,
+ logo_path: params.logo_path,
+ title: params.title,
output_path: parsed.output_path,
file_size_mb: parsed.file_size_mb,
duration: parsed.duration,
@@ -909,12 +1037,13 @@ export function createServer(): McpServer {
context_line: parsed.context_line,
preview_text: parsed.preview_text,
});
+
const uiStateForRecipe = await readUIState().catch(() => null);
const recipeSettings = uiStateForRecipe?.settings ?? {};
await history.persistClipRecipe(rec, {
- transcriptWords: params.transcript_words as WordTimestamp[] | undefined,
- logoPath: (params.logo_path as string) || recipeSettings.logoPath || null,
- outroPath: (params.outro_path as string) || recipeSettings.outroPath || null,
+ transcriptWords: params.transcript_words,
+ logoPath: params.logo_path || recipeSettings.logoPath || null,
+ outroPath: params.outro_path || recipeSettings.outroPath || null,
introPath: recipeSettings.introPath || null,
cleanFillers: params.clean_fillers ?? recipeSettings.cleanFillers ?? true,
keepSegments: keepSegments ?? undefined,
@@ -932,6 +1061,7 @@ export function createServer(): McpServer {
" → List all outputs: list_outputs\n" +
' → Try a different style: create_clip(clip_number: N, caption_style: "karaoke")',
);
+
return { content: [{ type: "text" as const, text: clipText }] };
} catch (err: unknown) {
return mcpError(err);
@@ -1029,17 +1159,19 @@ export function createServer(): McpServer {
let resolvedClips = params.clips;
let resolvedVideoPath = params.video_path;
let resolvedTranscriptWords = params.transcript_words;
+
if (!resolvedClips && (params.export_selected || params.clip_numbers)) {
const uiState = await readUIState();
const suggestions = uiState?.suggestions ?? [];
const settings = uiState?.settings ?? {};
- const deselected = (uiState?.deselectedIndices as number[]) || [];
+ const deselected = uiState?.deselectedIndices ?? [];
+
if (!resolvedVideoPath)
- resolvedVideoPath = (uiState?.videoPath ||
- uiState?.filePath ||
- "") as string;
+ resolvedVideoPath = uiState?.videoPath || uiState?.filePath || "";
+
if (!resolvedTranscriptWords) {
const transcript = uiState?.transcript;
+
if (transcript?.words) {
// handleBatchClips only runs this guard when transcript_words
// arrives null, so filling it from state here has to run the
@@ -1047,11 +1179,13 @@ export function createServer(): McpServer {
// would silently skip it.
const mismatch = transcriptVideoMismatch(
uiState?.transcriptVideoIdentity,
- resolvedVideoPath as string,
+ resolvedVideoPath,
);
+
if (mismatch) {
return { content: [{ type: "text" as const, text: mismatch }], isError: true };
}
+
resolvedTranscriptWords = transcript.words;
}
}
@@ -1059,42 +1193,11 @@ export function createServer(): McpServer {
if (params.export_selected) {
resolvedClips = suggestions
.filter((_, i) => !deselected.includes(i))
- .map((s, i) => ({
- start_second: s.start_second,
- end_second: s.end_second,
- title: s.title || `clip_${i + 1}`,
- caption_style:
- s.suggested_caption_style ||
- settings.captionStyle ||
- "hormozi",
- crop_strategy: settings.cropStrategy || "speaker",
- format: settings.format || "vertical",
- allow_ass_fallback: false,
- ...(s.segments &&
- s.segments.length > 0 && { keep_segments: s.segments }),
- hook: s.hook ?? null,
- })) as any;
+ .map((s, i) => exportClipFromSuggestion(s, `clip_${i + 1}`, settings));
} else if (params.clip_numbers) {
- resolvedClips = (params.clip_numbers as number[])
+ resolvedClips = params.clip_numbers
.filter((n) => n >= 1 && n <= suggestions.length)
- .map((n) => {
- const s = suggestions[n - 1];
- return {
- start_second: s.start_second,
- end_second: s.end_second,
- title: s.title || `clip_${n}`,
- caption_style:
- s.suggested_caption_style ||
- settings.captionStyle ||
- "hormozi",
- crop_strategy: settings.cropStrategy || "speaker",
- format: settings.format || "vertical",
- allow_ass_fallback: false,
- ...(s.segments &&
- s.segments.length > 0 && { keep_segments: s.segments }),
- hook: s.hook ?? null,
- };
- }) as any;
+ .map((n) => exportClipFromSuggestion(suggestions[n - 1], `clip_${n}`, settings));
}
}
@@ -1102,6 +1205,7 @@ export function createServer(): McpServer {
// The web server handles SSE broadcasts (export-started, job-update, job-complete)
let usedWebServer = false;
let finalResult: string = "";
+
try {
const webRes = await fetch(`${webServerUrl}/api/mcp/export`, {
method: "POST",
@@ -1117,8 +1221,9 @@ export function createServer(): McpServer {
write_clean_variant: params.write_clean_variant === true,
}),
});
+
if (webRes.ok) {
- const webData = (await webRes.json()) as WebJob;
+ const webData = webJobSchema.parse(await webRes.json());
const jobId = webData.job_id;
// async_mode: return job_id immediately so the caller can narrate
@@ -1132,35 +1237,42 @@ export function createServer(): McpServer {
job_id: jobId,
status: "running",
clip_count: (resolvedClips || []).length,
- next_step: `Poll job_status("${jobId}", wait_seconds: 30) in a loop, emitting one terse progress line per poll (e.g. "Rendering 3/7 — clip #3"). Stop when done=true.`,
+ next_step: `Poll job_status("${jobId}", wait_seconds: 30) in a loop, emitting one terse progress line per poll (e.g. "Rendering 3/7, clip #3"). Stop when done=true.`,
}),
},
],
};
}
- // Sync path — poll internally until completion (1 hour max)
+ // Sync path: poll internally until completion (1 hour max)
const deadline = Date.now() + 3600_000;
let lostJob = false;
+
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 2000));
+
const pollRes = await fetch(
`${webServerUrl}/api/job/${jobId}`,
);
+
if (!pollRes.ok) {
lostJob = true;
break;
}
- const job = (await pollRes.json()) as WebJob;
+
+ const job = webJobSchema.parse(await pollRes.json());
+
if (job.status === "done") {
usedWebServer = true;
finalResult = JSON.stringify(job.result, null, 2);
break;
}
+
if (job.status === "error") {
throw new Error(job.error || "Job failed");
}
}
+
if (!usedWebServer) {
throw new Error(
lostJob
@@ -1170,7 +1282,7 @@ export function createServer(): McpServer {
}
}
} catch (webErr: unknown) {
- if (!studioUnreachable(webErr, "batch_create_clips")) throw webErr;
+ if (!studioUnreachable(webErr instanceof Error ? webErr.message : String(webErr), "batch_create_clips")) throw webErr;
}
if (!usedWebServer) {
@@ -1194,6 +1306,7 @@ export function createServer(): McpServer {
" → Find more moments: get_ui_state(include_transcript: true) and suggest_clips again\n" +
" → Re-export with different styles: update_settings then batch_create_clips(export_selected: true)",
);
+
return { content: [{ type: "text" as const, text: batchText }] };
} catch (err: unknown) {
// Notify UI of error
@@ -1202,6 +1315,7 @@ export function createServer(): McpServer {
err: err instanceof Error ? err.stack : String(err),
});
const msg = err instanceof Error ? err.message : String(err);
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -1233,6 +1347,7 @@ export function createServer(): McpServer {
try {
if (action === "read_all" || action === "list") {
const files = await kb.listFiles();
+
if (files.length === 0) {
return {
content: [
@@ -1243,15 +1358,20 @@ export function createServer(): McpServer {
],
};
}
+
const summaries: string[] = [];
+
for (const f of files) {
let preview = "";
+
try {
const content = await kb.readFile(f.filename);
+
// First non-empty, non-heading line as preview
const lines = content
.split("\n")
.filter((l: string) => l.trim() && !l.startsWith("#"));
+
preview = lines[0]?.trim().slice(0, 100) || "";
} catch (err) {
log.debug("Failed to read KB file for preview", {
@@ -1259,35 +1379,44 @@ export function createServer(): McpServer {
err: err instanceof Error ? err.message : String(err),
});
}
+
summaries.push(
`- ${f.filename} (updated ${f.updatedAt})${preview ? `\n ${preview}` : ""}`,
);
}
+
return {
content: [
{
type: "text" as const,
- text: `Knowledge base (${files.length} files) — use read action with filename to get full content:\n${summaries.join("\n")}`,
+ text: `Knowledge base (${files.length} files). Use the read action with filename to get full content:\n${summaries.join("\n")}`,
},
],
};
}
+
if (action === "read" && filename) {
const text = await kb.readFile(filename);
+
return { content: [{ type: "text" as const, text }] };
}
+
if (action === "write" && filename && content) {
await kb.writeFile(filename, content);
+
return {
content: [{ type: "text" as const, text: `Saved ${filename}` }],
};
}
+
if (action === "delete" && filename) {
await kb.deleteFile(filename);
+
return {
content: [{ type: "text" as const, text: `Deleted ${filename}` }],
};
}
+
return {
content: [
{
@@ -1335,19 +1464,24 @@ export function createServer(): McpServer {
try {
if (action === "list") {
const items = await assets.list(type || undefined);
+
if (items.length === 0)
return {
content: [
{ type: "text" as const, text: "No assets registered." },
],
};
+
const text = items
.map((a) => `- ${a.name} (${a.type})${a.default ? " [default]" : ""}: ${a.path}`)
.join("\n");
+
return { content: [{ type: "text" as const, text }] };
}
+
if (action === "register" && name && path) {
const asset = await assets.register(name, path, type || inferType(path));
+
return {
content: [
{
@@ -1357,8 +1491,10 @@ export function createServer(): McpServer {
],
};
}
+
if (action === "import" && path && name) {
const asset = await assets.importFile(path, name, type || inferType(path));
+
return {
content: [
{
@@ -1368,8 +1504,10 @@ export function createServer(): McpServer {
],
};
}
+
if (action === "import_url" && url && name) {
const asset = await assets.importUrl(url, name, type);
+
return {
content: [
{
@@ -1379,16 +1517,20 @@ export function createServer(): McpServer {
],
};
}
+
if (action === "unregister" && name) {
await assets.unregister(name);
+
return {
content: [
{ type: "text" as const, text: `Unregistered "${name}"` },
],
};
}
+
if (action === "resolve" && name) {
const resolved = await assets.resolve(name);
+
return {
content: [
{
@@ -1398,8 +1540,10 @@ export function createServer(): McpServer {
],
};
}
+
if (action === "set_default" && name) {
const asset = await assets.setDefault(name);
+
return {
content: [
{
@@ -1409,22 +1553,27 @@ export function createServer(): McpServer {
],
};
}
+
if (action === "clear_default" && name) {
await assets.clearDefault(name);
+
return {
content: [
{ type: "text" as const, text: `"${name}" is no longer a default.` },
],
};
}
+
if (action === "rename" && name && new_name) {
const asset = await assets.rename(name, new_name);
+
return {
content: [
{ type: "text" as const, text: `Renamed to "${asset.name}".` },
],
};
}
+
return {
content: [
{
@@ -1491,6 +1640,7 @@ export function createServer(): McpServer {
content: [{ type: "text" as const, text: "Provide clip_id to delete." }],
};
const removed = await history.remove(clip_id);
+
return {
content: [
{
@@ -1502,24 +1652,29 @@ export function createServer(): McpServer {
],
};
}
+
if (action === "list") {
const entries = source_video
? await history.getBySource(source_video)
: await history.list(limit || 20);
+
if (entries.length === 0)
return {
content: [
{ type: "text" as const, text: "No clips in history." },
],
};
+
const text = entries
.map(
(e) =>
- `- "${e.title}" ${e.start_second}s–${e.end_second}s | ${e.caption_style} | ${e.created_at} | ${e.output_path}`,
+ `- "${e.title}" ${e.start_second}s-${e.end_second}s | ${e.caption_style} | ${e.created_at} | ${e.output_path}`,
)
.join("\n");
+
return { content: [{ type: "text" as const, text }] };
}
+
if (
action === "check" &&
source_video &&
@@ -1534,6 +1689,7 @@ export function createServer(): McpServer {
crop_strategy || "speaker",
format || "vertical",
);
+
if (dup) {
return {
content: [
@@ -1544,6 +1700,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [
{
@@ -1553,6 +1710,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [
{
@@ -1579,7 +1737,7 @@ export function createServer(): McpServer {
"batch_create_clips(clip_numbers), modify_clip, and toggle_clip.\n\n" +
"Set include_transcript=true to analyze transcript content. Returns a compact phrase-grouped " +
"markdown view (~10x smaller than raw segments) with speaker attribution, silence gaps, and " +
- "optional energy peaks — the primary surface for reasoning about clip boundaries.",
+ "optional energy peaks: the primary surface for reasoning about clip boundaries.",
{
include_transcript: z
.boolean()
@@ -1592,14 +1750,17 @@ export function createServer(): McpServer {
async ({ include_transcript }) => {
try {
const state = await readUIState();
+
if (!state) {
const guidance = await getWorkflowGuidance();
+
return { content: [{ type: "text" as const, text: guidance }] };
}
const lines: string[] = [];
lines.push(`Phase: ${state.phase}`);
lines.push(`Video: ${state.videoPath || state.filePath || "(none)"}`);
+
if (state.videoMissing) {
lines.push(
"WARNING: the video file above was not found on disk at last check (e.g. an external " +
@@ -1607,6 +1768,7 @@ export function createServer(): McpServer {
"batch_create_clips will fail until the file is reachable again.",
);
}
+
lines.push(
`Settings: caption=${state.settings?.captionStyle}, crop=${state.settings?.cropStrategy}, logo=${state.settings?.logoPath || "none"}`,
);
@@ -1624,51 +1786,61 @@ export function createServer(): McpServer {
lines.push(
"Clips (use these numbers with create_clip/batch_create_clips):",
);
+
for (let i = 0; i < allSuggestions.length; i++) {
const clip = allSuggestions[i];
const num = i + 1;
const title = clip.title || "untitled";
const start = clip.start_second ?? "?";
const end = clip.end_second ?? "?";
+
const duration =
- typeof start === "number" && typeof end === "number"
+ clip.start_second !== undefined && clip.end_second !== undefined
? `${Math.round(end - start)}s`
: "?";
+
const style = clip.suggested_caption_style || "hormozi";
+
const tag = deselected.includes(i)
? " [DESELECTED]"
: clip.changedSinceSelection
? " [CHANGED SINCE SELECTION, re-confirm before exporting]"
: "";
+
lines.push(
- ` #${num}: "${title}" (${start}s–${end}s, ${duration}) [${style}]${tag}`,
+ ` #${num}: "${title}" (${start}s-${end}s, ${duration}) [${style}]${tag}`,
);
}
}
if (include_transcript) {
// Prefer packed markdown (10x smaller, phrase-grouped, LLM-readable).
- // Auto-generated during transcription — see backend/services/transcript_packer.py.
+ // Auto-generated during transcription: see backend/services/transcript_packer.py.
let packed: string | null = null;
+
if (state.videoPath) {
packed = await transcriptCache.getPackedMarkdown(
state.videoPath,
state.transcript?.engine,
);
}
+
if (!packed && state.rawTranscriptText) {
packed = await transcriptCache.getPackedMarkdownFromText(
state.rawTranscriptText,
);
}
+
if (packed) {
lines.push("");
lines.push("=== PACKED TRANSCRIPT ===");
lines.push(packed);
} else if (state.transcript) {
const segments = state.transcript.segments || [];
+
if (segments.length) {
const segLines: string[] = [];
+
for (const seg of segments) {
const speaker = seg.speaker || "?";
const start = Math.floor(seg.start || 0);
@@ -1676,6 +1848,7 @@ export function createServer(): McpServer {
const text = seg.text || "";
segLines.push(`[${start}s-${end}s] ${speaker}: ${text}`);
}
+
lines.push("");
lines.push("=== TRANSCRIPT ===");
lines.push(capTranscriptText(segLines.join("\n")));
@@ -1683,7 +1856,7 @@ export function createServer(): McpServer {
} else if (state.rawTranscriptText) {
lines.push("");
lines.push(
- "=== RAW TRANSCRIPT (not yet parsed — use this to analyze and suggest clips) ===",
+ "=== RAW TRANSCRIPT (not yet parsed: use this to analyze and suggest clips) ===",
);
lines.push(capTranscriptText(state.rawTranscriptText));
}
@@ -1698,6 +1871,7 @@ export function createServer(): McpServer {
return { content: [{ type: "text" as const, text: lines.join("\n") }] };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
return {
content: [
{ type: "text" as const, text: `Error reading UI state: ${msg}` },
@@ -1771,7 +1945,8 @@ export function createServer(): McpServer {
// Mutate server-side so concurrent edits aren't lost to a wholesale
// state replace (clip_number is 1-based).
- const body: Record<string, unknown> = { action, updates };
+ const body: SuggestionsModifyBody = { action, updates };
+
if (clip_number !== undefined) body.index = clip_number - 1;
else if (clip_id) body.clip_id = clip_id;
else if (index !== undefined) body.index = index;
@@ -1781,11 +1956,9 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
- const data = (await res.json()) as ApiError & {
- index: number;
- clip: SuggestedClip;
- total: number;
- };
+
+ const data = clipEditResultSchema.parse(await res.json());
+
if (!res.ok || data.error) {
if (res.status === 404) {
return {
@@ -1797,6 +1970,7 @@ export function createServer(): McpServer {
],
};
}
+
throw new Error(data.error || `HTTP ${res.status}`);
}
@@ -1824,6 +1998,7 @@ export function createServer(): McpServer {
};
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -1834,6 +2009,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -1867,7 +2043,8 @@ export function createServer(): McpServer {
try {
// Mutate server-side so concurrent edits aren't lost to a wholesale
// state replace (clip_number is 1-based).
- const body: Record<string, unknown> = { action: "toggle", selected };
+ const body: SuggestionsModifyBody = { action: "toggle", selected };
+
if (clip_number !== undefined) body.index = clip_number - 1;
else if (clip_id) body.clip_id = clip_id;
else if (index !== undefined) body.index = index;
@@ -1877,12 +2054,9 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
- const data = (await res.json()) as ApiError & {
- index: number;
- clip: SuggestedClip;
- total: number;
- selectedCount: number;
- };
+
+ const data = clipEditResultSchema.parse(await res.json());
+
if (!res.ok || data.error) {
if (res.status === 404) {
return {
@@ -1894,6 +2068,7 @@ export function createServer(): McpServer {
],
};
}
+
throw new Error(data.error || `HTTP ${res.status}`);
}
@@ -1907,6 +2082,7 @@ export function createServer(): McpServer {
};
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -1917,6 +2093,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -1956,16 +2133,21 @@ export function createServer(): McpServer {
async ({ caption_style, crop_strategy, logo_path, outro_path, intro_path }) => {
try {
const settings: Record<string, string> = {};
+
if (caption_style) settings.captionStyle = caption_style;
+
if (crop_strategy) settings.cropStrategy = crop_strategy;
+
if (logo_path) {
const resolved = await assets.resolve(logo_path);
settings.logoPath = resolved || logo_path;
}
+
if (outro_path) {
const resolved = await assets.resolve(outro_path);
settings.outroPath = resolved || outro_path;
}
+
if (intro_path) {
const resolved = await assets.resolve(intro_path);
settings.introPath = resolved || intro_path;
@@ -1989,6 +2171,7 @@ export function createServer(): McpServer {
});
const parts = Object.entries(settings).map(([k, v]) => `${k}=${v}`);
+
return {
content: [
{
@@ -1999,6 +2182,7 @@ export function createServer(): McpServer {
};
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2009,6 +2193,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2035,8 +2220,10 @@ export function createServer(): McpServer {
async ({ video_path, clip_count, clip_duration_min, clip_duration_max, caption_style, captions_enabled, language, thumbnails_wanted, delivery_target, notes }) => {
try {
const keyPath = await resolveEpisodeKeyPath(video_path);
- const decisions: Record<string, unknown> = {};
+ const decisions: RecordedDecisions = {};
+
if (clip_count !== undefined) decisions.clipCount = clip_count;
+
if (clip_duration_min !== undefined || clip_duration_max !== undefined) {
const existing = await episodeState.get(keyPath);
// A side nobody gave stays absent; 0 would read as a real limit.
@@ -2047,11 +2234,17 @@ export function createServer(): McpServer {
...(max !== undefined && { max }),
};
}
+
if (caption_style !== undefined) decisions.captionStyle = caption_style;
+
if (captions_enabled !== undefined) decisions.captionsEnabled = captions_enabled;
+
if (language !== undefined) decisions.language = language;
+
if (thumbnails_wanted !== undefined) decisions.thumbnailsWanted = thumbnails_wanted;
+
if (delivery_target !== undefined) decisions.deliveryTarget = delivery_target;
+
if (notes !== undefined) decisions.notes = notes;
if (Object.keys(decisions).length === 0) {
@@ -2062,16 +2255,20 @@ export function createServer(): McpServer {
const recorded = await episodeState.record(keyPath, decisions);
const remaining = await episodeState.openQuestions(keyPath);
+
const lines = [
`Recorded: ${Object.keys(decisions).join(", ")}`,
remaining.length > 0
? `Still open: ${remaining.map((q) => q.question).join(" / ")}`
: "All episode decisions answered.",
];
+
void recorded;
+
return { content: [{ type: "text" as const, text: lines.join("\n") }] };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
return {
content: [{ type: "text" as const, text: `Error recording decisions: ${msg}` }],
isError: true,
@@ -2090,8 +2287,9 @@ export function createServer(): McpServer {
async () => {
try {
const res = await fetch(`${webServerUrl}/api/outputs`);
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const clips = (await res.json()) as OutputClip[];
+ const clips = outputClipsSchema.parse(await res.json());
if (!clips.length) {
return {
@@ -2103,6 +2301,7 @@ export function createServer(): McpServer {
const lines = clips.map((c) => {
const date = c.created ? c.created.split("T")[0] : "unknown";
+
return ` - ${c.filename} (${c.size_mb} MB, ${date})`;
});
@@ -2116,6 +2315,7 @@ export function createServer(): McpServer {
};
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2126,6 +2326,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2179,8 +2380,9 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action, name, config }),
});
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = (await res.json()) as PresetResult;
+ const data = presetResultSchema.parse(await res.json());
if (data.error) {
return {
@@ -2191,15 +2393,17 @@ export function createServer(): McpServer {
if (action === "list") {
const presets = data.presets ?? [];
+
if (!presets.length)
return {
content: [{ type: "text" as const, text: "No presets saved." }],
};
+
return {
content: [
{
type: "text" as const,
- text: `Presets:\n${presets.map((p) => ` - ${typeof p === "string" ? p : p.name || JSON.stringify(p)}`).join("\n")}`,
+ text: `Presets:\n${presets.map((p) => ` - ${p instanceof Object ? p.name || JSON.stringify(p) : p}`).join("\n")}`,
},
],
};
@@ -2208,13 +2412,18 @@ export function createServer(): McpServer {
if (action === "load" && data.config) {
// Push loaded config to UI settings
const settings: Record<string, string> = {};
+
if (data.config.caption_style)
settings.captionStyle = data.config.caption_style;
+
if (data.config.crop_strategy)
settings.cropStrategy = data.config.crop_strategy;
+
if (data.config.logo_path) settings.logoPath = data.config.logo_path;
+
if (data.config.outro_path)
settings.outroPath = data.config.outro_path;
+
if (Object.keys(settings).length) {
await fetch(`${webServerUrl}/api/ui-state`, {
method: "POST",
@@ -2222,6 +2431,7 @@ export function createServer(): McpServer {
body: JSON.stringify({ settings }),
});
}
+
return {
content: [
{
@@ -2253,6 +2463,7 @@ export function createServer(): McpServer {
};
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2263,6 +2474,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2290,46 +2502,67 @@ export function createServer(): McpServer {
if ((action === "export" || action === "import") && !filePath) {
return mcpError(`'path' is required for action '${action}'.`);
}
+
if (action === "set_layout" && !layout) {
return mcpError("'layout' is required for action 'set_layout': 'single' or 'pair'.");
}
+
const base = `${webServerUrl}/api/thumbnail-config`;
+
if (action === "set_layout") {
const current = await fetch(base);
+
if (!current.ok) throw new Error(`HTTP ${current.status}`);
+
const res = await fetch(base, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...(await current.json()), layout }),
});
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
+
return { content: [{ type: "text" as const, text: `Thumbnail layout set to ${layout}.` }] };
}
+
if (action === "show") {
const res = await fetch(base);
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
+
return { content: [{ type: "text" as const, text: JSON.stringify(await res.json(), null, 2) }] };
}
+
if (action === "export") {
const res = await fetch(base);
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
writeFileSync(filePath!, JSON.stringify(await res.json(), null, 2), "utf-8");
+
return { content: [{ type: "text" as const, text: `Exported thumbnail config to ${filePath}` }] };
}
+
if (action === "import") {
const parsed = JSON.parse(readFileSync(filePath!, "utf-8"));
const res = await fetch(base, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(parsed) });
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
+
return { content: [{ type: "text" as const, text: `Imported thumbnail config from ${filePath}` }] };
}
+
const res = await fetch(`${base}/reset`, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
+
return { content: [{ type: "text" as const, text: "Reset thumbnail config to the generic default." }] };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return { content: [{ type: "text" as const, text: `Web UI is not running. Start with: ${studioStartCommand()}` }] };
}
+
return mcpError(msg);
}
},
@@ -2366,9 +2599,13 @@ export function createServer(): McpServer {
// If no video_path, read from UI state
if (!vPath || !segs) {
const stateRes = await fetch(`${webServerUrl}/api/ui-state`);
+
if (stateRes.ok) {
- const state = (await stateRes.json()) as ServerUIState;
+ const state = // SAFETY: /api/ui-state responds with the studio's UIState plus transcriptWordCount.
+ (await stateRes.json()) as ServerUIState;
+
if (!vPath) vPath = state.videoPath || state.filePath;
+
if (!segs) {
const suggestions = state.suggestions ?? [];
segs = suggestions.map((s) => ({
@@ -2406,8 +2643,9 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ video_path: vPath, segments: segs }),
});
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = (await res.json()) as ApiError & Record<string, unknown>;
+ const data = apiResponseSchema.parse(await res.json());
if (data.error) {
return {
@@ -2423,6 +2661,7 @@ export function createServer(): McpServer {
};
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2433,6 +2672,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2510,14 +2750,17 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
});
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = (await res.json()) as ApiError & Record<string, unknown>;
+ const data = apiResponseSchema.parse(await res.json());
+
if (data.error) {
return {
content: [{ type: "text" as const, text: `Error: ${data.error}` }],
isError: true,
};
}
+
return {
content: [
{ type: "text" as const, text: JSON.stringify(data, null, 2) },
@@ -2525,6 +2768,7 @@ export function createServer(): McpServer {
};
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2535,6 +2779,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2643,31 +2888,39 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
});
- const data = (await res.json()) as ApiError & Record<string, unknown>;
+
+ const data = apiResponseSchema.parse(await res.json());
+
if (data.error) {
return {
content: [{ type: "text" as const, text: `Error: ${data.error}` }],
isError: true,
};
}
- const validation = (data.outputs as { validation?: { warnings?: string[] } } | undefined)?.validation;
+
+ const validation = data.outputs?.validation;
+
const warnings = validation?.warnings?.length
? `\n\n[Render warnings]\n${validation.warnings.map((w) => ` - ${w}`).join("\n")}`
: "";
- const text = typeof data.job_id === "string"
+
+ const text = data.job_id !== undefined
? withNextStep(
JSON.stringify(data, null, 2),
`Poll job_status("${data.job_id}", wait_seconds: 30) until done, then manage_multicam(action: "show", session_id) to read the result.`,
)
: JSON.stringify(data, null, 2) + warnings;
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [{ type: "text" as const, text: `Web UI is not running. Start with: ${studioStartCommand()}` }],
};
}
+
return mcpError(err);
}
},
@@ -2691,8 +2944,10 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ file_path }),
});
+
if (!selectRes.ok) {
- const err = (await selectRes.json()) as ApiError;
+ const err = apiErrorSchema.parse(await selectRes.json());
+
return {
content: [
{
@@ -2703,7 +2958,8 @@ export function createServer(): McpServer {
isError: true,
};
}
- const fileInfo = (await selectRes.json()) as FileInfo;
+
+ const fileInfo = fileInfoSchema.parse(await selectRes.json());
// Push to UI state
await fetch(`${webServerUrl}/api/ui-state`, {
@@ -2717,9 +2973,11 @@ export function createServer(): McpServer {
`Now transcribe it: transcribe_podcast(file_path: "${file_path}")\n` +
" Or if the user pastes a transcript in the UI, read it with get_ui_state(include_transcript: true)",
);
+
return { content: [{ type: "text" as const, text: setText }] };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2730,6 +2988,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2784,8 +3043,10 @@ export function createServer(): McpServer {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ file_path, transcript }),
});
+
if (!res.ok) {
- const err = (await res.json()) as ApiError;
+ const err = apiErrorSchema.parse(await res.json());
+
return {
content: [
{
@@ -2796,7 +3057,8 @@ export function createServer(): McpServer {
isError: true,
};
}
- const result = (await res.json()) as ImportTranscriptResult;
+
+ const result = importTranscriptResultSchema.parse(await res.json());
// Push transcript to UI state
await fetch(`${webServerUrl}/api/ui-state`, {
@@ -2813,14 +3075,17 @@ export function createServer(): McpServer {
const wordCount = result.data?.words?.length || 0;
const duration = result.data?.duration || 0;
+
const importText = withNextStep(
`Transcript imported: ${wordCount} words, ${Math.round(duration)}s duration.`,
"Now read the transcript with get_ui_state(include_transcript: true), " +
"analyze it for viral moments, then call suggest_clips with your picks.",
);
+
return { content: [{ type: "text" as const, text: importText }] };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2831,6 +3096,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2880,8 +3146,10 @@ export function createServer(): McpServer {
language,
}),
});
+
if (!res.ok) {
- const err = (await res.json()) as ApiError;
+ const err = apiErrorSchema.parse(await res.json());
+
return {
content: [
{
@@ -2892,7 +3160,8 @@ export function createServer(): McpServer {
isError: true,
};
}
- const result = (await res.json()) as ImportTranscriptResult;
+
+ const result = importTranscriptResultSchema.parse(await res.json());
// Push parsed transcript to UI state
await fetch(`${webServerUrl}/api/ui-state`, {
@@ -2909,14 +3178,17 @@ export function createServer(): McpServer {
const wordCount = result.data?.words?.length || 0;
const segCount = result.data?.segments?.length || 0;
+
const parseText = withNextStep(
`Transcript parsed: ${wordCount} words, ${segCount} segments.`,
"Now read the transcript with get_ui_state(include_transcript: true), " +
"analyze it for viral moments, then call suggest_clips with your picks.",
);
+
return { content: [{ type: "text" as const, text: parseText }] };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
+
if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
return {
content: [
@@ -2927,6 +3199,7 @@ export function createServer(): McpServer {
],
};
}
+
return {
content: [{ type: "text" as const, text: `Error: ${msg}` }],
isError: true,
@@ -2962,6 +3235,7 @@ export function createServer(): McpServer {
async (input) => {
try {
const text = await handleMineChannel(input);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -2995,6 +3269,7 @@ export function createServer(): McpServer {
async (input) => {
try {
const text = await handleCompareEngines(input);
+
return { content: [{ type: "text" as const, text }] };
} catch (err: unknown) {
return mcpError(err);
@@ -3009,7 +3284,7 @@ export function createServer(): McpServer {
// =============================================
server.prompt(
"workflow",
- "Complete podcli workflow guide — from podcast file to finished clips",
+ "Complete podcli workflow guide: from podcast file to finished clips",
async () => ({
messages: [
{
diff --git a/src/services/asset-manager.test.ts b/src/services/asset-manager.test.ts
index 22b48f3..5ec1c98 100644
--- a/src/services/asset-manager.test.ts
+++ b/src/services/asset-manager.test.ts
@@ -4,7 +4,9 @@ import { tmpdir } from "os";
import { join } from "path";
const tmp = mkdtempSync(join(tmpdir(), "podcli-assets-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
const { AssetManager } = await import("./asset-manager.js");
@@ -12,6 +14,7 @@ const { AssetManager } = await import("./asset-manager.js");
function makeFile(name: string): string {
const p = join(tmp, name);
writeFileSync(p, "stub");
+
return p;
}
diff --git a/src/services/asset-manager.ts b/src/services/asset-manager.ts
index 1bbf978..1f0ec09 100644
--- a/src/services/asset-manager.ts
+++ b/src/services/asset-manager.ts
@@ -4,6 +4,7 @@ import { join, extname } from "path";
import { spawn } from "child_process";
import { Readable } from "stream";
import { pipeline } from "stream/promises";
+import { z } from "zod";
import { paths, pythonEnv } from "../config/paths.js";
import { ASSETS_SCHEMA_VERSION } from "../models/index.js";
import type { Asset, AssetType, AssetRegistry } from "../models/index.js";
@@ -13,14 +14,35 @@ const VIDEO_EXTS = new Set([".mp4", ".mov", ".mkv", ".webm", ".m4v"]);
const IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".svg", ".webp", ".gif"]);
const AUDIO_EXTS = new Set([".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg"]);
+export const assetTypeSchema = z.enum(["logo", "outro", "intro", "music", "video", "image", "audio", "other"]);
+
+// Registries predate schemaVersion and were once a bare array, so each field is read leniently.
+const registryFileSchema = z.union([
+ z.array(z.unknown()).transform((assets) => ({ schemaVersion: undefined, assets })),
+ z.looseObject({ schemaVersion: z.number().optional(), assets: z.array(z.unknown()).catch([]) }),
+]);
+
+const registryAssetSchema = z.looseObject({
+ name: z.string(),
+ type: assetTypeSchema.catch("other"),
+ path: z.string(),
+ addedAt: z.string().default(""),
+ default: z.boolean().optional(),
+});
+
export const DEFAULTABLE_TYPES: AssetType[] = ["logo", "outro", "intro", "music"];
export function inferType(filePath: string): AssetType {
const ext = extname(filePath).toLowerCase();
+
if (ext === ".png" || ext === ".svg") return "logo";
+
if (IMAGE_EXTS.has(ext)) return "image";
+
if (VIDEO_EXTS.has(ext)) return "video";
+
if (AUDIO_EXTS.has(ext)) return "audio";
+
return "other";
}
@@ -41,23 +63,33 @@ export class AssetManager {
async load(): Promise<AssetRegistry> {
let registry: AssetRegistry;
+
try {
if (!existsSync(this.registryPath)) return { schemaVersion: ASSETS_SCHEMA_VERSION, assets: [] };
const raw = await readFile(this.registryPath, "utf-8");
- const parsed = JSON.parse(raw);
- const bag = Array.isArray(parsed) ? { assets: parsed } : (parsed ?? {});
- registry = { ...bag, assets: Array.isArray(bag.assets) ? bag.assets : [] } as AssetRegistry;
+ const file = registryFileSchema.parse(JSON.parse(raw));
+ registry = {
+ schemaVersion: file.schemaVersion,
+ assets: file.assets.flatMap((a) => {
+ const parsed = registryAssetSchema.safeParse(a);
+
+ return parsed.success ? [parsed.data] : [];
+ }),
+ };
} catch {
return { schemaVersion: ASSETS_SCHEMA_VERSION, assets: [] };
}
+
const { registry: migrated, changed } = migrate(registry);
+
if (changed) {
try {
await this.save(migrated);
} catch {
- // Read-only filesystem or a racing writer — serve the migrated view anyway.
+ // Read-only filesystem or a racing writer: serve the migrated view anyway.
}
}
+
return migrated;
}
@@ -73,23 +105,28 @@ export class AssetManager {
if (!existsSync(filePath)) {
throw new Error(`File not found: ${filePath}`);
}
+
const name = safeName(rawName);
const registry = await this.load();
const existing = registry.assets.findIndex((a) => a.name === name);
const prior = existing >= 0 ? registry.assets[existing] : undefined;
+
const asset: Asset = {
name,
type,
path: filePath,
addedAt: prior?.addedAt ?? new Date().toISOString(),
- ...(prior?.default ? { default: true } : {}),
+ ...(prior?.default && { default: true }),
};
+
if (existing >= 0) {
registry.assets[existing] = asset;
} else {
registry.assets.push(asset);
}
+
await this.save(registry);
+
return asset;
}
@@ -101,25 +138,32 @@ export class AssetManager {
async list(type?: string): Promise<Asset[]> {
const registry = await this.load();
+
if (type) return registry.assets.filter((a) => a.type === type);
+
return registry.assets;
}
async setDefault(name: string): Promise<Asset> {
const registry = await this.load();
const target = registry.assets.find((a) => a.name === name);
+
if (!target) throw new Error(`Asset not found: ${name}`);
+
for (const a of registry.assets) {
if (sameDefaultGroup(a.type, target.type)) delete a.default;
}
+
target.default = true;
await this.save(registry);
+
return target;
}
async clearDefault(name: string): Promise<void> {
const registry = await this.load();
const target = registry.assets.find((a) => a.name === name);
+
if (target) {
delete target.default;
await this.save(registry);
@@ -128,15 +172,20 @@ export class AssetManager {
async rename(name: string, newName: string): Promise<Asset> {
const trimmed = safeName(newName);
+
if (!trimmed) throw new Error("New name is required");
const registry = await this.load();
const target = registry.assets.find((a) => a.name === name);
+
if (!target) throw new Error(`Asset not found: ${name}`);
+
if (trimmed !== name && registry.assets.some((a) => a.name === trimmed)) {
throw new Error(`An asset named "${trimmed}" already exists`);
}
+
target.name = trimmed;
await this.save(registry);
+
return target;
}
@@ -144,8 +193,10 @@ export class AssetManager {
const registry = await this.load();
const group = registry.assets.filter((a) => sameDefaultGroup(a.type, type));
const flagged = group.find((a) => a.default && existsSync(a.path));
+
if (flagged) return flagged.path;
const firstExisting = group.find((a) => existsSync(a.path));
+
return firstExisting ? firstExisting.path : null;
}
@@ -153,8 +204,11 @@ export class AssetManager {
if (!nameOrPath) return null;
const registry = await this.load();
const asset = registry.assets.find((a) => a.name === nameOrPath);
+
if (asset && existsSync(asset.path)) return asset.path;
+
if (existsSync(nameOrPath)) return nameOrPath;
+
return null;
}
@@ -162,15 +216,18 @@ export class AssetManager {
await this.ensureDir();
const destPath = join(this.assetsDir, safeAssetFilename(name, sourcePath));
await copyFile(sourcePath, destPath);
+
return this.register(name, destPath, type);
}
async importUrl(url: string, name: string, type?: AssetType): Promise<Asset> {
assertSafeUrl(url);
await this.ensureDir();
+
const destPath = looksLikeDirectFile(url)
? await downloadDirect(url, join(this.assetsDir, safeAssetFilename(name, url)))
: await downloadWithYtDlp(url, this.assetsDir, name);
+
// Infer from the downloaded file, not the URL (query strings break extname).
return this.register(name, destPath, type ?? inferType(destPath));
}
@@ -183,37 +240,51 @@ export function safeName(name: string): string {
function sameDefaultGroup(a: string, b: string): boolean {
if (isOutroType(a) && isOutroType(b)) return true;
+
return a === b;
}
-export function migrate(registry: AssetRegistry): { registry: AssetRegistry; changed: boolean } {
+interface MigrationResult {
+ registry: AssetRegistry;
+ changed: boolean;
+}
+
+export function migrate(registry: AssetRegistry): MigrationResult {
let changed = false;
+
if (registry.schemaVersion !== ASSETS_SCHEMA_VERSION) changed = true;
const now = new Date().toISOString();
+
for (const asset of registry.assets) {
if (asset.type === "video") {
asset.type = "outro";
changed = true;
}
+
if (!asset.addedAt) {
asset.addedAt = now;
changed = true;
}
}
+
registry.schemaVersion = ASSETS_SCHEMA_VERSION;
+
return { registry, changed };
}
function safeAssetFilename(name: string, source: string): string {
const slug = name.replace(/[^a-zA-Z0-9._-]/g, "_") || "asset";
let ext = extname(new URL(source, "file://localhost/").pathname || source).toLowerCase();
+
if (!ext) ext = extname(source).toLowerCase();
+
return slug + ext;
}
function looksLikeDirectFile(url: string): boolean {
try {
const ext = extname(new URL(url).pathname).toLowerCase();
+
return IMAGE_EXTS.has(ext) || AUDIO_EXTS.has(ext) || VIDEO_EXTS.has(ext);
} catch {
return false;
@@ -225,24 +296,28 @@ const DOWNLOAD_TIMEOUT_MS = 120_000;
/** Basic SSRF guard: only http(s), and reject obvious localhost/private hosts. */
function assertSafeUrl(url: string): void {
let parsed: URL;
+
try {
parsed = new URL(url);
} catch {
throw new Error(`Invalid URL: ${url}`);
}
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error(`Unsupported URL protocol: ${parsed.protocol}`);
}
+
const host = parsed.hostname.toLowerCase();
+
if (
host === "localhost" ||
host === "0.0.0.0" ||
host === "::1" ||
host.endsWith(".localhost") ||
- /^127\./.test(host) ||
- /^10\./.test(host) ||
- /^192\.168\./.test(host) ||
- /^169\.254\./.test(host) ||
+ host.startsWith('127.') ||
+ host.startsWith('10.') ||
+ host.startsWith('192.168.') ||
+ host.startsWith('169.254.') ||
/^172\.(1[6-9]|2\d|3[01])\./.test(host)
) {
throw new Error(`Refusing to download from a private/loopback host: ${host}`);
@@ -252,15 +327,19 @@ function assertSafeUrl(url: string): void {
async function downloadDirect(url: string, destPath: string): Promise<string> {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), DOWNLOAD_TIMEOUT_MS);
+
try {
const res = await fetch(url, { redirect: "follow", signal: ac.signal });
+
if (!res.ok || !res.body) {
throw new Error(`Download failed (${res.status}) for ${url}`);
}
+
// pipeline rejects on source errors too, so a dropped connection can't
// throw an uncaught 'error' and crash the server.
// @ts-expect-error - Web ReadableStream is accepted by Node's fromWeb.
await pipeline(Readable.fromWeb(res.body), createWriteStream(destPath));
+
return destPath;
} finally {
clearTimeout(timer);
@@ -269,6 +348,7 @@ async function downloadDirect(url: string, destPath: string): Promise<string> {
function downloadWithYtDlp(url: string, destDir: string, name: string): Promise<string> {
const slug = name.replace(/[^a-zA-Z0-9._-]/g, "_") || "asset";
+
const args = buildYtDlpArgs({
url,
outputDir: destDir,
@@ -278,6 +358,7 @@ function downloadWithYtDlp(url: string, destDir: string, name: string): Promise<
cookiesFromBrowser: (process.env.PODCLI_YTDLP_BROWSER || "").trim().toLowerCase() || undefined,
extractorArgs: process.env.PODCLI_YT_EXTRACTOR_ARGS || undefined,
});
+
return new Promise((resolveP, rejectP) => {
const proc = spawn(paths.pythonPath, args, { env: pythonEnv() });
let stdout = "";
@@ -285,8 +366,10 @@ function downloadWithYtDlp(url: string, destDir: string, name: string): Promise<
let filePath = "";
proc.stdout.on("data", (c: Buffer) => {
stdout += c.toString();
+
for (const line of c.toString().split(/\r?\n/)) {
const t = line.trim();
+
if (t.startsWith("podcli-filepath:")) filePath = t.slice("podcli-filepath:".length);
}
});
@@ -294,9 +377,11 @@ function downloadWithYtDlp(url: string, destDir: string, name: string): Promise<
proc.on("error", (err) => rejectP(err));
proc.on("close", (code) => {
if (code !== 0) return rejectP(new Error(`yt-dlp failed for ${url}: ${stderr.slice(-800)}`));
+
if (!filePath || !existsSync(filePath)) {
return rejectP(new Error(`yt-dlp reported no output file for ${url}. ${stdout.slice(-400)}`));
}
+
resolveP(filePath);
});
});
diff --git a/src/services/asset-sync.test.ts b/src/services/asset-sync.test.ts
index 3332256..95a7c42 100644
--- a/src/services/asset-sync.test.ts
+++ b/src/services/asset-sync.test.ts
@@ -3,23 +3,25 @@ import { createHash } from "crypto";
import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import type { AssetCloud } from "./asset-sync.js";
const tmp = mkdtempSync(join(tmpdir(), "podcli-assetsync-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
const digest = (body: string) =>
createHash("sha256").update(Buffer.from(body)).digest("hex").slice(0, 32);
-vi.mock("./podcli-cloud.js", () => ({
- signedIn: vi.fn(async () => true),
- listAssets: vi.fn(async () => []),
- uploadAsset: vi.fn(async () => ({ unchanged: false })),
- checksum: (body: Buffer) =>
- createHash("sha256").update(body).digest("hex").slice(0, 32),
-}));
+const cloud = {
+ signedIn: vi.fn<AssetCloud["signedIn"]>(),
+ listAssets: vi.fn<AssetCloud["listAssets"]>(),
+ uploadAsset: vi.fn<AssetCloud["uploadAsset"]>(),
+ downloadAsset: vi.fn<AssetCloud["downloadAsset"]>(),
+ checksum: (body: Buffer) => createHash("sha256").update(body).digest("hex").slice(0, 32),
+} satisfies AssetCloud;
-const cloud = await import("./podcli-cloud.js");
const { push } = await import("./asset-sync.js");
const { AssetManager } = await import("./asset-manager.js");
@@ -32,17 +34,19 @@ describe("asset push", () => {
mkdirSync(join(tmp, "assets"), { recursive: true });
writeFileSync(intro, "intro bytes");
vi.clearAllMocks();
- vi.mocked(cloud.signedIn).mockResolvedValue(true);
+ cloud.signedIn.mockResolvedValue(true);
+ cloud.listAssets.mockResolvedValue([]);
+ cloud.uploadAsset.mockResolvedValue({ id: "new", unchanged: false });
assetName = (await new AssetManager().register("Show intro", intro, "intro")).name;
});
it("does not re-upload an asset the workspace already holds", async () => {
- vi.mocked(cloud.listAssets).mockResolvedValue([
+ cloud.listAssets.mockResolvedValue([
{ id: "1", name: assetName, kind: "intro", is_default: false,
size_bytes: "11", checksum: digest("intro bytes") },
]);
- const report = await push();
+ const report = await push(cloud);
expect(cloud.uploadAsset).not.toHaveBeenCalled();
expect(report.skipped).toContain(assetName);
@@ -50,21 +54,21 @@ describe("asset push", () => {
});
it("uploads when the local file has changed", async () => {
- vi.mocked(cloud.listAssets).mockResolvedValue([
+ cloud.listAssets.mockResolvedValue([
{ id: "1", name: assetName, kind: "intro", is_default: false,
size_bytes: "11", checksum: digest("something else") },
]);
- const report = await push();
+ const report = await push(cloud);
expect(cloud.uploadAsset).toHaveBeenCalledTimes(1);
expect(report.uploaded).toContain(assetName);
});
it("still uploads when the listing cannot be read", async () => {
- vi.mocked(cloud.listAssets).mockRejectedValue(new Error("offline"));
+ cloud.listAssets.mockRejectedValue(new Error("offline"));
- const report = await push();
+ const report = await push(cloud);
expect(cloud.uploadAsset).toHaveBeenCalledTimes(1);
expect(report.failed).toEqual([]);
diff --git a/src/services/asset-sync.ts b/src/services/asset-sync.ts
index 6265da1..6f2702f 100644
--- a/src/services/asset-sync.ts
+++ b/src/services/asset-sync.ts
@@ -1,10 +1,11 @@
import { existsSync } from "fs";
import { mkdir, readFile, writeFile } from "fs/promises";
import { join } from "path";
+import { z } from "zod";
import { paths } from "../config/paths.js";
import { AssetManager, inferType } from "./asset-manager.js";
import * as cloud from "./podcli-cloud.js";
-import type { Asset, AssetType } from "../models/index.js";
+import type { AssetType } from "../models/index.js";
/**
* Two-way sync between .podcli/assets/ and the workspace asset library.
@@ -14,15 +15,15 @@ import type { Asset, AssetType } from "../models/index.js";
* show's logo and outro without anyone emailing files around.
*/
-const SYNCABLE_KINDS: Record<AssetType, string> = {
- logo: "logo",
- intro: "intro",
- outro: "outro",
- music: "music",
-} as Record<AssetType, string>;
+const SYNCABLE_KINDS = new Map<AssetType, string>([
+ ["logo", "logo"],
+ ["intro", "intro"],
+ ["outro", "outro"],
+ ["music", "music"],
+]);
function cloudKind(type: AssetType): string {
- return SYNCABLE_KINDS[type] ?? "other";
+ return SYNCABLE_KINDS.get(type) ?? "other";
}
export type SyncReport = {
@@ -32,6 +33,12 @@ export type SyncReport = {
failed: Array<{ name: string; reason: string }>;
};
+/** The workspace calls asset sync makes. Tests pass a stand-in instead of the hosted API. */
+export type AssetCloud = Pick<
+ typeof cloud,
+ "signedIn" | "listAssets" | "uploadAsset" | "downloadAsset" | "checksum"
+>;
+
const empty = (): SyncReport => ({ uploaded: [], downloaded: [], skipped: [], failed: [] });
/**
@@ -41,16 +48,18 @@ const empty = (): SyncReport => ({ uploaded: [], downloaded: [], skipped: [], fa
* receiving it. Comparing first keeps a 200 MB intro off the wire on every
* sync; if the listing cannot be fetched, everything is uploaded as before.
*/
-export async function push(): Promise<SyncReport> {
+export async function push(client: AssetCloud = cloud): Promise<SyncReport> {
const report = empty();
- if (!(await cloud.signedIn())) return report;
+
+ if (!(await client.signedIn())) return report;
const manager = new AssetManager();
const registry = await manager.load();
let held = new Map<string, string>();
+
try {
- held = new Map((await cloud.listAssets()).map((a) => [a.name, a.checksum]));
+ held = new Map((await client.listAssets()).map((a) => [a.name, a.checksum]));
} catch {
// Fall through: an unreadable listing must not stop the push.
}
@@ -60,18 +69,22 @@ export async function push(): Promise<SyncReport> {
report.skipped.push(asset.name);
continue;
}
+
try {
const body = await readFile(asset.path);
- if (held.get(asset.name) === cloud.checksum(body)) {
+
+ if (held.get(asset.name) === client.checksum(body)) {
report.skipped.push(asset.name);
continue;
}
- const result = await cloud.uploadAsset(
+
+ const result = await client.uploadAsset(
asset.name,
cloudKind(asset.type),
body,
Boolean(asset.default),
);
+
if (result?.unchanged) report.skipped.push(asset.name);
else report.uploaded.push(asset.name);
} catch (err) {
@@ -81,6 +94,7 @@ export async function push(): Promise<SyncReport> {
});
}
}
+
return report;
}
@@ -88,39 +102,45 @@ export async function push(): Promise<SyncReport> {
* Pull workspace assets this machine is missing.
*
* Files land in .podcli/assets/ and are registered locally, so every existing
- * code path — rendering, presets, the studio — finds them exactly where it
+ * code path (rendering, presets, the studio) finds them exactly where it
* already looks. Nothing downstream needs to know they came from a server.
*/
-export async function pull(): Promise<SyncReport> {
+export async function pull(client: AssetCloud = cloud): Promise<SyncReport> {
const report = empty();
- if (!(await cloud.signedIn())) return report;
+
+ if (!(await client.signedIn())) return report;
const manager = new AssetManager();
const registry = await manager.load();
const known = new Map(registry.assets.map((a) => [a.name, a]));
- let remote: Awaited<ReturnType<typeof cloud.listAssets>>;
+ let remote: Awaited<ReturnType<AssetCloud["listAssets"]>>;
+
try {
- remote = await cloud.listAssets();
+ remote = await client.listAssets();
} catch (err) {
report.failed.push({
name: "(list)",
reason: err instanceof Error ? err.message : String(err),
});
+
return report;
}
const dir = join(paths.assets, "shared");
+
for (const entry of remote) {
const local = known.get(entry.name);
+
// A local file that already exists wins: the user's own copy is never
// silently overwritten by the workspace version.
if (local && existsSync(local.path)) {
report.skipped.push(entry.name);
continue;
}
+
try {
- const body = await cloud.downloadAsset(entry.id);
+ const body = await client.downloadAsset(entry.id);
await mkdir(dir, { recursive: true });
// The whole name, flattened: two workspace assets called `intro/logo.png`
// and `outro/logo.png` both end in `logo.png`, and the second download
@@ -139,6 +159,7 @@ export async function pull(): Promise<SyncReport> {
});
}
}
+
return report;
}
@@ -150,20 +171,17 @@ export async function pull(): Promise<SyncReport> {
* way back would turn a local video into "other" on the round trip. Guessing
* from the file is the better answer for exactly that case.
*/
-const ASSET_TYPES: readonly AssetType[] = [
- "logo", "outro", "intro", "music", "video", "image", "audio",
-];
+const pullableTypeSchema = z.enum(["logo", "outro", "intro", "music", "video", "image", "audio"]);
/** The workspace's own kind, when it is one this app models. */
function assetType(kind: string | undefined): AssetType | null {
- return kind && (ASSET_TYPES as readonly string[]).includes(kind)
- ? (kind as AssetType)
- : null;
+ return pullableTypeSchema.safeParse(kind).data ?? null;
}
-export async function sync(): Promise<SyncReport> {
- const up = await push();
- const down = await pull();
+export async function sync(client: AssetCloud = cloud): Promise<SyncReport> {
+ const up = await push(client);
+ const down = await pull(client);
+
return {
uploaded: up.uploaded,
downloaded: down.downloaded,
diff --git a/src/services/clips-history-cloud.test.ts b/src/services/clips-history-cloud.test.ts
index 8bd84b0..342467b 100644
--- a/src/services/clips-history-cloud.test.ts
+++ b/src/services/clips-history-cloud.test.ts
@@ -2,20 +2,24 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import type { HistoryCloud } from "./clips-history.js";
const tmp = mkdtempSync(join(tmpdir(), "podcli-clipcloud-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
-vi.mock("./podcli-cloud.js", () => ({
- signedIn: vi.fn(async () => false),
- sourceHash: vi.fn(async () => "abc123"),
- registerClip: vi.fn(async () => ({ id: "cloud-clip-1" })),
- uploadClipVideo: vi.fn(async () => true),
- logClipEvent: vi.fn(async () => undefined),
-}));
+process.env.PODCLI_CLOUD_SYNC = "1";
+
+const cloud = {
+ signedIn: vi.fn<HistoryCloud["signedIn"]>(),
+ sourceHash: vi.fn<HistoryCloud["sourceHash"]>(),
+ registerClip: vi.fn<HistoryCloud["registerClip"]>(),
+ uploadClipVideo: vi.fn<HistoryCloud["uploadClipVideo"]>(),
+ logClipEvent: vi.fn<HistoryCloud["logClipEvent"]>(),
+} satisfies HistoryCloud;
-const cloud = await import("./podcli-cloud.js");
const { ClipsHistory } = await import("./clips-history.js");
const source = join(tmp, "episode.mp4");
@@ -32,8 +36,11 @@ async function seed(history: InstanceType<typeof ClipsHistory>) {
duration: 42,
start_second: 10,
end_second: 52,
- format: "9:16",
- } as never);
+ format: "vertical",
+ caption_style: "hormozi",
+ crop_strategy: "face",
+ file_size_mb: 3,
+ });
}
describe("clip cloud sync", () => {
@@ -45,8 +52,29 @@ describe("clip cloud sync", () => {
writeFileSync(source, "source bytes");
writeFileSync(output, "rendered bytes");
vi.clearAllMocks();
- vi.mocked(cloud.signedIn).mockResolvedValue(false);
- history = new ClipsHistory();
+ cloud.signedIn.mockResolvedValue(false);
+ cloud.sourceHash.mockResolvedValue("abc123");
+ cloud.registerClip.mockResolvedValue({ id: "cloud-clip-1" });
+ cloud.uploadClipVideo.mockResolvedValue(true);
+ cloud.logClipEvent.mockResolvedValue(undefined);
+ history = new ClipsHistory(cloud);
+ });
+
+ it("makes no network call when sync is off, even when signed in", async () => {
+ cloud.signedIn.mockResolvedValue(true);
+ process.env.PODCLI_CLOUD_SYNC = "0";
+
+ try {
+ await seed(history);
+ await settle();
+ const result = await history.backfillCloud();
+
+ expect(result).toEqual({ synced: 0, failed: 0 });
+ expect(cloud.registerClip).not.toHaveBeenCalled();
+ expect(cloud.uploadClipVideo).not.toHaveBeenCalled();
+ } finally {
+ process.env.PODCLI_CLOUD_SYNC = "1";
+ }
});
it("makes no network call when signed out", async () => {
@@ -61,7 +89,7 @@ describe("clip cloud sync", () => {
it("uploads the rendered clip after registering it", async () => {
const entry = await seed(history);
await settle();
- vi.mocked(cloud.signedIn).mockResolvedValue(true);
+ cloud.signedIn.mockResolvedValue(true);
await history.backfillCloud();
@@ -75,7 +103,7 @@ describe("clip cloud sync", () => {
it("registers a clip once when two syncs overlap", async () => {
await seed(history);
await settle();
- vi.mocked(cloud.signedIn).mockResolvedValue(true);
+ cloud.signedIn.mockResolvedValue(true);
await Promise.all([history.backfillCloud(), history.backfillCloud()]);
@@ -86,10 +114,10 @@ describe("clip cloud sync", () => {
it("does not re-upload a clip whose video the workspace already has", async () => {
const entry = await seed(history);
await settle();
- vi.mocked(cloud.signedIn).mockResolvedValue(true);
+ cloud.signedIn.mockResolvedValue(true);
await history.backfillCloud();
vi.clearAllMocks();
- vi.mocked(cloud.signedIn).mockResolvedValue(true);
+ cloud.signedIn.mockResolvedValue(true);
await history.backfillCloud();
diff --git a/src/services/clips-history.test.ts b/src/services/clips-history.test.ts
index a553df1..d9712ee 100644
--- a/src/services/clips-history.test.ts
+++ b/src/services/clips-history.test.ts
@@ -5,14 +5,33 @@ import { join } from "path";
// Isolate PODCLI_HOME before the module (and its paths import) are evaluated.
const tmp = mkdtempSync(join(tmpdir(), "podcli-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
const { ClipsHistory } = await import("./clips-history.js");
+type NewClip = Parameters<InstanceType<typeof ClipsHistory>["record"]>[0];
+
+type ClipFields = Pick<
+ NewClip,
+ "source_video" | "output_path" | "start_second" | "end_second" | "caption_style" | "crop_strategy" | "title"
+> &
+ Partial<NewClip>;
+
+/** A history entry with the fields these tests do not care about filled in. */
+const clip = (fields: ClipFields): NewClip => ({
+ duration: fields.end_second - fields.start_second,
+ file_size_mb: 1,
+ format: "vertical",
+ ...fields,
+});
+
function makeFakeOutput(name: string): string {
const p = join(tmp, name);
writeFileSync(p, "stub");
+
return p;
}
@@ -27,7 +46,7 @@ describe("ClipsHistory", () => {
});
it("records and lists clips", async () => {
- await history.record({
+ await history.record(clip({
source_video: "/videos/show.mp4",
output_path: makeFakeOutput("a.mp4"),
start_second: 10,
@@ -35,7 +54,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "hook A",
- } as any);
+ }));
const list = await history.list();
expect(list).toHaveLength(1);
@@ -44,7 +63,7 @@ describe("ClipsHistory", () => {
it("findDuplicate matches within ±2s tolerance", async () => {
const output = makeFakeOutput("b.mp4");
- await history.record({
+ await history.record(clip({
source_video: "/videos/show.mp4",
output_path: output,
start_second: 10,
@@ -52,7 +71,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "original",
- } as any);
+ }));
const dup = await history.findDuplicate("/videos/show.mp4", 11, 41, "karaoke", "smart");
expect(dup).not.toBeNull();
@@ -64,7 +83,7 @@ describe("ClipsHistory", () => {
it("findDuplicate ignores entries whose output file is missing", async () => {
const output = makeFakeOutput("c.mp4");
- await history.record({
+ await history.record(clip({
source_video: "/videos/show.mp4",
output_path: output,
start_second: 100,
@@ -72,7 +91,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "ghost",
- } as any);
+ }));
rmSync(output);
const dup = await history.findDuplicate("/videos/show.mp4", 100, 130, "karaoke", "smart");
@@ -80,7 +99,7 @@ describe("ClipsHistory", () => {
});
it("minedYouTubeVideoIds reads the id out of the yt-dlp output template", async () => {
- await history.record({
+ await history.record(clip({
source_video: "/videos/Some Episode Title [aBc123_XYZ].mp4",
output_path: makeFakeOutput("d.mp4"),
start_second: 0,
@@ -88,14 +107,14 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "clip",
- } as any);
+ }));
const ids = await history.minedYouTubeVideoIds();
expect(ids.has("aBc123_XYZ")).toBe(true);
});
it("minedYouTubeVideoIds is empty when no source_video carries a bracketed id", async () => {
- await history.record({
+ await history.record(clip({
source_video: "/videos/local-recording.mp4",
output_path: makeFakeOutput("e.mp4"),
start_second: 0,
@@ -103,7 +122,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "clip",
- } as any);
+ }));
const ids = await history.minedYouTubeVideoIds();
expect(ids.size).toBe(0);
@@ -111,12 +130,13 @@ describe("ClipsHistory", () => {
it("recordBatchResults skips failed/output-less rows and applies defaults", async () => {
const ok = makeFakeOutput("batch-ok.mp4");
+
const recorded = await history.recordBatchResults(
[
{ status: "success", output_path: ok, start_second: 5, end_second: 20, title: "kept" },
{ status: "error", error: "boom" },
{ status: "success", title: "no output" },
- ] as any,
+ ],
{ sourceVideo: "/videos/show.mp4", defaultCaptionStyle: "hormozi", defaultCropStrategy: "speaker" },
);
@@ -131,15 +151,16 @@ describe("ClipsHistory", () => {
it("recordBatchResults resolves content_type and transcript_slice per row", async () => {
const ok = makeFakeOutput("batch-ct.mp4");
+
const recorded = await history.recordBatchResults(
- [{ status: "success", output_path: ok, start_second: 0, end_second: 10, title: "ct" }] as any,
+ [{ status: "success", output_path: ok, start_second: 0, end_second: 10, title: "ct" }],
{
sourceVideo: "/videos/show.mp4",
transcriptWords: [
- { word: "hello", start: 1, end: 2 },
- { word: "world", start: 3, end: 4 },
- { word: "later", start: 99, end: 100 },
- ] as any,
+ { word: "hello", start: 1, end: 2, confidence: 1 },
+ { word: "world", start: 3, end: 4, confidence: 1 },
+ { word: "later", start: 99, end: 100, confidence: 1 },
+ ],
contentTypeFor: (s, e) => (s === 0 && e === 10 ? "hook" : undefined),
},
);
@@ -156,7 +177,7 @@ describe("ClipsHistory", () => {
it("serializes concurrent records without losing entries", async () => {
await Promise.all(
Array.from({ length: 25 }, (_, i) =>
- history.record({
+ history.record(clip({
source_video: "/videos/show.mp4",
output_path: makeFakeOutput(`c-${i}.mp4`),
start_second: i,
@@ -164,7 +185,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: `clip ${i}`,
- } as any),
+ })),
),
);
const list = await history.list(100);
@@ -173,7 +194,7 @@ describe("ClipsHistory", () => {
});
it("findById and update require an exact id (no prefix match)", async () => {
- const rec = await history.record({
+ const rec = await history.record(clip({
source_video: "/videos/show.mp4",
output_path: makeFakeOutput("exact.mp4"),
start_second: 0,
@@ -181,7 +202,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "exact",
- } as any);
+ }));
expect(await history.findById(rec.id)).toBeDefined();
expect(await history.findById(rec.id.slice(0, 8))).toBeUndefined();
@@ -193,7 +214,7 @@ describe("ClipsHistory", () => {
});
it("resolveId accepts a full id or unambiguous ≥4-char prefix, rejects short/empty", async () => {
- const rec = await history.record({
+ const rec = await history.record(clip({
source_video: "/videos/show.mp4",
output_path: makeFakeOutput("resolve.mp4"),
start_second: 0,
@@ -201,7 +222,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "resolve",
- } as any);
+ }));
expect(await history.resolveId(rec.id)).toBe(rec.id);
expect(await history.resolveId(rec.id.slice(0, 8))).toBe(rec.id);
@@ -211,7 +232,7 @@ describe("ClipsHistory", () => {
it("findDuplicate matches by basename, not full path", async () => {
const output = makeFakeOutput("d.mp4");
- await history.record({
+ await history.record(clip({
source_video: "/absolute/path/one/show.mp4",
output_path: output,
start_second: 0,
@@ -219,7 +240,7 @@ describe("ClipsHistory", () => {
caption_style: "karaoke",
crop_strategy: "smart",
title: "basename test",
- } as any);
+ }));
const dup = await history.findDuplicate("/different/path/show.mp4", 0, 30, "karaoke", "smart");
expect(dup).not.toBeNull();
diff --git a/src/services/clips-history.ts b/src/services/clips-history.ts
index bd4d2c8..c2f683f 100644
--- a/src/services/clips-history.ts
+++ b/src/services/clips-history.ts
@@ -1,15 +1,75 @@
import { readFile, writeFile, mkdir, rm } from "fs/promises";
-import { existsSync } from "fs";
+import { existsSync, readFileSync } from "fs";
import { basename, join } from "path";
import { v4 as uuidv4 } from "uuid";
+import { z } from "zod";
import { paths } from "../config/paths.js";
import { writeFileAtomic } from "../utils/atomic-file.js";
+import type * as cloudApi from "./podcli-cloud.js";
import { sliceTranscript, sliceWords, findGroundingText } from "../utils/transcript.js";
import { isDemoMode, demoClips } from "../ui/demo-fixtures.js";
import type { BatchClipsResult, ClipHistoryEntry, ClipHook, Format, WordTimestamp } from "../models/index.js";
+/**
+ * Cloud clip sync uploads rendered videos and transcript slices, so it stays
+ * off until PODCLI_CLOUD_SYNC is turned on in the environment or the settings
+ * .env. The TypeScript side does not load that file itself, so it is read here.
+ */
+export function cloudSyncEnabled(): boolean {
+ const on = (v: string | undefined) => ["1", "true", "yes", "on"].includes((v ?? "").trim().toLowerCase());
+
+ if (process.env.PODCLI_CLOUD_SYNC !== undefined) return on(process.env.PODCLI_CLOUD_SYNC);
+
+ try {
+ const match = readFileSync(paths.envFile, "utf-8").match(/^PODCLI_CLOUD_SYNC=(.*)$/m);
+
+ return on(match?.[1]);
+ } catch {
+ return false;
+ }
+}
+
type BatchResultRow = BatchClipsResult["results"][number];
+const wordsSchema = z.array(
+ z.object({
+ word: z.string(),
+ start: z.number(),
+ end: z.number(),
+ confidence: z.number().default(0),
+ speaker: z.string().nullish(),
+ }),
+);
+
+const timeRangeSchema = z.object({ start: z.number(), end: z.number() });
+
+/** What a render needs to be repeated faithfully. Unknown fields are kept on rewrite. */
+const clipRecipeSchema = z.looseObject({
+ caption_style: z.string().optional(),
+ crop_strategy: z.string().optional(),
+ format: z.string().optional(),
+ logo_path: z.string().nullish(),
+ outro_path: z.string().nullish(),
+ intro_path: z.string().nullish(),
+ clean_fillers: z.boolean().optional(),
+ transcript_words: wordsSchema.optional(),
+ keep_segments: z.array(timeRangeSchema).optional(),
+ hook: z
+ .object({ start: z.number(), end: z.number(), mode: z.enum(["repeat", "move"]) })
+ .optional(),
+});
+
+export type ClipRecipe = z.infer<typeof clipRecipeSchema>;
+
+/** Reframe editor state: source-absolute keyframes plus the trim window. */
+export const reframeStateSchema = z.looseObject({
+ keyframes: z.array(z.object({ tAbs: z.number(), x_pct: z.number() })).optional(),
+ inSec: z.number().optional(),
+ outSec: z.number().optional(),
+});
+
+export type ReframeState = z.infer<typeof reframeStateSchema>;
+
interface BatchRecordContext {
sourceVideo: string;
transcriptWords?: WordTimestamp[] | null;
@@ -42,7 +102,19 @@ export interface BatchRecipeContext {
clipSpecs?: BatchClipSpec[];
}
+/** The workspace calls clip sync makes. Tests pass a stand-in instead of the hosted API. */
+export type HistoryCloud = Pick<
+ typeof cloudApi,
+ "signedIn" | "sourceHash" | "registerClip" | "uploadClipVideo" | "logClipEvent"
+>;
+
export class ClipsHistory {
+ constructor(private readonly cloudClient?: HistoryCloud) {}
+
+ private async loadCloud(): Promise<HistoryCloud> {
+ return this.cloudClient ?? (await import("./podcli-cloud.js"));
+ }
+
private historyPath = paths.clipsHistory;
// Serializes this process's own read-modify-write cycles so concurrent HTTP
// requests can't lose each other's edits. Cross-process safety (vs the Python
@@ -58,9 +130,12 @@ export class ClipsHistory {
async load(): Promise<ClipHistoryEntry[]> {
if (isDemoMode()) return demoClips();
+
try {
if (!existsSync(this.historyPath)) return [];
const raw = await readFile(this.historyPath, "utf-8");
+
+ // SAFETY: clips.json is written only by save(), which serializes ClipHistoryEntry[].
return JSON.parse(raw) as ClipHistoryEntry[];
} catch {
return [];
@@ -80,9 +155,12 @@ export class ClipsHistory {
const entries = await this.load();
const result = await fn(entries);
await this.save(entries);
+
return result;
});
+
this.writeChain = run.then(() => undefined, () => undefined);
+
return run;
}
@@ -92,34 +170,42 @@ export class ClipsHistory {
id: uuidv4(),
created_at: new Date().toISOString(),
};
+
await this.mutate((entries) => {
entries.push(full);
});
void this.syncToCloud(full);
+
return full;
}
/**
- * Mirror a rendered clip to the workspace, for signed-in users.
+ * Mirror a rendered clip to the workspace, for signed-in users who turned
+ * on PODCLI_CLOUD_SYNC.
*
* Deliberately not awaited and unable to throw: a clip that rendered
* successfully must be recorded locally whether or not a server was reachable.
* The local history file remains the source of truth; this is a copy.
*
- * Clips that fail to sync are left marked so a later sweep can backfill them —
+ * Clips that fail to sync are left marked so a later sweep can backfill them,
* the performance model wants the whole history, not the part that happened to
* have a working network.
*/
private async syncToCloud(entry: ClipHistoryEntry): Promise<void> {
// record() starts this in the background, so `podcli sync` can reach the
// same entry while it is still in flight and register the clip twice.
+ if (!cloudSyncEnabled()) return;
+
if (this.syncing.has(entry.id)) return;
this.syncing.add(entry.id);
+
try {
- const cloud = await import("./podcli-cloud.js");
+ const cloud = await this.loadCloud();
+
if (!(await cloud.signedIn())) return;
const source = entry.source_video;
+
if (!source) return;
const clipId = entry.cloud_id ?? (await cloud.registerClip({
@@ -134,6 +220,7 @@ export class ClipsHistory {
aspectRatio: entry.format,
transcriptSlice: entry.transcript_slice,
}))?.id;
+
if (!clipId) return;
await this.update(entry.id, { cloud_id: clipId });
@@ -149,6 +236,7 @@ export class ClipsHistory {
if (uploadable) {
hasVideo = await cloud.uploadClipVideo(clipId, entry.output_path);
+
if (hasVideo) await this.update(entry.id, { cloud_video_uploaded: true });
}
@@ -166,7 +254,7 @@ export class ClipsHistory {
}
// Persist every successful row of a batch render. Single source of truth for
- // turning backend batch results into history entries — callers used to inline
+ // turning backend batch results into history entries. Callers used to inline
// this loop, drifting on defaults and on which fields got recorded.
async recordBatchResults(
results: BatchResultRow[] | undefined,
@@ -174,6 +262,7 @@ export class ClipsHistory {
): Promise<ClipHistoryEntry[]> {
if (!results) return [];
const recorded: ClipHistoryEntry[] = [];
+
for (const r of results) {
if (r.status !== "success" || !r.output_path) continue;
const start = r.start_second || 0;
@@ -196,6 +285,7 @@ export class ClipsHistory {
}),
);
}
+
return recorded;
}
@@ -206,12 +296,15 @@ export class ClipsHistory {
): Promise<void> {
if (!rows?.length || !recorded.length) return;
let recordedIdx = 0;
+
for (const row of rows) {
if (row.status !== "success" || !row.output_path) continue;
const rec = recorded[recordedIdx++];
+
if (!rec) continue;
- const spec =
- typeof row.clip_index === "number" ? ctx.clipSpecs?.[row.clip_index] : undefined;
+
+ const spec = row.clip_index !== undefined ? ctx.clipSpecs?.[row.clip_index] : undefined;
+
await this.persistClipRecipe(rec, {
transcriptWords: ctx.transcriptWords,
logoPath: ctx.logoPath,
@@ -250,6 +343,7 @@ export class ClipsHistory {
...(ctx.keepSegments?.length && { keep_segments: ctx.keepSegments }),
...(ctx.hook && { hook: ctx.hook }),
});
+
if (ctx.keepSegments?.length) {
await this.update(rec.id, { keep_segments: ctx.keepSegments });
}
@@ -273,11 +367,17 @@ export class ClipsHistory {
return (
entries.find((e) => {
if (basename(e.source_video) !== srcName) return false;
+
if (e.caption_style !== captionStyle) return false;
+
if (e.crop_strategy !== cropStrategy) return false;
+
if ((e.format || "vertical") !== format) return false;
+
if (Math.abs(e.start_second - startSecond) > 2) return false;
+
if (Math.abs(e.end_second - endSecond) > 2) return false;
+
// Check output still exists
return existsSync(e.output_path);
}) || null
@@ -290,23 +390,28 @@ export class ClipsHistory {
async minedYouTubeVideoIds(): Promise<Set<string>> {
const entries = await this.load();
const ids = new Set<string>();
+
for (const e of entries) {
const m = basename(e.source_video || "").match(/\[([A-Za-z0-9_-]{6,})\]\.[^.]+$/);
+
if (m) ids.add(m[1]);
}
+
return ids;
}
async list(limit = 50): Promise<ClipHistoryEntry[]> {
const entries = await this.load();
+
return entries.slice(-limit).reverse();
}
- // Exact match only — REST routes feed req.params.id straight in, so a loose
+ // Exact match only: REST routes feed req.params.id straight in, so a loose
// prefix could target the wrong clip (and an empty prefix the first one).
async findById(id: string): Promise<ClipHistoryEntry | undefined> {
if (!id) return undefined;
const entries = await this.load();
+
return entries.find((e) => e.id === id);
}
@@ -315,30 +420,38 @@ export class ClipsHistory {
async resolveId(idOrPrefix: string): Promise<string | null> {
if (!idOrPrefix) return null;
const entries = await this.load();
+
if (entries.some((e) => e.id === idOrPrefix)) return idOrPrefix;
+
if (idOrPrefix.length < 4) return null;
const matches = entries.filter((e) => e.id.startsWith(idOrPrefix));
+
return matches.length === 1 ? matches[0].id : null;
}
async update(id: string, patch: Partial<ClipHistoryEntry>): Promise<ClipHistoryEntry | null> {
if (!id) return null;
+
const changed = await this.mutate((entries) => {
const e = entries.find((x) => x.id === id);
+
if (!e) return null;
const before = e.title;
Object.assign(e, patch);
+
return { entry: e, previousTitle: before };
});
+
if (!changed) return null;
// A human rewriting a generated title is the clearest taste signal podcli
- // gets — it says what the model produced and what a person preferred
+ // gets: it says what the model produced and what a person preferred
// instead. Reported only when the title actually changed, so the sync
// bookkeeping in syncToCloud can't trigger it.
if (patch.title !== undefined && patch.title !== changed.previousTitle) {
void this.reportEvent(changed.entry, "title_edited", changed.previousTitle, patch.title);
}
+
return changed.entry;
}
@@ -350,8 +463,10 @@ export class ClipsHistory {
after?: string,
): Promise<void> {
if (!entry.cloud_id) return;
+
try {
- const cloud = await import("./podcli-cloud.js");
+ const cloud = await this.loadCloud();
+
if (!(await cloud.signedIn())) return;
await cloud.logClipEvent(entry.cloud_id, kind, before, after);
} catch {
@@ -363,12 +478,14 @@ export class ClipsHistory {
* Push clips that never reached the workspace.
*
* Covers two cases that both matter: a render that happened while the network
- * was down, and — more importantly — everything rendered *before* the user
+ * was down, and, more importantly, everything rendered *before* the user
* subscribed. A new Pro user should start with their back catalogue behind the
* performance model, not an empty history.
*/
async backfillCloud(limit = 200): Promise<{ synced: number; failed: number }> {
- const cloud = await import("./podcli-cloud.js");
+ if (!cloudSyncEnabled()) return { synced: 0, failed: 0 };
+ const cloud = await this.loadCloud();
+
if (!(await cloud.signedIn())) return { synced: 0, failed: 0 };
// A clip whose source video has been moved or deleted can never be hashed,
@@ -382,16 +499,19 @@ export class ClipsHistory {
let synced = 0;
let failed = 0;
+
for (const entry of pending) {
try {
await this.syncToCloud(entry);
const after = await this.findById(entry.id);
+
if (after?.cloud_synced) synced++;
else failed++;
} catch {
failed++;
}
}
+
return { synced, failed };
}
@@ -400,14 +520,20 @@ export class ClipsHistory {
// Accepts a full id or an unambiguous prefix (MCP convenience).
async remove(idOrPrefix: string): Promise<ClipHistoryEntry | null> {
const id = await this.resolveId(idOrPrefix);
+
if (!id) return null;
- // Demo entries are read-only fixtures — never delete their (shipped) artifacts.
+
+ // Demo entries are read-only fixtures: never delete their (shipped) artifacts.
if (isDemoMode()) return (await this.findById(id)) ?? null;
+
const entry = await this.mutate((entries) => {
const idx = entries.findIndex((e) => e.id === id);
+
if (idx < 0) return null;
+
return entries.splice(idx, 1)[0];
});
+
if (!entry) return null;
const artifacts = [
@@ -416,16 +542,19 @@ export class ClipsHistory {
this.reframePath(entry.id),
entry.output_path,
];
+
await Promise.all(
artifacts.map((p) => (p ? rm(p, { force: true }) : Promise.resolve())),
);
await rm(join(paths.output, "thumbnails", entry.id), { recursive: true, force: true });
+
return entry;
}
async getBySource(videoPath: string): Promise<ClipHistoryEntry[]> {
const entries = await this.load();
const srcName = basename(videoPath);
+
return entries.filter((e) => basename(e.source_video) === srcName).reverse();
}
@@ -435,34 +564,34 @@ export class ClipsHistory {
return join(paths.history, "words", `${id}.json`);
}
- async saveWords(id: string, words: unknown[]): Promise<void> {
- if (!words || words.length === 0) return;
+ async saveWords(id: string, words: WordTimestamp[]): Promise<void> {
+ if (words.length === 0) return;
await mkdir(join(paths.history, "words"), { recursive: true });
await writeFile(this.wordsPath(id), JSON.stringify(words), "utf-8");
}
- async loadWords(id: string): Promise<unknown[]> {
+ async loadWords(id: string): Promise<WordTimestamp[]> {
try {
- return JSON.parse(await readFile(this.wordsPath(id), "utf-8"));
+ return wordsSchema.parse(JSON.parse(await readFile(this.wordsPath(id), "utf-8")));
} catch {
return [];
}
}
// Full render recipe (logo/outro/captions/fillers/segments/words) so a clip
- // can be re-rendered faithfully — e.g. after a manual reframe.
+ // can be re-rendered faithfully: e.g. after a manual reframe.
private recipePath(id: string): string {
return join(paths.history, "recipes", `${id}.json`);
}
- async saveRecipe(id: string, recipe: Record<string, unknown>): Promise<void> {
+ async saveRecipe(id: string, recipe: ClipRecipe): Promise<void> {
await mkdir(join(paths.history, "recipes"), { recursive: true });
await writeFile(this.recipePath(id), JSON.stringify(recipe), "utf-8");
}
- async loadRecipe(id: string): Promise<Record<string, unknown> | null> {
+ async loadRecipe(id: string): Promise<ClipRecipe | null> {
try {
- return JSON.parse(await readFile(this.recipePath(id), "utf-8"));
+ return clipRecipeSchema.safeParse(JSON.parse(await readFile(this.recipePath(id), "utf-8"))).data ?? null;
} catch {
return null;
}
@@ -473,14 +602,14 @@ export class ClipsHistory {
return join(paths.history, "reframe", `${id}.json`);
}
- async saveReframe(id: string, state: Record<string, unknown>): Promise<void> {
+ async saveReframe(id: string, state: ReframeState): Promise<void> {
await mkdir(join(paths.history, "reframe"), { recursive: true });
await writeFile(this.reframePath(id), JSON.stringify(state), "utf-8");
}
- async loadReframe(id: string): Promise<Record<string, unknown> | null> {
+ async loadReframe(id: string): Promise<ReframeState | null> {
try {
- return JSON.parse(await readFile(this.reframePath(id), "utf-8"));
+ return reframeStateSchema.safeParse(JSON.parse(await readFile(this.reframePath(id), "utf-8"))).data ?? null;
} catch {
return null;
}
diff --git a/src/services/engine-resolve.test.ts b/src/services/engine-resolve.test.ts
index 378729c..554b0a2 100644
--- a/src/services/engine-resolve.test.ts
+++ b/src/services/engine-resolve.test.ts
@@ -1,9 +1,13 @@
import { describe, it, expect, vi } from "vitest";
-import type { PythonExecutor } from "./python-executor.js";
+import type { TaskExecutor } from "./python-executor.js";
import { resolveTranscribeEngine, engineCanDiarize } from "./engine-resolve.js";
-function fakeExecutor(response: unknown): PythonExecutor {
- return { execute: vi.fn().mockResolvedValue(response) } as unknown as PythonExecutor;
+function fakeExecutor(response: { data: { engine: string } }): TaskExecutor {
+ return { execute: vi.fn().mockResolvedValue(response) };
+}
+
+function failingExecutor(): TaskExecutor {
+ return { execute: vi.fn().mockRejectedValue(new Error("boom")) };
}
describe("resolveTranscribeEngine", () => {
@@ -24,13 +28,13 @@ describe("resolveTranscribeEngine", () => {
});
it("falls back to the raw request if resolution itself fails", async () => {
- const executor = { execute: vi.fn().mockRejectedValue(new Error("boom")) } as unknown as PythonExecutor;
+ const executor = failingExecutor();
const engine = await resolveTranscribeEngine(executor, "whisper-py", "base");
expect(engine).toBe("whisper-py");
});
it("falls back to whisper-py when both the request and the resolution are empty", async () => {
- const executor = { execute: vi.fn().mockRejectedValue(new Error("boom")) } as unknown as PythonExecutor;
+ const executor = failingExecutor();
const engine = await resolveTranscribeEngine(executor, undefined, "base");
expect(engine).toBe("whisper-py");
});
diff --git a/src/services/engine-resolve.ts b/src/services/engine-resolve.ts
index 57fad83..b97a708 100644
--- a/src/services/engine-resolve.ts
+++ b/src/services/engine-resolve.ts
@@ -1,4 +1,4 @@
-import { PythonExecutor } from "./python-executor.js";
+import type { TaskExecutor } from "./python-executor.js";
/**
* Predicts which engine backend/services/transcription.py's transcribe_file
@@ -23,7 +23,7 @@ export function engineCanDiarize(engine: string | undefined): boolean {
}
export async function resolveTranscribeEngine(
- executor: PythonExecutor,
+ executor: TaskExecutor,
engine: string | undefined,
modelSize: string
): Promise<string> {
@@ -32,6 +32,7 @@ export async function resolveTranscribeEngine(
engine,
model_size: modelSize,
});
+
return result.data?.engine ?? engine ?? "whisper-py";
} catch {
// Resolution is a best-effort cache-key optimization; a failure here
diff --git a/src/services/episode-state.ts b/src/services/episode-state.ts
index f6da3b1..7572489 100644
--- a/src/services/episode-state.ts
+++ b/src/services/episode-state.ts
@@ -63,14 +63,19 @@ export class EpisodeState {
async keyFor(videoPath: string): Promise<string | null> {
const identity = computeVideoIdentity(resolve(videoPath));
+
if (!identity) return null; // video not found on disk, nothing to key against
+
return this.keyForIdentity(identity);
}
private async readAll(): Promise<DecisionsFile> {
if (!existsSync(this.filePath)) return {};
+
try {
const raw = await readFile(this.filePath, "utf-8");
+
+ // SAFETY: episode-decisions.json is written only by writeAll() below, which serializes a DecisionsFile.
return JSON.parse(raw) as DecisionsFile;
} catch (err) {
// A corrupt file must never silently wipe every episode's decisions.
@@ -82,6 +87,7 @@ export class EpisodeState {
err: err instanceof Error ? err.message : String(err),
quarantined,
});
+
return {};
}
}
@@ -95,13 +101,16 @@ export class EpisodeState {
private enqueue<T>(step: () => Promise<T>): Promise<T> {
const result = this.queue.then(step, step);
this.queue = result.catch(() => {});
+
return result;
}
async get(videoPath: string): Promise<EpisodeDecisions | null> {
const key = await this.keyFor(videoPath);
+
if (!key) return null;
const all = await this.readAll();
+
return all[key] ?? null;
}
@@ -111,13 +120,16 @@ export class EpisodeState {
decisions: Partial<Omit<EpisodeDecisions, "videoPath" | "fileSize" | "updatedAt">>,
): Promise<EpisodeDecisions> {
const abs = resolve(videoPath);
+
return this.enqueue(async () => {
const identity = computeVideoIdentity(abs);
+
if (!identity) throw new Error(`Video not found: ${abs}`); // nothing to key against
const key = this.keyForIdentity(identity);
const all = await this.readAll();
const existing = all[key];
+
const merged: EpisodeDecisions = {
...existing,
...decisions,
@@ -125,8 +137,10 @@ export class EpisodeState {
fileSize: identity.size,
updatedAt: Date.now(),
};
+
all[key] = merged;
await this.writeAll(all);
+
return merged;
});
}
@@ -134,6 +148,7 @@ export class EpisodeState {
/** Decisions relevant to the next step that have no answer recorded yet. */
async openQuestions(videoPath: string): Promise<OpenQuestion[]> {
const current = await this.get(videoPath);
+
return QUESTIONS.filter(({ field }) => current?.[field] === undefined);
}
}
diff --git a/src/services/file-manager.test.ts b/src/services/file-manager.test.ts
index 212b626..3157660 100644
--- a/src/services/file-manager.test.ts
+++ b/src/services/file-manager.test.ts
@@ -4,7 +4,9 @@ import { tmpdir } from "os";
import { join } from "path";
const tmp = mkdtempSync(join(tmpdir(), "podcli-fm-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
const { FileManager } = await import("./file-manager.js");
@@ -21,6 +23,7 @@ describe("FileManager", () => {
it("ensureDirectories creates all required directories", async () => {
await fm.ensureDirectories();
+
for (const name of ["cache", "working", "output", "history"]) {
expect(existsSync(join(tmp, name))).toBe(true);
}
@@ -78,11 +81,11 @@ describe("FileManager", () => {
await fm.ensureDirectories();
const working = join(tmp, "working");
- // Fresh dir — should survive
+ // Fresh dir: should survive
const fresh = join(working, "fresh");
mkdirSync(fresh);
- // Old dir — backdated to 5 days ago
+ // Old dir: backdated to 5 days ago
const old = join(working, "old");
mkdirSync(old);
const ago = new Date(Date.now() - 5 * 24 * 3600 * 1000);
diff --git a/src/services/file-manager.ts b/src/services/file-manager.ts
index 533a0f0..20ead01 100644
--- a/src/services/file-manager.ts
+++ b/src/services/file-manager.ts
@@ -7,6 +7,11 @@ import { paths } from "../config/paths.js";
/**
* Manages working directories and output files.
*/
+interface TaskDir {
+ taskId: string;
+ taskDir: string;
+}
+
export class FileManager {
async ensureDirectories() {
const dirs = [
@@ -20,6 +25,7 @@ export class FileManager {
paths.history,
paths.knowledge,
];
+
for (const dir of dirs) {
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
@@ -27,28 +33,33 @@ export class FileManager {
}
}
- createTaskDir(): { taskId: string; taskDir: string } {
+ createTaskDir(): TaskDir {
const taskId = uuidv4();
const taskDir = join(paths.working, taskId);
+
return { taskId, taskDir };
}
async ensureTaskDir(taskId: string): Promise<string> {
const taskDir = join(paths.working, taskId);
+
if (!existsSync(taskDir)) {
await mkdir(taskDir, { recursive: true });
}
+
return taskDir;
}
async moveToOutput(sourcePath: string, filename: string): Promise<string> {
const destPath = join(paths.output, filename);
await rename(sourcePath, destPath);
+
return destPath;
}
async cleanupTask(taskId: string): Promise<void> {
const taskDir = join(paths.working, taskId);
+
if (existsSync(taskDir)) {
await rm(taskDir, { recursive: true, force: true });
}
@@ -66,9 +77,11 @@ export class FileManager {
for (const entry of entries) {
const fullPath = join(paths.working, entry);
+
try {
const s = await stat(fullPath);
const ageHours = (now - s.mtimeMs) / (1000 * 60 * 60);
+
if (ageHours > maxAgeHours) {
await rm(fullPath, { recursive: true, force: true });
cleaned++;
diff --git a/src/services/knowledge-base.test.ts b/src/services/knowledge-base.test.ts
index 760d973..c52899e 100644
--- a/src/services/knowledge-base.test.ts
+++ b/src/services/knowledge-base.test.ts
@@ -4,7 +4,9 @@ import { tmpdir } from "os";
import { join } from "path";
const tmp = mkdtempSync(join(tmpdir(), "podcli-kb-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
const { KnowledgeBase, isFilledIn } = await import("./knowledge-base.js");
diff --git a/src/services/knowledge-base.ts b/src/services/knowledge-base.ts
index 5d6c00d..c09b401 100644
--- a/src/services/knowledge-base.ts
+++ b/src/services/knowledge-base.ts
@@ -3,6 +3,7 @@ import { existsSync } from "fs";
import { join } from "path";
import { paths } from "../config/paths.js";
import type { KnowledgeFile } from "../models/index.js";
+import { safePath } from "../utils/safe-path.js";
const templatesDir = join(paths.backendDir, "templates", "knowledge");
@@ -15,7 +16,9 @@ function placeholders(text: string): number {
export function isFilledIn(content: string, template: string): boolean {
const body = content.trim();
+
if (!body || body === template.trim()) return false;
+
return placeholders(body) <= placeholders(template) * 0.3;
}
@@ -36,36 +39,45 @@ export class KnowledgeBase {
private async loadTemplates(): Promise<Map<string, string>> {
const templates = new Map<string, string>();
let names: string[];
+
try {
names = (await readdir(templatesDir)).filter((f) => f.endsWith(".md")).sort();
} catch {
return templates;
}
+
for (const name of names) {
templates.set(name, await readFile(join(templatesDir, name), "utf-8"));
}
+
return templates;
}
/** Copy the starter templates in, never overwriting a file the user already has. */
async initFromTemplates(): Promise<{ created: string[]; kept: string[] }> {
const templates = await this.loadTemplates();
+
if (templates.size === 0) {
throw new Error(`No knowledge templates found at ${templatesDir}`);
}
+
await this.ensureDir();
const created: string[] = [];
const kept: string[] = [];
+
for (const name of templates.keys()) {
const target = join(this.dir, name);
+
if (existsSync(target)) {
kept.push(name);
continue;
}
+
await copyFile(join(templatesDir, name), target);
created.push(name);
}
+
return { created, kept };
}
@@ -76,15 +88,20 @@ export class KnowledgeBase {
const present: string[] = [];
const filled: string[] = [];
const missing: string[] = [];
+
for (const [name, template] of templates) {
const content = byName.get(name);
+
if (content === undefined) {
missing.push(name);
continue;
}
+
present.push(name);
+
if (isFilledIn(content, template)) filled.push(name);
}
+
return { templates: [...templates.keys()], present, filled, missing };
}
@@ -94,6 +111,7 @@ export class KnowledgeBase {
const mdFiles = entries.filter((f) => f.endsWith(".md"));
const files: KnowledgeFile[] = [];
+
for (const filename of mdFiles) {
const filePath = join(this.dir, filename);
const s = await stat(filePath);
@@ -104,14 +122,16 @@ export class KnowledgeBase {
updatedAt: s.mtime.toISOString(),
});
}
+
return files.sort((a, b) => a.filename.localeCompare(b.filename));
}
- /** Read all .md files concatenated — the main method used by MCP tools. */
+ /** Read all .md files concatenated: the main method used by MCP tools. */
async readAll(): Promise<string> {
const files = await this.listFiles();
// Skip README
const relevant = files.filter((f) => f.filename !== "README.md");
+
if (relevant.length === 0) return "";
return relevant
@@ -119,20 +139,32 @@ export class KnowledgeBase {
.join("\n\n");
}
+ private resolve(filename: string): string {
+ const filePath = safePath(this.dir, filename);
+
+ if (!filePath) throw new Error(`Invalid filename: ${filename}`);
+
+ return filePath;
+ }
+
async readFile(filename: string): Promise<string> {
- const filePath = join(this.dir, filename);
+ const filePath = this.resolve(filename);
+
if (!existsSync(filePath)) throw new Error(`File not found: ${filename}`);
+
return readFile(filePath, "utf-8");
}
async writeFile(filename: string, content: string): Promise<void> {
await this.ensureDir();
+
if (!filename.endsWith(".md")) filename += ".md";
- await writeFile(join(this.dir, filename), content, "utf-8");
+ await writeFile(this.resolve(filename), content, "utf-8");
}
async deleteFile(filename: string): Promise<void> {
- const filePath = join(this.dir, filename);
+ const filePath = this.resolve(filename);
+
if (existsSync(filePath)) await unlink(filePath);
}
}
diff --git a/src/services/knowledge-sync.test.ts b/src/services/knowledge-sync.test.ts
index 4a6ccee..851b8db 100644
--- a/src/services/knowledge-sync.test.ts
+++ b/src/services/knowledge-sync.test.ts
@@ -2,19 +2,21 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
import { mkdtempSync, rmSync, mkdirSync, existsSync, readdirSync, writeFileSync, readFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import type { KnowledgeCloud } from "./knowledge-sync.js";
const tmp = mkdtempSync(join(tmpdir(), "podcli-ksync-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
-vi.mock("./podcli-cloud.js", () => ({
- signedIn: vi.fn(async () => true),
- listKnowledge: vi.fn(async () => []),
- getKnowledge: vi.fn(async () => ({ content: "owned", version: 1 })),
- putKnowledge: vi.fn(async () => ({ conflict: false, version: 1, unchanged: true })),
-}));
+const cloud = {
+ signedIn: vi.fn<KnowledgeCloud["signedIn"]>(),
+ listKnowledge: vi.fn<KnowledgeCloud["listKnowledge"]>(),
+ getKnowledge: vi.fn<KnowledgeCloud["getKnowledge"]>(),
+ putKnowledge: vi.fn<KnowledgeCloud["putKnowledge"]>(),
+} satisfies KnowledgeCloud;
-const cloud = await import("./podcli-cloud.js");
const { sync } = await import("./knowledge-sync.js");
describe("knowledge sync", () => {
@@ -27,14 +29,18 @@ describe("knowledge sync", () => {
rmSync(join(tmp, "knowledge-sync.json"), { force: true });
mkdirSync(join(tmp, "knowledge"), { recursive: true });
vi.clearAllMocks();
+ cloud.signedIn.mockResolvedValue(true);
+ cloud.listKnowledge.mockResolvedValue([]);
+ cloud.getKnowledge.mockResolvedValue({ content: "owned", version: 1 });
+ cloud.putKnowledge.mockResolvedValue({ conflict: false, version: 1, unchanged: true });
});
it("refuses a workspace path that escapes the knowledge folder", async () => {
- vi.mocked(cloud.listKnowledge).mockResolvedValue([
+ cloud.listKnowledge.mockResolvedValue([
{ path: "../../pwned.md", version: 1, updated_at: "" },
]);
- const report = await sync();
+ const report = await sync(cloud);
expect(existsSync(join(tmp, "..", "pwned.md"))).toBe(false);
expect(report.pulled).toEqual([]);
@@ -45,14 +51,14 @@ describe("knowledge sync", () => {
it("never pushes shipped defaults over the workspace copy on a first sync", async () => {
writeFileSync(join(tmp, "knowledge", "02-voice-and-tone.md"), "# shipped default");
- vi.mocked(cloud.listKnowledge).mockResolvedValue([
+ cloud.listKnowledge.mockResolvedValue([
{ path: "02-voice-and-tone.md", version: 7, updated_at: "" },
]);
- vi.mocked(cloud.getKnowledge).mockResolvedValue({
+ cloud.getKnowledge.mockResolvedValue({
content: "# the team's real voice guide", version: 7,
});
- const report = await sync();
+ const report = await sync(cloud);
expect(cloud.putKnowledge).not.toHaveBeenCalled();
expect(report.conflicts).toEqual([{ path: "02-voice-and-tone.md", theirVersion: 7 }]);
@@ -65,12 +71,12 @@ describe("knowledge sync", () => {
it("adopts the workspace version when both copies already match", async () => {
writeFileSync(join(tmp, "knowledge", "05-title-formulas.md"), "# same bytes");
- vi.mocked(cloud.listKnowledge).mockResolvedValue([
+ cloud.listKnowledge.mockResolvedValue([
{ path: "05-title-formulas.md", version: 4, updated_at: "" },
]);
- vi.mocked(cloud.getKnowledge).mockResolvedValue({ content: "# same bytes", version: 4 });
+ cloud.getKnowledge.mockResolvedValue({ content: "# same bytes", version: 4 });
- const report = await sync();
+ const report = await sync(cloud);
expect(cloud.putKnowledge).not.toHaveBeenCalled();
expect(report.unchanged).toEqual(["05-title-formulas.md"]);
@@ -80,23 +86,23 @@ describe("knowledge sync", () => {
it("pushes a local file the workspace does not have", async () => {
writeFileSync(join(tmp, "knowledge", "99-mine.md"), "# only here");
- vi.mocked(cloud.listKnowledge).mockResolvedValue([]);
- vi.mocked(cloud.putKnowledge).mockResolvedValue({
+ cloud.listKnowledge.mockResolvedValue([]);
+ cloud.putKnowledge.mockResolvedValue({
conflict: false, version: 1, unchanged: false,
});
- const report = await sync();
+ const report = await sync(cloud);
expect(cloud.putKnowledge).toHaveBeenCalledWith("99-mine.md", "# only here", undefined);
expect(report.pushed).toEqual(["99-mine.md"]);
});
it("pulls a file the workspace has and this machine does not", async () => {
- vi.mocked(cloud.listKnowledge).mockResolvedValue([
+ cloud.listKnowledge.mockResolvedValue([
{ path: "02-voice-and-tone.md", version: 3, updated_at: "" },
]);
- const report = await sync();
+ const report = await sync(cloud);
expect(report.pulled).toEqual(["02-voice-and-tone.md"]);
expect(readdirSync(join(tmp, "knowledge"))).toContain("02-voice-and-tone.md");
diff --git a/src/services/knowledge-sync.ts b/src/services/knowledge-sync.ts
index cbd529c..30f010d 100644
--- a/src/services/knowledge-sync.ts
+++ b/src/services/knowledge-sync.ts
@@ -20,7 +20,7 @@ const STATE_FILE = "knowledge-sync.json";
* Version of each file as of the last successful sync.
*
* Without this there is no way to tell "I edited this" from "they edited this"
- * — both just look like a difference — and every sync would either clobber
+ * because both just look like a difference, and every sync would either clobber
* someone or refuse to do anything.
*/
type SyncState = Record<string, number>;
@@ -45,6 +45,7 @@ async function saveState(state: SyncState): Promise<void> {
function insideKnowledge(path: string): string | null {
const root = resolve(paths.knowledge);
const target = resolve(root, path);
+
return target.startsWith(root + sep) ? target : null;
}
@@ -62,10 +63,13 @@ async function localFiles(): Promise<string[]> {
if (!existsSync(paths.knowledge)) return [];
const found: string[] = [];
+
const walk = async (dir: string): Promise<void> => {
const entries = await readdir(dir, { withFileTypes: true });
+
for (const entry of entries) {
const full = join(dir, entry.name);
+
if (entry.isDirectory()) await walk(full);
else if (entry.isFile() && entry.name.endsWith(".md")) {
found.push(relative(paths.knowledge, full).split(sep).join("/"));
@@ -74,6 +78,7 @@ async function localFiles(): Promise<string[]> {
};
await walk(paths.knowledge);
+
return found.sort();
}
@@ -85,33 +90,40 @@ export type KnowledgeSyncReport = {
failed: Array<{ path: string; reason: string }>;
};
-export async function sync(): Promise<KnowledgeSyncReport> {
+/** The workspace calls knowledge sync makes. Tests pass a stand-in instead of the hosted API. */
+export type KnowledgeCloud = Pick<typeof cloud, "signedIn" | "listKnowledge" | "getKnowledge" | "putKnowledge">;
+
+export async function sync(client: KnowledgeCloud = cloud): Promise<KnowledgeSyncReport> {
const report: KnowledgeSyncReport = {
pushed: [], pulled: [], unchanged: [], conflicts: [], failed: [],
};
- if (!(await cloud.signedIn())) return report;
+
+ if (!(await client.signedIn())) return report;
const state = await loadState();
- const remote = new Map((await cloud.listKnowledge()).map((f) => [f.path, f]));
+ const remote = new Map((await client.listKnowledge()).map((f) => [f.path, f]));
const local = await localFiles();
const localSet = new Set(local);
// Reconciled before anything is pushed. podcli ships default knowledge files,
// so a machine that has never synced has a full set of boilerplate that would
- // otherwise be pushed straight over the workspace's real one — the server
+ // otherwise be pushed straight over the workspace's real one: the server
// skips its conflict check when no expectedVersion is sent.
const unresolved = new Set<string>();
+
for (const [path, meta] of remote) {
const target = insideKnowledge(path);
+
if (!target) {
report.failed.push({ path, reason: "path escapes the knowledge folder" });
unresolved.add(path);
continue;
}
+
if (state[path] !== undefined) continue;
try {
- const file = await cloud.getKnowledge(path);
+ const file = await client.getKnowledge(path);
const version = file.version ?? meta.version;
if (!localSet.has(path)) {
@@ -126,6 +138,7 @@ export async function sync(): Promise<KnowledgeSyncReport> {
// content is simply adopted; otherwise the workspace copy lands beside
// the local one and a human decides.
const mine = await readFile(target, "utf-8");
+
if (mine === file.content) {
state[path] = version;
report.unchanged.push(path);
@@ -134,6 +147,7 @@ export async function sync(): Promise<KnowledgeSyncReport> {
file.content, "utf-8");
report.conflicts.push({ path, theirVersion: version });
}
+
unresolved.add(path);
} catch (err) {
report.failed.push({ path, reason: err instanceof Error ? err.message : String(err) });
@@ -145,8 +159,10 @@ export async function sync(): Promise<KnowledgeSyncReport> {
if (unresolved.has(path)) continue;
const content = await readFile(join(paths.knowledge, path), "utf-8");
const known = state[path];
+
try {
- const result = await cloud.putKnowledge(path, content, known);
+ const result = await client.putKnowledge(path, content, known);
+
if (result.conflict) {
// Neither copy is discarded. The workspace version is written beside
// the local one so a human can compare and merge; nobody's work is
@@ -158,7 +174,9 @@ export async function sync(): Promise<KnowledgeSyncReport> {
report.conflicts.push({ path, theirVersion: version });
continue;
}
+
state[path] = result.version;
+
if (result.unchanged) report.unchanged.push(path);
else report.pushed.push(path);
} catch (err) {
@@ -168,5 +186,6 @@ export async function sync(): Promise<KnowledgeSyncReport> {
await saveState(state);
+
return report;
}
diff --git a/src/services/podcli-cloud.ts b/src/services/podcli-cloud.ts
index c669777..e0d2fe3 100644
--- a/src/services/podcli-cloud.ts
+++ b/src/services/podcli-cloud.ts
@@ -2,13 +2,14 @@ import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { readFile, stat } from "node:fs/promises";
import { join } from "node:path";
+import { z } from "zod";
import { paths } from "../config/paths.js";
/**
* Client for podcli Pro's hosted API.
*
* The Python backend has its own copy of this because the two runtimes cannot
- * share one — deliberate duplication of about eighty lines, not an accident.
+ * share one: deliberate duplication of about eighty lines, not an accident.
*
* Nothing here is secret. The server decides entitlement, so a patched client
* gets an HTTP 401 rather than free Pro.
@@ -28,12 +29,17 @@ export function apiUrl(): string {
* small file costs microseconds against the HTTP request that follows it, so
* caching bought nothing and cost correctness.
*/
+const authFileSchema = z.looseObject({ token: z.string().optional() });
+
export async function readToken(): Promise<string | null> {
const fromEnv = (process.env.PODCLI_TOKEN || "").trim();
+
if (fromEnv) return fromEnv;
+
try {
const raw = await readFile(join(paths.home, "auth.json"), "utf-8");
- return ((JSON.parse(raw).token as string | undefined) || "").trim() || null;
+
+ return (authFileSchema.parse(JSON.parse(raw)).token || "").trim() || null;
} catch {
return null;
}
@@ -43,28 +49,39 @@ export async function signedIn(): Promise<boolean> {
return (await readToken()) !== null;
}
-async function request(method: string, path: string, body?: unknown, timeoutMs = 30_000) {
+async function request<S extends z.ZodType, B extends object = object>(
+ method: string,
+ path: string,
+ schema: S,
+ body?: B,
+ timeoutMs = 30_000,
+): Promise<z.infer<S> | null> {
const token = await readToken();
+
if (!token) throw new Error("not signed in");
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
+
try {
const response = await fetch(`${apiUrl()}${path}`, {
method,
headers: {
authorization: `Bearer ${token}`,
- ...(body === undefined ? {} : { "content-type": "application/json" }),
+ ...(body !== undefined && { "content-type": "application/json" }),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: controller.signal,
});
+
if (!response.ok) {
const detail = await response.text().catch(() => "");
throw new Error(`HTTP ${response.status}${detail ? `: ${detail.slice(0, 200)}` : ""}`);
}
+
const text = await response.text();
- return text ? JSON.parse(text) : null;
+
+ return text ? schema.parse(JSON.parse(text)) : null;
} finally {
clearTimeout(timer);
}
@@ -80,7 +97,10 @@ async function request(method: string, path: string, body?: unknown, timeoutMs =
export async function sourceHash(videoPath: string): Promise<string> {
const hash = createHash("sha256");
const stream = createReadStream(videoPath, { start: 0, end: 8 * 1024 * 1024 - 1 });
- for await (const chunk of stream) hash.update(chunk as Buffer);
+
+ // No encoding is set on the stream, so every chunk is a Buffer.
+ for await (const chunk of stream) hash.update(Buffer.from(chunk));
+
return hash.digest("hex").slice(0, 32);
}
@@ -100,11 +120,11 @@ export type ClipRegistration = {
quote?: string;
reasoning?: string;
transcriptSlice?: string;
- extra?: Record<string, unknown>;
+ extra?: Record<string, string | number | boolean | null>;
};
export async function registerClip(clip: ClipRegistration): Promise<{ id: string } | null> {
- return request("POST", "/v1/clips", clip);
+ return request("POST", "/v1/clips", z.object({ id: z.string() }), clip);
}
/** Matches the server's body cap; a larger file is refused before the upload. */
@@ -113,14 +133,16 @@ const MAX_CLIP_BYTES = 200 * 1024 * 1024;
/**
* Send the rendered clip itself, so share links have something to play.
*
- * Only the rendered clip travels — never the source video. It is the whole
+ * Only the rendered clip travels: never the source video. It is the whole
* reason a share link can exist without the storage cost of the master.
*/
export async function uploadClipVideo(clipId: string, filePath: string): Promise<boolean> {
const token = await readToken();
+
if (!token) return false;
const { size } = await stat(filePath);
+
if (size === 0 || size > MAX_CLIP_BYTES) return false;
const response = await fetch(`${apiUrl()}/v1/clips/${clipId}/video`, {
@@ -129,65 +151,97 @@ export async function uploadClipVideo(clipId: string, filePath: string): Promise
body: await readFile(filePath),
signal: AbortSignal.timeout(300_000),
});
+
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 200)}`);
}
+
return true;
}
-export type Breakdown = {
- key: string;
- clips: number;
- retention: number | null;
- ctr: number | null;
- views: number | null;
-};
-
-export type Insights = {
- sampleSize: number;
- byContentType: Breakdown[];
- byCaptionStyle: Breakdown[];
- byLength: Breakdown[];
- topClips: Array<{ title: string; retention: number; views: number; content_type: string }>;
- guidance: string[];
-};
-
-export type Preferences = {
- titleEdits: Array<{ before: string; after: string }>;
- discardRate: number | null;
- observations: string[];
-};
+const breakdownSchema = z.object({
+ key: z.string(),
+ clips: z.number(),
+ retention: z.number().nullable(),
+ ctr: z.number().nullable(),
+ views: z.number().nullable(),
+});
+
+export type Breakdown = z.infer<typeof breakdownSchema>;
+
+const insightsSchema = z.object({
+ sampleSize: z.number(),
+ byContentType: z.array(breakdownSchema),
+ byCaptionStyle: z.array(breakdownSchema),
+ byLength: z.array(breakdownSchema),
+ topClips: z.array(
+ z.object({ title: z.string(), retention: z.number(), views: z.number(), content_type: z.string() }),
+ ),
+ guidance: z.array(z.string()),
+});
+
+export type Insights = z.infer<typeof insightsSchema>;
+
+const preferencesSchema = z.object({
+ titleEdits: z.array(z.object({ before: z.string(), after: z.string() })),
+ discardRate: z.number().nullable(),
+ observations: z.array(z.string()),
+});
+
+export type Preferences = z.infer<typeof preferencesSchema>;
// Nullable because `request` returns null for an empty body, and a caller that
// trusts the declared shape would dereference it.
export async function getInsights(): Promise<Insights | null> {
- return request("GET", "/v1/insights");
+ return request("GET", "/v1/insights", insightsSchema);
}
export async function getPreferences(): Promise<Preferences | null> {
- return request("GET", "/v1/insights/preferences");
+ return request("GET", "/v1/insights/preferences", preferencesSchema);
}
-export async function whoami(): Promise<{
- workspaceId: string;
- role: string;
- plan: string;
- workspace: { name: string; episodes_used: number };
-}> {
- return request("GET", "/v1/auth/me", undefined, 10_000);
+const whoamiSchema = z.object({
+ workspaceId: z.string(),
+ role: z.string(),
+ plan: z.string(),
+ workspace: z.object({ name: z.string(), episodes_used: z.number() }),
+});
+
+export type WhoamiResult = z.infer<typeof whoamiSchema>;
+
+export async function whoami(): Promise<WhoamiResult> {
+ const me = await request("GET", "/v1/auth/me", whoamiSchema, undefined, 10_000);
+
+ if (!me) throw new Error("empty response from /v1/auth/me");
+
+ return me;
}
-export type RemoteKnowledgeFile = { path: string; version: number; updated_at: string };
+const remoteKnowledgeFileSchema = z.object({ path: z.string(), version: z.number(), updated_at: z.string() });
+
+export type RemoteKnowledgeFile = z.infer<typeof remoteKnowledgeFileSchema>;
export async function listKnowledge(): Promise<RemoteKnowledgeFile[]> {
- const payload = await request("GET", "/v1/knowledge");
+ const payload = await request("GET", "/v1/knowledge", z.object({ files: z.array(remoteKnowledgeFileSchema).optional() }));
+
return payload?.files ?? [];
}
export async function getKnowledge(path: string): Promise<{ content: string; version: number }> {
- return request("GET", `/v1/knowledge/file?path=${encodeURIComponent(path)}`);
+ const file = await request(
+ "GET",
+ `/v1/knowledge/file?path=${encodeURIComponent(path)}`,
+ z.object({ content: z.string(), version: z.number() }),
+ );
+
+ if (!file) throw new Error(`empty response for knowledge file ${path}`);
+
+ return file;
}
+const knowledgeConflictSchema = z.object({ version: z.number(), content: z.string() });
+const knowledgePutSchema = z.object({ version: z.number(), unchanged: z.boolean().optional() });
+
export type PutKnowledgeResult =
| { conflict: false; version: number; unchanged: boolean }
| { conflict: true; version: number; content: string };
@@ -198,6 +252,7 @@ export async function putKnowledge(
expectedVersion?: number,
): Promise<PutKnowledgeResult> {
const token = await readToken();
+
if (!token) throw new Error("not signed in");
const response = await fetch(`${apiUrl()}/v1/knowledge/file`, {
@@ -210,24 +265,30 @@ export async function putKnowledge(
// A 409 is an expected outcome here, not an error: someone else edited the
// file. The body carries their version so the caller can show both.
if (response.status === 409) {
- const body = await response.json();
+ const body = knowledgeConflictSchema.parse(await response.json());
+
return { conflict: true, version: body.version, content: body.content };
}
+
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 200)}`);
}
- const body = await response.json();
+
+ const body = knowledgePutSchema.parse(await response.json());
+
return { conflict: false, version: body.version, unchanged: Boolean(body.unchanged) };
}
-export type RemoteAsset = {
- id: string;
- name: string;
- kind: string;
- is_default: boolean;
- size_bytes: string;
- checksum: string;
-};
+const remoteAssetSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ kind: z.string(),
+ is_default: z.boolean(),
+ size_bytes: z.string(),
+ checksum: z.string(),
+});
+
+export type RemoteAsset = z.infer<typeof remoteAssetSchema>;
/** Mirrors how the workspace digests an asset, so an upload can be skipped. */
export function checksum(body: Buffer): string {
@@ -235,10 +296,13 @@ export function checksum(body: Buffer): string {
}
export async function listAssets(): Promise<RemoteAsset[]> {
- const payload = await request("GET", "/v1/assets");
+ const payload = await request("GET", "/v1/assets", z.object({ assets: z.array(remoteAssetSchema).optional() }));
+
return payload?.assets ?? [];
}
+const uploadedAssetSchema = z.object({ id: z.string(), unchanged: z.boolean().optional() });
+
export async function uploadAsset(
name: string,
kind: string,
@@ -246,9 +310,11 @@ export async function uploadAsset(
isDefault = false,
): Promise<{ id: string; unchanged?: boolean }> {
const token = await readToken();
+
if (!token) throw new Error("not signed in");
const params = new URLSearchParams({ name, kind, isDefault: String(isDefault) });
+
const response = await fetch(`${apiUrl()}/v1/assets?${params}`, {
method: "PUT",
headers: {
@@ -259,21 +325,26 @@ export async function uploadAsset(
body: new Uint8Array(body),
signal: AbortSignal.timeout(300_000),
});
+
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 200)}`);
}
- return response.json();
+
+ return uploadedAssetSchema.parse(await response.json());
}
export async function downloadAsset(id: string): Promise<Buffer> {
const token = await readToken();
+
if (!token) throw new Error("not signed in");
const response = await fetch(`${apiUrl()}/v1/assets/${id}/download`, {
headers: { authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(300_000),
});
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
+
return Buffer.from(await response.arrayBuffer());
}
@@ -288,5 +359,5 @@ export async function logClipEvent(
before?: string,
after?: string,
): Promise<void> {
- await request("POST", `/v1/clips/${cloudClipId}/events`, { kind, before, after });
+ await request("POST", `/v1/clips/${cloudClipId}/events`, z.unknown(), { kind, before, after });
}
diff --git a/src/services/python-executor.test.ts b/src/services/python-executor.test.ts
index 56d269e..d391213 100644
--- a/src/services/python-executor.test.ts
+++ b/src/services/python-executor.test.ts
@@ -1,7 +1,6 @@
-import { EventEmitter } from "events";
-import type { ChildProcess } from "child_process";
+import { ChildProcess } from "child_process";
import { describe, it, expect, vi, afterEach } from "vitest";
-import { stderrTail, terminateProcessTree } from "./python-executor.js";
+import { stderrTail, terminateProcessTree, type SpawnProcess } from "./python-executor.js";
describe("stderrTail", () => {
it("returns short stderr unchanged", () => {
@@ -26,6 +25,7 @@ describe("stderrTail", () => {
' File "new.py", line 9',
"ValueError: actual failure",
].join("\n");
+
const tail = stderrTail(stderr);
expect(tail.startsWith("Traceback (most recent call last):")).toBe(true);
expect(tail).toContain("ValueError: actual failure");
@@ -42,9 +42,7 @@ describe("stderrTail", () => {
describe("terminateProcessTree", () => {
const fakeProc = () => {
- const proc = new EventEmitter() as unknown as ChildProcess;
- Object.assign(proc, { pid: 4242, exitCode: null, signalCode: null, kill: vi.fn() });
- return proc;
+ return Object.assign(new ChildProcess(), { pid: 4242, exitCode: null, signalCode: null, kill: vi.fn() });
};
afterEach(() => {
@@ -89,13 +87,12 @@ describe("terminateProcessTree", () => {
it("terminates the full Windows process tree", () => {
vi.useFakeTimers();
const proc = fakeProc();
- const taskkillProc = new EventEmitter();
- const spawnProcess = vi.fn().mockReturnValue(taskkillProc);
+ const spawnProcess = vi.fn<SpawnProcess>().mockReturnValue(new ChildProcess());
const kill = vi.spyOn(process, "kill").mockReturnValue(true);
terminateProcessTree(proc, 2000, {
platform: "win32",
- spawnProcess: spawnProcess as never,
+ spawnProcess,
});
expect(spawnProcess).toHaveBeenCalledWith(
diff --git a/src/services/python-executor.ts b/src/services/python-executor.ts
index 0b98753..dd48d71 100644
--- a/src/services/python-executor.ts
+++ b/src/services/python-executor.ts
@@ -1,5 +1,7 @@
-import { spawn, type ChildProcess } from "child_process";
+import { spawn, type ChildProcess, type SpawnOptions } from "child_process";
import { v4 as uuidv4 } from "uuid";
+import { z } from "zod";
+import { absentWhenNull } from "../utils/zod-helpers.js";
import { paths, pythonEnv } from "../config/paths.js";
import type { TaskRequest, TaskResult, ProgressEvent } from "../models/index.js";
@@ -7,9 +9,12 @@ type ProgressCallback = (event: ProgressEvent) => void;
const isWindows = process.platform === "win32";
+/** The one shape of spawn that taskkill needs, so a test can stand in for it. */
+export type SpawnProcess = (command: string, args: string[], options: SpawnOptions) => ChildProcess;
+
type ProcessTreeOptions = {
platform?: NodeJS.Platform;
- spawnProcess?: typeof spawn;
+ spawnProcess?: SpawnProcess;
};
function hasExited(proc: ChildProcess): boolean {
@@ -23,6 +28,7 @@ export function killProcessTree(
): void {
if (proc.pid === undefined || hasExited(proc)) return;
const platform = options.platform ?? process.platform;
+
try {
if (platform === "win32") {
const taskkill = (options.spawnProcess ?? spawn)(
@@ -30,6 +36,7 @@ export function killProcessTree(
["/pid", String(proc.pid), "/T", "/F"],
{ stdio: "ignore", windowsHide: true }
);
+
taskkill.once("error", () => undefined);
} else process.kill(-proc.pid, signal);
} catch {}
@@ -44,24 +51,32 @@ export function terminateProcessTree(
): void {
if (hasExited(proc)) return;
const platform = options.platform ?? process.platform;
+
if (platform === "win32") {
killProcessTree(proc, "SIGKILL", options);
+
return;
}
let exited = false;
let escalation: NodeJS.Timeout | undefined;
+
const onExit = (): void => {
exited = true;
+
if (escalation) clearTimeout(escalation);
};
+
proc.once("exit", onExit);
+
if (hasExited(proc)) {
proc.removeListener("exit", onExit);
+
return;
}
killProcessTree(proc, "SIGTERM", options);
+
if (exited || hasExited(proc)) return;
escalation = setTimeout(() => {
@@ -70,33 +85,93 @@ export function terminateProcessTree(
escalation.unref();
}
-// Prefer the last traceback block — that's where the actual failure is —
+// Prefer the last traceback block: that's where the actual failure is,
// and keep a tail long enough to include it.
export function stderrTail(stderr: string, maxChars = 4000): string {
const tb = stderr.lastIndexOf("Traceback (most recent call last):");
const tail = tb !== -1 ? stderr.slice(tb) : stderr;
+
return tail.slice(-maxChars);
}
+const resultEnvelopeSchema = z.looseObject({
+ task_id: z.string(),
+ status: z.enum(["success", "error"]),
+ data: z.unknown().optional(),
+ error: absentWhenNull(z.string()),
+});
+
+const clipResultRowSchema = z.looseObject({
+ clip_index: absentWhenNull(z.number()),
+ status: z.enum(["success", "error"]),
+ output_path: absentWhenNull(z.string()),
+ start_second: absentWhenNull(z.number()),
+ end_second: absentWhenNull(z.number()),
+ source_start_second: absentWhenNull(z.number()),
+ source_end_second: absentWhenNull(z.number()),
+ caption_style: absentWhenNull(z.string()),
+ crop_strategy: absentWhenNull(z.string()),
+ format: absentWhenNull(z.enum(["vertical", "horizontal", "square"])),
+ title: absentWhenNull(z.string()),
+ file_size_mb: absentWhenNull(z.number()),
+ duration: absentWhenNull(z.number()),
+ srt_path: absentWhenNull(z.string()),
+ vtt_path: absentWhenNull(z.string()),
+ clean_output_path: absentWhenNull(z.string()),
+ error: absentWhenNull(z.string()),
+});
+
+const progressEventSchema = z.looseObject({
+ task_id: z.string(),
+ stage: z.string(),
+ percent: z.number(),
+ message: z.string(),
+ clip_result: absentWhenNull(clipResultRowSchema),
+ partial: absentWhenNull(z.looseObject({})),
+});
+
function parseResultLine<T>(stdout: string): TaskResult<T> | null {
// The result is the last stdout line that parses to a JSON object with a
// status field; the backend may also print stray lines.
const lines = stdout.trim().split("\n");
+
for (let i = lines.length - 1; i >= 0; i--) {
const trimmed = lines[i].trim();
+
if (!trimmed.startsWith("{")) continue;
+
try {
- const parsed = JSON.parse(trimmed);
- if (parsed && typeof parsed === "object" && "status" in parsed) {
- return parsed as TaskResult<T>;
+ const parsed = resultEnvelopeSchema.safeParse(JSON.parse(trimmed));
+
+ if (parsed.success) {
+ // SAFETY: T is the data shape the caller declared for this task type, which the backend handler returns.
+ return { ...parsed.data, data: parsed.data.data as T | undefined };
}
} catch {
continue;
}
}
+
return null;
}
+/** The part of PythonExecutor that callers need, so a test can hand in a stand-in. */
+export type TaskExecutor = Pick<PythonExecutor, "execute">;
+
+export type ExecutorFactory = (timeoutMs?: number) => TaskExecutor;
+
+let executorFactory: ExecutorFactory = (timeoutMs) => new PythonExecutor(timeoutMs);
+
+/** The executor a long-lived service (the studio server) runs its backend tasks through. */
+export function createExecutor(timeoutMs?: number): TaskExecutor {
+ return executorFactory(timeoutMs);
+}
+
+/** Swap how createExecutor builds executors. Tests use this to keep Python out of the loop. */
+export function setExecutorFactory(factory: ExecutorFactory): void {
+ executorFactory = factory;
+}
+
/**
* Executes Python backend tasks via subprocess.
* Communication: JSON over stdin (request) → stdout (result), stderr (progress logs).
@@ -109,9 +184,9 @@ export class PythonExecutor {
this.timeoutMs = timeoutMs;
}
- async execute<T = Record<string, unknown>>(
+ async execute<T = object, P extends object = object>(
taskType: TaskRequest["task_type"],
- params: Record<string, unknown>,
+ params: P,
onProgress?: ProgressCallback
): Promise<TaskResult<T>> {
const taskId = uuidv4();
@@ -140,6 +215,7 @@ export class PythonExecutor {
const finish = (action: () => void): void => {
if (settled) return;
settled = true;
+
if (timer) clearTimeout(timer);
action();
};
@@ -161,9 +237,12 @@ export class PythonExecutor {
for (const line of lines) {
const trimmed = line.trim();
+
if (!trimmed || !trimmed.startsWith("{")) continue;
+
try {
- const event = JSON.parse(trimmed) as ProgressEvent;
+ const event = progressEventSchema.parse(JSON.parse(trimmed));
+
if (event.task_id === taskId && onProgress) {
onProgress(event);
}
@@ -184,6 +263,7 @@ export class PythonExecutor {
proc.on("close", (code) => {
finish(() => {
const result = parseResultLine<T>(stdout);
+
if (!result) {
reject(
new Error(
@@ -191,11 +271,13 @@ export class PythonExecutor {
`Stdout: ${stdout.slice(-300)}. Stderr: ${stderrTail(stderr)}`
)
);
+
return;
}
if (result.status === "error") {
reject(new Error(result.error || "Unknown Python error"));
+
return;
}
diff --git a/src/services/transcript-cache.test.ts b/src/services/transcript-cache.test.ts
index 89ec356..8827848 100644
--- a/src/services/transcript-cache.test.ts
+++ b/src/services/transcript-cache.test.ts
@@ -5,7 +5,9 @@ import { join } from "path";
import type { TranscriptResult } from "../models/index.js";
const tmp = mkdtempSync(join(tmpdir(), "podcli-cache-test-"));
+
process.env.PODCLI_HOME = tmp;
+
process.env.PODCLI_DATA = tmp;
const { TranscriptCache, hasSpeakerLabels, needsDiarizationRetry } = await import(
@@ -15,6 +17,7 @@ const { TranscriptCache, hasSpeakerLabels, needsDiarizationRetry } = await impor
function makeFakeVideo(name: string, content: string): string {
const p = join(tmp, name);
writeFileSync(p, content);
+
return p;
}
@@ -54,7 +57,7 @@ describe("TranscriptCache", () => {
expect(loaded?.words).toHaveLength(2);
});
- it("hashes the file content — different files get different cache keys", async () => {
+ it("hashes the file content: different files get different cache keys", async () => {
const a = makeFakeVideo("a.mp4", "content A");
const b = makeFakeVideo("b.mp4", "content B");
await cache.set(a, { ...fakeTranscript, transcript: "A" });
@@ -84,11 +87,13 @@ describe("TranscriptCache", () => {
const file = makeFakeVideo("packed-multi-key.mp4", "packed multi key");
mkdirSync(join(tmp, "packed"), { recursive: true });
const base = await cache.getFileHashForEngine(file, { engine: "whispercpp" });
+
const small = await cache.getFileHashForEngine(file, {
engine: "whispercpp",
model: "small",
language: "ka",
});
+
writeFileSync(join(tmp, "packed", `${base}.md`), "# base");
writeFileSync(join(tmp, "packed", `${small}.md`), "# small-ka");
expect(await cache.getPackedMarkdown(file, { engine: "whispercpp" })).toBe("# base");
@@ -107,11 +112,13 @@ describe("TranscriptCache", () => {
const first = await cache.getFileHashForEngine(file, { engine: "whispercpp", model: "small" });
writeFileSync(join(tmp, "packed", `${first}.md`), "# first");
await new Promise((r) => setTimeout(r, 5));
+
const second = await cache.getFileHashForEngine(file, {
engine: "whispercpp",
model: "medium",
language: "ka",
});
+
writeFileSync(join(tmp, "packed", `${second}.md`), "# second");
// Caller only knows the engine, not which model/language actually ran.
// Deterministic rule: most recently written entry for this hash+engine.
@@ -188,30 +195,30 @@ describe("TranscriptCache", () => {
});
+function spokenWord(speaker: string | null): TranscriptResult["words"][number] {
+ return { word: "hi", start: 0, end: 1, confidence: 1, speaker };
+}
+
describe("hasSpeakerLabels", () => {
it("accepts a transcript with speaker segments", () => {
expect(hasSpeakerLabels({ speaker_segments: [{ speaker: "S0", start: 0, end: 1 }] })).toBe(true);
});
it("accepts a transcript whose words carry speakers", () => {
- expect(hasSpeakerLabels({ words: [{ word: "hi", speaker: "SPEAKER_00" }] })).toBe(true);
+ expect(hasSpeakerLabels({ words: [spokenWord("SPEAKER_00")] })).toBe(true);
});
it("rejects a count with no labels behind it", () => {
// The packer emits "S?" on every line for this shape, so serving it back
// to a request for speakers would make re-transcribing a no-op.
expect(
- hasSpeakerLabels({ speakers: { num_speakers: 2 }, speaker_segments: [], words: [] }),
+ hasSpeakerLabels({ speaker_segments: [], words: [] }),
).toBe(false);
});
it("rejects the shape a whisper.cpp run leaves behind", () => {
expect(
- hasSpeakerLabels({
- speakers: { num_speakers: 0 },
- speaker_segments: [],
- words: [{ word: "hi", speaker: null }],
- }),
+ hasSpeakerLabels({ speaker_segments: [], words: [spokenWord(null)] }),
).toBe(false);
});
@@ -222,8 +229,8 @@ describe("hasSpeakerLabels", () => {
});
describe("needsDiarizationRetry", () => {
- const unlabelled = { diarization_attempted: false, words: [] };
- const attemptedButNoneFound = { diarization_attempted: true, words: [] };
+ const unlabelled = { diarization_attempted: false };
+ const attemptedButNoneFound = { diarization_attempted: true };
it("is false when diarization wasn't requested", () => {
expect(needsDiarizationRetry(unlabelled, false, true)).toBe(false);
diff --git a/src/services/transcript-cache.ts b/src/services/transcript-cache.ts
index ccda03a..274f01b 100644
--- a/src/services/transcript-cache.ts
+++ b/src/services/transcript-cache.ts
@@ -12,8 +12,14 @@ export interface CacheKeyParts {
model?: string;
language?: string;
}
+
export type CacheKey = string | CacheKeyParts;
+/** A bare string is the pre-existing call shape and means engine only. */
+function keyParts(key?: CacheKey): CacheKeyParts {
+ return key instanceof Object ? key : { engine: key };
+}
+
/**
* Caches transcripts by file hash so we don't re-transcribe
* the same podcast when creating multiple clips.
@@ -24,19 +30,16 @@ export type CacheKey = string | CacheKeyParts;
* that asks for speaker labels is otherwise answered with the speaker-less
* transcript that is already on disk. Re-transcribing then looks like a no-op.
*/
-export function hasSpeakerLabels(transcript: unknown): boolean {
- const t = transcript as {
- speaker_segments?: Array<{ speaker?: unknown }>;
- words?: Array<{ speaker?: unknown }>;
- } | null;
+export function hasSpeakerLabels(t: Partial<Pick<TranscriptResult, "speaker_segments" | "words">> | null | undefined): boolean {
if (!t) return false;
+
// Read the labels, not the count. A summary can report two speakers while
// the segments and per-word fields are both empty, and the packer then emits
// "S?" on every line. Trusting the count would serve that cache back to a
// request that asked for speakers.
- const labelled = (items?: Array<{ speaker?: unknown }>) =>
- items?.some((i) => typeof i.speaker === "string" && i.speaker.trim().length > 0) ??
- false;
+ const labelled = (items?: Array<{ speaker?: string | null }>) =>
+ items?.some((i) => (i.speaker?.trim().length ?? 0) > 0) ?? false;
+
return labelled(t.speaker_segments) || labelled(t.words);
}
@@ -51,13 +54,13 @@ export function hasSpeakerLabels(transcript: unknown): boolean {
* genuinely found one speaker".
*/
export function needsDiarizationRetry(
- cached: unknown,
+ cached: Pick<TranscriptResult, "diarization_attempted"> | null | undefined,
enableDiarization: boolean,
engineCanDiarize: boolean,
): boolean {
if (!cached || !enableDiarization || !engineCanDiarize) return false;
- const attempted = (cached as { diarization_attempted?: unknown }).diarization_attempted;
- return attempted !== true;
+
+ return cached.diarization_attempted !== true;
}
export class TranscriptCache {
@@ -94,13 +97,14 @@ export class TranscriptCache {
};
const stream = createReadStream(filePath);
- stream.on("data", (chunk) => {
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
+ stream.on("data", (buf: Buffer) => {
+
if (bytesRead < maxBytes) {
const remaining = maxBytes - bytesRead;
hash.update(buf.subarray(0, Math.min(buf.length, remaining)));
bytesRead += buf.length;
}
+
if (bytesRead >= maxBytes) {
stream.destroy();
}
@@ -128,15 +132,19 @@ export class TranscriptCache {
private engineSuffix(engine?: string): string {
const value = (engine ?? "").trim().toLowerCase();
+
if (["whispercpp", "whisper-cpp", "whisper.cpp", "cpp"].includes(value)) {
return "-whispercpp";
}
+
if (["assemblyai", "assembly-ai", "aai"].includes(value)) {
return "-assemblyai";
}
+
if (["omnilingual", "omni", "omnilingual-asr"].includes(value)) {
return "-omnilingual";
}
+
return "";
}
@@ -163,12 +171,13 @@ export class TranscriptCache {
* of silently colliding with that implicit default.
*/
private keySuffix(key?: CacheKey): string {
- const parts = typeof key === "string" ? { engine: key } : key ?? {};
+ const parts = keyParts(key);
const engineSuffix = this.engineSuffix(parts.engine);
const model = (parts.model ?? "").trim().toLowerCase();
const modelSuffix = model && model !== "base" ? `-m${model}` : "";
const language = this.sanitizeLanguage(parts.language);
const languageSuffix = language && language !== "auto" ? `-l${language}` : "";
+
return `${engineSuffix}${modelSuffix}${languageSuffix}`;
}
@@ -180,6 +189,8 @@ export class TranscriptCache {
if (!existsSync(cachePath)) return null;
const data = await readFile(cachePath, "utf-8");
+
+ // SAFETY: cache files are written only by set() and the Python transcription cache, both in TranscriptResult shape.
return JSON.parse(data) as TranscriptResult;
} catch {
return null;
@@ -204,19 +215,23 @@ export class TranscriptCache {
*/
async getPackedMarkdown(filePath: string, key?: CacheKey): Promise<string | null> {
try {
- const parts = typeof key === "string" ? { engine: key } : key ?? {};
+ const parts = keyParts(key);
+
if (parts.model !== undefined || parts.language !== undefined) {
// The caller knows exactly which combo it wants: read that key
// only, never silently substitute a different model/language's view.
const hash = await this.getFileHashForEngine(filePath, parts);
+
return await this.readPackedByHash(hash);
}
+
// The caller only knows the engine (e.g. get_ui_state, which has a
// cached transcript object but not the model/language that produced
// it), fall back to the same deterministic scan the Python side uses
// in find_cached_transcript_path.
const hash = await this.getFileHash(filePath);
const found = await this.findPackedPath(hash, parts.engine);
+
return found ? await readFile(found, "utf-8") : null;
} catch {
return null;
@@ -231,15 +246,20 @@ export class TranscriptCache {
private async findPackedPath(hash: string, engine?: string): Promise<string | null> {
const engineSuffix = this.engineSuffix(engine);
const exact = join(paths.packed, `${hash}${engineSuffix}.md`);
+
if (existsSync(exact)) return exact;
+
if (!existsSync(paths.packed)) return null;
const { readdirSync, statSync } = await import("fs");
const prefix = `${hash}${engineSuffix}`;
const tailRe = /^(-m[a-z0-9]+)?(-l[a-z0-9-]+)?\.md$/;
+
const candidates = readdirSync(paths.packed)
.filter((name) => name.startsWith(prefix) && tailRe.test(name.slice(prefix.length)))
.map((name) => join(paths.packed, name));
+
if (!candidates.length) return null;
+
return candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
}
@@ -254,6 +274,7 @@ export class TranscriptCache {
.update(rawText, "utf-8")
.digest("hex")
.slice(0, 16);
+
return await this.readPackedByHash(hash);
} catch {
return null;
@@ -262,7 +283,9 @@ export class TranscriptCache {
private async readPackedByHash(hash: string): Promise<string | null> {
const packedPath = join(paths.packed, `${hash}.md`);
+
if (!existsSync(packedPath)) return null;
+
return await readFile(packedPath, "utf-8");
}
}
diff --git a/src/services/ui-state-file.ts b/src/services/ui-state-file.ts
new file mode 100644
index 0000000..6fb3316
--- /dev/null
+++ b/src/services/ui-state-file.ts
@@ -0,0 +1,9 @@
+import { readFileSync } from "fs";
+import { paths } from "../config/paths.js";
+import type { UIState } from "../models/index.js";
+
+/** Read the studio's persisted session state. Throws when the file is missing or unreadable. */
+export function readUIStateFile(): UIState {
+ // SAFETY: ui-state.json is written only by the studio's persistState(), which serializes a UIState.
+ return JSON.parse(readFileSync(paths.uiState, "utf-8")) as UIState;
+}
diff --git a/src/sync.ts b/src/sync.ts
index 059afb9..a32c432 100644
--- a/src/sync.ts
+++ b/src/sync.ts
@@ -1,48 +1,58 @@
-import { ClipsHistory } from "./services/clips-history.js";
+import { ClipsHistory, cloudSyncEnabled } from "./services/clips-history.js";
import * as assetSync from "./services/asset-sync.js";
import * as knowledgeSync from "./services/knowledge-sync.js";
import * as cloud from "./services/podcli-cloud.js";
/**
- * `podcli sync` — reconcile this machine with the workspace.
+ * `podcli sync`: reconcile this machine with the workspace.
*
* Clips, assets, and knowledge each sync automatically at the moments that
* matter (render, login), so this is the manual catch-up: after working
* offline, after a teammate changes the brand guide, or on a new machine.
*
- * Every step is independent and none can fail another — a knowledge conflict
+ * Every step is independent and none can fail another: a knowledge conflict
* must not stop assets from arriving.
*/
async function main(): Promise<number> {
if (!(await cloud.signedIn())) {
console.log("Not signed in to podcli Pro. Run `podcli login` first.");
+
return 1;
}
let problems = 0;
console.log("Syncing clips...");
- try {
- const { synced, failed } = await new ClipsHistory().backfillCloud();
- console.log(
- synced || failed
- ? ` ${synced} synced${failed ? `, ${failed} failed` : ""}`
- : " already up to date",
- );
- problems += failed;
- } catch (err) {
- console.log(` failed: ${err instanceof Error ? err.message : String(err)}`);
- problems++;
+
+ if (!cloudSyncEnabled()) {
+ console.log(" skipped: clip sync uploads rendered videos. Set PODCLI_CLOUD_SYNC=1 to turn it on.");
+ } else {
+ try {
+ const { synced, failed } = await new ClipsHistory().backfillCloud();
+ console.log(
+ synced || failed
+ ? ` ${synced} synced${failed ? `, ${failed} failed` : ""}`
+ : " already up to date",
+ );
+ problems += failed;
+ } catch (err) {
+ console.log(` failed: ${err instanceof Error ? err.message : String(err)}`);
+ problems++;
+ }
}
console.log("Syncing assets...");
+
try {
const report = await assetSync.sync();
+
const parts = [
report.uploaded.length && `${report.uploaded.length} uploaded`,
report.downloaded.length && `${report.downloaded.length} downloaded`,
].filter(Boolean);
+
console.log(parts.length ? ` ${parts.join(", ")}` : " already up to date");
+
for (const f of report.failed) console.log(` ${f.name}: ${f.reason}`);
problems += report.failed.length;
} catch (err) {
@@ -51,20 +61,24 @@ async function main(): Promise<number> {
}
console.log("Syncing knowledge base...");
+
try {
const report = await knowledgeSync.sync();
+
const parts = [
report.pushed.length && `${report.pushed.length} pushed`,
report.pulled.length && `${report.pulled.length} pulled`,
].filter(Boolean);
+
console.log(parts.length ? ` ${parts.join(", ")}` : " already up to date");
for (const conflict of report.conflicts) {
console.log(
- ` conflict: ${conflict.path} — the workspace copy was saved as ` +
+ ` conflict: ${conflict.path}: the workspace copy was saved as ` +
`${conflict.path}.workspace-${conflict.theirVersion}. Merge it, then sync again.`,
);
}
+
for (const f of report.failed) console.log(` ${f.path}: ${f.reason}`);
problems += report.failed.length;
} catch (err) {
diff --git a/src/test-support/mcp-client.ts b/src/test-support/mcp-client.ts
new file mode 100644
index 0000000..2c3f42e
--- /dev/null
+++ b/src/test-support/mcp-client.ts
@@ -0,0 +1,49 @@
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+
+export interface ToolReply {
+ text: string;
+ isError: boolean;
+}
+
+/** Connect a client to the server over a linked in-memory pair, so tests call tools through the public protocol. */
+export async function connectClient(server: McpServer): Promise<Client> {
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: "podcli-test", version: "0.0.0" });
+ await Promise.all([server.connect(serverSide), client.connect(clientSide)]);
+
+ return client;
+}
+
+export interface ToolArgs {
+ [field: string]: string | number | boolean | string[];
+}
+
+export async function callTool(server: McpServer, name: string, args: ToolArgs): Promise<ToolReply> {
+ const client = await connectClient(server);
+
+ try {
+ const reply = await client.callTool({ name, arguments: args });
+ const content = Array.isArray(reply.content) ? reply.content : [];
+
+ return {
+ text: content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"),
+ isError: reply.isError === true,
+ };
+ } finally {
+ await client.close();
+ }
+}
+
+export async function listToolNames(server: McpServer): Promise<Set<string>> {
+ const client = await connectClient(server);
+
+ try {
+ const { tools } = await client.listTools();
+
+ return new Set(tools.map((tool) => tool.name));
+ } finally {
+ await client.close();
+ }
+}
diff --git a/src/test-support/stub-python-backend.ts b/src/test-support/stub-python-backend.ts
new file mode 100644
index 0000000..0cea200
--- /dev/null
+++ b/src/test-support/stub-python-backend.ts
@@ -0,0 +1,19 @@
+import { vi } from "vitest";
+
+/**
+ * Stand in for the Python backend: every task succeeds with whatever `reply` returns for its type.
+ *
+ * Loads python-executor on demand because it reads PODCLI_HOME through paths.ts, so a test has to
+ * set its environment first.
+ */
+export async function stubPythonBackend(reply: (taskType: string) => object = () => ({})): Promise<void> {
+ const { setExecutorFactory } = await import("../services/python-executor.js");
+
+ const execute = vi.fn().mockImplementation(async (taskType: string) => ({
+ task_id: "stub",
+ status: "success",
+ data: reply(taskType),
+ }));
+
+ setExecutorFactory(() => ({ execute }));
+}
diff --git a/src/thumbnail-config-tool.test.ts b/src/thumbnail-config-tool.test.ts
index 499fd22..f1e1601 100644
--- a/src/thumbnail-config-tool.test.ts
+++ b/src/thumbnail-config-tool.test.ts
@@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest
import { mkdtempSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { callTool, type ToolArgs } from "./test-support/mcp-client.js";
// manage_thumbnail_config talks to the studio's /api/thumbnail-config. These
// stub that endpoint and check what set_layout sends it.
@@ -21,6 +22,7 @@ beforeAll(async () => {
afterAll(() => {
if (savedHome === undefined) delete process.env.PODCLI_HOME;
else process.env.PODCLI_HOME = savedHome;
+
if (savedData === undefined) delete process.env.PODCLI_DATA;
else process.env.PODCLI_DATA = savedData;
rmSync(tmp, { recursive: true, force: true });
@@ -30,24 +32,20 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-function handler() {
- const server = createServer() as unknown as {
- _registeredTools: Record<string, { handler: (args: unknown, extra: unknown) => Promise<{ content: { text: string }[] }> }>;
- };
- return server._registeredTools.manage_thumbnail_config.handler;
-}
+const manageThumbnailConfig = (args: ToolArgs) => callTool(createServer(), "manage_thumbnail_config", args);
describe("manage_thumbnail_config set_layout", () => {
it("writes the layout into the template and keeps every other field", async () => {
const calls: { method: string; body?: string }[] = [];
vi.stubGlobal("fetch", vi.fn(async (_url: string, init?: RequestInit) => {
- calls.push({ method: init?.method ?? "GET", body: init?.body as string | undefined });
+ calls.push({ method: init?.method ?? "GET", body: init?.body === undefined ? undefined : String(init.body) });
+
return new Response(JSON.stringify({ accent_color: "#FF3366", layout: "single" }), { status: 200 });
}));
- const result = await handler()({ action: "set_layout", layout: "pair" }, {});
+ const result = await manageThumbnailConfig({ action: "set_layout", layout: "pair" });
- expect(result.content[0].text).toBe("Thumbnail layout set to pair.");
+ expect(result.text).toBe("Thumbnail layout set to pair.");
const put = calls.find((c) => c.method === "PUT");
expect(JSON.parse(put!.body!)).toEqual({ accent_color: "#FF3366", layout: "pair" });
});
@@ -55,8 +53,8 @@ describe("manage_thumbnail_config set_layout", () => {
it("asks for the layout when it is missing", async () => {
const fetch = vi.fn();
vi.stubGlobal("fetch", fetch);
- const result = await handler()({ action: "set_layout" }, {});
- expect(result.content[0].text).toContain("'layout' is required");
+ const result = await manageThumbnailConfig({ action: "set_layout" });
+ expect(result.text).toContain("'layout' is required");
expect(fetch).not.toHaveBeenCalled();
});
});
diff --git a/src/ui-state-offline.test.ts b/src/ui-state-offline.test.ts
index 5ee62fb..524c916 100644
--- a/src/ui-state-offline.test.ts
+++ b/src/ui-state-offline.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeAll, afterAll, afterEach } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { callTool } from "./test-support/mcp-client.js";
// get_ui_state used to report "Web UI is not running" whenever the Web UI
// process was down, even though the same state it would have served lives on
@@ -29,6 +30,7 @@ beforeAll(async () => {
afterAll(() => {
if (savedHome === undefined) delete process.env.PODCLI_HOME;
else process.env.PODCLI_HOME = savedHome;
+
if (savedData === undefined) delete process.env.PODCLI_DATA;
else process.env.PODCLI_DATA = savedData;
rmSync(tmp, { recursive: true, force: true });
@@ -39,15 +41,10 @@ afterEach(() => {
rmSync(uiStatePath, { force: true });
});
-function getUiStateHandler() {
- const server = createServer() as unknown as {
- _registeredTools: Record<string, { handler: (args: unknown, extra: unknown) => Promise<{ content: { text: string }[] }> }>;
- };
- return server._registeredTools["get_ui_state"].handler;
-}
+const getUiState = (include_transcript: boolean) => callTool(createServer(), "get_ui_state", { include_transcript });
function stubWebUiDown() {
- globalThis.fetch = (() => Promise.reject(new Error("fetch failed"))) as typeof fetch;
+ globalThis.fetch = () => Promise.reject(new Error("fetch failed"));
}
describe("get_ui_state offline fallback", () => {
@@ -65,9 +62,7 @@ describe("get_ui_state offline fallback", () => {
);
stubWebUiDown();
- const handler = getUiStateHandler();
- const result = await handler({ include_transcript: false }, {});
- const text = result.content[0].text;
+ const { text } = await getUiState(false);
expect(text).toContain("/videos/ep42.mp4");
expect(text).toContain("Transcript: 3 words");
@@ -77,9 +72,7 @@ describe("get_ui_state offline fallback", () => {
it("falls back to start-from-scratch guidance when there is no state anywhere", async () => {
stubWebUiDown();
- const handler = getUiStateHandler();
- const result = await handler({ include_transcript: false }, {});
- const text = result.content[0].text;
+ const { text } = await getUiState(false);
expect(text).toContain("Start from scratch");
});
diff --git a/src/ui/client/AnalyticsPage.tsx b/src/ui/client/AnalyticsPage.tsx
index 0c6cd67..98eb44e 100644
--- a/src/ui/client/AnalyticsPage.tsx
+++ b/src/ui/client/AnalyticsPage.tsx
@@ -6,6 +6,7 @@ import { api, upload, fmt } from "./lib";
import WorkspaceInsights from "./WorkspaceInsights";
interface Row { key: string; count: number; avgViews: number; avgRetention: number; avgCtr: number }
+
interface Data {
published: number; total: number;
byContentType: Row[]; byCaptionStyle: Row[]; byLength: Row[];
@@ -16,12 +17,16 @@ const fmtViews = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : Strin
function weighted(rows: Row[], metric: "avgRetention" | "avgCtr") {
const total = rows.reduce((s, r) => s + r.count, 0);
+
if (!total) return 0;
+
return Math.round(rows.reduce((s, r) => s + r[metric] * r.count, 0) / total);
}
+
function totalViews(rows: Row[]) {
return rows.reduce((s, r) => s + r.avgViews * r.count, 0);
}
+
function best(rows: Row[], metric: "avgRetention" | "avgCtr" | "avgViews") {
return rows.length ? rows.reduce((a, b) => (b[metric] > a[metric] ? b : a)) : null;
}
@@ -40,6 +45,7 @@ function StatTile({ icon, label, value, sub }: { icon: React.ReactNode; label: s
function BarGroup({ title, hint, rows, metric }: { title: string; hint: string; rows: Row[]; metric: "avgRetention" | "avgCtr" | "avgViews" }) {
const max = Math.max(1, ...rows.map((r) => r[metric]));
const unit = metric === "avgViews" ? "" : "%";
+
return (
<div className="section card">
<div className="section-label" style={{ marginBottom: 2 }}>{title}</div>
@@ -77,12 +83,15 @@ export default function AnalyticsPage() {
api("/youtube/status").then(setStatus).catch(() => {});
api("/youtube/config").then((c) => { setClientId(c.client_id || ""); setHasSecret(!!c.has_secret); }).catch(() => {});
};
+
useEffect(load, []);
const saveConfig = async () => {
setBusy(true); setMsg(null);
+
try {
- const r = await api("/youtube/config", { method: "PUT", body: JSON.stringify({ client_id: clientId, ...(clientSecret ? { client_secret: clientSecret } : {}) }) });
+ const r = await api("/youtube/config", { method: "PUT", body: JSON.stringify({ client_id: clientId, ...(clientSecret && { client_secret: clientSecret }) }) });
+
if (r.error) throw new Error(r.error);
setClientSecret(""); setHasSecret(true);
setMsg("Saved. Run podcli youtube auth in your terminal to authorize");
@@ -91,8 +100,10 @@ export default function AnalyticsPage() {
const sync = async (csvPath?: string) => {
setBusy(true); setMsg(null);
+
try {
const r = await api("/youtube/sync", { method: "POST", body: JSON.stringify(csvPath ? { csv_path: csvPath } : {}) });
+
if (r.error) throw new Error(r.error);
setMsg("Synced"); load();
} catch (e: any) { setMsg(`Sync failed: ${e.message}`); } finally { setBusy(false); }
@@ -100,6 +111,7 @@ export default function AnalyticsPage() {
const loadProposals = async () => {
setBusy(true); setMsg(null); setProposals(null);
+
try {
const r = await api<any>("/youtube/links");
setProposals(r.proposals || []);
@@ -108,6 +120,7 @@ export default function AnalyticsPage() {
const linkClip = async (clipId: string, videoId: string) => {
setLinkBusy(clipId);
+
try {
await api("/youtube/link", { method: "POST", body: JSON.stringify({ clip_id: clipId, video_id: videoId }) });
setProposals((ps) => (ps || []).filter((p) => p.clip_id !== clipId));
@@ -117,8 +130,10 @@ export default function AnalyticsPage() {
const analyze = async () => {
setBusy(true); setMsg("Analyzing top performers vs underperformers…");
+
try {
const r = await api("/youtube/learn", { method: "POST", body: "{}" });
+
if (r.error) throw new Error(r.error);
setMsg("Analysis written to the knowledge base. Claude will use it when picking shorts");
} catch (e: any) { setMsg(`Analysis failed: ${e.message}`); } finally { setBusy(false); }
@@ -126,9 +141,11 @@ export default function AnalyticsPage() {
const importCsv = async (f: File) => {
setBusy(true); setMsg(null);
+
try {
const fd = new FormData(); fd.append("file", f);
const up = await upload<any>("/upload", fd);
+
if (!up.file_path) throw new Error("upload failed");
await sync(up.file_path);
} catch (e: any) { setMsg(`Import failed: ${e.message}`); setBusy(false); }
@@ -138,11 +155,14 @@ export default function AnalyticsPage() {
const bestRetention = data ? best(data.byContentType, "avgRetention") : null;
const bestCtr = data ? best(data.byCaptionStyle, "avgCtr") : null;
const bestLength = data ? best(data.byLength, "avgRetention") : null;
- const insights = [
- bestRetention && { label: "Holds viewers best", value: bestRetention.key, metric: `${bestRetention.avgRetention}% retention` },
- bestCtr && { label: "Best packaging", value: `${bestCtr.key} captions`, metric: `${bestCtr.avgCtr}% CTR` },
- bestLength && { label: "Ideal length", value: bestLength.key, metric: `${bestLength.avgRetention}% retention` },
- ].filter(Boolean) as { label: string; value: string; metric: string }[];
+
+ const insights: { label: string; value: string; metric: string }[] = [];
+
+ if (bestRetention) insights.push({ label: "Holds viewers best", value: bestRetention.key, metric: `${bestRetention.avgRetention}% retention` });
+
+ if (bestCtr) insights.push({ label: "Best packaging", value: `${bestCtr.key} captions`, metric: `${bestCtr.avgCtr}% CTR` });
+
+ if (bestLength) insights.push({ label: "Ideal length", value: bestLength.key, metric: `${bestLength.avgRetention}% retention` });
return (
<div className="app">
diff --git a/src/ui/client/AssetPicker.tsx b/src/ui/client/AssetPicker.tsx
index c1380d9..b717cb5 100644
--- a/src/ui/client/AssetPicker.tsx
+++ b/src/ui/client/AssetPicker.tsx
@@ -6,12 +6,15 @@ import { useAssets, assetSrc, ASSET_GROUPS, type Asset, type AssetType } from ".
function Thumb({ asset }: { asset: Asset }) {
const src = assetSrc(asset.name);
+
if (asset.type === "logo" || asset.type === "image") {
return <img className="picker-thumb" src={src} alt="" />;
}
+
if (asset.type === "outro" || asset.type === "intro" || asset.type === "video") {
return <video className="picker-thumb" src={src} muted preload="metadata" />;
}
+
return <div className="picker-thumb picker-thumb-file" />;
}
@@ -41,15 +44,19 @@ export default function AssetPicker({
useEffect(() => {
if (!open) return;
+
const close = (e: MouseEvent) => {
- if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
+ if (ref.current && !(e.target instanceof Node && ref.current.contains(e.target))) setOpen(false);
};
+
document.addEventListener("mousedown", close);
+
return () => document.removeEventListener("mousedown", close);
}, [open]);
async function onUpload(f: File) {
setUploading(true);
+
try {
const asset = await uploadFile(f, type);
onChange(asset.path);
@@ -95,7 +102,9 @@ export default function AssetPicker({
type="file"
accept={ASSET_GROUPS.find((g) => g.type === type)?.accept ?? "*/*"}
style={{ display: "none" }}
- onChange={(e) => { const f = e.target.files?.[0]; e.target.value = ""; if (f) onUpload(f); }}
+ onChange={(e) => { const f = e.target.files?.[0]; e.target.value = "";
+
+ if (f) onUpload(f); }}
/>
<div className="asset-picker-foot">
<button className="asset-picker-opt" disabled={uploading} onClick={() => fileRef.current?.click()}>
@@ -112,6 +121,8 @@ export default function AssetPicker({
function matchesGroup(assetType: AssetType, groupType: AssetType): boolean {
if (groupType === "outro") return assetType === "outro" || assetType === "video";
+
if (groupType === "music") return assetType === "music" || assetType === "audio";
+
return assetType === groupType;
}
diff --git a/src/ui/client/AssetsPage.tsx b/src/ui/client/AssetsPage.tsx
index d51c106..126dc96 100644
--- a/src/ui/client/AssetsPage.tsx
+++ b/src/ui/client/AssetsPage.tsx
@@ -24,15 +24,21 @@ function AudioPlayer({ src }: { src: string }) {
const toggle = () => {
const a = ref.current;
+
if (!a) return;
- a.paused ? a.play() : a.pause();
+
+ if (a.paused) void a.play();
+ else a.pause();
};
+
const seek = (clientX: number, el: HTMLDivElement) => {
const a = ref.current;
+
if (!a || !dur) return;
const r = el.getBoundingClientRect();
a.currentTime = Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * dur;
};
+
const pct = dur ? (t / dur) * 100 : 0;
return (
@@ -63,20 +69,25 @@ function AudioPlayer({ src }: { src: string }) {
function Preview({ asset, onOpen }: { asset: Asset; onOpen: () => void }) {
const src = assetSrc(asset.name);
+
if (asset.type === "logo" || asset.type === "image") {
return <img className="asset-thumb clickable" src={src} alt={asset.name} loading="lazy" onClick={onOpen} />;
}
+
if (asset.type === "outro" || asset.type === "intro" || asset.type === "video") {
return <video className="asset-thumb clickable" src={src} muted preload="metadata" onClick={onOpen} />;
}
+
if (asset.type === "music" || asset.type === "audio") {
return <div className="asset-thumb asset-thumb-audio"><AudioPlayer src={src} /></div>;
}
+
return <div className="asset-thumb asset-thumb-file clickable" onClick={onOpen}>{extLabel(asset.path)}</div>;
}
function AssetLightbox({ asset, onClose }: { asset: Asset; onClose: () => void }) {
const src = assetSrc(asset.name);
+
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="modal-body" onClick={(e) => e.stopPropagation()}>
@@ -101,6 +112,7 @@ function AssetLightbox({ asset, onClose }: { asset: Asset; onClose: () => void }
function extLabel(path: string): string {
const ext = (path.split(".").pop() || "").toUpperCase();
+
return ext.length <= 4 ? ext : "FILE";
}
@@ -113,15 +125,18 @@ function OverflowMenu({ items }: { items: { label: string; onClick: () => void;
useEffect(() => {
if (!open) return;
+
// Skip the trigger so its onClick can toggle closed, not reopen.
const onDocMouseDown = (e: MouseEvent) => {
- if (btnRef.current?.contains(e.target as Node)) return;
+ if (e.target instanceof Node && btnRef.current?.contains(e.target)) return;
setOpen(false);
};
+
const dismiss = () => setOpen(false);
document.addEventListener("mousedown", onDocMouseDown);
window.addEventListener("scroll", dismiss, true);
window.addEventListener("resize", dismiss);
+
return () => {
document.removeEventListener("mousedown", onDocMouseDown);
window.removeEventListener("scroll", dismiss, true);
@@ -131,13 +146,16 @@ function OverflowMenu({ items }: { items: { label: string; onClick: () => void;
function openMenu() {
const r = btnRef.current?.getBoundingClientRect();
+
if (r) {
const menuHeight = items.length * 34 + 8;
const left = Math.max(8, Math.min(r.right - MENU_WIDTH, window.innerWidth - MENU_WIDTH - 8));
let top = r.bottom + 4;
+
if (top + menuHeight > window.innerHeight - 8) top = Math.max(8, r.top - menuHeight - 4);
setPos({ top, left });
}
+
setOpen((v) => !v);
}
@@ -196,6 +214,7 @@ function AssetCard({
if (!renaming) return;
setRenaming(false);
const next = draft.trim();
+
if (next && next !== asset.name) onRename(next);
else setDraft(asset.name);
}
@@ -217,6 +236,7 @@ function AssetCard({
onBlur={commitRename}
onKeyDown={(e) => {
if (e.key === "Enter") commitRename();
+
if (e.key === "Escape") { setDraft(asset.name); setRenaming(false); }
}}
/>
@@ -274,7 +294,10 @@ export default function AssetsPage() {
function toggleSelect(name: string) {
setSelected((prev) => {
const next = new Set(prev);
- next.has(name) ? next.delete(name) : next.add(name);
+
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+
return next;
});
}
@@ -284,6 +307,7 @@ export default function AssetsPage() {
setSelected((p) => {
const n = new Set(p);
n.delete(name);
+
return n;
});
}
@@ -351,6 +375,7 @@ export default function AssetsPage() {
onToggleDefault={(a) => wrap(a.default ? clearDefault(a.name) : setDefault(a.name))}
onUpload={async (file) => {
setBusy(group.type);
+
try {
await uploadFile(file, group.type);
} catch (e) {
@@ -429,7 +454,9 @@ function BrandDefaults({ onError }: { onError: (m: string) => void }) {
function matchesGroup(assetType: AssetType, groupType: AssetType): boolean {
if (groupType === "outro") return assetType === "outro" || assetType === "video";
+
if (groupType === "music") return assetType === "music" || assetType === "audio";
+
return assetType === groupType;
}
@@ -469,6 +496,7 @@ function AssetSection({
useEffect(() => {
if (job?.status === "done") setJobId(null);
+
if (job?.status === "error") {
setJobErr(job.error || "Download failed");
setJobId(null);
@@ -477,10 +505,12 @@ function AssetSection({
async function submitUrl() {
const u = urlDraft.trim();
+
if (!u) return;
setUrlDraft("");
setUrlOpen(false);
setJobErr(null);
+
try {
setJobId(await onImportUrl(u));
} catch (e) {
@@ -542,6 +572,7 @@ function AssetSection({
style={{ display: "none" }}
onChange={(e) => {
const f = e.target.files?.[0];
+
if (f) onUpload(f);
e.target.value = "";
}}
diff --git a/src/ui/client/ClipDetail.tsx b/src/ui/client/ClipDetail.tsx
index 39f9fda..8bac97e 100644
--- a/src/ui/client/ClipDetail.tsx
+++ b/src/ui/client/ClipDetail.tsx
@@ -83,6 +83,7 @@ export default function ClipDetail() {
.then((d: Clip[]) => {
const found = Array.isArray(d) ? d.find((c) => c.id === id || String(c.id).startsWith(id || "\0")) : null;
setClip(found || null);
+
if (found) {
setTitle(found.title);
setCaptionStyle(found.caption_style);
@@ -96,6 +97,7 @@ export default function ClipDetail() {
})
.finally(() => setLoading(false));
};
+
useEffect(load, [id]);
useEffect(() => {
api("/integrations")
@@ -104,6 +106,7 @@ export default function ClipDetail() {
}, []);
if (loading) return <div className="app"><div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--text2)", padding: 40 }}><div className="spinner sm" /> Loading…</div></div>;
+
if (!clip) return <div className="app"><PageHeader title="Clip not found" /><Link to="/" style={{ color: "var(--accent)", display: "inline-flex", alignItems: "center", gap: 4 }}><BackIcon /> Library</Link></div>;
const tc = clip.thumbnail_config || {};
@@ -115,8 +118,10 @@ export default function ClipDetail() {
const save = async () => {
setBusy("save"); setMsg(null); setMsgErr(false);
+
try {
const r = await patch({ title, caption_style: captionStyle });
+
if (r.error) throw new Error(r.error);
load();
} catch (e: any) { setMsg(`Save failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
@@ -124,12 +129,16 @@ export default function ClipDetail() {
const loadOptions = async () => {
setBusy("options"); setMsg(null); setMsgErr(false);
+
try {
const r = await api(`/clips/${clip.id}/thumbnail/options?texts=6&frames=6`);
+
if (r.error) throw new Error(r.error);
setTextOpts(r.texts || []);
setFrameOpts(r.frames || []);
+
if ((r.frames || []).length) setSelFrame({ path: r.frames[0].path, info: r.frames[0] });
+
if (!(r.texts || []).length && !(r.frames || []).length) { setMsg("No options. Is the AI CLI installed and the source video available?"); setMsgErr(true); }
else if (r.warning) { setMsg(r.warning); setMsgErr(true); }
} catch (e: any) { setMsg(`Options failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
@@ -137,9 +146,11 @@ export default function ClipDetail() {
const uploadFrame = async (f: File) => {
setBusy("upload"); setMsg(null); setMsgErr(false);
+
try {
const fd = new FormData(); fd.append("file", f);
const r = await upload<any>("/upload", fd);
+
if (!r.file_path) throw new Error("upload failed");
setSelFrame({ path: r.file_path });
} catch (e: any) { setMsg(`Upload failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
@@ -148,8 +159,14 @@ export default function ClipDetail() {
const pairLayout = thumbLayout === "pair";
const renderThumb = async () => {
- if (!selFrame && needsFrame(thumbLayout)) { setMsg("Select or upload a frame first"); setMsgErr(true); return; }
+ if (!selFrame && needsFrame(thumbLayout)) {
+ setMsg("Select or upload a frame first"); setMsgErr(true);
+
+ return;
+ }
+
setBusy("render"); setMsg(null); setMsgErr(false);
+
try {
const r = await api(`/clips/${clip.id}/thumbnail/render`, {
method: "POST",
@@ -159,32 +176,49 @@ export default function ClipDetail() {
layout: thumbLayout, swap: pairLayout && swapSides,
}),
});
+
if (r.error) throw new Error(r.error);
setBust(Date.now()); load();
+
if (r.note) { setMsg(r.note); setMsgErr(true); }
else { setMsg(r.people?.length ? `Thumbnail generated: ${describePeople(r.people)}` : "Thumbnail generated"); setMsgErr(false); }
} catch (e: any) { setMsg(`Generate failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
};
const loadLogoPreviews = async () => {
- if (!logoPath) { setMsg("Select a logo first"); setMsgErr(true); return; }
+ if (!logoPath) {
+ setMsg("Select a logo first"); setMsgErr(true);
+
+ return;
+ }
+
setBusy("logo-preview"); setMsg(null); setMsgErr(false);
+
try {
const r = await api(`/clips/${clip.id}/logo/previews?logo_path=${encodeURIComponent(logoPath)}`);
+
if (r.error) throw new Error(r.error);
setLogoPreviews(r.previews || []);
+
if (r.previews?.[0]?.position) setLogoPosition(r.previews[0].position);
} catch (e: any) { setMsg(`Logo previews failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
};
const applyLogo = async () => {
- if (!logoPath) { setMsg("Select a logo first"); setMsgErr(true); return; }
+ if (!logoPath) {
+ setMsg("Select a logo first"); setMsgErr(true);
+
+ return;
+ }
+
setBusy("logo-apply"); setMsg(null); setMsgErr(false);
+
try {
const r = await api(`/clips/${clip.id}/logo`, {
method: "POST",
body: JSON.stringify({ action: "apply", logo_path: logoPath, logo_position: logoPosition }),
});
+
if (r.error) throw new Error(r.error);
setBust(Date.now()); load();
setMsg("Logo applied. Backup saved for removal"); setMsgErr(false);
@@ -193,8 +227,10 @@ export default function ClipDetail() {
const removeLogo = async () => {
setBusy("logo-remove"); setMsg(null); setMsgErr(false);
+
try {
const r = await api(`/clips/${clip.id}/logo`, { method: "POST", body: JSON.stringify({ action: "remove" }) });
+
if (r.error) throw new Error(r.error);
setLogoPreviews([]);
setBust(Date.now()); load();
@@ -203,28 +239,40 @@ export default function ClipDetail() {
};
// Pull a different frame from the clip (cycles the ranked candidates) and
- // re-render — same one-click flow as Regenerate, but swaps the background frame.
+ // re-render: same one-click flow as Regenerate, but swaps the background frame.
const newFrame = async () => {
setBusy("newframe"); setMsg(null); setMsgErr(false);
+
try {
let frames = frameOpts;
+
if (!frames.length) {
const r = await api(`/clips/${clip.id}/thumbnail/options?texts=6&frames=8`);
+
if (r.error) throw new Error(r.error);
frames = r.frames || [];
setFrameOpts(frames);
+
if ((r.texts || []).length) setTextOpts(r.texts);
}
- if (!frames.length) { setMsg("No frames found in this clip"); setMsgErr(true); return; }
+
+ if (!frames.length) {
+ setMsg("No frames found in this clip"); setMsgErr(true);
+
+ return;
+ }
+
const curIdx = frames.findIndex((f: any) => f.path === selFrame?.path);
const next = ((curIdx < 0 ? frameIdx : curIdx) + 1) % frames.length;
setFrameIdx(next);
const frame = frames[next];
setSelFrame({ path: frame.path, info: frame });
+
const r = await api(`/clips/${clip.id}/thumbnail/render`, {
method: "POST",
body: JSON.stringify({ line1: line1 || undefined, line2: line2 || undefined, frame_path: frame.path, frame_info: frame }),
});
+
if (r.error) throw new Error(r.error);
setBust(Date.now()); load();
setMsg(`New frame from clip (${next + 1}/${frames.length})`); setMsgErr(false);
@@ -233,8 +281,10 @@ export default function ClipDetail() {
const reopen = async () => {
setBusy("reopen"); setMsg(null); setMsgErr(false);
+
try {
const r = await api(`/clips/${clip.id}/reopen`, { method: "POST", body: "{}" });
+
if (r.error) throw new Error(r.error);
navigate("/episode");
} catch (e: any) { setMsg(`Reopen failed: ${e.message}`); setMsgErr(true); setBusy(null); }
@@ -242,8 +292,10 @@ export default function ClipDetail() {
const exportDavinci = async () => {
setBusy("davinci"); setMsg(null); setMsgErr(false);
+
try {
const r = await api(`/clips/${clip.id}/davinci`, { method: "POST", body: "{}" });
+
if (r.error) throw new Error(r.error);
setMsg(r.path ? `DaVinci project: ${r.path}` : "Exported"); setMsgErr(false);
} catch (e: any) { setMsg(`DaVinci export failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
@@ -251,6 +303,7 @@ export default function ClipDetail() {
const generateContent = async () => {
setBusy("content"); setMsg(null); setMsgErr(false);
+
try {
const body = {
clip: {
@@ -262,8 +315,11 @@ export default function ClipDetail() {
? [{ start: clip.start_second, text: clip.transcript_slice }]
: [],
};
+
const r = await api("/generate-content", { method: "POST", body: JSON.stringify(body) });
+
if (r.error) throw new Error(r.error);
+
if (!r.titles?.length && !r.description) throw new Error("AI CLI returned nothing. Is claude/codex installed?");
load();
} catch (e: any) { setMsg(`Content generation failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
@@ -272,6 +328,7 @@ export default function ClipDetail() {
const del = async () => {
if (!window.confirm(`Delete "${clip.title}"? This removes the rendered file too.`)) return;
setBusy("delete"); setMsg(null); setMsgErr(false);
+
try {
await api(`/clips/${clip.id}`, { method: "DELETE" });
navigate("/");
@@ -464,6 +521,7 @@ export default function ClipDetail() {
<div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
{clip.generated_titles.map((t, i) => {
const clean = t.replace(/^\d+\.\s*/, "");
+
return (
<button key={i} className={`title-option ${title === clean ? "selected" : ""}`} onClick={() => { setTitle(clean); setMsg("Title set. Click save to apply"); setMsgErr(false); }}>
{t}
diff --git a/src/ui/client/ClipPlayer.tsx b/src/ui/client/ClipPlayer.tsx
index 8f312ed..266da15 100644
--- a/src/ui/client/ClipPlayer.tsx
+++ b/src/ui/client/ClipPlayer.tsx
@@ -17,13 +17,16 @@ export default function ClipPlayer({ src, poster, onTime }: { src: string; poste
const toggle = () => {
const v = ref.current;
+
if (!v) return;
+
if (v.paused) v.play();
else v.pause();
};
const seekAt = (clientX: number, el: HTMLDivElement) => {
const v = ref.current;
+
if (!v || !dur) return;
const rect = el.getBoundingClientRect();
v.currentTime = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)) * dur;
diff --git a/src/ui/client/CommandPalette.tsx b/src/ui/client/CommandPalette.tsx
index d5e55a9..f6dafc1 100644
--- a/src/ui/client/CommandPalette.tsx
+++ b/src/ui/client/CommandPalette.tsx
@@ -52,9 +52,11 @@ export default function CommandPalette() {
setOpen((v) => !v);
}
};
+
const onTrigger = () => setOpen(true);
window.addEventListener("keydown", onKey);
window.addEventListener("open-command-palette", onTrigger);
+
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("open-command-palette", onTrigger);
@@ -64,6 +66,7 @@ export default function CommandPalette() {
useEffect(() => {
if (!open) return;
inputRef.current?.focus();
+
if (loaded.current) return;
Promise.allSettled([
api<{ id: string; title: string }[]>("/history?limit=100").then((h) => setClips(h || [])),
@@ -78,32 +81,42 @@ export default function CommandPalette() {
const results = useMemo<Cmd[]>(() => {
const q = query.trim().toLowerCase();
+
const pageCmds: Cmd[] = PAGES.map((p) => ({
id: `p:${p.path}`, label: p.label, group: "Pages", keywords: p.kw,
run: () => navigate(p.path),
}));
+
const clipCmds: Cmd[] = clips.map((c) => ({
id: `c:${c.id}`, label: c.title || "Untitled clip", sub: "Clip", group: "Clips",
run: () => navigate(`/clip/${c.id}`),
}));
+
const assetCmds: Cmd[] = assets.map((a) => ({
id: `a:${a.name}`, label: a.name, sub: a.type, group: "Assets",
run: () => navigate("/assets"),
}));
+
const all = [...pageCmds, ...clipCmds, ...assetCmds];
+
if (!q) return pageCmds;
+
const match = (c: Cmd) =>
c.label.toLowerCase().includes(q) ||
(c.sub?.toLowerCase().includes(q) ?? false) ||
(c.keywords?.includes(q) ?? false);
+
return all.filter(match).slice(0, 24);
}, [query, clips, assets, navigate]);
const groups = useMemo(() => {
const order: Cmd["group"][] = ["Pages", "Clips", "Assets"];
- return order
- .map((g) => ({ group: g, items: results.filter((r) => r.group === g) }))
- .filter((g) => g.items.length > 0);
+
+ return order.flatMap((g) => {
+ const items = results.filter((r) => r.group === g);
+
+ return items.length > 0 ? [{ group: g, items }] : [];
+ });
}, [results]);
const flat = results;
@@ -138,6 +151,7 @@ export default function CommandPalette() {
<div className="cmdk-group-label">{g.group}</div>
{g.items.map((c) => {
const idx = flat.indexOf(c);
+
return (
<button
key={c.id}
diff --git a/src/ui/client/ConfigPage.tsx b/src/ui/client/ConfigPage.tsx
index aa2b4e5..5dbca82 100644
--- a/src/ui/client/ConfigPage.tsx
+++ b/src/ui/client/ConfigPage.tsx
@@ -43,6 +43,7 @@ export default function ConfigPage() {
try {
const data = await api<{ settings?: SettingRow[]; ai_cli?: AiCliStatus }>("/settings");
setSettings(data.settings || []);
+
if (data.ai_cli) {
setAiCli(data.ai_cli);
} else {
@@ -59,6 +60,7 @@ export default function ConfigPage() {
async function refreshAiCli() {
setAiRefresh((n) => n + 1);
+
try {
setAiCli(await api<AiCliStatus>("/ai-cli-status"));
} catch {
@@ -75,13 +77,16 @@ export default function ConfigPage() {
setSavingKey(key);
setMsg(null);
const value = secret ? (secretInputs[key] ?? "") : (pathInputs[key] ?? "");
+
try {
await api("/settings", { method: "POST", body: JSON.stringify({ key, value }) });
+
if (secret) {
setSecretInputs((p) => ({ ...p, [key]: "" }));
} else {
setPathInputs((p) => ({ ...p, [key]: "" }));
}
+
setMsg({ text: `${key} saved.`, ok: true });
await loadSettings();
await refreshAiCli();
@@ -95,6 +100,7 @@ export default function ConfigPage() {
async function clearSetting(key: string) {
setSavingKey(key);
setMsg(null);
+
try {
await api("/settings", { method: "POST", body: JSON.stringify({ key, value: "" }) });
setPathInputs((p) => ({ ...p, [key]: "" }));
@@ -110,6 +116,7 @@ export default function ConfigPage() {
async function onMigrate() {
setMsg({ text: "Migrating…", ok: true });
+
try {
const data = await api<any>("/config/migrate", { method: "POST" });
setMsg({ text: `Moved ${data.moved_json || 0} cache file(s).`, ok: true });
@@ -125,12 +132,14 @@ export default function ConfigPage() {
async function onImport() {
const file = fileRef.current?.files?.[0];
+
if (!file) return;
const fd = new FormData();
fd.append("bundle", file);
fd.append("activate", activate ? "1" : "0");
setMsg({ text: "Importing…", ok: true });
setImporting(true);
+
try {
const data = await upload<any>("/config/import", fd);
setMsg({ text: data.backup ? `Imported into ${data.home} · backup ${data.backup}` : `Imported into ${data.home}`, ok: true });
diff --git a/src/ui/client/ConfirmDialog.tsx b/src/ui/client/ConfirmDialog.tsx
index 3f4aa4e..85b748d 100644
--- a/src/ui/client/ConfirmDialog.tsx
+++ b/src/ui/client/ConfirmDialog.tsx
@@ -20,7 +20,9 @@ export default function ConfirmDialog({
onCancel: () => void;
}) {
const dialogRef = useDialog(open, onCancel);
+
if (!open) return null;
+
return createPortal(
<div className="modal-overlay" onClick={onCancel}>
<div
diff --git a/src/ui/client/ContentStudio.tsx b/src/ui/client/ContentStudio.tsx
index aca73d0..28a5a09 100644
--- a/src/ui/client/ContentStudio.tsx
+++ b/src/ui/client/ContentStudio.tsx
@@ -14,10 +14,14 @@ interface ContentResult {
const STORE = "podcli.content-studio";
+type ContentMode = "episode" | "shorts";
+
+const CONTENT_MODES: readonly ContentMode[] = ["episode", "shorts"];
+
export default function ContentStudio() {
const [title, setTitle] = useState("");
const [transcript, setTranscript] = useState("");
- const [mode, setMode] = useState<"episode" | "shorts">("shorts");
+ const [mode, setMode] = useState<ContentMode>("shorts");
const [busy, setBusy] = useState(false);
const [stage, setStage] = useState<string | null>(null);
const [msg, setMsg] = useState<string | null>(null);
@@ -36,12 +40,14 @@ export default function ContentStudio() {
useEffect(() => {
try {
const saved = JSON.parse(localStorage.getItem(STORE) || "null");
+
if (saved?.result) {
setResult(saved.result);
setTitle(saved.title || "");
setMode(saved.mode === "episode" ? "episode" : "shorts");
}
} catch {}
+
api("/ui-state")
.then((s) => {
setSessionText(s?.transcript?.transcript || s?.rawTranscriptText || "");
@@ -65,10 +71,13 @@ export default function ContentStudio() {
const generate = async () => {
if (isBusy) return;
+
if (!transcript.trim()) {
setMsg("Paste a transcript first");
+
return;
}
+
setBusy(true);
setMsg(null);
setResult(null);
@@ -76,22 +85,30 @@ export default function ContentStudio() {
const streamId = Math.random().toString(36).slice(2);
const es = new EventSource("/api/events");
es.addEventListener("content-partial", (e) => {
+ if (!(e instanceof MessageEvent)) return;
+
try {
- const d = JSON.parse((e as MessageEvent).data);
+ const d = JSON.parse(e.data);
+
if (d.stream_id === streamId && d.partial) setResult(d.partial);
} catch {}
});
es.addEventListener("job-update", (e) => {
+ if (!(e instanceof MessageEvent)) return;
+
try {
- const d = JSON.parse((e as MessageEvent).data);
+ const d = JSON.parse(e.data);
+
if (d.message) setStage(d.message);
} catch {}
});
+
try {
const r = await api<ContentResult>("/content-studio/generate", {
method: "POST",
body: JSON.stringify({ title: title || undefined, transcript_text: transcript, mode, stream_id: streamId }),
});
+
if (!r.titles?.length && !r.description) throw new Error("AI CLI returned nothing. Is claude or codex installed?");
setResult(r);
persist(r);
@@ -109,7 +126,9 @@ export default function ContentStudio() {
method: "POST",
body: JSON.stringify({ instruction, transcript_text: transcript || undefined, mode }),
});
+
if (r.error) throw new Error(r.error);
+
return r.text?.trim() || null;
};
@@ -118,6 +137,7 @@ export default function ContentStudio() {
setCustomBusy(true);
setCustomOut(null);
setMsg(null);
+
try {
setCustomOut((await runCustom(customReq.trim())) || "No output.");
} catch (e: any) {
@@ -127,22 +147,25 @@ export default function ContentStudio() {
}
};
- const REGEN: Record<string, string> = {
- titles: "Give me 8 fresh YouTube title options for this content, one per line, numbered 1-8. Return only the titles.",
- description: "Rewrite the YouTube description for this content. Return only the description text, no labels.",
- tags: "Give a comma-separated list of 10-15 YouTube tags for this content. Return only the tags.",
- hashtags: "Give 5 relevant hashtags for this content. Return only the hashtags, space-separated.",
- };
+ const REGEN = new Map([
+ ["titles", "Give me 8 fresh YouTube title options for this content, one per line, numbered 1-8. Return only the titles."],
+ ["description", "Rewrite the YouTube description for this content. Return only the description text, no labels."],
+ ["tags", "Give a comma-separated list of 10-15 YouTube tags for this content. Return only the tags."],
+ ["hashtags", "Give 5 relevant hashtags for this content. Return only the hashtags, space-separated."],
+ ]);
const regenerate = async (field: string) => {
if (isBusy) return;
setRegenBusy(true);
setMsg(null);
+
try {
- const instruction = `${REGEN[field]}${regenNote.trim() ? ` Extra guidance: ${regenNote.trim()}` : ""}`;
+ const instruction = `${REGEN.get(field)}${regenNote.trim() ? ` Extra guidance: ${regenNote.trim()}` : ""}`;
const text = await runCustom(instruction);
+
if (!text) throw new Error("empty response");
- const next = { ...(result || {}) } as ContentResult;
+ const next: ContentResult = { ...result };
+
if (field === "titles") {
next.titles = text
.split(/\r?\n/)
@@ -192,10 +215,12 @@ export default function ContentStudio() {
) : null;
const hasTitle = !!(result?.titles?.length || title.trim());
+
const previewTitle =
result?.titles?.[0]?.replace(/^\d+\.\s*/, "").replace(/^["']|["']$/g, "") ||
title.trim() ||
"Your title appears here";
+
const vertical = mode === "shorts";
return (
@@ -230,7 +255,7 @@ export default function ContentStudio() {
/>
<div style={{ display: "flex", gap: 10, marginTop: 12, alignItems: "center" }}>
- <select value={mode} onChange={(e) => setMode(e.target.value as "episode" | "shorts")} style={{ flex: 1 }}>
+ <select value={mode} onChange={(e) => setMode(CONTENT_MODES.find((m) => m === e.target.value) ?? mode)} style={{ flex: 1 }}>
<option value="episode">Full episode (long-form)</option>
<option value="shorts">Short / clip</option>
</select>
@@ -294,6 +319,7 @@ export default function ContentStudio() {
<div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
{result.titles.map((t, i) => {
const clean = t.replace(/^\d+\.\s*/, "");
+
return (
<button key={i} className={`title-option stream-in ${copied === clean ? "selected" : ""}`} onClick={() => copy(clean)}>
{t}{copied === clean ? " · copied" : ""}
diff --git a/src/ui/client/CopyButton.tsx b/src/ui/client/CopyButton.tsx
index 897f685..2556c21 100644
--- a/src/ui/client/CopyButton.tsx
+++ b/src/ui/client/CopyButton.tsx
@@ -5,6 +5,7 @@ async function copyText(value: string): Promise<void> {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(value);
+
return;
}
} catch {
@@ -17,11 +18,14 @@ async function copyText(value: string): Promise<void> {
field.style.position = "fixed";
field.style.opacity = "0";
field.style.pointerEvents = "none";
+
const activeElement = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
+
document.body.appendChild(field);
let copied = false;
+
try {
field.select();
copied = document.execCommand("copy");
@@ -29,6 +33,7 @@ async function copyText(value: string): Promise<void> {
field.remove();
activeElement?.focus({ preventScroll: true });
}
+
if (!copied) throw new Error("Clipboard unavailable");
}
@@ -76,9 +81,11 @@ export default function CopyButton({
const handleCopy = async (event: React.MouseEvent<HTMLButtonElement>) => {
if (stopPropagation) event.stopPropagation();
const value = getText ? getText() : text;
+
if (!value) return;
if (timerRef.current) window.clearTimeout(timerRef.current);
+
try {
await copyText(value);
setFailed(false);
diff --git a/src/ui/client/EpisodeWorkspace.jsx b/src/ui/client/EpisodeWorkspace.jsx
index 2cd9ec4..4039276 100644
--- a/src/ui/client/EpisodeWorkspace.jsx
+++ b/src/ui/client/EpisodeWorkspace.jsx
@@ -50,19 +50,25 @@ const FORMAT_BOUNDS = {
square: { min: 20, max: 45, ceiling: 60 },
horizontal: { min: 60, max: 300, ceiling: 360 },
};
+
const boundsFor = (f) => FORMAT_BOUNDS[f] || FORMAT_BOUNDS.vertical;
const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
const fmtSaved = (s) => s < 10 ? `${Number(s || 0).toFixed(1)}s` : fmt(s);
const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());
+
const onKeyActivate = (fn) => (e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); fn(e); }
};
+
const api = async (path, opts = {}) => {
const res = await fetch(`/api${path}`, { headers: { 'Content-Type': 'application/json', ...opts.headers }, ...opts });
let body = null;
+
try { body = await res.json(); } catch { /* empty / non-JSON body */ }
+
if (!res.ok) return { error: (body && body.error) || `HTTP ${res.status}` };
+
return body ?? {};
};
@@ -72,7 +78,9 @@ const onKeyActivate = (fn) => (e) => {
const fd = new FormData();
fd.append('file', file);
xhr.upload.onprogress = (e) => { if (e.lengthComputable && onProgress) onProgress(Math.round((e.loaded / e.total) * 100)); };
+
xhr.onload = () => { try { resolve(JSON.parse(xhr.responseText)); } catch (e) { reject(e); } };
+
xhr.onerror = () => reject(new Error('Upload failed'));
xhr.open('POST', '/api/upload');
xhr.send(fd);
@@ -82,12 +90,22 @@ const onKeyActivate = (fn) => (e) => {
function useJob(jobId) {
const [state, setState] = useState(null);
useEffect(() => {
- if (!jobId) { setState(null); return; }
+ if (!jobId) {
+ setState(null);
+
+ return;
+ }
+
const es = new EventSource(`/api/job/${jobId}/stream`);
- es.onmessage = e => { const d = JSON.parse(e.data); setState(d); if (d.status === 'done' || d.status === 'error') es.close(); };
+ es.onmessage = e => { const d = JSON.parse(e.data); setState(d);
+
+ if (d.status === 'done' || d.status === 'error') es.close(); };
+
es.onerror = () => es.close();
+
return () => es.close();
}, [jobId]);
+
return state;
}
@@ -97,9 +115,11 @@ const onKeyActivate = (fn) => (e) => {
const [connected, setConnected] = useState(false);
useEffect(() => {
const es = new EventSource('/api/events');
+
const handle = (type) => (e) => {
try { setLastEvent({ type, data: JSON.parse(e.data), ts: Date.now() }); } catch { }
};
+
es.addEventListener('state', (e) => { setConnected(true); handle('state')(e); });
es.addEventListener('state-sync', handle('state-sync'));
es.addEventListener('export-started', handle('export-started'));
@@ -107,8 +127,10 @@ const onKeyActivate = (fn) => (e) => {
es.addEventListener('job-complete', handle('job-complete'));
es.addEventListener('job-error', handle('job-error'));
es.onerror = () => { };
+
return () => es.close();
}, []);
+
return { lastEvent, connected };
}
@@ -120,13 +142,16 @@ const onKeyActivate = (fn) => (e) => {
const PROD_TO_PCT = (margin) => ((margin / 1920) * 100).toFixed(1) + '%';
const CAPTION_BOTTOMS = { upper: PROD_TO_PCT(760), center: PROD_TO_PCT(480), lower: PROD_TO_PCT(220) };
const captionBottom = (cfg, position) => CAPTION_BOTTOMS[position] || cfg.bottom;
+
const logoPlacement = (position) => {
const vertical = position.startsWith('bottom-') ? { bottom: '7%', top: 'auto' } : { top: '7%', bottom: 'auto' };
+
const horizontal = position.endsWith('-right')
? { right: '3%', left: 'auto', transform: 'none' }
: position.endsWith('-center')
? { left: '50%', right: 'auto', transform: 'translateX(-50%)' }
: { left: '3%', right: 'auto', transform: 'none' };
+
return { ...vertical, ...horizontal };
};
@@ -141,6 +166,7 @@ const onKeyActivate = (fn) => (e) => {
function LogoPositionPicker({ value, onChange, disabled }) {
const activeLabel = LOGO_POSITIONS.find(([position]) => position === value)?.[1] || 'Top left';
+
return (
<div className="logo-position-control">
<div className="logo-position-picker" role="radiogroup" aria-label="Logo position">
@@ -198,11 +224,12 @@ const onKeyActivate = (fn) => (e) => {
function splitBrandedLines(chunk) {
if (chunk.length <= 2) return [chunk, []];
+
return [chunk.slice(0, 2), chunk.slice(2)];
}
- function TikTokWireframe({ activeClip, captionStyle }) {
+ function TikTokWireframe() {
const Heart = () => <HeartGlyph size={28} fill="#fff" strokeWidth={0} />;
const Comment = () => <MessageCircle size={28} fill="#fff" strokeWidth={0} />;
const Bookmark = () => <BookmarkGlyph size={26} fill="#fff" strokeWidth={0} />;
@@ -214,16 +241,21 @@ const onKeyActivate = (fn) => (e) => {
const NavFriends = () => <UsersGlyph className="tt-nav-icon" fill="#fff" color="#fff" strokeWidth={1.5} />;
const NavInbox = () => <Inbox className="tt-nav-icon" color="#fff" strokeWidth={2.2} />;
const NavProfile = () => <UserGlyph className="tt-nav-icon" fill="#fff" color="#fff" strokeWidth={1.5} />;
+
const fmtCount = (n) => {
if (n >= 100000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
+
if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
+
return String(n);
};
+
const likes = fmtCount(999000);
const comments = fmtCount(2463);
const saves = fmtCount(60500);
const shares = fmtCount(2230);
const caption = activeClip ? activeClip.title : 'Description #shorts #podcast';
+
return (
<div className="tt-overlay">
<div className="tt-top">
@@ -315,6 +347,7 @@ const onKeyActivate = (fn) => (e) => {
</span>
);
}
+
return (
<span key={`${w}-${i}`} style={{
color: isActive ? cfg.activeColor : cfg.color,
@@ -329,6 +362,7 @@ const onKeyActivate = (fn) => (e) => {
if (cfg.splitLines && !singleLine) {
const [line1, line2] = splitBrandedLines(chunk);
const startIdx2 = line1.length;
+
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
<div style={{ whiteSpace: 'nowrap' }}>
@@ -373,17 +407,21 @@ const onKeyActivate = (fn) => (e) => {
}}>{inner}</div>
);
}
+
return <div style={{ whiteSpace: singleLine ? 'nowrap' : 'normal' }}>{inner}</div>;
}
function useLiveCaptionPreview({ videoUrl, videoRef, captionStyle, activeClip, transcriptWords }) {
const cfg = STYLE_CONFIGS[captionStyle] || STYLE_CONFIGS.branded;
+
const sourcePool = useMemo(() => {
const words = selectPreviewWords(transcriptWords, activeClip);
+
return words.length >= 2 ? words : null;
}, [activeClip, transcriptWords]);
const usingSample = !sourcePool;
+
const poolWords = useMemo(
() => sourcePool || cfg.sample.map(text => ({ text, start: 0, end: 0 })),
[sourcePool, cfg.sample]
@@ -402,25 +440,35 @@ const onKeyActivate = (fn) => (e) => {
useEffect(() => {
setCursor(0);
setClock(0);
+
if (poolWords.length <= 1) return;
+
if (timed) {
let raf;
+
const step = () => {
const v = videoRef?.current;
+
if (v) setClock(v.currentTime);
raf = requestAnimationFrame(step);
};
+
raf = requestAnimationFrame(step);
+
return () => cancelAnimationFrame(raf);
}
+
const tick = captionStyle === 'karaoke' ? 320 : 420;
const iv = setInterval(() => setCursor(i => (i + 1) % poolWords.length), tick);
+
return () => clearInterval(iv);
}, [captionStyle, poolWords, timed]);
let activeChunk = null, activeWordInChunk = 0;
+
if (timed) {
activeChunk = activePreviewChunk(chunks, clock) || null;
+
if (activeChunk) {
for (let k = 0; k < activeChunk.words.length; k++) {
if (activeChunk.words[k].start <= clock) activeWordInChunk = k;
@@ -429,12 +477,14 @@ const onKeyActivate = (fn) => (e) => {
}
} else {
let consumed = 0;
+
for (const chunk of chunks) {
if (cursor < consumed + chunk.words.length) {
activeChunk = chunk;
activeWordInChunk = cursor - consumed;
break;
}
+
consumed += chunk.words.length;
}
}
@@ -446,6 +496,7 @@ const onKeyActivate = (fn) => (e) => {
const { cfg, usingSample, activeChunk, activeWordInChunk } = useLiveCaptionPreview({
videoUrl, videoRef, captionStyle, activeClip, transcriptWords,
});
+
const [logoBroken, setLogoBroken] = useState(false);
useEffect(() => { setLogoBroken(false); }, [logoPreviewUrl]);
@@ -507,7 +558,7 @@ const onKeyActivate = (fn) => (e) => {
</div>
)}
{videoUrl && showTikTokFrame && (
- <TikTokWireframe activeClip={activeClip} captionStyle={captionStyle} />
+ <TikTokWireframe />
)}
</div>
<div className="preview-toggle-row">
@@ -524,6 +575,7 @@ const onKeyActivate = (fn) => (e) => {
const { cfg, usingSample, activeChunk, activeWordInChunk } = useLiveCaptionPreview({
videoUrl, videoRef, captionStyle, activeClip: null, transcriptWords,
});
+
const [logoBroken, setLogoBroken] = useState(false);
const [playing, setPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
@@ -533,10 +585,13 @@ const onKeyActivate = (fn) => (e) => {
const togglePlay = () => {
const video = videoRef?.current;
+
if (!video) return;
+
if (video.paused) video.play().catch(() => {});
else video.pause();
};
+
const progress = duration > 0 ? Math.max(0, Math.min(100, (currentTime / duration) * 100)) : 0;
return (
@@ -614,6 +669,7 @@ const onKeyActivate = (fn) => (e) => {
const cfg = STYLE_CONFIGS[captionStyle] || STYLE_CONFIGS.branded;
// Sample "color" comes from the active-word style of the caption preset.
const swatch = (cfg.activeStyle && (cfg.activeStyle.color || cfg.activeStyle.background)) || '#ffffff';
+
const rows = [
['Caption style', captionStyle],
['Crop', cropStrategy],
@@ -623,9 +679,13 @@ const onKeyActivate = (fn) => (e) => {
['Quality', quality || 'standard'],
['Clean fillers', cleanFillers ? 'on' : 'off'],
];
+
if (logoPath) rows.push(['Logo', `${logoPath.split('/').pop()} · ${logoPosition}`]);
+
if (outroPath) rows.push(['Outro', outroPath.split('/').pop()]);
+
if (activePreset) rows.push(['Preset', activePreset]);
+
return (
<div className="spec-recap fade-in">
{rows.map(([k, v]) => (
@@ -725,10 +785,13 @@ const onKeyActivate = (fn) => (e) => {
const [logoPath, setLogoPath] = useState('');
const [outroPath, setOutroPath] = useState('');
const [introPath, setIntroPath] = useState('');
+
const logoPreviewUrl = useMemo(() => {
const name = resolveAssetName(assets, logoPath, 'logo');
+
return name ? assetSrc(name) : '';
}, [assets, logoPath]);
+
const [stateHydrated, setStateHydrated] = useState(false);
const hydrationTargetRef = useRef(null);
const videoFileRef = useRef();
@@ -740,10 +803,12 @@ const onKeyActivate = (fn) => (e) => {
const [transcript, setTranscript] = useState(null);
const [transcriptOpen, setTranscriptOpen] = useState(true);
const [transcriptFormat, setTranscriptFormat] = useState('readable');
+
const formattedTranscript = useMemo(
() => formatTranscriptText(transcript, transcriptFormat),
[transcript, transcriptFormat],
);
+
const [suggestions, setSuggestions] = useState([]);
const [deselected, setDeselected] = useState(new Set());
const [batchJobId, setBatchJobId] = useState(null);
@@ -823,12 +888,16 @@ const onKeyActivate = (fn) => (e) => {
const exportMenuRef = useRef(null);
useEffect(() => {
if (!exportMenuOpen) return;
+
const onDown = (e) => {
if (exportMenuRef.current && !exportMenuRef.current.contains(e.target)) setExportMenuOpen(false);
};
+
const onKey = (e) => { if (e.key === 'Escape') setExportMenuOpen(false); };
+
document.addEventListener('mousedown', onDown);
document.addEventListener('keydown', onKey);
+
return () => {
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey);
@@ -847,32 +916,49 @@ const onKeyActivate = (fn) => (e) => {
useEffect(() => {
api('/encoder-info').then(d => { if (d.best) setEncoderInfo(d); }).catch(() => { });
api('/speaker-status').then(d => setSpeakerStatus(d)).catch(() => { });
- api('/corrections').then(d => { if (d && typeof d === 'object') setCorrections(d); }).catch(() => { });
+ api('/corrections').then(d => { if (d instanceof Object) setCorrections(d); }).catch(() => { });
}, []);
// Fetch presets on mount
const fetchPresets = () => { api('/presets').then(d => { if (d.presets) setPresets(d.presets); }).catch(() => {}); };
+
useEffect(fetchPresets, []);
const loadPreset = async (name) => {
- if (!name) { setActivePreset(''); return; }
+ if (!name) {
+ setActivePreset('');
+
+ return;
+ }
+
try {
const response = await api('/presets', { method: 'POST', body: JSON.stringify({ action: 'get', name }) });
const d = response.config || response;
+
if (d.caption_style) setCaptionStyle(d.caption_style);
+
if (d.caption_position) setCaptionPosition(d.caption_position);
+
if (d.caption_font_scale) setCaptionFontScale(Number(d.caption_font_scale));
+
if (d.logo_position) setLogoPosition(d.logo_position);
+
if (d.crop_strategy) setCropStrategy(d.crop_strategy);
+
if (d.format) setFormat(d.format);
+
if (d.logo_path !== undefined) setLogoPath(d.logo_path || '');
+
if (d.outro_path !== undefined) setOutroPath(d.outro_path || '');
+
if (d.intro_path !== undefined) setIntroPath(d.intro_path || '');
+
if (d.video_path !== undefined) {
const nextVideoPath = d.video_path || '';
const changedVideo = nextVideoPath.trim() !== videoPath.trim();
setVideoPath(nextVideoPath);
setFile(null);
+
if (changedVideo) {
setSilenceOriginal(null);
setSilencePlan(null);
@@ -884,14 +970,23 @@ const onKeyActivate = (fn) => (e) => {
autoTranscribeRef.current = '';
}
}
+
if (d.clean_fillers !== undefined) setCleanFillers(d.clean_fillers);
+
if (d.quality) setQuality(d.quality);
+
if (d.top_clips) setTopClips(d.top_clips);
+
if (d.min_clip_duration) setMinDuration(d.min_clip_duration);
+
if (d.max_clip_duration) setMaxDuration(d.max_clip_duration);
+
if (d.energy_boost !== undefined) setEnergyBoost(d.energy_boost);
+
if (d.whisper_model) setWhisperModel(d.whisper_model);
+
if (d.transcription_engine) setTranscriptionEngine(d.transcription_engine);
+
if (d.time_adjust !== undefined) setTimeAdjust(d.time_adjust);
setActivePreset(name);
} catch {}
@@ -900,6 +995,7 @@ const onKeyActivate = (fn) => (e) => {
const savePreset = async () => {
if (!presetName.trim()) return;
setPresetSaving(true);
+
try {
await api('/presets', { method: 'POST', body: JSON.stringify({
action: 'save', name: presetName.trim(),
@@ -914,8 +1010,10 @@ const onKeyActivate = (fn) => (e) => {
const deletePreset = async (name) => {
if (!confirm(`Delete preset "${name}"?`)) return;
+
try {
await api('/presets', { method: 'POST', body: JSON.stringify({ action: 'delete', name }) });
+
if (activePreset === name) setActivePreset('');
fetchPresets();
} catch {}
@@ -924,6 +1022,7 @@ const onKeyActivate = (fn) => (e) => {
// Clip editing
const openClipEdit = (idx) => {
const clip = suggestions[idx];
+
if (!clip) return;
setEditingClip(idx);
setEditForm({
@@ -939,18 +1038,22 @@ const onKeyActivate = (fn) => (e) => {
// Saving drops segments, but the server restores them while the range
// stays within half a second, so the hook is checked against the same.
const editedClip = editingClip !== null ? suggestions[editingClip] : null;
+
const editSegments = editedClip
&& Math.abs(editedClip.start_second - editForm.start) < 0.5
&& Math.abs(editedClip.end_second - editForm.end) < 0.5
? editedClip.segments : undefined;
+
const editHookError = validateHook(editForm.hook, editForm.start, editForm.end, editSegments);
const setEditHook = (patch) => setEditForm(f => ({ ...f, hook: patch && { ...f.hook, ...patch } }));
+
const addEditHook = () => setEditForm(f => ({
...f, hook: { start: f.start, end: Math.min(f.end, f.start + 3), mode: 'repeat' },
}));
const clampEditTime = (v) => {
const n = Number.isFinite(v) ? Math.max(0, v) : 0;
+
return editDuration ? Math.min(n, editDuration) : n;
};
@@ -971,8 +1074,10 @@ const onKeyActivate = (fn) => (e) => {
segments: undefined,
hook: editForm.hook || undefined,
};
+
return next;
});
+
// The score was measured over the old range, so it no longer describes this clip.
if (reTimed) setEnergyData(prev => dropEnergy(prev, edited));
setEditingClip(null);
@@ -980,17 +1085,21 @@ const onKeyActivate = (fn) => (e) => {
const deleteClipEdit = () => {
if (editingClip === null) return;
+
if (!confirm(`Delete clip "${editForm.title}" from this batch?`)) return;
const removed = suggestions[editingClip];
setSuggestions(prev => prev.filter((_, i) => i !== editingClip));
setDeselected(prev => {
const next = new Set();
+
for (const idx of prev) {
if (idx < editingClip) next.add(idx);
else if (idx > editingClip) next.add(idx - 1);
}
+
return next;
});
+
if (removed) setEnergyData(prev => dropEnergy(prev, removed));
setEditingClip(null);
};
@@ -999,10 +1108,12 @@ const onKeyActivate = (fn) => (e) => {
const analyzeEnergy = async () => {
setAnalyzingEnergy(true);
const analyzed = suggestions;
+
try {
const segments = analyzed.map(c => ({ start: c.start_second, end: c.end_second }));
const vp = file?.file_path || videoPath.trim();
const d = await api('/analyze-energy', { method: 'POST', body: JSON.stringify({ video_path: vp, segments }) });
+
// Backend returns { segment_scores: [0-10, ...], peak_times: [...] }
if (Array.isArray(d.segment_scores)) setEnergyData(buildEnergyMap(d.segment_scores, analyzed));
} catch {}
@@ -1014,11 +1125,19 @@ const onKeyActivate = (fn) => (e) => {
if (!vp || transcribing || transcript) return;
setTranscribing(true);
setCachedTranscript(false);
+
try {
const fileData = await api('/select-file', { method: 'POST', body: JSON.stringify({ file_path: vp }) });
- if (fileData.error) { setTranscribing(false); return; }
+
+ if (fileData.error) {
+ setTranscribing(false);
+
+ return;
+ }
+
setFile(fileData);
const engine = transcriptionEngine === 'whisper' ? undefined : transcriptionEngine;
+
const data = await api('/transcribe', { method: 'POST', body: JSON.stringify({
file_path: vp,
model_size: whisperModel,
@@ -1026,11 +1145,14 @@ const onKeyActivate = (fn) => (e) => {
assemblyai_api_key: transcriptionEngine === 'assemblyai' ? assemblyAiKey.trim() : undefined,
enable_diarization: transcriptionEngine === 'assemblyai' || speakerStatus?.configured !== false,
}) });
+
if (data.error) {
setError(data.error);
setTranscribing(false);
+
return;
}
+
if (data.cached && data.data) {
// Instant cache hit
setTranscript(data.data);
@@ -1047,6 +1169,7 @@ const onKeyActivate = (fn) => (e) => {
// Watch transcribe job completion
useEffect(() => {
if (!transcribeStream) return;
+
if (transcribeStream.status === 'done') {
setTranscript(transcribeStream.result);
setTranscribing(false);
@@ -1062,6 +1185,7 @@ const onKeyActivate = (fn) => (e) => {
const autoTranscribeRef = useRef('');
useEffect(() => {
const vp = videoPath.trim();
+
if (transcriptMode === 'whisper' && transcriptionEngine === 'whisper' && vp && !isHttpUrl(vp) && !transcript && !transcribing && vp !== autoTranscribeRef.current) {
autoTranscribeRef.current = vp;
autoTranscribe(vp);
@@ -1070,6 +1194,7 @@ const onKeyActivate = (fn) => (e) => {
// Fetch clip history on mount and after exports
const fetchHistory = () => { fetch('/api/history?limit=50').then(r => r.json()).then(d => { if (Array.isArray(d)) setClipHistory(d); }).catch(() => { }); };
+
useEffect(fetchHistory, []);
useEffect(() => { if (phase === 'done') fetchHistory(); }, [phase]);
@@ -1084,6 +1209,7 @@ const onKeyActivate = (fn) => (e) => {
const prevTranscriptRef = useRef(null);
useEffect(() => {
if (!stateHydrated) return;
+
const syncable = {
videoPath,
silenceOriginal,
@@ -1095,7 +1221,9 @@ const onKeyActivate = (fn) => (e) => {
results,
energyData,
};
+
const signature = JSON.stringify(syncable);
+
// React may expose the readiness flag before every restored field has
// committed. Skip that one intermediate render rather than erasing
// server state, but release the guard either way: a signature that
@@ -1103,13 +1231,17 @@ const onKeyActivate = (fn) => (e) => {
if (hydrationTargetRef.current) {
const target = hydrationTargetRef.current;
hydrationTargetRef.current = null;
+
if (signature !== target) return;
}
+
const transcriptChanged = transcript !== prevTranscriptRef.current;
const state = buildUiStateSyncPayload(syncable, file?.file_path || '', transcript, transcriptChanged);
const key = JSON.stringify(state);
+
if (key === prevSyncRef.current) return;
prevSyncRef.current = key;
+
if (transcriptChanged) prevTranscriptRef.current = transcript;
fetch('/api/ui-state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: key }).catch(() => { });
}, [stateHydrated, videoPath, file, silenceOriginal, silencePlan, suggestions, deselected, captionStyle, captionPosition, captionFontScale, logoPosition, cropStrategy, format, logoPath, outroPath, introPath, cleanFillers, silenceThreshold, silenceMinPause, silencePadding, phase, results, energyData, transcript]);
@@ -1118,8 +1250,10 @@ const onKeyActivate = (fn) => (e) => {
const prevRawRef = useRef('');
useEffect(() => {
if (!stateHydrated) return;
+
if (transcriptText === prevRawRef.current) return;
prevRawRef.current = transcriptText;
+
if (transcriptText.trim()) {
fetch('/api/ui-state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ _source: 'ui', rawTranscriptText: transcriptText }) }).catch(() => { });
}
@@ -1131,12 +1265,14 @@ const onKeyActivate = (fn) => (e) => {
);
const applyClipResult = useCallback((row) => {
- if (!row || typeof row.clip_index !== 'number') return;
+ if (!row || !Number.isInteger(row.clip_index)) return;
setResults(prev => {
const cur = prev[row.clip_index];
+
if (cur && cur.status === row.status && cur.output_path === row.output_path) return prev;
const next = [...prev];
next[row.clip_index] = row;
+
return next;
});
}, []);
@@ -1149,6 +1285,7 @@ const onKeyActivate = (fn) => (e) => {
if (sseEvent.type === 'state-sync' || sseEvent.type === 'state') {
const d = sseEvent.data;
+
if (sseEvent.type === 'state') {
hydrationTargetRef.current = JSON.stringify({
videoPath: d.videoPath || '',
@@ -1176,37 +1313,64 @@ const onKeyActivate = (fn) => (e) => {
energyData: d.energyData || {},
});
}
+
if (d.suggestions) setSuggestions(d.suggestions);
+
if (d.energyData !== undefined) setEnergyData(d.energyData || {});
+
if (d.deselectedIndices !== undefined) setDeselected(new Set(d.deselectedIndices));
else if (d.suggestions && !d.deselectedIndices) setDeselected(new Set());
+
if (d.phase) setPhase(d.phase);
+
if (sseEvent.type === 'state' && Array.isArray(d.results)) setResults(d.results);
+
if (d.activeExportJobId !== undefined) setBatchJobId(d.activeExportJobId);
+
if (d.videoPath !== undefined) setVideoPath(d.videoPath);
+
if (d.silenceOriginal !== undefined) setSilenceOriginal(d.silenceOriginal);
+
if (d.silencePlan !== undefined) setSilencePlan(d.silencePlan);
+
if (d.transcript !== undefined) {
setTranscript(d.transcript);
+
if (d.videoPath) autoTranscribeRef.current = d.videoPath;
+
if (d.transcript === null) autoTranscribeRef.current = '';
}
+
if (d.rawTranscriptText !== undefined && (d.transcript === null || !transcript)) setTranscriptText(d.rawTranscriptText);
+
if (d.settings) {
if (d.settings.captionStyle) setCaptionStyle(d.settings.captionStyle);
+
if (d.settings.captionPosition) setCaptionPosition(d.settings.captionPosition);
+
if (d.settings.captionFontScale) setCaptionFontScale(Number(d.settings.captionFontScale));
+
if (d.settings.logoPosition) setLogoPosition(d.settings.logoPosition);
+
if (d.settings.cropStrategy) setCropStrategy(d.settings.cropStrategy);
+
if (d.settings.format) setFormat(d.settings.format);
+
if (d.settings.logoPath !== undefined) setLogoPath(d.settings.logoPath);
+
if (d.settings.outroPath !== undefined) setOutroPath(d.settings.outroPath);
+
if (d.settings.introPath !== undefined) setIntroPath(d.settings.introPath);
+
if (d.settings.cleanFillers !== undefined) setCleanFillers(d.settings.cleanFillers !== false);
+
if (d.settings.silenceThreshold !== undefined) setSilenceThreshold(Number(d.settings.silenceThreshold));
+
if (d.settings.silenceMinPause !== undefined) setSilenceMinPause(Number(d.settings.silenceMinPause));
+
if (d.settings.silencePadding !== undefined) setSilencePadding(Number(d.settings.silencePadding));
}
+
// Flip readiness in the same React batch as the restored fields. The
// first sync therefore contains restored values, never mount defaults.
if (sseEvent.type === 'state') {
@@ -1239,14 +1403,14 @@ const onKeyActivate = (fn) => (e) => {
const [activeClipIdx, setActiveClipIdx] = useState(null);
const [previewSrc, setPreviewSrc] = useState(null); // null=source, string=rendered clip filename
const [previewMode, setPreviewMode] = useState('clips'); // clips | youtube
- const [settingsFlash, setSettingsFlash] = useState(null);
+ const [, setSettingsFlash] = useState(null);
const [clipEnded, setClipEnded] = useState(false);
const previewSessionRef = useRef(Date.now().toString(36));
const activeClip = activeClipIdx !== null ? suggestions[activeClipIdx] : null;
// An agent can delete a clip out from under the cursor, leaving it on a row
- // that no longer exists — space would then deselect an index nobody owns.
+ // that no longer exists: space would then deselect an index nobody owns.
useEffect(() => {
setActiveClipIdx(prev => clampClipIndex(prev, suggestions.length));
}, [suggestions.length]);
@@ -1257,6 +1421,7 @@ const onKeyActivate = (fn) => (e) => {
: videoPath && !isHttpUrl(videoPath)
? `/api/stream-source?path=${encodeURIComponent(videoPath)}&preview=${previewSessionRef.current}`
: null;
+
const youtubePreviewTitle = (videoPath.split(/[\\/]/).pop() || 'Full episode')
.replace(/\.[^.]+$/, '')
.replace(/[_-]+/g, ' ')
@@ -1266,22 +1431,29 @@ const onKeyActivate = (fn) => (e) => {
// its end boundary so the preview doesn't run into the rest of the episode
useEffect(() => {
setClipEnded(false);
+
if (activeClipIdx === null || previewSrc) return;
const v = videoRef.current;
+
if (!activeClip || !v) return;
+
const seek = () => {
v.currentTime = activeClip.start_second;
v.play().catch(() => { });
};
+
if (v.readyState >= 1) seek();
else v.addEventListener('loadedmetadata', seek, { once: true });
+
const onTime = () => {
if (v.currentTime >= activeClip.end_second) {
v.pause();
setClipEnded(true);
}
};
+
v.addEventListener('timeupdate', onTime);
+
return () => {
v.removeEventListener('loadedmetadata', seek);
v.removeEventListener('timeupdate', onTime);
@@ -1290,6 +1462,7 @@ const onKeyActivate = (fn) => (e) => {
const replayClip = () => {
const v = videoRef.current;
+
if (!v || !activeClip) return;
v.currentTime = activeClip.start_second;
setClipEnded(false);
@@ -1310,6 +1483,7 @@ const onKeyActivate = (fn) => (e) => {
const onClipClick = (idx) => {
setPreviewMode('clips');
setActiveClipIdx(idx);
+
if (previewSrc) setPreviewSrc(null);
};
@@ -1348,9 +1522,12 @@ const onKeyActivate = (fn) => (e) => {
const setUploadedVideo = useCallback(async (file) => {
if (!file) return;
setBrowsing(true); setError(null);
+
try {
const d = await uploadFile(file, () => { });
+
if (d.error) setError(d.error);
+
if (d.file_path) {
setVideoPath(d.file_path);
setFile({ file_path: d.file_path });
@@ -1375,12 +1552,25 @@ const onKeyActivate = (fn) => (e) => {
const downloadVideo = async () => {
const url = videoPath.trim();
+
if (!url || downloadingVideo) return;
setDownloadingVideo(true); setError(null);
+
try {
const d = await api('/download-video', { method: 'POST', body: JSON.stringify({ url }) });
- if (d.error) { setError(d.error); setDownloadingVideo(false); return; }
- if (d.job_id) { setDownloadJobId(d.job_id); return; }
+
+ if (d.error) {
+ setError(d.error); setDownloadingVideo(false);
+
+ return;
+ }
+
+ if (d.job_id) {
+ setDownloadJobId(d.job_id);
+
+ return;
+ }
+
setError('Download failed: missing job id');
setDownloadingVideo(false);
} catch (e) { setError('Download failed: ' + e.message); setDownloadingVideo(false); }
@@ -1388,14 +1578,18 @@ const onKeyActivate = (fn) => (e) => {
useEffect(() => {
if (!downloadStream) return;
+
if (downloadStream.status === 'done') {
const d = downloadStream.result;
+
if (!d?.file_path) {
setError('Download finished without a video file.');
setDownloadingVideo(false);
setDownloadJobId(null);
+
return;
}
+
setFile(d);
setVideoPath(d.file_path);
setSilenceOriginal(null);
@@ -1422,15 +1616,25 @@ const onKeyActivate = (fn) => (e) => {
const findMoment = async () => {
const text = momentText.trim();
+
if (!text || findingMoment) return;
setFindingMoment(true); setError(null); setMomentNotice(null);
+
try {
const d = await api('/find-moment', { method: 'POST', body: JSON.stringify({ text }) });
- if (d.error) { setError(d.error); return; }
+
+ if (d.error) {
+ setError(d.error);
+
+ return;
+ }
+
if (!d.added) {
setMomentNotice(d.found ? 'Those moments are already in your clips.' : "Couldn't find that moment. Try different wording or a direct quote.");
+
return;
}
+
// suggestions refresh via the SSE state-sync broadcast
setMomentText('');
setMomentNotice(`Added ${d.added} moment${d.added !== 1 ? 's' : ''}.`);
@@ -1459,6 +1663,7 @@ const onKeyActivate = (fn) => (e) => {
setPhase('exporting'); setResults([]);
const sc = suggestions.filter((_, i) => !deselected.has(i));
const vp = videoPath.trim() || file?.file_path;
+
const data = await api('/batch-clips', {
method: 'POST', body: JSON.stringify({
video_path: vp,
@@ -1467,6 +1672,7 @@ const onKeyActivate = (fn) => (e) => {
caption_position: captionPosition, caption_font_scale: captionFontScale, logo_position: logoPosition,
})
});
+
setBatchJobId(data.job_id);
};
@@ -1474,6 +1680,7 @@ const onKeyActivate = (fn) => (e) => {
setError(null);
setFullEpisodeResult(null);
const vp = videoPath.trim() || file?.file_path;
+
const data = await api('/export-full-episode', {
method: 'POST', body: JSON.stringify({
video_path: vp,
@@ -1485,10 +1692,13 @@ const onKeyActivate = (fn) => (e) => {
logo_path: captionStyle === 'branded' ? logoPath || undefined : undefined,
})
});
+
if (data.error) {
setError(data.error);
+
return;
}
+
setFullEpisodeJobId(data.job_id);
};
@@ -1497,6 +1707,7 @@ const onKeyActivate = (fn) => (e) => {
setFullEpisodeResult(fullEpisodeStream.result || null);
setFullEpisodeJobId(null);
}
+
if (fullEpisodeStream?.status === 'error') {
setError('Full episode export failed: ' + (fullEpisodeStream.error || 'Unknown error'));
setFullEpisodeJobId(null);
@@ -1505,9 +1716,11 @@ const onKeyActivate = (fn) => (e) => {
const analyzeSilence = async () => {
const vp = videoPath.trim() || file?.file_path;
+
if (!vp || !transcript?.words?.length || silenceOriginal) return;
setError(null);
setSilencePlan(null);
+
const data = await api('/analyze-silence', {
method: 'POST',
body: JSON.stringify({
@@ -1518,15 +1731,23 @@ const onKeyActivate = (fn) => (e) => {
padding_seconds: silencePadding,
}),
});
- if (data.error) { setError(data.error); return; }
+
+ if (data.error) {
+ setError(data.error);
+
+ return;
+ }
+
setSilenceAnalyzeJobId(data.job_id);
};
const applySilenceRemoval = async () => {
const vp = videoPath.trim() || file?.file_path;
+
if (!vp || !transcript || !silencePlan?.keep_segments?.length || silenceOriginal) return;
setError(null);
pendingSilenceOriginalRef.current = { videoPath: vp, transcript };
+
const data = await api('/render-silence-removed', {
method: 'POST',
body: JSON.stringify({
@@ -1535,11 +1756,14 @@ const onKeyActivate = (fn) => (e) => {
transcript,
}),
});
+
if (data.error) {
pendingSilenceOriginalRef.current = null;
setError(data.error);
+
return;
}
+
setSilenceRenderJobId(data.job_id);
};
@@ -1579,17 +1803,19 @@ const onKeyActivate = (fn) => (e) => {
if (silenceRenderStream?.status === 'done') {
const rendered = silenceRenderStream.result;
const original = pendingSilenceOriginalRef.current;
+
if (rendered?.output_path && rendered?.transcript && original) {
setSilenceOriginal(original);
setVideoPath(rendered.output_path);
setFile({ file_path: rendered.output_path });
setTranscript(rendered.transcript);
- setSilencePlan(prev => ({ ...(prev || {}), applied: true, output_path: rendered.output_path }));
+ setSilencePlan(prev => ({ ...prev, applied: true, output_path: rendered.output_path }));
resetClipWorkForSource();
autoTranscribeRef.current = rendered.output_path;
} else {
setError('Silence removal finished but returned no usable episode. Try again.');
}
+
pendingSilenceOriginalRef.current = null;
setSilenceRenderJobId(null);
} else if (silenceRenderStream?.status === 'error') {
@@ -1601,22 +1827,27 @@ const onKeyActivate = (fn) => (e) => {
useEffect(() => {
if (!batchStream) return;
+
const rows = Array.isArray(batchStream.clip_results)
? batchStream.clip_results
: batchStream.clip_result ? [batchStream.clip_result] : [];
+
rows.forEach(applyClipResult);
}, [batchStream, applyClipResult]);
useEffect(() => {
if (batchStream?.status === 'done') { setPhase('done'); setResults(batchStream.result?.results || []); setBatchJobId(null); }
+
if (batchStream?.status === 'error') { setError('Export failed: ' + batchStream.error); setPhase('review'); setBatchJobId(null); }
}, [batchStream?.status]);
const retryClipRef = useRef(null);
+
const retryClip = async (idx) => {
const sc = suggestions.filter((_, i) => !deselected.has(i));
const c = sc[idx]; retryClipRef.current = c; setRetryIdx(idx); setRetryJobId(null);
const vp = file?.file_path || videoPath.trim();
+
const data = await api('/create-clip', {
method: 'POST', body: JSON.stringify({
video_path: vp, start_second: c.start_second, end_second: c.end_second,
@@ -1626,29 +1857,41 @@ const onKeyActivate = (fn) => (e) => {
hook: c.hook || null,
})
});
+
setRetryJobId(data.job_id);
};
useEffect(() => {
if (retryStream?.status !== 'done') return;
const c = retryClipRef.current;
+
const row = {
...retryStream.result,
status: 'success',
...(c && { source_start_second: c.start_second, source_end_second: c.end_second }),
};
+
setResults(prev => {
const key = resultBoundsKey(row);
const found = key ? prev.findIndex(r => resultBoundsKey(r) === key) : -1;
- const at = found >= 0 ? found : typeof retryIdx === 'number' ? retryIdx : prev.length;
+ const at = found >= 0 ? found : Number.isInteger(retryIdx) ? retryIdx : prev.length;
const next = [...prev];
next[at] = row;
+
return next;
});
setRetryIdx(null); setRetryJobId(null);
}, [retryStream?.status]);
- const toggleClip = (i) => setDeselected(prev => { const n = new Set(prev); n.has(i) ? n.delete(i) : n.add(i); return n; });
+ const toggleClip = (i) => setDeselected(prev => {
+ const n = new Set(prev);
+
+ if (n.has(i)) n.delete(i);
+ else n.add(i);
+
+ return n;
+ });
+
const selectedClips = suggestions.filter((_, i) => !deselected.has(i));
const selectedCount = selectedClips.length;
const clipRowRefs = useRef([]);
@@ -1658,22 +1901,29 @@ const onKeyActivate = (fn) => (e) => {
const onKey = (e) => {
if (e.metaKey || e.ctrlKey || e.altKey) return;
const t = e.target instanceof Element ? e.target : null;
+
if (t?.closest('input, textarea, select, [contenteditable="true"]')) return;
// Reviewing a clip means focusing its row, so the row is the one control
// these keys must still reach. Anything else that activates on the same
// key would fire twice.
const control = t?.closest('button, a, [role="button"], [role="checkbox"], [role="switch"], [role="tab"], [role="menuitem"]');
+
if (control && !control.hasAttribute('data-clip-row')) return;
+
if (editingClip !== null || previewFile) return;
+
if (!suggestions.length) return;
const key = e.key.toLowerCase();
+
if (key === 'j' || key === 'k') {
e.preventDefault();
setPreviewSrc(null);
const cur = activeClipIdx === null ? -1 : activeClipIdx;
+
const next = key === 'j'
? Math.min(cur + 1, suggestions.length - 1)
: Math.max(cur - 1, 0);
+
setActiveClipIdx(next);
// Without this the focus ring, the highlight, and what Enter
// re-activates drift onto different rows.
@@ -1688,57 +1938,62 @@ const onKeyActivate = (fn) => (e) => {
openClipEdit(activeClipIdx);
}
};
+
window.addEventListener('keydown', onKey);
+
return () => window.removeEventListener('keydown', onKey);
}, [suggestions, phase, activeClipIdx, editingClip, previewFile]);
- const buildLocalPrompt = () => {
- const parts = [];
- const hasTranscriptReady = transcript || transcriptText.trim();
- if (transcriptMode === 'whisper' && !hasTranscriptReady) {
- parts.push(`Transcribe the podcast at ${videoPath} using transcribe_podcast with model_size="${whisperModel}".`);
- parts.push('Then find the 5-8 best viral-worthy moments and call suggest_clips.');
- } else {
- parts.push('Use get_ui_state with include_transcript=true to read the full transcript.');
- parts.push('Find the 5-8 best viral-worthy moments: hot takes, strong opinions, funny moments, actionable advice, and emotional stories.');
- parts.push('Then call suggest_clips with your suggestions.');
- }
- const settings = [];
- if (videoPath) settings.push(`Video: ${videoPath.split(/[\\/]/).pop()}`);
- settings.push(`Style: ${captionStyle}`);
- settings.push(`Crop: ${cropStrategy}`);
- if (logoPath) settings.push(`Logo: set`);
- if (outroPath) settings.push(`Outro: set`);
- parts.push(`Current settings: ${settings.join(', ')}`);
- return parts.join('\n');
- };
const copyGeneratePrompt = async () => {
if (isProcessing) return;
+
if (sourceIsUrl) {
setError('Download the video first, then find best moments.');
+
return;
}
+
// If user has pasted a transcript but it hasn't been parsed yet, parse it first
if (transcriptMode === 'import' && transcriptText.trim() && !transcript) {
setError(null);
setPhase('parsing');
const fileData = await api('/select-file', { method: 'POST', body: JSON.stringify({ file_path: videoPath.trim() }) });
- if (fileData.error) { setError(fileData.error); setPhase('idle'); return; }
+
+ if (fileData.error) {
+ setError(fileData.error); setPhase('idle');
+
+ return;
+ }
+
setFile(fileData);
const text = transcriptText.trim();
const isJson = text.startsWith('{') || text.startsWith('[');
let t = null;
+
if (isJson) {
const parsed = JSON.parse(text);
const tr = Array.isArray(parsed) ? { words: parsed } : parsed;
const data = await api('/import-transcript', { method: 'POST', body: JSON.stringify({ file_path: videoPath.trim(), transcript: tr }) });
- if (data.error) { setError(data.error); setPhase('idle'); return; }
+
+ if (data.error) {
+ setError(data.error); setPhase('idle');
+
+ return;
+ }
+
t = data.data;
} else {
const data = await api('/parse-transcript', { method: 'POST', body: JSON.stringify({ file_path: videoPath.trim(), raw_text: text, time_adjust: timeAdjust }) });
- if (data.error) { setError(data.error); setPhase('idle'); return; }
+
+ if (data.error) {
+ setError(data.error); setPhase('idle');
+
+ return;
+ }
+
t = data.data;
}
+
setTranscript(t);
// Sync transcript + video to server immediately (don't wait for React useEffect)
await fetch('/api/ui-state', {
@@ -1766,22 +2021,25 @@ const onKeyActivate = (fn) => (e) => {
// Ask Claude directly for clip suggestions (same as CLI)
setPhase('suggesting');
setGenerateCopied(false);
+
try {
const res = await fetch('/api/claude-suggest', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ top_n: topClips, min_duration: minDuration, max_duration: maxDuration }),
});
+
const data = await res.json();
if (!res.ok) {
setPhase('idle');
setError(data.error || 'Suggestion failed');
+
return;
}
if (data.clips && data.clips.length > 0) {
- // Claude returned suggestions — populate directly
+ // Claude returned suggestions: populate directly
const mapped = data.clips.map((c, i) => ({
clip_id: `claude-${i}`,
title: c.title,
@@ -1795,23 +2053,27 @@ const onKeyActivate = (fn) => (e) => {
segments: c.segments,
duration: c.duration ?? Math.round((c.end_second || 0) - (c.start_second || 0)),
}));
+
setSuggestions(mapped);
setEnergyData({});
setPhase('review');
} else if (data.fallback === 'clipboard') {
- // Claude not installed — fall back to clipboard copy
+ // Claude not installed: fall back to clipboard copy
setPhase('idle');
setError('Claude Code not found. Install it for automatic clip selection, or use MCP.');
let prompt;
+
try {
const pRes = await fetch('/api/generate-prompt', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'suggest' }),
});
+
const pData = await pRes.json();
prompt = pData.prompt || '';
} catch { prompt = ''; }
+
if (prompt) {
navigator.clipboard.writeText(prompt).then(() => {
setGenerateCopied(true);
@@ -1832,6 +2094,7 @@ const onKeyActivate = (fn) => (e) => {
const silenceBusy = !!silenceAnalyzeJobId || !!silenceRenderJobId;
const isProcessing = phase === 'parsing' || phase === 'suggesting' || phase === 'exporting' || transcribing || downloadingVideo || fullEpisodeBusy || silenceBusy;
const sourceIsUrl = isHttpUrl(videoPath);
+
const exportStats = phase === 'done' ? {
total: results.length || selectedClips.length,
ok: results.filter(r => r?.status === 'success').length,
@@ -1843,7 +2106,9 @@ const onKeyActivate = (fn) => (e) => {
const getExportStatus = (clip, resultIdx) => {
if (phase !== 'exporting') return null;
const r = resultFor(clip, resultIdx);
+
if (r) return r.status === 'error' ? 'failed' : 'exported';
+
return batchStream ? 'pending' : null;
};
@@ -1852,8 +2117,15 @@ const onKeyActivate = (fn) => (e) => {
const f = e.dataTransfer?.files?.[0];
setUploadedVideo(f);
};
- const handleTranscriptDrop = (e) => { e.preventDefault(); setTranscriptDragOver(false); const files = e.dataTransfer?.files; if (!files?.length) return; const f = files[0]; setTranscriptFileName(f.name); const reader = new FileReader(); reader.onload = (ev) => setTranscriptText(ev.target.result); reader.readAsText(f); };
- const handleTranscriptFileSelect = (e) => { const f = e.target.files?.[0]; if (!f) return; setTranscriptFileName(f.name); const reader = new FileReader(); reader.onload = (ev) => setTranscriptText(ev.target.result); reader.readAsText(f); };
+
+ const handleTranscriptDrop = (e) => { e.preventDefault(); setTranscriptDragOver(false); const files = e.dataTransfer?.files;
+
+ if (!files?.length) return; const f = files[0]; setTranscriptFileName(f.name); const reader = new FileReader(); reader.onload = (ev) => setTranscriptText(ev.target.result); reader.readAsText(f); };
+
+ const handleTranscriptFileSelect = (e) => { const f = e.target.files?.[0];
+
+ if (!f) return; setTranscriptFileName(f.name); const reader = new FileReader(); reader.onload = (ev) => setTranscriptText(ev.target.result); reader.readAsText(f); };
+
const preventDef = (e) => e.preventDefault();
return (
@@ -2210,7 +2482,9 @@ const onKeyActivate = (fn) => (e) => {
// A zero or missing duration would emit NaN%, which
// the browser drops, leaving the bar unpositioned.
const span = Number(silencePlan.source_duration) || 0;
+
if (span <= 0) return null;
+
return (
<span key={index} className="silence-cut" style={{
left: `${(range.start / span) * 100}%`,
@@ -2259,7 +2533,9 @@ const onKeyActivate = (fn) => (e) => {
{showPresetSave ? (
<div className="preset-save-row">
<input type="text" placeholder="Preset name" value={presetName} onChange={e => setPresetName(e.target.value)}
- onKeyDown={e => { if (e.key === 'Enter') savePreset(); if (e.key === 'Escape') setShowPresetSave(false); }}
+ onKeyDown={e => { if (e.key === 'Enter') savePreset();
+
+ if (e.key === 'Escape') setShowPresetSave(false); }}
autoFocus disabled={presetSaving} />
<button className="btn btn-primary btn-sm" onClick={savePreset} disabled={!presetName.trim() || presetSaving}>
{presetSaving ? <div className="spinner sm" /> : 'Save'}
@@ -2698,7 +2974,7 @@ const onKeyActivate = (fn) => (e) => {
{phase === 'done' && exportStats && (exportStats.failed > 0 || exportStats.ok < exportStats.total) && (
<div className={`set-note ${exportStats.ok === 0 ? 'err' : ''}`} style={{ marginTop: 14, background: exportStats.ok === 0 ? undefined : 'var(--amber-subtle, rgba(251,191,36,0.1))', color: exportStats.ok === 0 ? undefined : 'var(--amber, #f59e0b)', border: exportStats.ok === 0 ? undefined : '1px solid rgba(251,191,36,0.25)' }}>
{exportStats.ok} of {exportStats.total} clip{exportStats.total !== 1 ? 's' : ''} exported
- {exportStats.failed > 0 && ` — ${exportStats.failed} failed`}
+ {exportStats.failed > 0 && `, ${exportStats.failed} failed`}
{exportStats.failed > 0 && results.filter(r => r?.status === 'error').slice(0, 3).map((r, i) => (
<span key={i} style={{ display: 'block', marginTop: 4, fontSize: 11, opacity: 0.9 }}>{r.error?.slice(0, 120)}</span>
))}
@@ -2785,11 +3061,16 @@ const onKeyActivate = (fn) => (e) => {
const ago = ((Date.now() - date.getTime()) / 3600000);
const timeStr = ago < 1 ? `${Math.round(ago * 60)}m ago` : ago < 24 ? `${Math.round(ago)}h ago` : date.toLocaleDateString();
const fname = c.output_path?.split('/').pop() || c.title;
+
return (
<div key={c.id || i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', background: 'var(--surface)', borderRadius: 'var(--radius-sm)', fontSize: 12, cursor: 'pointer' }}
role="button" tabIndex={0} aria-label={`Preview ${c.title || fname}`}
- onClick={() => { const f = c.output_path?.split('/').pop(); if (f) onPlayRendered(f); }}
- onKeyDown={onKeyActivate(() => { const f = c.output_path?.split('/').pop(); if (f) onPlayRendered(f); })}>
+ onClick={() => { const f = c.output_path?.split('/').pop();
+
+ if (f) onPlayRendered(f); }}
+ onKeyDown={onKeyActivate(() => { const f = c.output_path?.split('/').pop();
+
+ if (f) onPlayRendered(f); })}>
<div style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--green)', flexShrink: 0 }} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.title || fname}</div>
@@ -2806,7 +3087,7 @@ const onKeyActivate = (fn) => (e) => {
)}
</div>
- {/* ═══════════ RIGHT COLUMN — PREVIEW ═══════════ */}
+ {/* ═══════════ RIGHT COLUMN: PREVIEW ═══════════ */}
<div className="preview-col">
<div className="preview-panel">
@@ -2855,7 +3136,7 @@ const onKeyActivate = (fn) => (e) => {
</div>
)}
- {/* Style preview mockup — hidden when rendered clip is playing, whose
+ {/* Style preview mockup: hidden when rendered clip is playing, whose
captions are already burned in and whose clock is clip-relative */}
{previewMode === 'clips' && !previewSrc && (
<LivePhonePreview
diff --git a/src/ui/client/HighlightsPage.tsx b/src/ui/client/HighlightsPage.tsx
index ef4e4d0..9fd1616 100644
--- a/src/ui/client/HighlightsPage.tsx
+++ b/src/ui/client/HighlightsPage.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from "react";
import { PageHeader } from "./Page";
-import { api, basename, fmt } from "./lib";
+import { api, basename, fmt, upload } from "./lib";
import { useJob } from "./useJob";
import AssetPicker from "./AssetPicker";
import RecentSources from "./RecentSources";
@@ -43,14 +43,33 @@ interface SessionSummary {
type Format = "vertical" | "horizontal" | "square";
+const FORMATS: readonly Format[] = ["vertical", "horizontal", "square"];
+
+interface ReelRequest {
+ action: string;
+ session_id?: string;
+ logo?: string;
+ index?: number;
+ op?: string;
+ seconds?: number;
+ video_path?: string;
+ video_paths?: string[];
+ profile?: string;
+ format?: Format;
+ auto?: boolean;
+ top_n?: number;
+ min_dur?: number;
+ max_dur?: number;
+}
+
const download = (p: string) => `/api/reel-download?path=${encodeURIComponent(p)}`;
const isHttpUrl = (v: string) => /^https?:\/\//i.test(v.trim());
-const FORMAT_LABEL: Record<Format, string> = {
- horizontal: "16:9",
- vertical: "9:16",
- square: "1:1",
-};
+const FORMAT_LABEL = new Map<string, string>([
+ ["horizontal", "16:9"],
+ ["vertical", "9:16"],
+ ["square", "1:1"],
+]);
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
@@ -76,6 +95,7 @@ function DownloadRow({
const fired = useRef(false);
useEffect(() => {
if (!job || fired.current) return;
+
if (job.status === "done") {
fired.current = true;
onDone(jobId, job.result?.file_path);
@@ -84,6 +104,7 @@ function DownloadRow({
onError(jobId, job.error);
}
}, [job?.status]);
+
return (
<div className="file-badge">
<div className="spinner sm" />
@@ -120,6 +141,7 @@ export default function HighlightsPage() {
method: "POST",
body: JSON.stringify({ action: "list" }),
});
+
setSessions(r.sessions || []);
} catch {
/* list is best-effort */
@@ -133,9 +155,10 @@ export default function HighlightsPage() {
.catch(() => {});
}, []);
- async function call(body: Record<string, unknown>, label: string) {
+ async function call(body: ReelRequest, label: string) {
setBusy(true);
setMsg(label);
+
try {
const r = await api<HighlightsResp>("/reel", { method: "POST", body: JSON.stringify(body) });
setSession(r);
@@ -151,10 +174,12 @@ export default function HighlightsPage() {
const addPath = (p: string) =>
setVideoPaths((prev) => (p && !prev.includes(p) ? [...prev, p] : prev));
+
const removePath = (i: number) => setVideoPaths((prev) => prev.filter((_, n) => n !== i));
async function browse() {
setBrowsing(true);
+
try {
const d = await api<{ file_path?: string; file_paths?: string[] }>("/browse-file?multiple=1");
const picked = d.file_paths?.length ? d.file_paths : d.file_path ? [d.file_path] : [];
@@ -168,15 +193,16 @@ export default function HighlightsPage() {
async function uploadDropped(files: File[]) {
setBrowsing(true);
+
try {
for (const file of files) {
setMsg(`Uploading ${file.name}…`);
const fd = new FormData();
fd.append("file", file);
- const res = await fetch("/api/upload", { method: "POST", body: fd });
- const d = (await res.json()) as { file_path?: string; error?: string };
+ const d = await upload<{ file_path?: string }>("/upload", fd);
+
if (d.file_path) addPath(d.file_path);
- else setMsg(d.error || "Upload failed");
+ else setMsg("Upload failed");
}
} catch {
setMsg("Upload failed");
@@ -190,6 +216,7 @@ export default function HighlightsPage() {
e.preventDefault();
setDragOver(false);
const files = Array.from(e.dataTransfer.files || []);
+
if (files.length) uploadDropped(files);
}
@@ -199,6 +226,7 @@ export default function HighlightsPage() {
method: "POST",
body: JSON.stringify({ url }),
});
+
if (d.error) setMsg("Download failed: " + d.error);
else if (d.job_id) setDownloads((prev) => [...prev, { jobId: d.job_id!, url }]);
} catch (e) {
@@ -208,9 +236,11 @@ export default function HighlightsPage() {
const onDownloadDone = (jobId: string, filePath?: string) => {
setDownloads((prev) => prev.filter((d) => d.jobId !== jobId));
+
if (filePath) addPath(filePath);
else setMsg("Download finished without a video file.");
};
+
const onDownloadError = (jobId: string, error?: string) => {
setDownloads((prev) => prev.filter((d) => d.jobId !== jobId));
setMsg("Download failed: " + (error || "unknown error"));
@@ -218,10 +248,12 @@ export default function HighlightsPage() {
function commitDraft() {
const p = pathDraft.trim();
+
if (p) {
if (isHttpUrl(p)) startDownload(p);
else addPath(p);
}
+
setPathDraft("");
}
@@ -244,9 +276,10 @@ export default function HighlightsPage() {
const detect = () => {
const seed =
videoPaths.length === 1 ? { video_path: videoPaths[0] } : { video_paths: videoPaths };
+
const tuning = auto ? { auto: true } : { top_n: topN, min_dur: minDur, max_dur: maxDur };
call(
- { action: "new", ...seed, profile: "auto", format, ...tuning, ...(logoPath ? { logo: logoPath } : {}) },
+ { action: "new", ...seed, profile: "auto", format, ...tuning, ...(logoPath && { logo: logoPath }) },
videoPaths.length > 1
? `Finding the best moments across ${videoPaths.length} videos (one-time)…`
: "Finding the best moments (one-time, ~2 min)…",
@@ -263,11 +296,13 @@ export default function HighlightsPage() {
if (!session) return;
setSession({ ...session, moments: session.moments.map((m, i) => (i === index ? { ...m, start, end } : m)) });
setSaving(true);
+
try {
const r = await api<HighlightsResp>("/reel", {
method: "POST",
body: JSON.stringify({ action: "edit", session_id: session.session_id, index: index + 1, op: "set", start, end }),
});
+
setSession(r);
} finally {
setSaving(false);
@@ -276,10 +311,13 @@ export default function HighlightsPage() {
async function remove(e: React.MouseEvent, id: string) {
e.stopPropagation();
+
if (!window.confirm("Delete this highlights session?")) return;
setBusy(true);
+
try {
await api("/reel", { method: "POST", body: JSON.stringify({ action: "delete", session_id: id }) });
+
if (session?.session_id === id) setSession(null);
refreshList();
} finally {
@@ -356,7 +394,7 @@ export default function HighlightsPage() {
<div className="row" style={{ marginTop: 14 }}>
<Field label="Format">
- <select value={format} onChange={(e) => setFormat(e.target.value as Format)}>
+ <select value={format} onChange={(e) => setFormat(FORMATS.find((f) => f === e.target.value) ?? format)}>
<option value="horizontal">Horizontal 16:9</option>
<option value="vertical">Vertical 9:16</option>
<option value="square">Square 1:1</option>
@@ -502,7 +540,7 @@ export default function HighlightsPage() {
</div>
<div className="meta" style={{ gap: 8 }}>
<span className="pill pill-blue">{s.profile}</span>
- <span className="hint">{FORMAT_LABEL[s.format as Format] || s.format}</span>
+ <span className="hint">{FORMAT_LABEL.get(s.format) || s.format}</span>
<span className="hint">·</span>
<span className="hint">{s.enabled_count}/{s.moment_count} moments</span>
</div>
diff --git a/src/ui/client/IntegrationsPage.tsx b/src/ui/client/IntegrationsPage.tsx
index e2ae281..76cb137 100644
--- a/src/ui/client/IntegrationsPage.tsx
+++ b/src/ui/client/IntegrationsPage.tsx
@@ -2,12 +2,12 @@ import React, { useEffect, useState } from "react";
import { PageHeader } from "./Page";
import { api } from "./lib";
-const CATEGORY: Record<string, string> = {
- editor_export: "Editor export",
- platform_upload: "Platform upload",
- productivity: "Productivity",
- ai_helper: "AI helper",
-};
+const CATEGORY = new Map([
+ ["editor_export", "Editor export"],
+ ["platform_upload", "Platform upload"],
+ ["productivity", "Productivity"],
+ ["ai_helper", "AI helper"],
+]);
export default function IntegrationsPage() {
const [integrations, setIntegrations] = useState<any[] | null>(null);
@@ -32,6 +32,7 @@ export default function IntegrationsPage() {
const name = int.name;
const next = !int.enabled;
setBusy((b) => ({ ...b, [name]: true }));
+
try {
await api(`/integrations/${encodeURIComponent(name)}`, {
method: "POST",
@@ -67,7 +68,7 @@ export default function IntegrationsPage() {
<div className="name">
{int.name}
<span className="pill pill-blue" style={{ marginLeft: 8, fontSize: 10 }}>
- {CATEGORY[int.category] || int.category}
+ {CATEGORY.get(int.category) || int.category}
</span>
</div>
{int.description && <div className="desc">{int.description}</div>}
diff --git a/src/ui/client/KnowledgePage.jsx b/src/ui/client/KnowledgePage.jsx
index 05813a4..e1df4ac 100644
--- a/src/ui/client/KnowledgePage.jsx
+++ b/src/ui/client/KnowledgePage.jsx
@@ -39,6 +39,7 @@ export default function KnowledgePage() {
const saveFile = async () => {
if (!activeFile) return;
+
try {
await api(`/knowledge/${encodeURIComponent(activeFile)}`, { method: 'POST', body: JSON.stringify({ content: editorContent }) });
setDirty(false);
@@ -49,10 +50,14 @@ export default function KnowledgePage() {
const deleteFile = async (filename, e) => {
e.stopPropagation();
+
if (!confirm(`Delete ${filename}?`)) return;
+
try {
await api(`/knowledge/${encodeURIComponent(filename)}`, { method: 'DELETE' });
+
if (activeFile === filename) { setActiveFile(null); setEditorContent(''); }
+
showToast('Deleted');
loadFiles();
} catch (e) { showToast(`Delete failed: ${e.message}`); }
@@ -60,13 +65,17 @@ export default function KnowledgePage() {
const createFile = async () => {
let name = newName.trim();
+
if (!name) return;
+
if (!name.endsWith('.md')) name += '.md';
+
try {
await api(`/knowledge/${encodeURIComponent(name)}`, { method: 'POST', body: JSON.stringify({ content: `# ${name.replace('.md', '')}\n\n` }) });
setNewName('');
await loadFiles();
const created = (await api('/knowledge')).find(f => f.filename === name);
+
if (created) openFile(created);
showToast('Created');
} catch (e) { showToast(`Create failed: ${e.message}`); }
@@ -74,6 +83,7 @@ export default function KnowledgePage() {
const createStarterFiles = async () => {
setCreating(true);
+
try {
const r = await api('/knowledge/init', { method: 'POST' });
setCreated(r.created || []);
@@ -84,10 +94,13 @@ export default function KnowledgePage() {
const uploadFiles = async (fileList, label) => {
const fd = new FormData();
+
for (const f of fileList) {
if (f.name.endsWith('.md') || f.name.endsWith('.txt')) fd.append('files', f);
}
+
if (!fd.has('files')) return;
+
try {
await upload('/knowledge/upload', fd);
showToast(`${label} added`);
@@ -98,6 +111,7 @@ export default function KnowledgePage() {
const handleDrop = async (e) => {
e.preventDefault();
setDragOver(false);
+
if (!e.dataTransfer.files.length) return;
await uploadFiles(e.dataTransfer.files, `${e.dataTransfer.files.length} file(s)`);
};
diff --git a/src/ui/client/Layout.tsx b/src/ui/client/Layout.tsx
index 25b2b35..1db8b18 100644
--- a/src/ui/client/Layout.tsx
+++ b/src/ui/client/Layout.tsx
@@ -18,23 +18,26 @@ import {
import CommandPalette from "./CommandPalette";
import AccountChip from "./AccountChip";
-const icons: Record<string, typeof LayoutGrid> = {
- library: LayoutGrid,
- episode: Play,
- content: FileText,
- thumbnail: Image,
- knowledge: BookOpen,
- config: Settings,
- integrations: Plug,
- mcp: Terminal,
- analytics: BarChart3,
- highlights: Scissors,
- assets: Package,
- multicam: Video,
-};
+const icons = new Map([
+ ["library", LayoutGrid],
+ ["episode", Play],
+ ["content", FileText],
+ ["thumbnail", Image],
+ ["knowledge", BookOpen],
+ ["config", Settings],
+ ["integrations", Plug],
+ ["mcp", Terminal],
+ ["analytics", BarChart3],
+ ["highlights", Scissors],
+ ["assets", Package],
+ ["multicam", Video],
+]);
function Icon({ name }: { name: string }) {
- const Glyph = icons[name];
+ const Glyph = icons.get(name);
+
+ if (!Glyph) return null;
+
return <Glyph className="ico" strokeWidth={1.8} />;
}
diff --git a/src/ui/client/McpSetupPage.tsx b/src/ui/client/McpSetupPage.tsx
index f8cefd3..3ecbd56 100644
--- a/src/ui/client/McpSetupPage.tsx
+++ b/src/ui/client/McpSetupPage.tsx
@@ -30,6 +30,7 @@ export default function McpSetupPage() {
api<any>("/integration-info")
.then((data) => {
setMcpPath(data.mcp_path || data.dist_path);
+
if (data.server_ok) {
setStatusKind("ok");
setStatusText("Ready");
@@ -45,6 +46,7 @@ export default function McpSetupPage() {
}, []);
const serverPath = mcpPath ?? "<path-to>/mcp-server.mjs";
+
const desktopJson = JSON.stringify(
{
mcpServers: {
diff --git a/src/ui/client/MomentTrim.tsx b/src/ui/client/MomentTrim.tsx
index 3224393..d05000c 100644
--- a/src/ui/client/MomentTrim.tsx
+++ b/src/ui/client/MomentTrim.tsx
@@ -39,14 +39,17 @@ export default function MomentTrim({
useEffect(() => {
setDraft(null);
const v = video.current;
+
if (v) v.currentTime = startProp;
setCur(startProp);
}, [startProp, endProp, src]);
const timeAt = (clientX: number) => {
const el = trackRef.current;
+
if (!el) return winA;
const r = el.getBoundingClientRect();
+
return winA + Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * span;
};
@@ -55,9 +58,12 @@ export default function MomentTrim({
const t = timeAt(e.clientX);
setDraft((d) => {
const base = d ?? { start: startProp, end: endProp };
+
if (drag.current === "in") return { start: Math.min(t, base.end - 0.5), end: base.end };
+
return { start: base.start, end: Math.max(t, base.start + 0.5) };
});
+
if (video.current) {
video.current.currentTime = t;
setCur(t);
@@ -68,12 +74,15 @@ export default function MomentTrim({
if (!drag.current) return;
e.currentTarget.releasePointerCapture(e.pointerId);
drag.current = null;
+
if (draft) onCommit(round1(draft.start), round1(draft.end));
};
const toggle = () => {
const v = video.current;
+
if (!v) return;
+
if (v.paused) {
if (v.currentTime < start || v.currentTime >= end) v.currentTime = start;
v.play();
@@ -82,6 +91,7 @@ export default function MomentTrim({
const onTime = (e: React.SyntheticEvent<HTMLVideoElement>) => {
const t = e.currentTarget.currentTime;
+
if (playing && t >= end) {
e.currentTarget.currentTime = start;
setCur(start);
diff --git a/src/ui/client/RecentSources.tsx b/src/ui/client/RecentSources.tsx
index 9c3c717..399ab97 100644
--- a/src/ui/client/RecentSources.tsx
+++ b/src/ui/client/RecentSources.tsx
@@ -21,6 +21,7 @@ export default function RecentSources({
}, []);
const options = items.filter((s) => !exclude.includes(s.path));
+
if (options.length === 0) return null;
return (
diff --git a/src/ui/client/ReframeEditor.tsx b/src/ui/client/ReframeEditor.tsx
index 72ebbde..b7977c1 100644
--- a/src/ui/client/ReframeEditor.tsx
+++ b/src/ui/client/ReframeEditor.tsx
@@ -40,10 +40,12 @@ export default function ReframeEditor({
const clampCenter = (p: number) => Math.max(half, Math.min(100 - half, p));
useEffect(() => {
- api(`/clips/${clipId}/reframe`).then((r) => {
- if (Array.isArray(r?.keyframes)) setKeyframes(r.keyframes);
- if (typeof r?.inSec === "number") setInSec(r.inSec);
- if (typeof r?.outSec === "number") setOutSec(r.outSec);
+ api<{ keyframes?: Keyframe[]; inSec?: number; outSec?: number }>(`/clips/${clipId}/reframe`).then((r) => {
+ if (r.keyframes) setKeyframes(r.keyframes);
+
+ if (r.inSec !== undefined) setInSec(r.inSec);
+
+ if (r.outSec !== undefined) setOutSec(r.outSec);
}).catch(() => {});
api(`/clips/${clipId}/cuts`)
.then((r) => setCuts(Array.isArray(r?.cuts) ? r.cuts : []))
@@ -53,20 +55,25 @@ export default function ReframeEditor({
const onMeta = () => {
const v = videoRef.current;
+
if (!v) return;
+
if (v.videoWidth) setBoxPct(Math.min(100, ((v.videoHeight * 9) / 16 / v.videoWidth) * 100));
+
if (v.duration && Number.isFinite(v.duration)) setSrcDur(v.duration);
v.currentTime = start;
};
const reflectKeyframe = (absT: number) => {
const at = keyframes.slice().sort((a, b) => a.tAbs - b.tAbs).filter((k) => k.tAbs <= absT).pop();
+
if (at) setCenterPct(at.x_pct);
};
const seek = (absT: number) => {
const v = videoRef.current;
const clamped = Math.max(bufStart, Math.min(bufEnd, absT));
+
if (v) v.currentTime = clamped;
setTAbs(clamped);
reflectKeyframe(clamped);
@@ -74,14 +81,19 @@ export default function ReframeEditor({
const togglePlay = () => {
const v = videoRef.current;
+
if (!v) return;
+
if (v.paused) { if (v.currentTime >= bufEnd) v.currentTime = bufStart; v.play(); } else v.pause();
};
const onTimeUpdate = () => {
const v = videoRef.current;
+
if (!v) return;
+
if (v.currentTime >= bufEnd) { v.pause(); v.currentTime = bufEnd; }
+
setTAbs(v.currentTime);
reflectKeyframe(v.currentTime);
};
@@ -100,19 +112,24 @@ export default function ReframeEditor({
const jumpCut = (dir: 1 | -1) => {
const next = dir > 0 ? cuts.find((c) => c > tAbs + 0.05) : [...cuts].reverse().find((c) => c < tAbs - 0.05);
+
if (next != null) seek(next);
};
const xToTime = (clientX: number) => {
const r = trackRef.current!.getBoundingClientRect();
+
return bufStart + Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * win;
};
+
const applyDrag = (clientX: number) => {
const tt = xToTime(clientX);
+
if (dragMode.current === "in") { setInSec(Math.min(tt, outSec - 0.2)); seek(tt); }
else if (dragMode.current === "out") { setOutSec(Math.max(tt, inSec + 0.2)); seek(tt); }
else seek(tt);
};
+
const onTrackDown = (e: React.PointerEvent<HTMLDivElement>) => {
e.currentTarget.setPointerCapture(e.pointerId);
const tt = xToTime(e.clientX);
@@ -124,6 +141,7 @@ export default function ReframeEditor({
const apply = async () => {
const kf = keyframes.length ? keyframes : [{ tAbs: inSec, x_pct: +centerPct.toFixed(1) }];
setBusy(true); setErr(null);
+
try {
const r = await api(`/clips/${clipId}/rerender`, {
method: "POST",
@@ -131,6 +149,7 @@ export default function ReframeEditor({
? { caption_style, trim: { inSec: +inSec.toFixed(3), outSec: +outSec.toFixed(3) } }
: { caption_style, reframe: { keyframes: kf, inSec: +inSec.toFixed(3), outSec: +outSec.toFixed(3) } }),
});
+
if (r.error) throw new Error(r.error);
onDone();
} catch (e: any) { setErr(e.message); setBusy(false); }
diff --git a/src/ui/client/SetupChecklist.tsx b/src/ui/client/SetupChecklist.tsx
index f333c8e..2d17a21 100644
--- a/src/ui/client/SetupChecklist.tsx
+++ b/src/ui/client/SetupChecklist.tsx
@@ -39,6 +39,7 @@ export default function SetupChecklist() {
const createKnowledge = async () => {
setCreating(true);
setError(null);
+
try {
await api("/knowledge/init", { method: "POST" });
load();
@@ -89,6 +90,7 @@ export default function SetupChecklist() {
];
const done = steps.filter((s) => s.done).length;
+
if (done === steps.length) return null;
return (
diff --git a/src/ui/client/StudioHome.tsx b/src/ui/client/StudioHome.tsx
index ae68924..4afcbef 100644
--- a/src/ui/client/StudioHome.tsx
+++ b/src/ui/client/StudioHome.tsx
@@ -26,10 +26,12 @@ interface Episode {
function groupEpisodes(clips: Clip[]): Episode[] {
const map = new Map<string, Clip[]>();
+
for (const c of clips) {
const key = basename(c.source_video) || "unknown";
(map.get(key) ?? map.set(key, []).get(key)!).push(c);
}
+
return Array.from(map.entries())
.map(([source, list]) => ({
source,
@@ -56,19 +58,30 @@ export default function StudioHome() {
loadHistory();
const events = new EventSource("/api/events");
events.addEventListener("history-updated", loadHistory);
- const onStart = (e: MessageEvent) => { try { setExporting(JSON.parse(e.data).clipCount || 0); } catch { setExporting(1); } };
+
+ const onStart = (e: Event) => {
+ try {
+ setExporting(e instanceof MessageEvent ? JSON.parse(e.data).clipCount || 0 : 1);
+ } catch {
+ setExporting(1);
+ }
+ };
+
const onEnd = () => setExporting(0);
- events.addEventListener("export-started", onStart as EventListener);
- events.addEventListener("job-complete", onEnd as EventListener);
- events.addEventListener("job-error", onEnd as EventListener);
+ events.addEventListener("export-started", onStart);
+ events.addEventListener("job-complete", onEnd);
+ events.addEventListener("job-error", onEnd);
+
return () => events.close();
}, []);
const remove = async (e: React.MouseEvent, c: Clip) => {
e.preventDefault();
e.stopPropagation();
+
if (deleting || !window.confirm(`Delete "${c.title}"? This removes the rendered file too.`)) return;
setDeleting(c.id);
+
try {
await api(`/clips/${c.id}`, { method: "DELETE" });
setClips((prev) => prev.filter((x) => x.id !== c.id));
@@ -118,6 +131,7 @@ export default function StudioHome() {
{ep.clips.map((c) => {
const file = basename(c.output_path);
const thumb = c.thumbnail_config?.preview_path;
+
return (
<Link key={c.id} to={`/clip/${c.id}`} className="clip-card">
<button
diff --git a/src/ui/client/ThumbnailStudio.tsx b/src/ui/client/ThumbnailStudio.tsx
index 3f41379..17a17d5 100644
--- a/src/ui/client/ThumbnailStudio.tsx
+++ b/src/ui/client/ThumbnailStudio.tsx
@@ -31,8 +31,10 @@ export default function ThumbnailStudio() {
const browse = async () => {
setBusy("browse"); setMsg(null); setMsgErr(false);
+
try {
const r = await api("/browse-file");
+
if (r.file_path) setVideo({ path: r.file_path, name: r.filename || basename(r.file_path) });
} catch (e: any) {
if (e.message !== "cancelled") { setMsg(`Browse failed: ${e.message}`); setMsgErr(true); }
@@ -41,11 +43,14 @@ export default function ThumbnailStudio() {
const uploadFile = async (f: File) => {
setBusy("upload"); setMsg(null); setMsgErr(false);
+
try {
const fd = new FormData();
fd.append("file", f);
const r = await upload<any>("/upload", fd);
+
if (!r.file_path) throw new Error("upload failed");
+
if (isImage(f.name)) {
setSelFrame({ path: r.file_path });
setPreview(null);
@@ -57,8 +62,14 @@ export default function ThumbnailStudio() {
};
const loadOptions = async () => {
- if (!title.trim()) { setMsg("Enter a title first, headlines are written from it"); setMsgErr(true); return; }
+ if (!title.trim()) {
+ setMsg("Enter a title first, headlines are written from it"); setMsgErr(true);
+
+ return;
+ }
+
setBusy("options"); setMsg(null); setMsgErr(false);
+
try {
const r = await api("/thumbnail-studio/options", {
method: "POST",
@@ -69,18 +80,27 @@ export default function ThumbnailStudio() {
end: endS !== "" ? Number(endS) : undefined,
}),
});
+
setTextOpts(r.texts || []);
setFrameOpts(r.frames || []);
setBust(Date.now());
+
if ((r.frames || []).length) setSelFrame({ path: r.frames[0].path, info: r.frames[0] });
+
if (!(r.texts || []).length && !(r.frames || []).length) { setMsg("No options. Is the AI CLI installed? Pick a video for frame options."); setMsgErr(true); }
else if (r.warning) { setMsg(r.warning); setMsgErr(true); }
} catch (e: any) { setMsg(`Options failed: ${e.message}`); setMsgErr(true); } finally { setBusy(null); }
};
const render = async () => {
- if (!selFrame) { setMsg("Select a frame or upload an image first"); setMsgErr(true); return; }
+ if (!selFrame) {
+ setMsg("Select a frame or upload an image first"); setMsgErr(true);
+
+ return;
+ }
+
setBusy("render"); setMsg(null); setMsgErr(false);
+
try {
const r = await api("/thumbnail-studio/render", {
method: "POST",
@@ -92,6 +112,7 @@ export default function ThumbnailStudio() {
frame_info: selFrame.info,
}),
});
+
if (!r.path) throw new Error("no thumbnail produced");
setPreview(r.path);
setBust(Date.now());
@@ -100,13 +121,20 @@ export default function ThumbnailStudio() {
};
// Pull a different frame from the source (cycles the ranked candidates) and
- // re-render — same one-click flow as Regenerate, but swaps the background frame.
+ // re-render: same one-click flow as Regenerate, but swaps the background frame.
const newFrame = async () => {
setBusy("newframe"); setMsg(null); setMsgErr(false);
+
try {
let frames = frameOpts;
+
if (!frames.length) {
- if (!title.trim()) { setMsg("Enter a title first, headlines are written from it"); setMsgErr(true); return; }
+ if (!title.trim()) {
+ setMsg("Enter a title first, headlines are written from it"); setMsgErr(true);
+
+ return;
+ }
+
const r = await api("/thumbnail-studio/options", {
method: "POST",
body: JSON.stringify({
@@ -116,20 +144,30 @@ export default function ThumbnailStudio() {
end: endS !== "" ? Number(endS) : undefined,
}),
});
+
frames = r.frames || [];
setFrameOpts(frames);
+
if ((r.texts || []).length) setTextOpts(r.texts);
}
- if (!frames.length) { setMsg("No frames found. Pick a video source first."); setMsgErr(true); return; }
+
+ if (!frames.length) {
+ setMsg("No frames found. Pick a video source first."); setMsgErr(true);
+
+ return;
+ }
+
const curIdx = frames.findIndex((f: any) => f.path === selFrame?.path);
const next = ((curIdx < 0 ? frameIdx : curIdx) + 1) % frames.length;
setFrameIdx(next);
const frame = frames[next];
setSelFrame({ path: frame.path, info: frame });
+
const r = await api("/thumbnail-studio/render", {
method: "POST",
body: JSON.stringify({ title, line1: line1 || undefined, line2: line2 || undefined, frame_path: frame.path, frame_info: frame }),
});
+
if (!r.path) throw new Error("no thumbnail produced");
setPreview(r.path);
setBust(Date.now());
diff --git a/src/ui/client/ThumbnailTemplate.tsx b/src/ui/client/ThumbnailTemplate.tsx
index bb256ef..ecf2660 100644
--- a/src/ui/client/ThumbnailTemplate.tsx
+++ b/src/ui/client/ThumbnailTemplate.tsx
@@ -3,8 +3,12 @@ import { PageHeader } from "./Page";
import { api, labelStyle } from "./lib";
import { BackIcon } from "./icons";
-type Cfg = Record<string, any>;
+type CfgValue = string | number | boolean;
+
+type Cfg = Record<string, CfgValue>;
+
type FieldType = "color" | "num" | "text" | "bool" | "select";
+
interface Field { k: string; t: FieldType; opts?: string[]; wide?: boolean }
const GROUPS: { group: string; items: Field[] }[] = [
@@ -52,13 +56,18 @@ const GROUPS: { group: string; items: Field[] }[] = [
const KNOWN = new Set(GROUPS.flatMap((g) => g.items.map((i) => i.k)));
const titleCase = (k: string) => k.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
-const isHex = (v: any) => typeof v === "string" && /^#[0-9a-fA-F]{6}$/.test(v);
-const px = (v: any, s: number, f = 0) => { const n = parseFloat(String(v ?? "").replace(/[^0-9.]/g, "")); return (Number.isFinite(n) ? n : f) * s; };
-const isPct = (v: any) => typeof v === "string" && v.trim().endsWith("%");
+const isHex = (v: string) => /^#[0-9a-fA-F]{6}$/.test(v);
+
+const px = (v: CfgValue | undefined, s: number, f = 0) => { const n = parseFloat(String(v ?? "").replace(/[^0-9.]/g, ""));
+
+ return (Number.isFinite(n) ? n : f) * s; };
+
+const isPct = (v: CfgValue | undefined) => String(v ?? "").trim().endsWith("%");
const SCALE = 300 / 1080;
-function padToPreview(pad: any): string {
+function padToPreview(pad: CfgValue | undefined): string {
const parts = String(pad ?? "30px 45px").trim().split(/\s+/).map((p) => `${px(p, SCALE)}px`);
+
return parts.join(" ") || "8px 12px";
}
@@ -68,16 +77,25 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {
const [msg, setMsg] = useState<string | null>(null);
const importRef = useRef<HTMLInputElement>(null);
- const load = () => api("/thumbnail-config").then((d) => setCfg(d && typeof d === "object" ? d : {})).catch(() => setCfg({}));
+ const load = () => api<Cfg>("/thumbnail-config").then((d) => setCfg(d instanceof Object ? d : {})).catch(() => setCfg({}));
useEffect(() => { load(); }, []);
if (!cfg) return <div className="app"><div style={{ display: "flex", gap: 10, alignItems: "center", color: "var(--text2)", padding: 40 }}><div className="spinner sm" /> Loading…</div></div>;
- const set = (k: string, v: any) => setCfg({ ...cfg, [k]: v });
+ const set = (k: string, v: CfgValue) => setCfg({ ...cfg, [k]: v });
+
+ const text = (k: string, fallback: string) => {
+ const v = cfg[k];
+
+ return v === undefined || v === "" ? fallback : String(v);
+ };
+
const save = async () => {
setBusy("save"); setMsg(null);
+
try {
const r = await api("/thumbnail-config", { method: "PUT", body: JSON.stringify(cfg) });
+
if (r.error) throw new Error(r.error);
setMsg("Saved. New thumbnails use this template");
} catch (e: any) { setMsg(`Save failed: ${e.message}`); } finally { setBusy(null); }
@@ -93,10 +111,13 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {
const importCfg = async (f: File) => {
setBusy("import"); setMsg(null);
+
try {
const parsed = JSON.parse(await f.text());
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not a config object");
+
+ if (!(parsed instanceof Object) || Array.isArray(parsed)) throw new Error("not a config object");
const r = await api("/thumbnail-config", { method: "PUT", body: JSON.stringify(parsed) });
+
if (r.error) throw new Error(r.error);
await load();
setMsg("Imported. New thumbnails use this template");
@@ -106,8 +127,10 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {
const reset = async () => {
if (!window.confirm("Reset to the generic default template? Your current settings will be removed.")) return;
setBusy("reset"); setMsg(null);
+
try {
const r = await api("/thumbnail-config/reset", { method: "POST", body: "{}" });
+
if (r.error) throw new Error(r.error);
await load();
setMsg("Reset to the generic default template");
@@ -116,24 +139,27 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {
const field = (f: Field) => {
const v = cfg[f.k];
+ const s = v === undefined ? "" : String(v);
+
if (f.t === "bool") return (
<label key={f.k} className="meta" style={{ display: "flex", alignItems: "center", gap: 8, paddingTop: 18 }}>
<input type="checkbox" checked={v !== false && v !== undefined ? !!v : false} onChange={(e) => set(f.k, e.target.checked)} /> {titleCase(f.k)}
</label>
);
+
return (
<div key={f.k} className={f.wide ? "full" : ""}>
<label style={labelStyle}>{titleCase(f.k)}</label>
{f.t === "color" ? (
<div className="thumb-swatch-row">
- {isHex(v) && <input type="color" value={v} onChange={(e) => set(f.k, e.target.value)} />}
- {!isHex(v) && <span style={{ width: 28, height: 28, borderRadius: 6, border: "1px solid var(--border)", background: v || "transparent", flexShrink: 0 }} />}
- <input type="text" value={v ?? ""} onChange={(e) => set(f.k, e.target.value)} style={{ flex: 1, minWidth: 0 }} />
+ {isHex(s) && <input type="color" value={s} onChange={(e) => set(f.k, e.target.value)} />}
+ {!isHex(s) && <span style={{ width: 28, height: 28, borderRadius: 6, border: "1px solid var(--border)", background: s || "transparent", flexShrink: 0 }} />}
+ <input type="text" value={s} onChange={(e) => set(f.k, e.target.value)} style={{ flex: 1, minWidth: 0 }} />
</div>
) : f.t === "select" ? (
- <select value={v ?? ""} onChange={(e) => set(f.k, e.target.value)}>{f.opts!.map((o) => <option key={o} value={o}>{o}</option>)}</select>
+ <select value={s} onChange={(e) => set(f.k, e.target.value)}>{f.opts!.map((o) => <option key={o} value={o}>{o}</option>)}</select>
) : (
- <input type={f.t === "num" ? "number" : "text"} value={v ?? ""} step="any"
+ <input type={f.t === "num" ? "number" : "text"} value={s} step="any"
onChange={(e) => set(f.k, f.t === "num" ? (e.target.value === "" ? "" : Number(e.target.value)) : e.target.value)}
style={{ width: "100%" }} />
)}
@@ -144,10 +170,10 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {
const others = Object.keys(cfg).filter((k) => !KNOWN.has(k) && !k.startsWith("_"));
// ── Live preview ──
- const bg = cfg.bg_color || "#0D0D0D";
- const accent = cfg.accent_color || "#35C7C6";
- const headline = cfg.line1_color || cfg.text_color || "#FFFFFF";
- const boxTop = isPct(cfg.box_y) ? cfg.box_y : "75%";
+ const bg = text("bg_color", "#0D0D0D");
+ const accent = text("accent_color", "#35C7C6");
+ const headline = text("line1_color", text("text_color", "#FFFFFF"));
+ const boxTop = isPct(cfg.box_y) ? text("box_y", "75%") : "75%";
return (
<div className="app">
@@ -160,17 +186,17 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {
<div className="tmpl-preview">
<label style={labelStyle}>Preview</label>
<div className="thumb-stage" style={{ background: bg, border: `${px(cfg.frame_border_width, SCALE, 3)}px solid ${accent}` }}>
- <div style={{ position: "absolute", inset: 0, background: `linear-gradient(to top, ${cfg.gradient_bottom_end_color || bg} 0%, transparent 50%)` }} />
+ <div style={{ position: "absolute", inset: 0, background: `linear-gradient(to top, ${text("gradient_bottom_end_color", bg)} 0%, transparent 50%)` }} />
<div style={{
position: "absolute", left: `${px(cfg.box_x, SCALE, 55)}px`, right: `${px(cfg.box_x, SCALE, 55)}px`, top: boxTop,
- background: cfg.box_fill_color || "rgba(13,13,13,0.85)",
+ background: text("box_fill_color", "rgba(13,13,13,0.85)"),
border: `${px(cfg.box_border_width, SCALE, 3)}px solid ${accent}`, padding: padToPreview(cfg.box_padding),
textAlign: "center",
}}>
<div style={{ fontSize: px(cfg.line1_font_size, SCALE, 74), fontWeight: Number(cfg.line1_font_weight) || 700, color: headline, textTransform: cfg.line1_uppercase !== false ? "uppercase" : "none", lineHeight: Number(cfg.line1_line_height) || 1.15, letterSpacing: px(cfg.line1_letter_spacing, SCALE, 2), marginBottom: px(cfg.line1_margin_bottom, SCALE, 10) }}>
Intelligence is now
</div>
- <span style={{ fontSize: px(cfg.line2_font_size, SCALE, 70), fontWeight: Number(cfg.line2_font_weight) || 600, fontStyle: (cfg.line2_font_style || "italic") === "italic" ? "italic" : "normal", background: accent, color: cfg.line2_text_color || "#0D0D0D", padding: padToPreview(cfg.line2_highlight_padding || "6px 20px"), textTransform: cfg.line2_uppercase !== false ? "uppercase" : "none", letterSpacing: px(cfg.line2_letter_spacing, SCALE, 1), display: "inline-block", lineHeight: Number(cfg.line2_line_height) || 1.15 }}>
+ <span style={{ fontSize: px(cfg.line2_font_size, SCALE, 70), fontWeight: Number(cfg.line2_font_weight) || 600, fontStyle: text("line2_font_style", "italic") === "italic" ? "italic" : "normal", background: accent, color: text("line2_text_color", "#0D0D0D"), padding: padToPreview(cfg.line2_highlight_padding || "6px 20px"), textTransform: cfg.line2_uppercase !== false ? "uppercase" : "none", letterSpacing: px(cfg.line2_letter_spacing, SCALE, 1), display: "inline-block", lineHeight: Number(cfg.line2_line_height) || 1.15 }}>
a commodity
</span>
</div>
@@ -195,7 +221,7 @@ export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {
{others.length > 0 && (
<div className="section">
<div className="section-label">Other</div>
- <div className="thumb-fields">{others.map((k) => field({ k, t: typeof cfg[k] === "number" ? "num" : "text" }))}</div>
+ <div className="thumb-fields">{others.map((k) => field({ k, t: Number.isFinite(cfg[k]) ? "num" : "text" }))}</div>
</div>
)}
</div>
diff --git a/src/ui/client/WorkspaceInsights.tsx b/src/ui/client/WorkspaceInsights.tsx
index b21583e..06f84c9 100644
--- a/src/ui/client/WorkspaceInsights.tsx
+++ b/src/ui/client/WorkspaceInsights.tsx
@@ -6,7 +6,7 @@ import { labelStyle } from "./lib";
* Workspace-wide performance and learned house style.
*
* Renders nothing at all when signed out. A free user sees the Analytics page
- * they have always seen — no locked panel, no upsell banner, no greyed-out
+ * they have always seen: no locked panel, no upsell banner, no greyed-out
* button. This section exists because the workspace data exists.
*/
@@ -47,7 +47,7 @@ export default function WorkspaceInsights() {
const hasModel = (insights.guidance?.length ?? 0) > 0;
const hasStyle = (preferences?.observations?.length ?? 0) > 0;
- // Signed in but nothing learned yet. Say why, and say what changes it —
+ // Signed in but nothing learned yet. Say why, and say what changes it:
// an empty panel with no explanation reads as broken.
if (!hasModel && !hasStyle) {
return (
diff --git a/src/ui/client/captionChunks.test.ts b/src/ui/client/captionChunks.test.ts
index da3d788..d173587 100644
--- a/src/ui/client/captionChunks.test.ts
+++ b/src/ui/client/captionChunks.test.ts
@@ -21,9 +21,9 @@ const words: PreviewWord[] = [
];
const asRendererWords = (ws: PreviewWord[]): Word[] =>
- ws.map((w) => ({ word: w.text, start: w.start, end: w.end, speaker: w.speaker ?? null })) as Word[];
+ ws.map((w): Word => ({ word: w.text, start: w.start, end: w.end, speaker: w.speaker ?? undefined }));
-const shapes = (chunks: { words: { text?: string; word?: string }[] }[]) =>
+const captionTexts = (chunks: { words: { text?: string; word?: string }[] }[]) =>
chunks.map((c) => c.words.map((w) => w.text ?? w.word));
describe("buildPreviewChunks", () => {
@@ -37,6 +37,7 @@ describe("buildPreviewChunks", () => {
{ wordsPerChunk: 6, absorbTail: 2 },
]) {
const preview = buildPreviewChunks(words, cfg, 6);
+
const rendered = buildChunks(asRendererWords(words), {
perChunk: cfg.wordsPerChunk,
maxChars: cfg.maxCharsPerChunk,
@@ -44,14 +45,15 @@ describe("buildPreviewChunks", () => {
splitTail: cfg.splitTail,
clipEnd: 6,
});
- expect(shapes(preview)).toEqual(shapes(rendered));
+
+ expect(captionTexts(preview)).toEqual(captionTexts(rendered));
expect(preview.map((c) => c.displayEnd)).toEqual(rendered.map((c) => c.displayEnd));
}
});
it("breaks on terminal punctuation, speaker change and long gaps", () => {
const chunks = buildPreviewChunks(words, { wordsPerChunk: 6, absorbTail: 2 });
- expect(shapes(chunks)).toEqual([
+ expect(captionTexts(chunks)).toEqual([
["the", "secret", "to", "growth."],
["is", "boring", "work"],
["really?"],
@@ -80,10 +82,12 @@ describe("buildPreviewChunks", () => {
end: index * 0.5 + 0.4,
speaker: "A",
}));
+
const source = selectPreviewWords(transcript, {
start_second: 0,
end_second: 60,
});
+
const chunks = buildPreviewChunks(source, { wordsPerChunk: 5, absorbTail: 1 }, 60);
expect(source).toHaveLength(120);
diff --git a/src/ui/client/captionChunks.ts b/src/ui/client/captionChunks.ts
index 9179c6c..9f4e16b 100644
--- a/src/ui/client/captionChunks.ts
+++ b/src/ui/client/captionChunks.ts
@@ -75,6 +75,7 @@ function hasBreakBetween(words: PreviewWord[], from: number, to: number): boolea
for (let i = from; i < to; i++) {
if (breaksAfter(words[i], words[i + 1])) return true;
}
+
return false;
}
@@ -92,11 +93,14 @@ export function buildPreviewChunks(
while (end < words.length && end - i < cfg.wordsPerChunk) {
if (breaksAfter(words[end - 1], words[end])) break;
+
if (cfg.maxCharsPerChunk != null) {
const nextChars = charCount + 1 + words[end].text.trim().length;
+
if (nextChars > cfg.maxCharsPerChunk) break;
charCount = nextChars;
}
+
end += 1;
}
@@ -108,6 +112,7 @@ export function buildPreviewChunks(
) {
end = words.length;
}
+
if (cfg.splitTail && words.length - end === 1 && end - i > 2) {
end -= 1;
}
@@ -120,9 +125,11 @@ export function buildPreviewChunks(
for (let k = 0; k < chunks.length; k++) {
const next = chunks[k + 1];
+
const hold = next
? Math.min(next.start, chunks[k].end + GAP_FILL_MAX_SECONDS)
: chunks[k].end + LAST_CHUNK_HOLD_SECONDS;
+
const capped = clipEnd != null ? Math.min(hold, clipEnd) : hold;
chunks[k].displayEnd = Math.max(chunks[k].end, capped);
}
@@ -140,6 +147,7 @@ export function activePreviewChunk(
while (low <= high) {
const middle = Math.floor((low + high) / 2);
const chunk = chunks[middle];
+
if (time < chunk.start) {
high = middle - 1;
} else if (time >= chunk.displayEnd) {
diff --git a/src/ui/client/lib.test.ts b/src/ui/client/lib.test.ts
index 657716b..e5a71ad 100644
--- a/src/ui/client/lib.test.ts
+++ b/src/ui/client/lib.test.ts
@@ -54,6 +54,7 @@ describe("findClipResult", () => {
const results = [
{ status: "success", output_path: "/out/third.mp4", source_start_second: 640, source_end_second: 700 },
];
+
expect(findClipResult(results, clips[0], 0)).toBeUndefined();
expect(findClipResult(results, clips[1], 1)).toBeUndefined();
expect(findClipResult(results, clips[2], 2)?.output_path).toBe("/out/third.mp4");
@@ -65,6 +66,7 @@ describe("findClipResult", () => {
undefined,
{ status: "success", output_path: "/out/b.mp4", source_start_second: 120, source_end_second: 165 },
];
+
expect(findClipResult(results, clips[0], 0)).toBeUndefined();
expect(findClipResult(results, clips[1], 1)?.output_path).toBe("/out/b.mp4");
});
@@ -78,6 +80,7 @@ describe("findClipResult", () => {
const results = [
{ status: "success", output_path: "/out/a.mp4", source_start_second: 10.001, source_end_second: 40 },
];
+
expect(findClipResult(results, clips[0], 0)?.output_path).toBe("/out/a.mp4");
});
});
@@ -120,6 +123,7 @@ describe("buildEnergyMap", () => {
{ start_second: 10, end_second: 40 },
{ start_second: 120, end_second: 165 },
];
+
const map = buildEnergyMap([9, 3], legacy);
expect(map[clipKey(legacy[0])].score).toBe(9);
expect(map[clipKey(legacy[1])].score).toBe(3);
@@ -176,6 +180,7 @@ describe("formatTranscriptText", () => {
{ start: 2, end: 4, text: "Today we discuss relationships." },
],
};
+
expect(formatTranscriptText(transcript)).toBe(
"Welcome to the show. Today we discuss relationships.",
);
@@ -188,6 +193,7 @@ describe("formatTranscriptText", () => {
{ start: 8, end: 12, text: "Relationships matter.", speaker: "SPEAKER_01" },
],
};
+
expect(formatTranscriptText(transcript)).toBe(
"Speaker 1\nWhy did you start?\n\nSpeaker 2\nRelationships matter.",
);
@@ -197,6 +203,7 @@ describe("formatTranscriptText", () => {
const transcript = {
segments: [{ start: 0, end: 2, text: "Welcome back.", speaker: "Speaker 1" }],
};
+
expect(formatTranscriptText(transcript)).toBe("Speaker 1\nWelcome back.");
});
@@ -204,6 +211,7 @@ describe("formatTranscriptText", () => {
const transcript = {
segments: [{ start: 65.2, end: 70, text: "A useful answer." }],
};
+
expect(formatTranscriptText(transcript, "timestamped")).toBe(
"[1:05]\nA useful answer.",
);
diff --git a/src/ui/client/lib.ts b/src/ui/client/lib.ts
index 21e7a5c..f594cd1 100644
--- a/src/ui/client/lib.ts
+++ b/src/ui/client/lib.ts
@@ -9,6 +9,7 @@ export const fmt = (s: number) => {
const seconds = Math.floor(t % 60);
const mm = String(minutes).padStart(2, "0");
const ss = String(seconds).padStart(2, "0");
+
return hours > 0 ? `${hours}:${mm}:${ss}` : `${minutes}:${ss}`;
};
@@ -17,6 +18,7 @@ export function describePeople(people: ThumbnailPerson[]): string {
return people
.map((p) => {
const who = p.role ?? `${p.side} person`;
+
return p.source_time == null ? who : `${who} at ${fmt(p.source_time)}`;
})
.join(", ");
@@ -50,19 +52,23 @@ const CASELESS_SCRIPT_RANGES: Array<[number, number]> = [
function isCaselessScriptChar(ch: string): boolean {
const cp = ch.codePointAt(0) ?? 0;
+
return CASELESS_SCRIPT_RANGES.some(([lo, hi]) => cp >= lo && cp <= hi);
}
export function safeUpper(text: string): string {
if (!text) return text;
let hasCaseless = false;
+
for (const ch of text) {
if (isCaselessScriptChar(ch)) {
hasCaseless = true;
break;
}
}
+
if (!hasCaseless) return text.toUpperCase();
+
return Array.from(text)
.map((ch) => (isCaselessScriptChar(ch) ? ch : ch.toUpperCase()))
.join("");
@@ -82,27 +88,33 @@ async function request<T>(path: string, opts: RequestInit, jsonHeaders: boolean)
const res = await fetch(`/api${path}`, {
...opts,
headers: jsonHeaders
- ? { "Content-Type": "application/json", ...(opts.headers || {}) }
+ ? { "Content-Type": "application/json", ...opts.headers }
: opts.headers,
});
const text = await res.text();
- let body: any = undefined;
+ let body: unknown;
+ let plainText: string | undefined;
+
if (text) {
try {
body = JSON.parse(text);
} catch {
+ plainText = text;
body = text;
}
}
- if (!res.ok || (body && typeof body === "object" && body.error)) {
- const msg =
- (typeof body === "string" && body) ||
- (body && (body.error || body.message)) ||
- `HTTP ${res.status}`;
+ const errorField = body instanceof Object && "error" in body ? body.error : undefined;
+ const messageField = body instanceof Object && "message" in body ? body.message : undefined;
+
+ if (!res.ok || errorField) {
+ const msg = plainText || errorField || messageField || `HTTP ${res.status}`;
+
throw new ApiError(String(msg), res.status);
}
+
+ // SAFETY: each caller names T as the JSON its /api route returns.
return body as T;
}
@@ -119,8 +131,11 @@ export function upload<T = any>(path: string, form: FormData): Promise<T> {
export function timeAgo(iso: string): string {
const ms = Date.now() - new Date(iso).getTime();
const h = ms / 3_600_000;
+
if (h < 1) return `${Math.max(1, Math.round(h * 60))}m ago`;
+
if (h < 24) return `${Math.round(h)}h ago`;
+
return new Date(iso).toLocaleDateString();
}
@@ -143,6 +158,7 @@ export function resolveAssetName(
type?: string,
): string | null {
if (!reference) return null;
+
return assets.find(
(asset) =>
(!type || asset.type === type) &&
@@ -165,39 +181,51 @@ interface TranscriptLike {
export type TranscriptFormat = "readable" | "timestamped";
+function isFiniteSecond(value: number | undefined): value is number {
+ return Number.isFinite(value);
+}
+
interface TranscriptParagraph {
start: number;
speaker: string | null;
text: string;
}
-const cleanTranscriptText = (value: unknown): string =>
- typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
+const cleanTranscriptText = (value: string | null | undefined): string =>
+ value ? value.replace(/\s+/g, " ").trim() : "";
const endsSentence = (value: string): boolean => /[.!?…][\]})"']?$/.test(value);
function friendlySpeaker(value: string | null | undefined): string | null {
const speaker = cleanTranscriptText(value);
+
if (!speaker) return null;
const machineLabel = speaker.match(/^speaker[_-]+0*(\d+)$/i);
+
if (machineLabel) return `Speaker ${Number(machineLabel[1]) + 1}`;
+
return speaker.replace(/_/g, " ");
}
function paragraphsFromPlainText(value: string): TranscriptParagraph[] {
const text = cleanTranscriptText(value);
+
if (!text) return [];
const sentences = text.split(/(?<=[.!?…])\s+/).filter(Boolean);
const paragraphs: TranscriptParagraph[] = [];
let buffer = "";
+
for (const sentence of sentences) {
buffer = buffer ? `${buffer} ${sentence}` : sentence;
+
if (buffer.length >= 420 || sentences.length === 1) {
paragraphs.push({ start: 0, speaker: null, text: buffer });
buffer = "";
}
}
+
if (buffer) paragraphs.push({ start: 0, speaker: null, text: buffer });
+
return paragraphs;
}
@@ -205,6 +233,7 @@ function transcriptParagraphs(transcript: TranscriptLike | null | undefined): Tr
const segments = Array.isArray(transcript?.segments)
? transcript.segments.filter((segment) => cleanTranscriptText(segment?.text))
: [];
+
if (!segments.length) {
return paragraphsFromPlainText(transcript?.transcript || transcript?.text || "");
}
@@ -212,6 +241,7 @@ function transcriptParagraphs(transcript: TranscriptLike | null | undefined): Tr
const paragraphs: TranscriptParagraph[] = [];
let current: TranscriptParagraph | null = null;
let previousEnd: number | null = null;
+
const flush = () => {
if (current?.text) paragraphs.push(current);
current = null;
@@ -219,15 +249,15 @@ function transcriptParagraphs(transcript: TranscriptLike | null | undefined): Tr
for (const segment of segments) {
const text = cleanTranscriptText(segment.text);
- const segmentStart: number = typeof segment.start === "number" && Number.isFinite(segment.start)
- ? segment.start
- : previousEnd ?? 0;
- const segmentEnd: number = typeof segment.end === "number" && Number.isFinite(segment.end)
- ? segment.end
- : segmentStart;
+
+ const segmentStart: number = isFiniteSecond(segment.start) ? segment.start : previousEnd ?? 0;
+
+ const segmentEnd: number = isFiniteSecond(segment.end) ? segment.end : segmentStart;
+
const speaker = friendlySpeaker(segment.speaker);
const speakerChanged = current !== null && current.speaker !== speaker;
const longPause = current !== null && previousEnd !== null && segmentStart - previousEnd >= 2.5;
+
if (speakerChanged || longPause) flush();
if (!current) current = { start: segmentStart, speaker, text };
@@ -238,7 +268,9 @@ function transcriptParagraphs(transcript: TranscriptLike | null | undefined): Tr
flush();
}
}
+
flush();
+
return paragraphs;
}
@@ -252,6 +284,7 @@ export function formatTranscriptText(
const heading = format === "timestamped"
? `[${fmt(paragraph.start)}]${paragraph.speaker ? ` ${paragraph.speaker}` : ""}`
: paragraph.speaker;
+
return heading ? `${heading}\n${paragraph.text}` : paragraph.text;
})
.join("\n\n");
@@ -262,7 +295,7 @@ export function formatTranscriptText(
// every row with the bounds of the clip it rendered; match a result to a clip on
// those instead of on position.
export const clipBoundsKey = (start?: number, end?: number): string | null =>
- typeof start === "number" && typeof end === "number"
+ start !== undefined && end !== undefined
? `${start.toFixed(2)}:${end.toFixed(2)}`
: null;
@@ -270,9 +303,10 @@ export const resultBoundsKey = (row?: ClipResultRow | null): string | null =>
row ? clipBoundsKey(row.source_start_second, row.source_end_second) : null;
interface ClipResultRow {
+ status?: string;
+ output_path?: string;
source_start_second?: number;
source_end_second?: number;
- [key: string]: unknown;
}
interface ClipIdentity {
@@ -289,37 +323,44 @@ export const clipKey = (clip: ClipIdentity): string =>
clip.clip_id || clipBoundsKey(clip.start_second, clip.end_second) || "";
type EnergyLevel = "high" | "medium" | "low";
+
interface EnergyEntry {
score: number;
level: EnergyLevel;
}
+interface EnergyMap {
+ [clipKey: string]: EnergyEntry;
+}
+
const energyLevel = (score: number): EnergyLevel =>
score >= 7 ? "high" : score >= 4 ? "medium" : "low";
/** Maps the backend's positional segment scores onto the clips they were measured for. */
export function buildEnergyMap(
- scores: unknown[],
+ scores: ReadonlyArray<number | null | undefined>,
clips: ClipIdentity[],
-): Record<string, EnergyEntry> {
- const map: Record<string, EnergyEntry> = {};
+): EnergyMap {
+ const map: EnergyMap = {};
scores.forEach((score, i) => {
const clip = clips[i];
- if (!clip || typeof score !== "number") return;
+
+ if (!clip || score === null || score === undefined) return;
const key = clipKey(clip);
+
if (key) map[key] = { score, level: energyLevel(score) };
});
+
return map;
}
-export function dropEnergy(
- map: Record<string, EnergyEntry>,
- clip: ClipIdentity,
-): Record<string, EnergyEntry> {
+export function dropEnergy(map: EnergyMap, clip: ClipIdentity): EnergyMap {
const key = clipKey(clip);
+
if (!key || !(key in map)) return map;
const next = { ...map };
delete next[key];
+
return next;
}
@@ -338,11 +379,15 @@ export function findClipResult<T extends ClipResultRow>(
positionalIdx: number,
): T | undefined {
const key = clipBoundsKey(clip.start_second, clip.end_second);
+
if (key) {
const keyed = results.find((row) => resultBoundsKey(row) === key);
+
if (keyed) return keyed;
}
+
const row = results[positionalIdx];
+
return row && !resultBoundsKey(row) ? row : undefined;
}
@@ -356,12 +401,12 @@ export function findClipResult<T extends ClipResultRow>(
* clears the transcript server-side as if it were stale. One request can't
* race with itself.
*/
-export function buildUiStateSyncPayload(
- syncable: Record<string, unknown>,
+export function buildUiStateSyncPayload<S extends object, X>(
+ syncable: S,
filePath: string,
- transcript: unknown,
+ transcript: X,
transcriptChanged: boolean,
-): Record<string, unknown> {
+): { _source: "ui"; filePath: string } & S & { transcript?: X } {
return {
_source: "ui",
filePath,
diff --git a/src/ui/client/multicam-auto-cut.tsx b/src/ui/client/multicam-auto-cut.tsx
index 47fa876..0c0e249 100644
--- a/src/ui/client/multicam-auto-cut.tsx
+++ b/src/ui/client/multicam-auto-cut.tsx
@@ -1,6 +1,7 @@
import React, { useState } from "react";
import { fmt } from "./lib";
-import type { McCutSettings, McSession, McStyle } from "./multicam-types";
+import type { McCutSettings, McCutSettingChanges, McEditBody, McSession } from "./multicam-types";
+import { mcStyle } from "./multicam-types";
// Mirrors the clamps in multicam.update_mapping so the inputs never show a value the server won't use.
const LIMITS = {
@@ -19,7 +20,7 @@ export default function MulticamAutoCut({
}: {
session: McSession;
locked: boolean;
- onRecut: (extra: Record<string, unknown>) => void;
+ onRecut: (extra: McEditBody) => void;
}) {
const [open, setOpen] = useState(false);
const [range, setRange] = useState({ range_start: session.range_start ?? 0, range_end: session.range_end ?? session.timeline_duration });
@@ -54,7 +55,7 @@ export default function MulticamAutoCut({
Style
<select
value={settings.style}
- onChange={(e) => setSettings({ ...settings, style: e.target.value as McStyle })}
+ onChange={(e) => setSettings({ ...settings, style: mcStyle(e.target.value) ?? settings.style })}
style={{ width: "auto", padding: "4px 28px 4px 10px", fontSize: 12 }}
>
<option value="auto">Automatic ({session.auto_style === "remote" ? "remote call" : "studio"})</option>
@@ -77,11 +78,14 @@ export default function MulticamAutoCut({
disabled={locked}
onClick={() => {
// Only what was changed is sent: anything else follows the style's own defaults.
- const changed = Object.fromEntries(
- Object.entries(settings).filter(([k, v]) => v !== session.cut_settings[k as keyof McCutSettings]),
+ const current = new Map<string, McCutSettings[keyof McCutSettings]>(Object.entries(session.cut_settings));
+
+ const changed: McCutSettingChanges = Object.fromEntries(
+ Object.entries(settings).filter(([k, v]) => v !== current.get(k)),
);
+
const rangeChanged = range.range_start !== (session.range_start ?? 0) || range.range_end !== (session.range_end ?? session.timeline_duration);
- onRecut({ ...(rangeChanged ? range : {}), cut_settings: changed });
+ onRecut({ ...(rangeChanged && range), cut_settings: changed });
}}
>
Cut again
diff --git a/src/ui/client/multicam-deliver.tsx b/src/ui/client/multicam-deliver.tsx
index e8d7c2c..cb4ddec 100644
--- a/src/ui/client/multicam-deliver.tsx
+++ b/src/ui/client/multicam-deliver.tsx
@@ -18,6 +18,7 @@ export function DeliverActions({
onExport: (format: "premiere" | "fcpxml") => void;
}) {
const why = exportable ? undefined : "Editor timelines can't carry call layouts yet. Render the MP4 instead.";
+
return (
<>
<button className="btn btn-ghost btn-sm" disabled={locked || !exportable} title={why} onClick={() => onExport("premiere")}>Export for Premiere</button>
@@ -37,12 +38,14 @@ export default function MulticamResults({
onMakeClips: () => void;
}) {
const { video, stems = [], premiere, fcpxml, duration } = session.outputs;
+
const downloads = [
...(video ? [{ path: video, label: basename(video) }] : []),
...stems.map((path) => ({ path, label: basename(path) })),
...(premiere ? [{ path: premiere, label: "Premiere XML" }] : []),
...(fcpxml ? [{ path: fcpxml, label: "Final Cut XML" }] : []),
];
+
if (!downloads.length) return null;
return (
diff --git a/src/ui/client/multicam-page.tsx b/src/ui/client/multicam-page.tsx
index d38a4c7..b4cb4d3 100644
--- a/src/ui/client/multicam-page.tsx
+++ b/src/ui/client/multicam-page.tsx
@@ -10,7 +10,7 @@ import MulticamSync from "./multicam-sync";
import MulticamSummary from "./multicam-summary";
import MulticamResults, { DeliverActions } from "./multicam-deliver";
import MulticamCloud from "./multicam-cloud";
-import type { McJobKind, McPreviewsResp, McSession, McSessionSummary } from "./multicam-types";
+import type { McEditBody, McJobKind, McPreviewsResp, McRequestBody, McSession, McSessionSummary } from "./multicam-types";
const JOB_LABEL: Record<McJobKind, string> = {
sync: "Syncing",
@@ -21,8 +21,8 @@ const JOB_LABEL: Record<McJobKind, string> = {
pull: "Rendering the cloud edit",
};
-const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
-const post = <T,>(body: Record<string, unknown>) => api<T>("/multicam", { method: "POST", body: JSON.stringify(body) });
+const errorText = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));
+const post = <T,>(body: McRequestBody) => api<T>("/multicam", { method: "POST", body: JSON.stringify(body) });
export default function MulticamPage() {
const navigate = useNavigate();
@@ -35,20 +35,22 @@ export default function MulticamPage() {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [job, setJob] = useState<{ id: string; kind: McJobKind } | null>(null);
- const jobState = useJob(job?.id ?? null);
+ const jobState = useJob<McSession>(job?.id ?? null);
const [peopleDraft, setPeopleDraft] = useState<string[]>(["Host", "Guest"]);
const [sourcesOpen, setSourcesOpen] = useState(false);
// A running job owns the session until it finishes, so edits can't race it and get overwritten.
const locked = busy || job !== null;
- async function call<T = McSession>(body: Record<string, unknown>): Promise<T | null> {
+ async function call<T = McSession>(body: McRequestBody): Promise<T | null> {
setBusy(true);
setError(null);
+
try {
return await post<T>(body);
} catch (e) {
setError(errorText(e));
+
return null;
} finally {
setBusy(false);
@@ -58,17 +60,18 @@ export default function MulticamPage() {
function adopt(next: McSession | null) {
if (!next) return;
setSession(next);
+
if (next.active_job) setJob({ id: next.active_job.id, kind: next.active_job.action });
}
- const mutate = (body: Record<string, unknown>) =>
- session && call({ ...body, session_id: session.session_id }).then(adopt);
+ const mutate = (body: McEditBody) =>
+ session && call({ action: "map", ...body, session_id: session.session_id }).then(adopt);
function refreshList() {
post<{ sessions: McSessionSummary[] }>({ action: "list" }).then((r) => setSessions(r.sessions)).catch(() => {});
}
- function startJob(kind: McJobKind, extra: Record<string, unknown> = {}, sessionId = session?.session_id) {
+ function startJob(kind: McJobKind, extra: McEditBody = {}, sessionId = session?.session_id) {
if (!sessionId) return;
call<{ job_id: string }>({ action: kind, session_id: sessionId, ...extra }).then((r) => {
if (r) setJob({ id: r.job_id, kind });
@@ -80,11 +83,14 @@ export default function MulticamPage() {
useEffect(() => {
setStills({});
setSourcesOpen(false);
+
if (!openId) {
setSession(null);
setJob(null);
+
return;
}
+
if (session?.session_id !== openId) call({ action: "show", session_id: openId }).then(adopt);
}, [openId]);
@@ -99,32 +105,41 @@ export default function MulticamPage() {
useEffect(() => {
if (!job || !jobState) return;
+
if (jobState.status === "error") {
setError(jobState.error || `${JOB_LABEL[job.kind]} failed. Check the files and try again.`);
setJob(null);
+
return;
}
+
if (jobState.status !== "done") return;
- const result = jobState.result as unknown as McSession;
+ const result = jobState.result;
+
+ if (!result) return;
setJob(null);
setSession(result);
refreshList();
// A clean sync goes straight to cutting: that's the step everyone takes next.
const allSynced = result.sources.every((s) => s.role === "ignore" || s.offset !== null);
+
if (job.kind === "sync" && allSynced) startJob("plan", {}, result.session_id);
}, [jobState?.status]);
- async function startSession(seed: Record<string, unknown>): Promise<boolean> {
+ async function startSession(seed: { folder?: string; files?: string[] }): Promise<boolean> {
const r = await call({ action: "new", ...seed, people: peopleDraft.filter((n) => n.trim()) });
+
if (!r) return false;
adopt(r);
setSearchParams({ session: r.session_id });
refreshList();
+
return true;
}
async function deleteSession(id: string) {
if (!window.confirm("Delete this multicam edit? Your recordings stay where they are.")) return;
+
if (await call({ action: "delete", session_id: id })) {
if (session?.session_id === id) setSearchParams({});
refreshList();
@@ -138,7 +153,9 @@ export default function MulticamPage() {
async function onMakeClips() {
const video = session?.outputs.video;
+
if (!video) return;
+
try {
await api("/ui-state", {
method: "POST",
@@ -168,6 +185,7 @@ export default function MulticamPage() {
jobState?.progress ? ` (${Math.round(jobState.progress)}%)` : ""
}`
: null;
+
const synced = !!session?.sources.some((s) => s.sync?.status);
const unsynced = session?.sources.filter((s) => s.role !== "ignore" && s.offset === null) || [];
const showSources = !session || !cutReady || sourcesOpen || unsynced.length > 0;
@@ -186,6 +204,7 @@ export default function MulticamPage() {
locked={locked}
exportable={!session.cuts.some((c) => {
const cam = session.sources.find((s) => s.id === c.source_id);
+
return !!cam && (!!cam.parent || cam.members.length > 0);
})}
onRender={() => startJob("render", { stems: true })}
diff --git a/src/ui/client/multicam-sources.tsx b/src/ui/client/multicam-sources.tsx
index 3463f04..8865698 100644
--- a/src/ui/client/multicam-sources.tsx
+++ b/src/ui/client/multicam-sources.tsx
@@ -3,6 +3,7 @@ import { fmt, basename } from "./lib";
import { AudioIcon } from "./icons";
import PersonChip from "./multicam-person-chip";
import type { McEdit, McPerson, McRole, McSession, McSource } from "./multicam-types";
+import { mcRole } from "./multicam-types";
import { mcImageUrl } from "./multicam-types";
const selectStyle = { width: "auto" } as const;
@@ -27,6 +28,7 @@ export default function MulticamSources({
function commitName(person: McPerson) {
const draft = nameDraft[person.id]?.trim();
+
if (!draft || draft === person.name) return;
savePeople(session.people.map((p) => (p.id === person.id ? { ...p, name: draft } : p)));
}
@@ -95,11 +97,13 @@ function SourceRow({
disabled: boolean;
}) {
const split = source.channel_people.length > 0;
+
const details = [
fmt(source.duration),
source.kind === "video" ? `${source.width}x${source.height}` : "Audio",
source.has_audio ? `${source.audio_channels}ch audio` : "No audio",
];
+
const personOptions = people.map((p) => <option key={p.id} value={p.id}>{p.name}</option>);
return (
@@ -127,7 +131,7 @@ function SourceRow({
{source.guessed && source.role !== "ignore" && <span className="pill pill-amber">Guessed</span>}
<div style={{ display: "flex", alignItems: "center", gap: 10, marginLeft: "auto", flexWrap: "wrap", justifyContent: "flex-end" }}>
- <select value={source.role} disabled={disabled} style={selectStyle} onChange={(e) => onEdit({ role: e.target.value as McRole })}>
+ <select value={source.role} disabled={disabled} style={selectStyle} onChange={(e) => onEdit({ role: mcRole(e.target.value) })}>
<option value="camera" disabled={source.kind === "audio"}>Camera</option>
<option value="mic" disabled={!source.has_audio}>Mic</option>
<option value="ignore">Ignore</option>
diff --git a/src/ui/client/multicam-start.tsx b/src/ui/client/multicam-start.tsx
index 3a00809..3ebc29f 100644
--- a/src/ui/client/multicam-start.tsx
+++ b/src/ui/client/multicam-start.tsx
@@ -26,9 +26,11 @@ export default function MulticamStart({
async function browse(query: string, seed: (d: { folder?: string; file_paths?: string[] }) => { folder?: string; files?: string[] } | null) {
setBrowsing(true);
+
try {
const d = await api<{ folder?: string; file_paths?: string[] }>(`/browse-file?${query}`);
const picked = seed(d);
+
if (picked) await onStart(picked);
} catch {
/* dialog cancelled */
@@ -39,6 +41,7 @@ export default function MulticamStart({
async function commitPath() {
const folder = pathDraft.trim();
+
if (folder && (await onStart({ folder }))) setPathDraft("");
}
diff --git a/src/ui/client/multicam-summary.tsx b/src/ui/client/multicam-summary.tsx
index cf1715f..b8cc632 100644
--- a/src/ui/client/multicam-summary.tsx
+++ b/src/ui/client/multicam-summary.tsx
@@ -1,7 +1,7 @@
import React from "react";
import { fmt } from "./lib";
import MulticamAutoCut from "./multicam-auto-cut";
-import type { McEdit, McSession } from "./multicam-types";
+import type { McEdit, McEditBody, McSession } from "./multicam-types";
import { cameraColorMap, whoLabel } from "./multicam-types";
export default function MulticamSummary({
@@ -13,7 +13,7 @@ export default function MulticamSummary({
session: McSession;
locked: boolean;
onEdit: McEdit;
- onRecut: (extra: Record<string, unknown>) => void;
+ onRecut: (extra: McEditBody) => void;
}) {
const cameras = session.sources.filter((s) => s.role === "camera" && s.offset !== null);
const colors = cameraColorMap(cameras.map((c) => c.id));
diff --git a/src/ui/client/multicam-sync.tsx b/src/ui/client/multicam-sync.tsx
index 73db9b3..299ab70 100644
--- a/src/ui/client/multicam-sync.tsx
+++ b/src/ui/client/multicam-sync.tsx
@@ -1,16 +1,23 @@
import React, { useState } from "react";
import { basename } from "./lib";
-import type { McEdit, McPerson, McSession, McSource } from "./multicam-types";
+import type { McEdit, McPerson, McSession, McSource, McSourceEdit } from "./multicam-types";
import { whoLabel } from "./multicam-types";
-const STATUS: Record<string, { label: string; color: string; pill: string }> = {
- reference: { label: "Reference", color: "var(--green)", pill: "pill-green" },
- ok: { label: "Synced", color: "var(--green)", pill: "pill-green" },
- review: { label: "Check sync", color: "var(--amber)", pill: "pill-amber" },
- rough: { label: "Rough sync", color: "var(--amber)", pill: "pill-amber" },
- manual: { label: "Set by hand", color: "var(--blue)", pill: "pill-sky" },
- assumed: { label: "Starts with the others", color: "var(--amber)", pill: "pill-amber" },
-};
+interface SyncStatusStyle {
+ label: string;
+ color: string;
+ pill: string;
+}
+
+const STATUS = new Map<string, SyncStatusStyle>([
+ ["reference", { label: "Reference", color: "var(--green)", pill: "pill-green" }],
+ ["ok", { label: "Synced", color: "var(--green)", pill: "pill-green" }],
+ ["review", { label: "Check sync", color: "var(--amber)", pill: "pill-amber" }],
+ ["rough", { label: "Rough sync", color: "var(--amber)", pill: "pill-amber" }],
+ ["manual", { label: "Set by hand", color: "var(--blue)", pill: "pill-sky" }],
+ ["assumed", { label: "Starts with the others", color: "var(--amber)", pill: "pill-amber" }],
+]);
+
const NOT_SYNCED = { label: "Not synced", color: "var(--red)", pill: "pill-red" };
export default function MulticamSync({
@@ -37,6 +44,7 @@ export default function MulticamSync({
{active.map((source, i) => {
const start = source.timeline_start ?? 0;
const end = source.timeline_end ?? start;
+
return (
<div
key={source.id}
@@ -44,7 +52,7 @@ export default function MulticamSync({
style={{
position: "absolute", top: i * 34 + 4, left: `${(start / duration) * 100}%`,
width: `${Math.max(0.5, ((end - start) / duration) * 100)}%`, height: 24,
- background: (STATUS[source.sync.status || ""] || NOT_SYNCED).color, opacity: 0.85, borderRadius: 4,
+ background: (STATUS.get(source.sync.status || "") || NOT_SYNCED).color, opacity: 0.85, borderRadius: 4,
display: "flex", alignItems: "center", padding: "0 8px", fontSize: 11, color: "var(--bg)",
fontWeight: 600, overflow: "hidden", whiteSpace: "nowrap",
}}
@@ -71,14 +79,15 @@ export default function MulticamSync({
}
function SyncRow({ source, people, onEdit, disabled }: { source: McSource; people: McPerson[]; onEdit: McEdit; disabled: boolean }) {
- const status = STATUS[source.sync.status || ""] || NOT_SYNCED;
+ const status = STATUS.get(source.sync.status || "") || NOT_SYNCED;
const [draft, setDraft] = useState("");
const frame = 1 / (source.fps || 30);
const drift = source.sync.drift_ppm;
- const edit = (change: Record<string, number>) => onEdit({ action: "map", sources: [{ id: source.id, ...change }] });
+ const edit = (change: McSourceEdit) => onEdit({ action: "map", sources: [{ id: source.id, ...change }] });
function saveOffset() {
const offset = Number(draft);
+
if (draft.trim() === "" || !Number.isFinite(offset)) return;
edit({ offset });
setDraft("");
@@ -94,7 +103,7 @@ function SyncRow({ source, people, onEdit, disabled }: { source: McSource; peopl
</div>
<span className={`pill ${status.pill}`}>{status.label}</span>
- {typeof drift === "number" && Math.abs(drift) >= 5 && (
+ {drift !== undefined && Math.abs(drift) >= 5 && (
<span className="hint">Clock drift {Math.round(drift)} ppm, corrected</span>
)}
{source.offset === null && (
diff --git a/src/ui/client/multicam-types.ts b/src/ui/client/multicam-types.ts
index cdc3384..e4899fc 100644
--- a/src/ui/client/multicam-types.ts
+++ b/src/ui/client/multicam-types.ts
@@ -9,6 +9,12 @@ export interface McPerson {
}
export type McRole = "camera" | "mic" | "ignore";
+
+const MC_ROLES: readonly McRole[] = ["camera", "mic", "ignore"];
+
+/** The role named by a <select> value, or undefined for a value that is not a role. */
+export const mcRole = (value: string): McRole | undefined => MC_ROLES.find((role) => role === value);
+
export type McSyncStatus = "reference" | "ok" | "review" | "rough" | "failed" | "manual" | "assumed";
export interface McSourceSync {
@@ -61,6 +67,11 @@ export interface McCut {
export type McStyle = "auto" | "studio" | "remote";
+const MC_STYLES: readonly McStyle[] = ["auto", "studio", "remote"];
+
+/** The style named by a <select> value, or undefined for a value that is not a style. */
+export const mcStyle = (value: string): McStyle | undefined => MC_STYLES.find((style) => style === value);
+
export interface McCutSettings {
style: McStyle;
min_shot: number;
@@ -156,20 +167,59 @@ export const personName = (people: McPerson[], id: string): string =>
/** Who a file shows or records, in the words the UI uses everywhere. */
export function whoLabel(people: McPerson[], source: McSource): string {
if (source.role === "camera") return source.person === "wide" ? "Everyone (wide)" : personName(people, source.person);
+
if (source.channel_people.length) return source.channel_people.map((id) => personName(people, id) || "Nobody").join(" / ");
+
return source.person ? personName(people, source.person) : "Shared room mic";
}
-export type McEdit = (body: Record<string, unknown>) => void;
+export interface McSourceEdit {
+ role?: McRole;
+ person?: string;
+ channel_people?: string[];
+ offset?: number;
+ nudge?: number;
+}
+
+/** Cut settings that differ from the session's, keyed by setting name. */
+export type McCutSettingChanges = Record<string, string | number | boolean>;
+
+/** Fields an edit can set on a multicam session (the body of POST /api/multicam, minus routing). */
+export interface McEditBody {
+ action?: string;
+ sources?: Array<{ id: string } & McSourceEdit>;
+ people?: McPerson[];
+ look?: string;
+ format?: string;
+ stems?: boolean;
+ range_start?: number;
+ range_end?: number;
+ cut_settings?: McCutSettingChanges;
+}
+
+export interface McRequestBody extends Omit<McEditBody, "people"> {
+ action: string;
+ session_id?: string;
+ folder?: string;
+ files?: string[];
+ people?: McPerson[] | string[];
+}
+
+export type McEdit = (body: McEditBody) => void;
+
+interface CameraColors {
+ [cameraId: string]: string;
+}
// One color per camera in the order the cameras are listed, so the shot strip
// and the legend agree on which color means which camera.
const CAMERA_COLORS = ["var(--accent)", "var(--green)", "var(--blue)", "var(--amber)", "var(--red)", "var(--text2)"];
-export function cameraColorMap(cameraIds: string[]): Record<string, string> {
- const map: Record<string, string> = {};
+export function cameraColorMap(cameraIds: string[]): CameraColors {
+ const map: CameraColors = {};
cameraIds.forEach((id, i) => {
map[id] = CAMERA_COLORS[i % CAMERA_COLORS.length];
});
+
return map;
}
diff --git a/src/ui/client/useAssets.ts b/src/ui/client/useAssets.ts
index da8226e..0001357 100644
--- a/src/ui/client/useAssets.ts
+++ b/src/ui/client/useAssets.ts
@@ -51,10 +51,12 @@ export function useAssets({ live = true }: { live?: boolean } = {}) {
useEffect(() => {
refresh();
+
if (!live) return;
const es = new EventSource("/api/events");
const onChange = () => refresh();
es.addEventListener("assets-updated", onChange);
+
return () => es.close();
}, [refresh, live]);
@@ -63,9 +65,11 @@ export function useAssets({ live = true }: { live?: boolean } = {}) {
const fd = new FormData();
fd.append("file", file);
fd.append("type", type);
+
if (name) fd.append("name", name);
const asset = await upload<Asset>("/assets/upload", fd);
await refresh();
+
return asset;
},
[refresh],
@@ -77,6 +81,7 @@ export function useAssets({ live = true }: { live?: boolean } = {}) {
method: "POST",
body: JSON.stringify({ url, type, name }),
});
+
return res.job_id;
},
[],
diff --git a/src/ui/client/useDialog.ts b/src/ui/client/useDialog.ts
index 4f20726..50c35dd 100644
--- a/src/ui/client/useDialog.ts
+++ b/src/ui/client/useDialog.ts
@@ -11,25 +11,32 @@ export function useDialog(active: boolean, onClose: () => void) {
useEffect(() => {
if (!active) return;
const node = ref.current;
+
if (!node) return;
- const previous = document.activeElement as HTMLElement | null;
+ const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
const focusables = () => Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE));
+
if (!node.contains(document.activeElement)) {
(focusables()[0] || node).focus();
}
+
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.stopPropagation();
closeRef.current();
+
return;
}
+
if (e.key !== "Tab") return;
const els = focusables();
+
if (!els.length) return;
const first = els[0];
const last = els[els.length - 1];
const current = document.activeElement;
const outside = !node.contains(current);
+
if (e.shiftKey && (current === first || outside)) {
e.preventDefault();
last.focus();
@@ -38,7 +45,9 @@ export function useDialog(active: boolean, onClose: () => void) {
first.focus();
}
};
+
document.addEventListener("keydown", onKey, true);
+
return () => {
document.removeEventListener("keydown", onKey, true);
previous?.focus?.();
diff --git a/src/ui/client/useJob.ts b/src/ui/client/useJob.ts
index 861b18c..abe21fc 100644
--- a/src/ui/client/useJob.ts
+++ b/src/ui/client/useJob.ts
@@ -1,26 +1,35 @@
import { useEffect, useState } from "react";
-export interface JobState {
+export interface JobResult {
+ file_path?: string;
+}
+
+export interface JobState<R = JobResult> {
status?: string;
progress?: number;
message?: string;
error?: string;
- result?: { file_path?: string; [key: string]: unknown };
+ result?: R;
}
-export function useJob(jobId: string | null): JobState | null {
- const [state, setState] = useState<JobState | null>(null);
+export function useJob<R = JobResult>(jobId: string | null): JobState<R> | null {
+ const [state, setState] = useState<JobState<R> | null>(null);
useEffect(() => {
if (!jobId) {
setState(null);
+
return;
}
+
const es = new EventSource(`/api/job/${jobId}/stream`);
es.onmessage = (e) => {
- const d = JSON.parse(e.data) as JobState;
+ // SAFETY: the job stream sends the job record, whose result is R for the job this hook was given.
+ const d = JSON.parse(e.data) as JobState<R>;
setState(d);
+
if (d.status === "done" || d.status === "error") es.close();
};
+
es.onerror = () => {
es.close();
// Surface a dropped connection so consumers don't hang on the last status.
@@ -30,7 +39,9 @@ export function useJob(jobId: string | null): JobState | null {
: { ...s, status: "error", error: s?.error || "Lost connection to the job stream" },
);
};
+
return () => es.close();
}, [jobId]);
+
return state;
}
diff --git a/src/ui/demo-fixtures.test.ts b/src/ui/demo-fixtures.test.ts
index fc4727c..4405905 100644
--- a/src/ui/demo-fixtures.test.ts
+++ b/src/ui/demo-fixtures.test.ts
@@ -6,6 +6,7 @@ describe("demo fixtures", () => {
it("exposes clips that light up the library and analytics", () => {
const clips = demoClips();
expect(clips.length).toBeGreaterThanOrEqual(6);
+
for (const c of clips) {
expect(c.id).toBeTruthy();
expect(c.title).toBeTruthy();
@@ -25,6 +26,7 @@ describe("demo fixtures", () => {
for (const c of demoClips()) {
expect(existsSync(c.thumbnail_config!.preview_path!)).toBe(true);
}
+
expect(existsSync(DEMO_ASSETS_DIR)).toBe(true);
});
});
@@ -45,7 +47,7 @@ describe("ClipsHistory in demo mode", () => {
const removed = await history.remove(first.id);
expect(removed?.id).toBe(first.id);
expect(existsSync(first.thumbnail_config!.preview_path!)).toBe(true);
- // Still all there — the delete was a no-op against read-only fixtures.
+ // Still all there: the delete was a no-op against read-only fixtures.
expect((await history.list(500)).length).toBe(demoClips().length);
});
});
diff --git a/src/ui/public/css/styles.css b/src/ui/public/css/styles.css
index e730e57..d303674 100644
--- a/src/ui/public/css/styles.css
+++ b/src/ui/public/css/styles.css
@@ -1,4 +1,4 @@
-/* ─── podcli — Shared Styles ─── */
+/* ─── podcli: Shared Styles ─── */
:root {
--bg: #0f0e0d;
diff --git a/src/ui/web-server-outputs.test.ts b/src/ui/web-server-outputs.test.ts
index 7ba4371..9d86b8c 100644
--- a/src/ui/web-server-outputs.test.ts
+++ b/src/ui/web-server-outputs.test.ts
@@ -1,7 +1,9 @@
-import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";
+import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { z } from "zod";
+import { stubPythonBackend } from "../test-support/stub-python-backend.js";
// A re-render reuses its output path, so a "_clean.mp4" variant from a
// previous render that this pass doesn't produce could sit next to the new
@@ -9,7 +11,8 @@ import { join } from "path";
// unrelated-looking clip instead of folding it into the main clip's entry.
const tmp = mkdtempSync(join(tmpdir(), "podcli-outputs-"));
-const savedEnv: Record<string, string | undefined> = {
+
+const savedEnv = {
PODCLI_HOME: process.env.PODCLI_HOME,
PODCLI_DATA: process.env.PODCLI_DATA,
PODCLI_OUTPUT: process.env.PODCLI_OUTPUT,
@@ -18,15 +21,7 @@ const savedEnv: Record<string, string | undefined> = {
const PORT = 18426;
-vi.mock("../services/python-executor.js", async (importOriginal) => {
- const original = await importOriginal<typeof import("../services/python-executor.js")>();
- class StubExecutor {
- async execute() {
- return { data: {} };
- }
- }
- return { ...original, PythonExecutor: StubExecutor };
-});
+const outputClipsSchema = z.array(z.object({ filename: z.string(), clean_output_path: z.string().optional() }));
let outputDir: string;
@@ -34,12 +29,15 @@ async function waitForServer(): Promise<void> {
for (let i = 0; i < 50; i++) {
try {
const res = await fetch(`http://127.0.0.1:${PORT}/api/ui-state`);
+
if (res.ok) return;
} catch {
// not up yet
}
+
await new Promise((r) => setTimeout(r, 100));
}
+
throw new Error("web server never came up");
}
@@ -56,6 +54,9 @@ beforeAll(async () => {
writeFileSync(join(outputDir, "clip-a_clean.mp4"), "clean variant bytes");
writeFileSync(join(outputDir, "clip-b.mp4"), "a second clip with no clean variant");
+ // The web server spawns the Python backend on startup (manage_config status
+ // check) and per request. Stub it so the test never depends on a real backend.
+ await stubPythonBackend();
await import("./web-server.js");
await waitForServer();
}, 20_000);
@@ -65,13 +66,14 @@ afterAll(() => {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
+
rmSync(tmp, { recursive: true, force: true });
});
describe("GET /api/outputs", () => {
it("folds a clip's _clean.mp4 variant into its own entry instead of listing it separately", async () => {
const res = await fetch(`http://127.0.0.1:${PORT}/api/outputs`);
- const clips = (await res.json()) as Array<{ filename: string; clean_output_path?: string }>;
+ const clips = outputClipsSchema.parse(await res.json());
const filenames = clips.map((c) => c.filename);
expect(filenames).toContain("clip-a.mp4");
diff --git a/src/ui/web-server-studio-edit.test.ts b/src/ui/web-server-studio-edit.test.ts
index 6989e17..e219899 100644
--- a/src/ui/web-server-studio-edit.test.ts
+++ b/src/ui/web-server-studio-edit.test.ts
@@ -1,7 +1,8 @@
-import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";
+import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { stubPythonBackend } from "../test-support/stub-python-backend.js";
// The studio's "_source: 'ui'" suggestions merge in POST /api/ui-state
// restores a clip's segments from server state when the studio's edit
@@ -14,7 +15,8 @@ import { join } from "path";
// excluded it.
const tmp = mkdtempSync(join(tmpdir(), "podcli-studio-edit-"));
-const savedEnv: Record<string, string | undefined> = {
+
+const savedEnv = {
PODCLI_HOME: process.env.PODCLI_HOME,
PODCLI_DATA: process.env.PODCLI_DATA,
PODCLI_PORT: process.env.PODCLI_PORT,
@@ -22,26 +24,19 @@ const savedEnv: Record<string, string | undefined> = {
const PORT = 18427;
-vi.mock("../services/python-executor.js", async (importOriginal) => {
- const original = await importOriginal<typeof import("../services/python-executor.js")>();
- class StubExecutor {
- async execute() {
- return { data: {} };
- }
- }
- return { ...original, PythonExecutor: StubExecutor };
-});
-
async function waitForServer(): Promise<void> {
for (let i = 0; i < 50; i++) {
try {
const res = await fetch(`http://127.0.0.1:${PORT}/api/ui-state`);
+
if (res.ok) return;
} catch {
// not up yet
}
+
await new Promise((r) => setTimeout(r, 100));
}
+
throw new Error("web server never came up");
}
@@ -51,6 +46,9 @@ beforeAll(async () => {
process.env.PODCLI_PORT = String(PORT);
mkdirSync(process.env.PODCLI_HOME, { recursive: true });
+ // The web server spawns the Python backend on startup (manage_config status
+ // check) and per request. Stub it so the test never depends on a real backend.
+ await stubPythonBackend();
await import("./web-server.js");
await waitForServer();
}, 20_000);
@@ -60,6 +58,7 @@ afterAll(() => {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
+
rmSync(tmp, { recursive: true, force: true });
});
@@ -97,6 +96,7 @@ describe("POST /api/ui-state studio suggestions merge", () => {
segments: undefined,
hook: { start: 12, end: 15, mode: "repeat" },
};
+
await fetch(`http://127.0.0.1:${PORT}/api/ui-state`, {
method: "POST",
headers: { "Content-Type": "application/json" },
diff --git a/src/ui/web-server-transcribe-identity.test.ts b/src/ui/web-server-transcribe-identity.test.ts
index c381c55..531495a 100644
--- a/src/ui/web-server-transcribe-identity.test.ts
+++ b/src/ui/web-server-transcribe-identity.test.ts
@@ -1,7 +1,8 @@
-import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";
+import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { stubPythonBackend } from "../test-support/stub-python-backend.js";
// transcribe_start (POST /api/transcribe) used to update uiState.transcript
// and uiState.videoPath without setting transcriptVideoIdentity. The next
@@ -13,7 +14,8 @@ import { join } from "path";
// checks the persisted ui-state.json, not just the in-memory handler logic.
const tmp = mkdtempSync(join(tmpdir(), "podcli-transcribe-identity-"));
-const savedEnv: Record<string, string | undefined> = {
+
+const savedEnv = {
PODCLI_HOME: process.env.PODCLI_HOME,
PODCLI_DATA: process.env.PODCLI_DATA,
PODCLI_PORT: process.env.PODCLI_PORT,
@@ -21,24 +23,13 @@ const savedEnv: Record<string, string | undefined> = {
const PORT = 18424;
-// The web server spawns the Python backend on startup (manage_config status
-// check) and per-transcribe-request (engine resolution). Stub it so the test
-// never depends on a real backend or network call, and resolves instantly.
-vi.mock("../services/python-executor.js", async (importOriginal) => {
- const original = await importOriginal<typeof import("../services/python-executor.js")>();
- class StubExecutor {
- async execute(taskType: string) {
- if (taskType === "resolve_transcribe_engine") {
- return { data: { engine: "whisper-py" } };
- }
- if (taskType === "transcribe") {
- return { data: { engine: "whisper-py", words: [{ word: "hi", start: 0, end: 1 }] } };
- }
- return { data: {} };
- }
- }
- return { ...original, PythonExecutor: StubExecutor };
-});
+interface PersistedUiState {
+ transcriptVideoIdentity?: { path?: string };
+}
+
+interface JobSnapshot {
+ status?: string;
+}
let videoPath: string;
let uiStatePath: string;
@@ -47,12 +38,15 @@ async function waitForServer(): Promise<void> {
for (let i = 0; i < 50; i++) {
try {
const res = await fetch(`http://127.0.0.1:${PORT}/api/ui-state`);
+
if (res.ok) return;
} catch {
// not up yet
}
+
await new Promise((r) => setTimeout(r, 100));
}
+
throw new Error("web server never came up");
}
@@ -70,10 +64,28 @@ beforeAll(async () => {
const cache = new TranscriptCache();
await cache.set(
videoPath,
- { words: [{ word: "hi", start: 0, end: 1 }] } as never,
+ {
+ transcript: "hi",
+ segments: [],
+ words: [{ word: "hi", start: 0, end: 1, confidence: 1 }],
+ duration: 1,
+ language: "en",
+ speakers: { num_speakers: 0, speakers: {} },
+ speaker_segments: [],
+ },
{ engine: "whisper-py", model: "base", language: undefined },
);
+ // The web server spawns the Python backend on startup (manage_config status
+ // check) and per-transcribe-request (engine resolution). Stub it so the test
+ // never depends on a real backend or network call, and resolves instantly.
+ await stubPythonBackend((taskType) => {
+ if (taskType === "resolve_transcribe_engine") return { engine: "whisper-py" };
+
+ if (taskType === "transcribe") return { engine: "whisper-py", words: [{ word: "hi", start: 0, end: 1 }] };
+
+ return {};
+ });
await import("./web-server.js");
await waitForServer();
}, 20_000);
@@ -96,21 +108,26 @@ describe("POST /api/transcribe", () => {
enable_diarization: false,
}),
});
+
const body = await res.json();
expect(body.cached).toBe(true);
// /api/ui-state doesn't echo transcriptVideoIdentity, and persistState()
// debounces its write to disk by 500ms, so poll the persisted file.
- let uiState: { transcriptVideoIdentity?: { path?: string } } = {};
+ let uiState: PersistedUiState = {};
+
for (let i = 0; i < 20; i++) {
try {
uiState = JSON.parse(readFileSync(uiStatePath, "utf-8"));
+
if (uiState.transcriptVideoIdentity) break;
} catch {
// not written yet
}
+
await new Promise((r) => setTimeout(r, 100));
}
+
expect(uiState.transcriptVideoIdentity).toBeTruthy();
expect(uiState.transcriptVideoIdentity?.path).toBe(videoPath);
});
@@ -128,26 +145,34 @@ describe("POST /api/transcribe", () => {
enable_diarization: false,
}),
});
+
const { job_id } = await res.json();
- let job: { status?: string } = {};
+ let job: JobSnapshot = {};
+
for (let i = 0; i < 50; i++) {
job = await (await fetch(`http://127.0.0.1:${PORT}/api/job/${job_id}`)).json();
+
if (job.status === "done" || job.status === "error") break;
await new Promise((r) => setTimeout(r, 100));
}
+
expect(job.status).toBe("done");
- let uiState: { transcriptVideoIdentity?: { path?: string } } = {};
+ let uiState: PersistedUiState = {};
+
for (let i = 0; i < 20; i++) {
try {
uiState = JSON.parse(readFileSync(uiStatePath, "utf-8"));
+
if (uiState.transcriptVideoIdentity?.path === freshVideoPath) break;
} catch {
// not written yet
}
+
await new Promise((r) => setTimeout(r, 100));
}
+
expect(uiState.transcriptVideoIdentity?.path).toBe(freshVideoPath);
});
});
diff --git a/src/ui/web-server-video-change-broadcast.test.ts b/src/ui/web-server-video-change-broadcast.test.ts
index 242b932..75a734e 100644
--- a/src/ui/web-server-video-change-broadcast.test.ts
+++ b/src/ui/web-server-video-change-broadcast.test.ts
@@ -1,7 +1,8 @@
-import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";
+import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { stubPythonBackend } from "../test-support/stub-python-backend.js";
// A bare set_video from MCP (videoPath with no transcript in the same
// request) clears the server's transcript/suggestions/selections, since
@@ -13,7 +14,8 @@ import { join } from "path";
// server.
const tmp = mkdtempSync(join(tmpdir(), "podcli-video-change-broadcast-"));
-const savedEnv: Record<string, string | undefined> = {
+
+const savedEnv = {
PODCLI_HOME: process.env.PODCLI_HOME,
PODCLI_DATA: process.env.PODCLI_DATA,
PODCLI_PORT: process.env.PODCLI_PORT,
@@ -21,26 +23,19 @@ const savedEnv: Record<string, string | undefined> = {
const PORT = 18429;
-vi.mock("../services/python-executor.js", async (importOriginal) => {
- const original = await importOriginal<typeof import("../services/python-executor.js")>();
- class StubExecutor {
- async execute() {
- return { data: {} };
- }
- }
- return { ...original, PythonExecutor: StubExecutor };
-});
-
async function waitForServer(): Promise<void> {
for (let i = 0; i < 50; i++) {
try {
const res = await fetch(`http://127.0.0.1:${PORT}/api/ui-state`);
+
if (res.ok) return;
} catch {
// not up yet
}
+
await new Promise((r) => setTimeout(r, 100));
}
+
throw new Error("web server never came up");
}
@@ -50,6 +45,9 @@ beforeAll(async () => {
process.env.PODCLI_PORT = String(PORT);
mkdirSync(process.env.PODCLI_HOME, { recursive: true });
+ // The web server spawns the Python backend on startup (manage_config status
+ // check) and per request. Stub it so the test never depends on a real backend.
+ await stubPythonBackend();
await import("./web-server.js");
await waitForServer();
}, 20_000);
@@ -59,40 +57,52 @@ afterAll(() => {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
+
rmSync(tmp, { recursive: true, force: true });
});
/** Collects every "event: state-sync" payload broadcast while `during` runs. */
-async function captureStateSyncEvents(during: () => Promise<void>): Promise<Array<Record<string, unknown>>> {
+interface StateSyncEvent {
+ videoPath?: string;
+ transcript?: object | null;
+ suggestions?: object[];
+}
+
+async function captureStateSyncEvents(during: () => Promise<void>): Promise<StateSyncEvent[]> {
const res = await fetch(`http://127.0.0.1:${PORT}/api/events`);
const reader = res.body!.getReader();
const decoder = new TextDecoder();
let buffer = "";
- const events: Array<Record<string, unknown>> = [];
+ const events: StateSyncEvent[] = [];
const pump = async () => {
for (;;) {
const { value, done } = await reader.read();
+
if (done) return;
buffer += decoder.decode(value, { stream: true });
let idx;
+
while ((idx = buffer.indexOf("\n\n")) !== -1) {
const chunk = buffer.slice(0, idx);
buffer = buffer.slice(idx + 2);
const eventLine = chunk.split("\n").find((l) => l.startsWith("event: "));
const dataLine = chunk.split("\n").find((l) => l.startsWith("data: "));
+
if (eventLine?.slice(7) === "state-sync" && dataLine) {
events.push(JSON.parse(dataLine.slice(6)));
}
}
}
};
+
const pumpPromise = pump();
await during();
await new Promise((r) => setTimeout(r, 200)); // let the broadcast land
await reader.cancel();
await pumpPromise.catch(() => {});
+
return events;
}
diff --git a/src/ui/web-server-video-missing.test.ts b/src/ui/web-server-video-missing.test.ts
index f3f8a6c..1067809 100644
--- a/src/ui/web-server-video-missing.test.ts
+++ b/src/ui/web-server-video-missing.test.ts
@@ -1,7 +1,8 @@
-import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";
+import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
+import { stubPythonBackend } from "../test-support/stub-python-backend.js";
// Loading persisted state at startup used to wipe the transcript and
// suggestions whenever the saved videoPath didn't exist on disk (e.g. an
@@ -10,7 +11,8 @@ import { join } from "path";
// video as missing instead.
const tmp = mkdtempSync(join(tmpdir(), "podcli-video-missing-"));
-const savedEnv: Record<string, string | undefined> = {
+
+const savedEnv = {
PODCLI_HOME: process.env.PODCLI_HOME,
PODCLI_DATA: process.env.PODCLI_DATA,
PODCLI_PORT: process.env.PODCLI_PORT,
@@ -18,26 +20,19 @@ const savedEnv: Record<string, string | undefined> = {
const PORT = 18428;
-vi.mock("../services/python-executor.js", async (importOriginal) => {
- const original = await importOriginal<typeof import("../services/python-executor.js")>();
- class StubExecutor {
- async execute() {
- return { data: {} };
- }
- }
- return { ...original, PythonExecutor: StubExecutor };
-});
-
async function waitForServer(): Promise<void> {
for (let i = 0; i < 50; i++) {
try {
const res = await fetch(`http://127.0.0.1:${PORT}/api/ui-state`);
+
if (res.ok) return;
} catch {
// not up yet
}
+
await new Promise((r) => setTimeout(r, 100));
}
+
throw new Error("web server never came up");
}
@@ -62,6 +57,9 @@ beforeAll(async () => {
}),
);
+ // The web server spawns the Python backend on startup (manage_config status
+ // check) and per request. Stub it so the test never depends on a real backend.
+ await stubPythonBackend();
await import("./web-server.js");
await waitForServer();
}, 20_000);
@@ -71,6 +69,7 @@ afterAll(() => {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
+
rmSync(tmp, { recursive: true, force: true });
});
diff --git a/src/ui/web-server.ts b/src/ui/web-server.ts
index 0785e8a..4697630 100644
--- a/src/ui/web-server.ts
+++ b/src/ui/web-server.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
- * podcli — Web UI Server
+ * podcli: Web UI Server
*
* Express server that provides:
* - File upload endpoint for podcast videos
@@ -10,6 +10,7 @@
*/
import express from "express";
+import { z } from "zod";
import multer from "multer";
import {
createReadStream,
@@ -27,29 +28,34 @@ import { execSync, execFileSync, spawn } from "child_process";
import { lookup } from "dns/promises";
import { isIP } from "net";
import { tmpdir } from "os";
+import { stripVTControlCharacters } from "util";
import { fileURLToPath } from "url";
+import { safePath } from "../utils/safe-path.js";
+import { rejectReason } from "../utils/local-request.js";
+import { EventEmitter } from "events";
import { v4 as uuidv4 } from "uuid";
-import { PythonExecutor, terminateProcessTree } from "../services/python-executor.js";
+import { createExecutor, terminateProcessTree } from "../services/python-executor.js";
import { needsDiarizationRetry, TranscriptCache } from "../services/transcript-cache.js";
import { resolveTranscribeEngine, engineCanDiarize } from "../services/engine-resolve.js";
import { FileManager } from "../services/file-manager.js";
-import { AssetManager, inferType, safeName } from "../services/asset-manager.js";
-import { ClipsHistory } from "../services/clips-history.js";
+import { AssetManager, assetTypeSchema, inferType, safeName } from "../services/asset-manager.js";
+import { ClipsHistory, reframeStateSchema } from "../services/clips-history.js";
import { KnowledgeBase } from "../services/knowledge-base.js";
import { paths, pythonEnv } from "../config/paths.js";
import { webServerPort } from "../config/server.js";
import { writeFileAtomicSync } from "../utils/atomic-file.js";
import { maxClipSeconds, validateClipRange, validateSuggestionRange } from "../utils/clip-validation.js";
import { playbackDuration, validateHook } from "../utils/clip-hook.js";
-import { needsFrame, parseThumbnailRender, thumbnailRenderArgs } from "../utils/thumbnail-layout.js";
+import { hookSchema } from "../handlers/suggest-clips.handler.js";
+import { needsFrame, thumbnailRenderArgs } from "../utils/thumbnail-layout.js";
+import { parseThumbnailRender } from "../utils/thumbnail-render-output.js";
import { advanceProgress, tagSubmittedClip, tagSubmittedClips } from "../utils/clip-results.js";
import { DEMO_ASSETS_DIR } from "./demo-fixtures.js";
import { registerConfigIntegrationRoutes } from "../handlers/integrations.routes.js";
import { childLogger } from "../utils/logger.js";
import {
sliceTranscript,
- sliceWords,
findContentType,
findGroundingText,
findSuggestionForRange,
@@ -68,7 +74,6 @@ import {
} from "../utils/full-episode-export.js";
import { buildYtDlpArgs, isCookieBrowser, ytDlpHint } from "../utils/ytdlp-args.js";
import type {
- AssetType,
BatchClipsResult,
ClipHistoryEntry,
ClipHook,
@@ -82,6 +87,9 @@ import type {
const log = childLogger("web-server");
+const stringValue = z.string();
+const numberValue = z.number();
+
const __dirname = dirname(fileURLToPath(import.meta.url));
const publicDir = existsSync(join(__dirname, "public", "index.html"))
@@ -93,22 +101,13 @@ const PORT = webServerPort;
const DEMO = process.env.PODCLI_DEMO === "1";
// --- Services ---
-const executor = new PythonExecutor();
+const executor = createExecutor();
const cache = new TranscriptCache();
const fileManager = new FileManager();
const assetManager = new AssetManager();
const clipsHistory = new ClipsHistory();
const knowledgeBase = new KnowledgeBase();
-// --- Path Traversal Protection ---
-function safePath(base: string, filename: string): string | null {
- const root = path.resolve(base);
- const resolved = path.resolve(base, filename);
- // Compare on a path boundary so "/data/output-evil" isn't accepted as inside "/data/output".
- if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;
- return resolved;
-}
-
// --- State ---
// Track active jobs so the UI can poll progress
interface JobState {
@@ -124,16 +123,63 @@ interface JobState {
clip_results?: unknown[];
}
-const jobs = new Map<string, JobState>();
+// Fires with a job id whenever a tracked field of that job changes, so the
+// per-job SSE stream can push instead of polling.
+const jobEvents = new EventEmitter();
+
+jobEvents.setMaxListeners(0);
+
+const pendingJobEvents = new Set<string>();
+
+// One event per burst of assignments (status, progress, message, result are
+// usually set back to back), so a listener never sees a half-updated job.
+function notifyJobChanged(id: string): void {
+ if (pendingJobEvents.has(id)) return;
+ pendingJobEvents.add(id);
+ setImmediate(() => {
+ pendingJobEvents.delete(id);
+ jobEvents.emit(id);
+ });
+}
+
+const TRACKED_JOB_FIELDS = ["status", "progress", "message", "result", "error", "clip_results"] as const;
+
+// Job handlers mutate the object they pass to set() in place, in dozens of
+// places. Turning its tracked fields into accessors reports every change
+// without touching those call sites.
+class JobStore extends Map<string, JobState> {
+ set(id: string, job: JobState): this {
+ for (const field of TRACKED_JOB_FIELDS) {
+ let value = job[field];
+ Object.defineProperty(job, field, {
+ enumerable: true,
+ configurable: true,
+ get: () => value,
+ set: (next) => {
+ if (next === value) return;
+ value = next;
+ notifyJobChanged(id);
+ },
+ });
+ }
+
+ return super.set(id, job);
+ }
+}
+
+const jobs = new JobStore();
// Sweep terminal jobs so the map doesn't grow forever. Completion isn't
// stamped at the many done/error sites; the sweeper stamps it on first sight,
// so a job survives at least one full retention window after finishing.
const JOB_RETENTION_MS = 30 * 60_000;
+
setInterval(() => {
const now = Date.now();
+
for (const [id, job] of jobs) {
if (job.status !== "done" && job.status !== "error") continue;
+
if (job.finishedAt === undefined) {
job.finishedAt = now;
} else if (now - job.finishedAt > JOB_RETENTION_MS) {
@@ -144,7 +190,9 @@ setInterval(() => {
/** Transcript data stored per file, plus optional face-tracking hints. */
type ServerTranscript = TranscriptResult & { face_map?: unknown };
+
type SilenceOriginal = { videoPath: string; transcript: ServerTranscript };
+
type SilencePlan = {
keep_segments: Array<{ start: number; end: number }>;
removed_ranges: Array<{ start: number; end: number }>;
@@ -153,7 +201,6 @@ type SilencePlan = {
removed_duration: number;
removed_percent: number;
cut_count: number;
- [key: string]: unknown;
};
// Store the latest transcript per uploaded file for the session
@@ -193,7 +240,7 @@ interface UIState {
};
phase: string;
results: unknown[];
- energyData: Record<string, unknown>;
+ energyData: Record<string, number[]>;
lastUpdated: number;
}
@@ -208,9 +255,11 @@ function loadPersistedState(): UIState {
// session the file may rejoin; flag it instead so the caller can warn
// and skip anything that needs the file on disk right now.
const videoMissing = !!saved.videoPath && !existsSync(saved.videoPath);
+
if (saved.silenceOriginal?.videoPath && !existsSync(saved.silenceOriginal.videoPath)) {
saved.silenceOriginal = null;
}
+
return {
videoPath: saved.videoPath || "",
filePath: saved.filePath || "",
@@ -255,6 +304,7 @@ function loadPersistedState(): UIState {
err: errMsg(err),
});
}
+
return {
videoPath: "",
filePath: "",
@@ -297,7 +347,7 @@ const uiState: UIState = loadPersistedState();
const allowedSourcePaths = new Set<string>();
// Recent source videos, referenced in place (never copied) so they can be
-// re-picked without re-uploading. Persisted as paths only — no GB bloat.
+// re-picked without re-uploading. Persisted as paths only, no GB bloat.
const sourcesFile = join(paths.home, "sources.json");
const VIDEO_SOURCE_EXTS = new Set([".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"]);
let recentSources: string[] = loadRecentSources();
@@ -305,7 +355,8 @@ let recentSources: string[] = loadRecentSources();
function loadRecentSources(): string[] {
try {
const raw = JSON.parse(readFileSync(sourcesFile, "utf-8"));
- return Array.isArray(raw) ? raw.filter((p) => typeof p === "string") : [];
+
+ return z.array(z.string()).catch([]).parse(raw);
} catch {
return [];
}
@@ -314,6 +365,7 @@ function loadRecentSources(): string[] {
function rememberSource(realPath: string): void {
if (!VIDEO_SOURCE_EXTS.has(extname(realPath).toLowerCase())) return;
recentSources = [realPath, ...recentSources.filter((p) => p !== realPath)].slice(0, 40);
+
try {
writeFileAtomicSync(sourcesFile, JSON.stringify(recentSources, null, 2));
} catch {}
@@ -321,31 +373,37 @@ function rememberSource(realPath: string): void {
function registerSourcePath(p: string | undefined | null): void {
if (!p) return;
+
try {
const real = realpathSync(path.resolve(p));
allowedSourcePaths.add(real);
rememberSource(real);
} catch {}
}
+
registerSourcePath(uiState.videoPath);
+
registerSourcePath(uiState.silenceOriginal?.videoPath);
// Client-supplied source paths are honoured only after the user uploaded or
// selected the file this session. existsSync alone would let a forged request
// probe, read, or re-encode any file the server user can reach.
-function resolveAllowedSource(p: unknown): string | null {
- if (typeof p !== "string" || !p) return null;
+function resolveAllowedSource(p: string | undefined): string | null {
+ if (!p) return null;
let real: string;
+
try {
real = realpathSync(path.resolve(p));
} catch {
return null;
}
+
return allowedSourcePaths.has(real) ? real : null;
}
// Debounced save to disk
let saveTimer: ReturnType<typeof setTimeout> | null = null;
+
function persistState() {
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
@@ -359,19 +417,31 @@ function persistState() {
// SSE clients for the global event bus
import type { Request, Response } from "express";
+
const sseClients: Response[] = [];
function streamVideo(req: Request, res: Response, filePath: string, contentType = "video/mp4") {
+ if (contentType === "image/svg+xml") {
+ // An uploaded SVG can carry script. Sandboxing it keeps that script out of
+ // the studio's origin when the file is opened directly.
+ res.setHeader("Content-Security-Policy", "sandbox");
+ }
+
const fileSize = statSync(filePath).size;
const range = req.headers.range;
+
const onErr = (stream: ReturnType<typeof createReadStream>) =>
stream.on("error", () => res.destroy());
+
if (range) {
const resolved = resolveByteRange(range, fileSize);
+
if (!resolved) {
res.writeHead(416, { "Content-Range": `bytes */${fileSize}` }).end();
+
return;
}
+
const { start, end } = resolved;
res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
@@ -390,8 +460,9 @@ function streamVideo(req: Request, res: Response, filePath: string, contentType
}
}
-function broadcastSSE(event: string, data: unknown) {
+function broadcastSSE<T>(event: string, data: T) {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
+
for (let i = sseClients.length - 1; i >= 0; i--) {
try {
sseClients[i].write(payload);
@@ -424,7 +495,9 @@ type ExportClip = {
* An explicit hook: null stays null, so a render can opt out of one. */
function enrichClipFromSuggestion<T extends ExportClip>(clip: T): T {
const match = findSuggestionForRange(uiState.suggestions, clip.start_second, clip.end_second);
+
if (!match) return clip;
+
return {
...clip,
...(!clip.keep_segments?.length && match.segments?.length && { keep_segments: match.segments }),
@@ -436,8 +509,10 @@ function exportHookError(clips: ExportClip[]): string | null {
for (let i = 0; i < clips.length; i++) {
const c = clips[i];
const err = validateHook(c.hook, c.start_second, c.end_second, c.keep_segments);
+
if (err) return clips.length > 1 ? `Clip ${i + 1}: ${err}` : err;
}
+
return null;
}
@@ -489,13 +564,17 @@ function createBatchHistoryRecorder({
contentTypeFor: (s, e) => findContentType(uiState.suggestions, s, e),
suggestions: uiState.suggestions,
});
+
let recordedIdx = 0;
+
for (const row of rows) {
if (row.status !== "success" || !row.output_path) continue;
const rec = recorded[recordedIdx++];
+
if (!rec) continue;
- const spec =
- typeof row.clip_index === "number" ? clipSpecs?.[row.clip_index] : undefined;
+
+ const spec = row.clip_index !== undefined ? clipSpecs?.[row.clip_index] : undefined;
+
try {
await clipsHistory.persistClipRecipe(rec, {
transcriptWords,
@@ -510,37 +589,58 @@ function createBatchHistoryRecorder({
log.warn(`Failed to save recipe for ${label} clip`, { err: errMsg(err) });
}
}
+
for (const row of rows) {
- if (row.status === "success" && row.output_path && typeof row.clip_index === "number") {
+ if (row.status === "success" && row.output_path && row.clip_index !== undefined) {
recordedClipIndexes.add(row.clip_index);
}
}
+
broadcastHistoryUpdated(jobId, recorded);
};
return {
recordProgress(event: ProgressEvent) {
if (event.stage !== "clip_complete" || !event.clip_result) return;
+
const write = recordRows([event.clip_result]).catch((err) => {
log.warn(`Failed to record completed ${label} clip to history`, {
err: errMsg(err),
});
});
+
pendingWrites.push(write);
},
async recordRemaining(results: BatchClipsResult["results"] | undefined) {
await Promise.allSettled(pendingWrites);
+
const remaining = results?.filter(
(row) =>
- typeof row.clip_index !== "number" ||
+ row.clip_index === undefined ||
!recordedClipIndexes.has(row.clip_index),
);
+
if (remaining?.length) await recordRows(remaining);
},
};
}
// --- Middleware ---
+const bindHost = process.env.PODCLI_HOST || "127.0.0.1";
+const bindsLoopbackOnly = ["127.0.0.1", "localhost", "::1"].includes(bindHost);
+
+app.use((req, res, next) => {
+ const reason = rejectReason(req.method, req.headers, !bindsLoopbackOnly);
+
+ if (reason) {
+ res.status(403).json({ error: reason });
+
+ return;
+ }
+
+ next();
+});
+
app.use(express.json({ limit: "50mb" }));
// Serve static frontend. redirect:false so the /assets page route isn't shadowed
@@ -549,6 +649,7 @@ app.use(express.static(publicDir, { redirect: false }));
// File upload config
const uploadDir = join(paths.working, "uploads");
+
const upload = multer({
storage: multer.diskStorage({
destination: async (_req, _file, cb) => {
@@ -575,7 +676,9 @@ const upload = multer({
".jpeg",
".svg",
];
+
const ext = extname(file.originalname).toLowerCase();
+
if (allowed.includes(ext)) {
cb(null, true);
} else {
@@ -619,9 +722,11 @@ function activeBlockingJobs(): JobState[] {
function isPublicIp(address: string): boolean {
const family = isIP(address);
const mapped = address.toLowerCase().startsWith("::ffff:") ? address.slice(7) : "";
+
if (mapped) {
if (isIP(mapped) === 4) return isPublicIp(mapped);
const parts = mapped.split(":").map((part) => Number.parseInt(part, 16));
+
if (parts.length === 2 && parts.every((part) => Number.isFinite(part))) {
return isPublicIp([
parts[0] >> 8,
@@ -631,9 +736,11 @@ function isPublicIp(address: string): boolean {
].join("."));
}
}
+
if (family === 4) {
const parts = address.split(".").map((part) => Number(part));
const [a, b] = parts;
+
return !(
a === 0 ||
a === 10 ||
@@ -646,8 +753,10 @@ function isPublicIp(address: string): boolean {
a >= 224
);
}
+
if (family === 6) {
const normalized = address.toLowerCase();
+
return !(
normalized === "::1" ||
normalized === "::" ||
@@ -656,27 +765,34 @@ function isPublicIp(address: string): boolean {
normalized.startsWith("fe80:")
);
}
+
return false;
}
-async function validateDownloadUrl(rawUrl: unknown): Promise<string> {
- if (typeof rawUrl !== "string" || !rawUrl.trim()) {
+async function validateDownloadUrl(rawUrl: string | undefined): Promise<string> {
+ if (!rawUrl?.trim()) {
throw new Error("url is required");
}
+
let parsed: URL;
+
try {
parsed = new URL(rawUrl.trim());
} catch {
throw new Error(`Invalid URL: ${rawUrl}`);
}
+
if (!["http:", "https:"].includes(parsed.protocol)) {
throw new Error(`Unsupported URL protocol: ${parsed.protocol}. Use http or https.`);
}
+
// Best-effort SSRF preflight: yt-dlp still resolves redirects itself at download time.
const addresses = await lookup(parsed.hostname, { all: true, verbatim: false });
+
if (addresses.length === 0 || addresses.some((entry) => !isPublicIp(entry.address))) {
throw new Error(`Download URL host is not allowed: ${parsed.hostname}. Use a public video URL.`);
}
+
return parsed.toString();
}
@@ -688,13 +804,16 @@ async function validateDownloadUrl(rawUrl: unknown): Promise<string> {
app.post("/api/session-cache/clear", async (_req, res) => {
try {
const active = activeBlockingJobs();
+
if (active.length > 0) {
res.status(409).json({
error: "Cannot clear session cache while jobs are running",
jobs: active.map((job) => ({ id: job.id, type: job.type, status: job.status })),
});
+
return;
}
+
clearEpisodeSessionState();
persistState();
broadcastSSE("state-sync", uiState);
@@ -705,13 +824,15 @@ app.post("/api/session-cache/clear", async (_req, res) => {
});
/**
- * POST /api/upload — Upload a podcast file
+ * POST /api/upload: Upload a podcast file
*/
app.post("/api/upload", upload.single("file"), (req, res) => {
if (!req.file) {
res.status(400).json({ error: "No file uploaded" });
+
return;
}
+
registerSourcePath(req.file.path);
res.json({
file_path: req.file.path,
@@ -721,21 +842,24 @@ app.post("/api/upload", upload.single("file"), (req, res) => {
});
/**
- * POST /api/download-video — Download a video URL with yt-dlp into uploads.
+ * POST /api/download-video: Download a video URL with yt-dlp into uploads.
*/
/** The browser whose cookies yt-dlp should read, from the request or the env. */
-function cookieBrowser(fromRequest: unknown): string | undefined {
- if (isCookieBrowser(fromRequest)) return fromRequest;
+function cookieBrowser(fromRequest: string | undefined): string | undefined {
+ if (fromRequest !== undefined && isCookieBrowser(fromRequest)) return fromRequest;
const configured = (process.env.PODCLI_YTDLP_BROWSER || "").trim().toLowerCase();
+
return isCookieBrowser(configured) ? configured : undefined;
}
app.post("/api/download-video", async (req, res) => {
let url: string;
+
try {
- url = await validateDownloadUrl(req.body?.url);
+ url = await validateDownloadUrl(stringValue.safeParse(req.body?.url).data);
} catch (err) {
res.status(400).json({ error: errMsg(err) });
+
return;
}
@@ -743,10 +867,12 @@ app.post("/api/download-video", async (req, res) => {
await mkdir(uploadDir, { recursive: true });
} catch (err) {
res.status(500).json({ error: `Failed to create upload directory: ${errMsg(err)}` });
+
return;
}
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "download_video",
@@ -755,6 +881,7 @@ app.post("/api/download-video", async (req, res) => {
message: "Downloading video",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
const args = buildYtDlpArgs({
@@ -763,10 +890,11 @@ app.post("/api/download-video", async (req, res) => {
outputTemplate: "%(title).200B [%(id)s].%(ext)s",
ffmpegLocation: paths.ffmpegPath,
jsRuntimeNodePath: process.execPath,
- cookiesFromBrowser: cookieBrowser(req.body?.browser),
+ cookiesFromBrowser: cookieBrowser(stringValue.safeParse(req.body?.browser).data),
extractorArgs: process.env.PODCLI_YT_EXTRACTOR_ARGS || undefined,
progressTemplate: "download:podcli-progress:%(progress._percent_str)s",
});
+
// Detached so a kill takes out yt-dlp's ffmpeg children with it.
const proc = spawn(paths.pythonPath, args, {
env: pythonEnv(),
@@ -779,6 +907,7 @@ app.post("/api/download-video", async (req, res) => {
let settled = false;
let responded = false;
const timer = setTimeout(() => terminateProcessTree(proc), 3600_000);
+
const finish = (action: () => void): void => {
if (settled) return;
settled = true;
@@ -789,13 +918,16 @@ app.post("/api/download-video", async (req, res) => {
const readYtDlpOutput = (raw: string): void => {
for (const line of raw.split(/\r?\n/)) {
const progress = line.match(/podcli-progress:\s*(\d+(?:\.\d+)?)%/);
+
if (progress) {
job.progress = Number(progress[1]);
job.message = "Downloading video";
broadcastSSE("job-update", { jobId, progress: job.progress, message: job.message });
continue;
}
+
const trimmed = line.trim();
+
if (trimmed.startsWith("podcli-filepath:")) {
outputFilePath = trimmed.slice("podcli-filepath:".length);
}
@@ -811,6 +943,7 @@ app.post("/api/download-video", async (req, res) => {
const raw = chunk.toString();
stderr += raw;
readYtDlpOutput(raw);
+
if (stderr && job.progress === 0) {
job.message = "Downloading video";
}
@@ -831,15 +964,18 @@ app.post("/api/download-video", async (req, res) => {
job.error = `yt-dlp failed for ${url} with exit code ${code}.${hint ? ` ${hint}` : ""} stderr: ${stderr.slice(-1200)}`;
job.message = job.error;
broadcastSSE("job-error", { jobId, error: job.error });
+
return;
}
const filePath = outputFilePath;
+
if (!filePath || !existsSync(filePath)) {
job.status = "error";
job.error = `yt-dlp finished but did not report an output file. stdout: ${stdout.slice(-1200)} stderr: ${stderr.slice(-1200)}`;
job.message = job.error;
broadcastSSE("job-error", { jobId, error: job.error });
+
return;
}
@@ -874,14 +1010,17 @@ app.post("/api/download-video", async (req, res) => {
});
/**
- * POST /api/select-file — Use an existing local file (no upload needed)
+ * POST /api/select-file: Use an existing local file (no upload needed)
*/
app.post("/api/select-file", (req, res) => {
const { file_path } = req.body;
+
if (!file_path || !existsSync(file_path)) {
res.status(400).json({ error: "File not found" });
+
return;
}
+
const stat = statSync(file_path);
registerSourcePath(file_path);
res.json({
@@ -894,8 +1033,10 @@ app.post("/api/select-file", (req, res) => {
/** Native folder dialog; returns the chosen directory, or null when cancelled. */
function pickFolder(): string | null {
const prompt = "Choose the folder with this episode's recordings";
+
try {
let raw: string;
+
if (process.platform === "darwin") {
raw = execFileSync("osascript", ["-e", `POSIX path of (choose folder with prompt "${prompt}")`], {
encoding: "utf-8",
@@ -908,6 +1049,7 @@ function pickFolder(): string | null {
`$f.Description = '${prompt.replace(/'/g, "''")}';`,
"if ($f.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $f.SelectedPath }",
].join(" ");
+
raw = execSync(`powershell -NoProfile -STA -EncodedCommand ${Buffer.from(ps, "utf16le").toString("base64")}`, {
encoding: "utf-8",
timeout: 120_000,
@@ -915,7 +1057,9 @@ function pickFolder(): string | null {
} else {
raw = execFileSync("zenity", ["--file-selection", "--directory"], { encoding: "utf-8", timeout: 120_000 });
}
+
const folder = raw.trim();
+
return folder && existsSync(folder) && statSync(folder).isDirectory() ? folder : null;
} catch {
return null;
@@ -923,17 +1067,21 @@ function pickFolder(): string | null {
}
/**
- * GET /api/browse-file — Open native OS file dialog and return the selected path
+ * GET /api/browse-file: Open native OS file dialog and return the selected path
*/
app.get("/api/browse-file", (req, res) => {
const multiple = req.query.multiple === "1" || req.query.multiple === "true";
+
if (req.query.folder === "1") {
const folder = pickFolder();
res.json(folder ? { folder } : { error: "cancelled" });
+
return;
}
+
try {
let raw: string;
+
if (process.platform === "darwin") {
const mult = multiple ? " with multiple selections allowed" : "";
raw = execFileSync(
@@ -958,6 +1106,7 @@ app.get("/api/browse-file", (req, res) => {
multiple ? "$f.Multiselect = $true;" : "",
"if ($f.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $f.FileNames -join [Environment]::NewLine }",
].join(" ");
+
const encoded = Buffer.from(ps, "utf16le").toString("base64");
raw = execSync(`powershell -NoProfile -STA -EncodedCommand ${encoded}`, {
encoding: "utf-8",
@@ -965,15 +1114,19 @@ app.get("/api/browse-file", (req, res) => {
});
} else {
const args = ["--file-selection", "--file-filter=Media files|*.mp4 *.mov *.mkv *.webm *.mp3 *.wav *.m4a"];
+
if (multiple) args.push("--multiple", "--separator=\n");
raw = execFileSync("zenity", args, { encoding: "utf-8", timeout: 120_000 });
}
const paths = raw.split("\n").map((p) => p.trim()).filter((p) => p && existsSync(p));
+
if (paths.length === 0) {
res.json({ error: "cancelled" });
+
return;
}
+
for (const p of paths) registerSourcePath(p);
const stat = statSync(paths[0]);
res.json({
@@ -989,7 +1142,7 @@ app.get("/api/browse-file", (req, res) => {
});
/**
- * POST /api/import-transcript — Import an existing transcript (skip Whisper)
+ * POST /api/import-transcript: Import an existing transcript (skip Whisper)
* Accepts: { file_path, transcript } where transcript is an object with:
* - text: string (full transcript text)
* - words: Array<{ word, start, end, speaker? }>
@@ -1001,20 +1154,23 @@ app.post("/api/import-transcript", (req, res) => {
if (!file_path) {
res.status(400).json({ error: "file_path is required" });
+
return;
}
+
if (!transcript || !transcript.words || !Array.isArray(transcript.words)) {
res.status(400).json({
error:
"transcript must include a 'words' array with { word, start, end } objects",
});
+
return;
}
// Build a full transcript result from the imported data
- const result: Record<string, unknown> = {
+ const result: ServerTranscript & { imported: true } = {
transcript:
- transcript.text || transcript.words.map((w: any) => w.word).join(" "),
+ transcript.text || transcript.words.map((w: WordTimestamp) => w.word).join(" "),
words: transcript.words,
segments: transcript.segments || [],
duration:
@@ -1023,12 +1179,12 @@ app.post("/api/import-transcript", (req, res) => {
? transcript.words[transcript.words.length - 1].end
: 0),
language: transcript.language || "en",
- speakers: transcript.speakers || null,
- speaker_segments: transcript.speaker_segments || null,
+ speakers: transcript.speakers || {},
+ speaker_segments: transcript.speaker_segments || [],
imported: true,
};
- sessionTranscripts.set(file_path, result as unknown as ServerTranscript);
+ sessionTranscripts.set(file_path, result);
res.json({
status: "done",
@@ -1039,7 +1195,7 @@ app.post("/api/import-transcript", (req, res) => {
});
/**
- * POST /api/parse-transcript — Parse a speaker-labeled plain text transcript
+ * POST /api/parse-transcript: Parse a speaker-labeled plain text transcript
* Format: "Speaker (MM:SS)\ntext...\n\nSpeaker2 (MM:SS)\ntext..."
* Uses Python backend to generate word-level timestamps.
*/
@@ -1048,15 +1204,18 @@ app.post("/api/parse-transcript", async (req, res) => {
if (!file_path) {
res.status(400).json({ error: "file_path is required" });
+
return;
}
+
if (!raw_text) {
res.status(400).json({ error: "raw_text is required" });
+
return;
}
try {
- const result = await executor.execute("parse_transcript", {
+ const result = await executor.execute<ServerTranscript>("parse_transcript", {
raw_text,
total_duration: total_duration || null,
time_adjust: time_adjust || 0,
@@ -1064,10 +1223,7 @@ app.post("/api/parse-transcript", async (req, res) => {
});
if (result.data) {
- sessionTranscripts.set(
- file_path,
- result.data as unknown as ServerTranscript,
- );
+ sessionTranscripts.set(file_path, result.data);
}
res.json({
@@ -1083,7 +1239,7 @@ app.post("/api/parse-transcript", async (req, res) => {
});
/**
- * POST /api/transcribe — Start transcription job
+ * POST /api/transcribe: Start transcription job
*/
app.post("/api/transcribe", async (req, res) => {
const {
@@ -1100,8 +1256,10 @@ app.post("/api/transcribe", async (req, res) => {
if (!file_path || !existsSync(file_path)) {
res.status(400).json({ error: "File not found" });
+
return;
}
+
// A sample is a positive window, not merely a present key, matching
// transcribe.handler.ts and backend/services/transcription.py exactly.
const isSample = (duration_seconds ?? 0) > 0 || (start_seconds ?? 0) > 0;
@@ -1116,13 +1274,15 @@ app.post("/api/transcribe", async (req, res) => {
// populate the session/UI state from the main cache (keyed by, and
// assumed to describe, the whole file).
const cachedRaw = isSample ? null : await cache.get(file_path, cacheKey);
+
const cached = needsDiarizationRetry(cachedRaw, enable_diarization, engineCanDiarize(resolvedEngine))
? null
: cachedRaw;
+
if (cached) {
const jobId = uuidv4();
- sessionTranscripts.set(file_path, cached as unknown as ServerTranscript);
- uiState.transcript = cached as unknown as typeof uiState.transcript;
+ sessionTranscripts.set(file_path, cached);
+ uiState.transcript = cached;
uiState.videoPath = file_path;
uiState.filePath = file_path;
uiState.videoMissing = false;
@@ -1136,10 +1296,12 @@ app.post("/api/transcribe", async (req, res) => {
cached: true,
data: cached,
});
+
return;
}
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "transcribe",
@@ -1148,13 +1310,14 @@ app.post("/api/transcribe", async (req, res) => {
message: "Starting transcription...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
res.json({ job_id: jobId, status: "running" });
// Run async
executor
- .execute(
+ .execute<ServerTranscript>(
"transcribe",
{
file_path,
@@ -1180,15 +1343,14 @@ app.post("/api/transcribe", async (req, res) => {
// A sample result is a slice, not the episode. Leave the session/UI
// state and the main cache alone. The caller reads it via job_status.
- if (isSample) return;
+ const transcript = result.data;
- sessionTranscripts.set(
- file_path,
- result.data as unknown as ServerTranscript,
- );
+ if (isSample || !transcript) return;
+
+ sessionTranscripts.set(file_path, transcript);
// Populate uiState.transcript with the FULL result so downstream
// batch_create_clips can resolve transcript_words for caption burn-in.
- uiState.transcript = result.data as unknown as typeof uiState.transcript;
+ uiState.transcript = transcript;
uiState.videoPath = file_path;
uiState.filePath = file_path;
uiState.videoMissing = false;
@@ -1200,13 +1362,14 @@ app.post("/api/transcribe", async (req, res) => {
// forever: the job id lived only in the tab that started it, and nothing
// else announces that the transcript landed.
broadcastSSE("state-sync", uiState);
+
// Cache it under the engine it actually ran with. A fresh resolution
// (or the pre-transcribe request) can differ from what transcribe_file
// fell back to once it tried loading the model for real.
try {
- const actualEngine =
- (result.data as unknown as TranscriptResult | undefined)?.engine ?? resolvedEngine;
- await cache.set(file_path, result.data as unknown as TranscriptResult, {
+ const actualEngine = transcript.engine ?? resolvedEngine;
+
+ await cache.set(file_path, transcript, {
engine: actualEngine,
model: model_size,
language,
@@ -1234,7 +1397,7 @@ function sessionWords(): unknown[] {
}
/**
- * POST /api/create-clip — Start clip creation job
+ * POST /api/create-clip: Start clip creation job
*/
app.post("/api/create-clip", async (req, res) => {
const {
@@ -1258,6 +1421,7 @@ app.post("/api/create-clip", async (req, res) => {
if (!video_path || !existsSync(video_path)) {
res.status(400).json({ error: "Video file not found" });
+
return;
}
@@ -1265,83 +1429,122 @@ app.post("/api/create-clip", async (req, res) => {
let logo_path: string | null = null;
let outro_path: string | null = null;
let intro_path: string | null = null;
+
for (const [key, raw] of [["logo", req.body.logo_path], ["outro", req.body.outro_path], ["intro", req.body.intro_path]] as const) {
if (!raw) continue;
const resolved = await assetManager.resolve(raw);
+
if (!resolved) {
res.status(400).json({ error: `${key} not found: ${raw}` });
+
return;
}
+
if (key === "logo") logo_path = resolved;
else if (key === "outro") outro_path = resolved;
else intro_path = resolved;
}
// Validate clip params before spawning Python
- if (typeof start_second !== "number" || typeof end_second !== "number") {
+ if (!numberValue.safeParse(start_second).success || !numberValue.safeParse(end_second).success) {
res
.status(400)
.json({ error: "start_second and end_second must be numbers" });
+
return;
}
+
if (end_second <= start_second) {
res
.status(400)
.json({ error: "end_second must be greater than start_second" });
+
return;
}
+
const duration = end_second - start_second;
const maxDur = format === "horizontal" ? 300 : 180;
+
if (duration > maxDur) {
res.status(400).json({
error: `Clip too long (${Math.round(duration)}s). Max ${maxDur} seconds.`,
});
+
return;
}
+
const validStyles = ["hormozi", "karaoke", "subtle", "branded"];
+
if (!validStyles.includes(caption_style)) {
res
.status(400)
.json({ error: `Invalid caption style. Use: ${validStyles.join(", ")}` });
+
return;
}
+
const validCrops = ["center", "face", "speaker"];
+
if (!validCrops.includes(crop_strategy)) {
res
.status(400)
.json({ error: `Invalid crop strategy. Use: ${validCrops.join(", ")}` });
+
return;
}
+
const validFormats = ["vertical", "horizontal", "square"];
+
if (!validFormats.includes(format)) {
res
.status(400)
.json({ error: `Invalid format. Use: ${validFormats.join(", ")}` });
+
return;
}
+
const validCaptionPositions = ["auto", "upper", "center", "lower"];
const validLogoPositions = ["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"];
+
if (!validCaptionPositions.includes(caption_position) || !validLogoPositions.includes(logo_position)) {
res.status(400).json({ error: "Invalid caption or logo position" });
+
return;
}
+
const normalizedFontScale = Math.max(60, Math.min(160, Number(caption_font_scale) || 100));
+ const parsedHook = hookSchema.nullish().safeParse(hook);
+
+ if (!parsedHook.success) {
+ res.status(400).json({
+ error:
+ validateHook(hook, start_second, end_second, keep_segments) ??
+ "hook must be an object with start, end and mode",
+ });
+
+ return;
+ }
+
await fileManager.ensureDirectories();
const enriched = enrichClipFromSuggestion({
start_second,
end_second,
keep_segments: Array.isArray(keep_segments) ? keep_segments : undefined,
- hook: hook as ClipHook | null | undefined,
+ hook: parsedHook.data,
});
+
const hookError = exportHookError([enriched]);
+
if (hookError) {
res.status(400).json({ error: hookError });
+
return;
}
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "create_clip",
@@ -1350,6 +1553,7 @@ app.post("/api/create-clip", async (req, res) => {
message: "Preparing clip...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
res.json({ job_id: jobId, status: "running" });
@@ -1388,9 +1592,11 @@ app.post("/api/create-clip", async (req, res) => {
job.progress = 100;
job.message = "Clip created!";
job.result = result.data;
+
// Record to history
try {
const d = result.data;
+
const rec = await clipsHistory.record({
source_video: video_path,
start_second,
@@ -1409,6 +1615,7 @@ app.post("/api/create-clip", async (req, res) => {
transcript_slice: sliceTranscript(transcript_words, start_second, end_second),
...findGroundingText(uiState.suggestions, start_second, end_second),
});
+
await clipsHistory.persistClipRecipe(rec, {
transcriptWords: transcript_words,
logoPath: logo_path,
@@ -1425,6 +1632,7 @@ app.post("/api/create-clip", async (req, res) => {
err: errMsg(err),
});
}
+
broadcastSSE("job-complete", { jobId, result: result.data });
})
.catch((err) => {
@@ -1436,7 +1644,7 @@ app.post("/api/create-clip", async (req, res) => {
});
/**
- * POST /api/batch-clips — Create multiple clips
+ * POST /api/batch-clips: Create multiple clips
*/
app.post("/api/batch-clips", async (req, res) => {
const {
@@ -1453,50 +1661,68 @@ app.post("/api/batch-clips", async (req, res) => {
if (!video_path || !existsSync(video_path)) {
res.status(400).json({ error: "Video file not found" });
+
return;
}
+
if (!clips || !Array.isArray(clips) || clips.length === 0) {
res.status(400).json({ error: "No clips provided" });
+
return;
}
+
if (!["auto", "upper", "center", "lower"].includes(caption_position) ||
!["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"].includes(logo_position)) {
res.status(400).json({ error: "Invalid caption or logo position" });
+
return;
}
+
const normalizedFontScale = Math.max(60, Math.min(160, Number(caption_font_scale) || 100));
let logo_path: string | null = null;
let outro_path: string | null = null;
let intro_path: string | null = null;
+
for (const [key, raw] of [["logo", req.body.logo_path], ["outro", req.body.outro_path], ["intro", req.body.intro_path]] as const) {
if (!raw) continue;
const resolved = await assetManager.resolve(raw);
+
if (!resolved) {
res.status(400).json({ error: `${key} not found: ${raw}` });
+
return;
}
+
if (key === "logo") logo_path = resolved;
else if (key === "outro") outro_path = resolved;
else intro_path = resolved;
}
+
// Validate each clip's timing
for (let i = 0; i < clips.length; i++) {
const c = clips[i];
const dur = (c.end_second || 0) - (c.start_second || 0);
+
if (dur <= 0) {
res.status(400).json({ error: `Clip ${i + 1}: end must be after start` });
+
return;
}
+
if (c.format && !["vertical", "horizontal", "square"].includes(c.format)) {
res.status(400).json({ error: `Clip ${i + 1}: invalid format "${c.format}". Use: vertical, horizontal, square` });
+
return;
}
+
const maxDur = maxClipSeconds(c.format || format);
+
if (dur > maxDur) {
res.status(400).json({
error: `Clip ${i + 1}: too long (${Math.round(dur)}s). Max ${maxDur}s.`,
});
+
return;
}
}
@@ -1505,12 +1731,15 @@ app.post("/api/batch-clips", async (req, res) => {
const enrichedClips = clips.map((c: ExportClip) => enrichClipFromSuggestion(c));
const batchHookError = exportHookError(enrichedClips);
+
if (batchHookError) {
res.status(400).json({ error: batchHookError });
+
return;
}
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "batch_clips",
@@ -1519,6 +1748,7 @@ app.post("/api/batch-clips", async (req, res) => {
message: "Starting batch...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
const historyRecorder = createBatchHistoryRecorder({
@@ -1561,12 +1791,15 @@ app.post("/api/batch-clips", async (req, res) => {
const progress = advanceProgress(job, event.percent);
job.message = event.message;
historyRecorder.recordProgress(event);
+
const clipResult = event.clip_result
? tagSubmittedClip(event.clip_result, enrichedClips)
: undefined;
+
if (event.stage === "clip_complete" && clipResult) {
(job.clip_results ??= []).push(clipResult);
}
+
broadcastSSE("job-update", {
jobId,
progress,
@@ -1585,6 +1818,7 @@ app.post("/api/batch-clips", async (req, res) => {
// Persist here too: the studio tab may be closed (an MCP-driven
// export), and it only stores results when it hears job-complete.
uiState.results = data?.results ?? [];
+
// Record successful clips to history
try {
await historyRecorder.recordRemaining(result.data?.results);
@@ -1593,6 +1827,7 @@ app.post("/api/batch-clips", async (req, res) => {
err: errMsg(err),
});
}
+
setExportState("done", null);
broadcastSSE("job-complete", { jobId, result: data });
})
@@ -1610,15 +1845,18 @@ function findFullEpisodeRenderer(): string | null {
join(paths.projectRoot, "remotion", "render-full-episode.mjs"),
join(paths.projectRoot, "runtime", "remotion", "render-full-episode.mjs"),
];
+
return candidates.find((candidate) => existsSync(candidate)) || null;
}
function reserveFullEpisodeOutput(videoPath: string): string {
const stem = fullEpisodeOutputStem(videoPath);
let candidate = join(paths.output, `${stem}.mp4`);
+
for (let suffix = 2; existsSync(candidate); suffix++) {
candidate = join(paths.output, `${stem}-${suffix}.mp4`);
}
+
return candidate;
}
@@ -1631,28 +1869,37 @@ app.post("/api/analyze-silence", async (req, res) => {
min_silence_seconds = 0.65,
padding_seconds = 0.12,
} = req.body || {};
- const sourcePath = resolveAllowedSource(video_path);
+
+ const sourcePath = resolveAllowedSource(stringValue.safeParse(video_path).data);
+
if (!sourcePath) {
res.status(400).json({ error: "Select a local episode first" });
+
return;
}
+
if (!Array.isArray(transcript_words) || transcript_words.length === 0) {
res.status(400).json({ error: "Transcribe the episode before removing silence" });
+
return;
}
+
const normalizedThreshold = Number(threshold);
const normalizedPause = Number(min_silence_seconds);
const normalizedPadding = Number(padding_seconds);
+
if (
!Number.isFinite(normalizedThreshold) || normalizedThreshold < 0.25 || normalizedThreshold > 0.8 ||
!Number.isFinite(normalizedPause) || normalizedPause < 0.3 || normalizedPause > 5 ||
!Number.isFinite(normalizedPadding) || normalizedPadding < 0.02 || normalizedPadding > 0.5
) {
res.status(400).json({ error: "Invalid silence-removal settings" });
+
return;
}
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "silence_analysis",
@@ -1661,6 +1908,7 @@ app.post("/api/analyze-silence", async (req, res) => {
message: "Preparing local silence analysis...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
res.json({ job_id: jobId, status: "running" });
@@ -1688,34 +1936,47 @@ app.post("/api/analyze-silence", async (req, res) => {
/** Render an approved keep plan locally, preserving the source and remapping captions. */
app.post("/api/render-silence-removed", async (req, res) => {
const { video_path, keep_segments, transcript } = req.body || {};
- const sourcePath = resolveAllowedSource(video_path);
+ const sourcePath = resolveAllowedSource(stringValue.safeParse(video_path).data);
+
if (!sourcePath) {
res.status(400).json({ error: "Source episode not found" });
+
return;
}
+
if (!Array.isArray(transcript?.words) || transcript.words.length === 0) {
res.status(400).json({ error: "Transcript is required to keep caption timing aligned" });
+
return;
}
+
if (!Array.isArray(keep_segments) || keep_segments.length === 0 || keep_segments.length > 5000) {
res.status(400).json({ error: "Invalid silence-removal plan" });
+
return;
}
+
const normalizedSegments: Array<{ start: number; end: number }> = [];
let previousEnd = 0;
+
for (const item of keep_segments) {
const start = Number(item?.start);
const end = Number(item?.end);
+
if (!Number.isFinite(start) || !Number.isFinite(end) || start < previousEnd || end <= start) {
res.status(400).json({ error: "Silence-removal ranges must be ordered and non-overlapping" });
+
return;
}
+
normalizedSegments.push({ start, end });
previousEnd = end;
}
+
await fileManager.ensureDirectories();
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "silence_render",
@@ -1724,6 +1985,7 @@ app.post("/api/render-silence-removed", async (req, res) => {
message: "Creating compact episode...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
res.json({ job_id: jobId, status: "running" });
@@ -1745,6 +2007,7 @@ app.post("/api/render-silence-removed", async (req, res) => {
job.progress = 100;
job.message = "Compact episode ready";
job.result = result.data;
+
if (result.data?.output_path) registerSourcePath(result.data.output_path);
}).catch((err) => {
job.status = "error";
@@ -1754,7 +2017,7 @@ app.post("/api/render-silence-removed", async (req, res) => {
});
/**
- * POST /api/export-full-episode — Burn captions into the complete current source.
+ * POST /api/export-full-episode: Burn captions into the complete current source.
*
* Full episodes bypass clip duration limits and retain the source dimensions.
* The renderer chunks its temporary alpha overlay to keep disk use bounded.
@@ -1769,38 +2032,52 @@ app.post("/api/export-full-episode", async (req, res) => {
logo_position = "top-left",
} = req.body || {};
- const sourcePath = resolveAllowedSource(video_path);
+ const sourcePath = resolveAllowedSource(stringValue.safeParse(video_path).data);
+
if (!sourcePath) {
res.status(400).json({ error: "Video file not found" });
+
return;
}
+
if (!Array.isArray(transcript_words) || transcript_words.length === 0) {
res.status(400).json({ error: "Transcribe the episode before exporting it with captions" });
+
return;
}
+
if (!FULL_EPISODE_CAPTION_STYLES.includes(caption_style)) {
res.status(400).json({ error: `Invalid caption style. Use: ${FULL_EPISODE_CAPTION_STYLES.join(", ")}` });
+
return;
}
+
if (!["auto", "upper", "center", "lower"].includes(caption_position) ||
!["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"].includes(logo_position)) {
res.status(400).json({ error: "Invalid caption or logo position" });
+
return;
}
+
const normalizedFontScale = Math.max(60, Math.min(160, Number(caption_font_scale) || 100));
let logoPath: string | null = null;
+
if (req.body.logo_path) {
logoPath = await assetManager.resolve(req.body.logo_path);
+
if (!logoPath) {
res.status(400).json({ error: `logo not found: ${req.body.logo_path}` });
+
return;
}
}
const renderer = findFullEpisodeRenderer();
+
if (!renderer) {
res.status(500).json({ error: "Full-episode renderer is not installed" });
+
return;
}
@@ -1810,6 +2087,7 @@ app.post("/api/export-full-episode", async (req, res) => {
writeFileSync(wordsPath, JSON.stringify({ words: transcript_words }), "utf-8");
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "full_episode",
@@ -1818,6 +2096,7 @@ app.post("/api/export-full-episode", async (req, res) => {
message: "Preparing full episode...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
res.json({ job_id: jobId, status: "running" });
@@ -1833,6 +2112,7 @@ app.post("/api/export-full-episode", async (req, res) => {
"--caption-font-scale", String(normalizedFontScale),
"--logo-position", logo_position,
];
+
if (caption_style === "branded" && logoPath) args.push("--logo", logoPath);
const child = spawn(process.execPath, args, {
@@ -1846,18 +2126,23 @@ app.post("/api/export-full-episode", async (req, res) => {
let stdoutCarry = "";
let stderrTail = "";
+
const consumeStdout = (text: string, flush = false) => {
stdoutCarry += text;
const lines = stdoutCarry.split(/\r?\n/);
stdoutCarry = flush ? "" : lines.pop() || "";
+
for (const line of lines) {
const update = parseFullEpisodeProgress(line);
+
if (!update) continue;
job.progress = Math.max(job.progress, update.percent);
job.message = update.message;
}
+
if (flush && stdoutCarry) {
const update = parseFullEpisodeProgress(stdoutCarry);
+
if (update) {
job.progress = Math.max(job.progress, update.percent);
job.message = update.message;
@@ -1873,17 +2158,22 @@ app.post("/api/export-full-episode", async (req, res) => {
job.status = "error";
job.error = err.message;
job.message = `Error: ${err.message}`;
+
try { await unlink(wordsPath); } catch { /* best effort */ }
});
child.on("close", async (code) => {
consumeStdout("", true);
+
try { await unlink(wordsPath); } catch { /* best effort */ }
+
if (job.status === "error") return;
+
if (code !== 0 || !existsSync(outputPath)) {
const detail = stderrTail.trim().split(/\r?\n/).slice(-4).join("\n");
job.status = "error";
job.error = detail || `Renderer exited with code ${code}`;
job.message = `Error: ${job.error}`;
+
return;
}
@@ -1901,25 +2191,30 @@ app.post("/api/export-full-episode", async (req, res) => {
});
/**
- * GET /api/job/:id — Poll job status + progress
+ * GET /api/job/:id: Poll job status + progress
*/
app.get("/api/job/:id", (req, res) => {
const job = jobs.get(req.params.id);
+
if (!job) {
res.status(404).json({ error: "Job not found" });
+
return;
}
+
res.json(job);
});
/**
- * GET /api/job/:id/stream — SSE progress stream
+ * GET /api/job/:id/stream: SSE progress stream
*/
app.get("/api/job/:id/stream", (req, res) => {
const jobId = req.params.id;
const job = jobs.get(jobId);
+
if (!job) {
res.status(404).json({ error: "Job not found" });
+
return;
}
@@ -1929,14 +2224,12 @@ app.get("/api/job/:id/stream", (req, res) => {
Connection: "keep-alive",
});
- const interval = setInterval(() => {
+ let closeTimer: NodeJS.Timeout | undefined;
+
+ const write = (): boolean => {
const current = jobs.get(jobId);
- if (!current) {
- clearInterval(interval);
- res.end();
- return;
- }
+ if (!current) return false;
res.write(
`data: ${JSON.stringify({
status: current.status,
@@ -1948,17 +2241,35 @@ app.get("/api/job/:id/stream", (req, res) => {
})}\n\n`,
);
- if (current.status === "done" || current.status === "error") {
- clearInterval(interval);
- setTimeout(() => res.end(), 500);
+ return current.status === "done" || current.status === "error";
+ };
+
+ const cleanup = () => {
+ jobEvents.off(jobId, send);
+ clearTimeout(closeTimer);
+ };
+
+ function send() {
+ const terminal = write();
+
+ if (terminal && !closeTimer) {
+ // Some handlers set status before result, across an await. Hold the
+ // stream briefly and send the settled job once more.
+ closeTimer = setTimeout(() => {
+ write();
+ cleanup();
+ res.end();
+ }, 500);
}
- }, 500);
+ }
- req.on("close", () => clearInterval(interval));
+ jobEvents.on(jobId, send);
+ req.on("close", cleanup);
+ send();
});
/**
- * GET /api/outputs — List finished clips
+ * GET /api/outputs: List finished clips
*/
/**
* Workspace-wide performance, for signed-in users.
@@ -1970,12 +2281,14 @@ app.get("/api/job/:id/stream", (req, res) => {
app.get("/api/pro/insights", async (_req, res) => {
try {
const cloud = await import("../services/podcli-cloud.js");
+
if (!(await cloud.signedIn())) return res.json({ signedIn: false });
const [insights, preferences] = await Promise.all([
cloud.getInsights(),
cloud.getPreferences(),
]);
+
res.json({ signedIn: true, insights, preferences });
} catch (err) {
// A workspace that can't be reached must not break the local analytics the
@@ -1987,6 +2300,7 @@ app.get("/api/pro/insights", async (_req, res) => {
app.get("/api/pro/account", async (_req, res) => {
try {
const cloud = await import("../services/podcli-cloud.js");
+
if (!(await cloud.signedIn())) return res.json({ signedIn: false });
const me = await cloud.whoami();
res.json({
@@ -2010,11 +2324,13 @@ app.get("/api/outputs", async (_req, res) => {
// its main clip. Fold it into that clip's entry instead of listing it
// as a second, unrelated-looking clip.
const cleanByStem = new Map<string, string>();
+
for (const f of mp4Files) {
if (f.endsWith("_clean.mp4")) {
cleanByStem.set(f.slice(0, -"_clean.mp4".length), f);
}
}
+
const clips = mp4Files
.filter((f) => !f.endsWith("_clean.mp4"))
.map((f) => {
@@ -2022,6 +2338,7 @@ app.get("/api/outputs", async (_req, res) => {
const stat = statSync(fullPath);
const stem = f.slice(0, -".mp4".length);
const cleanFilename = cleanByStem.get(stem);
+
return {
filename: f,
path: fullPath,
@@ -2033,6 +2350,7 @@ app.get("/api/outputs", async (_req, res) => {
.sort(
(a, b) => new Date(b.created).getTime() - new Date(a.created).getTime(),
);
+
res.json(clips);
} catch {
res.json([]);
@@ -2040,34 +2358,44 @@ app.get("/api/outputs", async (_req, res) => {
});
/**
- * GET /api/download/:filename — Download a finished clip
+ * GET /api/download/:filename: Download a finished clip
*/
app.get("/api/download/:filename", (req, res) => {
const filePath = safePath(paths.output, req.params.filename);
+
if (!filePath) {
res.status(400).json({ error: "Invalid filename" });
+
return;
}
+
if (!existsSync(filePath)) {
res.status(404).json({ error: "File not found" });
+
return;
}
+
res.download(filePath);
});
/**
- * GET /api/preview/:filename — Stream a video clip for in-browser playback
+ * GET /api/preview/:filename: Stream a video clip for in-browser playback
*/
app.get("/api/preview/:filename", (req, res) => {
const filePath = safePath(paths.output, req.params.filename);
+
if (!filePath) {
res.status(400).json({ error: "Invalid filename" });
+
return;
}
+
if (!existsSync(filePath)) {
res.status(404).json({ error: "File not found" });
+
return;
}
+
streamVideo(req, res, filePath);
});
@@ -2082,31 +2410,42 @@ async function serveClipById(
mode: "preview" | "download",
) {
const entry = await clipsHistory.findById(id);
+
if (!entry || !entry.output_path) {
res.status(404).json({ error: "Clip not found" });
+
return;
}
+
let real: string;
+
try {
real = realpathSync(entry.output_path);
} catch {
res.status(404).json({ error: "File no longer exists" });
+
return;
}
+
if (!statSync(real).isFile() || !/\.(mp4|mov|mkv|webm)$/i.test(real)) {
res.status(400).json({ error: "Unsupported clip file" });
+
return;
}
+
if (mode === "download") {
res.download(real);
+
return;
}
- const mimeTypes: Record<string, string> = {
- ".webm": "video/webm",
- ".mov": "video/quicktime",
- ".mkv": "video/x-matroska",
- };
- streamVideo(req, res, real, mimeTypes[extname(real).toLowerCase()] || "video/mp4");
+
+ const mimeTypes = new Map([
+ [".webm", "video/webm"],
+ [".mov", "video/quicktime"],
+ [".mkv", "video/x-matroska"],
+ ]);
+
+ streamVideo(req, res, real, mimeTypes.get(extname(real).toLowerCase()) || "video/mp4");
}
app.get("/api/clips/:id/preview", (req, res) => {
@@ -2118,65 +2457,75 @@ app.get("/api/clips/:id/download", (req, res) => {
});
/**
- * GET /api/stream-source — Stream the source video for in-browser preview
+ * GET /api/stream-source: Stream the source video for in-browser preview
* Accepts ?path= query param (must be a file previously validated via /select-file or /upload)
*/
app.get("/api/stream-source", (req, res) => {
- const filePath = req.query.path as string;
+ const filePath = stringValue.safeParse(req.query.path).data;
+
if (!filePath || !existsSync(filePath)) {
res.status(404).json({ error: "File not found" });
+
return;
}
// Extension gate: only media/image types stream, so this never serves
// .env/key/token files regardless of the path checks below.
- const mediaMime: Record<string, string> = {
- ".mp4": "video/mp4",
- ".m4v": "video/mp4",
- ".webm": "video/webm",
- ".mov": "video/quicktime",
- ".avi": "video/x-msvideo",
- ".mkv": "video/x-matroska",
- ".mp3": "audio/mpeg",
- ".wav": "audio/wav",
- ".m4a": "audio/mp4",
- ".aac": "audio/aac",
- ".flac": "audio/flac",
- ".aif": "audio/aiff",
- ".aiff": "audio/aiff",
- ".mts": "video/mp2t",
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".webp": "image/webp",
- ".gif": "image/gif",
- ".svg": "image/svg+xml",
- };
- const mime = mediaMime[extname(filePath).toLowerCase()];
+ const mediaMime = new Map([
+ [".mp4", "video/mp4"],
+ [".m4v", "video/mp4"],
+ [".webm", "video/webm"],
+ [".mov", "video/quicktime"],
+ [".avi", "video/x-msvideo"],
+ [".mkv", "video/x-matroska"],
+ [".mp3", "audio/mpeg"],
+ [".wav", "audio/wav"],
+ [".m4a", "audio/mp4"],
+ [".aac", "audio/aac"],
+ [".flac", "audio/flac"],
+ [".aif", "audio/aiff"],
+ [".aiff", "audio/aiff"],
+ [".mts", "video/mp2t"],
+ [".png", "image/png"],
+ [".jpg", "image/jpeg"],
+ [".jpeg", "image/jpeg"],
+ [".webp", "image/webp"],
+ [".gif", "image/gif"],
+ [".svg", "image/svg+xml"],
+ ]);
+
+ const mime = mediaMime.get(extname(filePath).toLowerCase());
+
if (!mime) {
res.status(403).json({ error: "Access denied: unsupported media type" });
+
return;
}
// realpath defeats symlinks pointing outside the allowed set.
let resolvedPath: string;
+
try {
resolvedPath = realpathSync(path.resolve(filePath));
} catch {
res.status(404).json({ error: "File not found" });
+
return;
}
const uploadsRoot = path.resolve(join(paths.working, "uploads"));
const relativeToUploads = path.relative(uploadsRoot, resolvedPath);
+
const isUploadedFile =
relativeToUploads !== "" &&
!relativeToUploads.startsWith("..") &&
!path.isAbsolute(relativeToUploads);
+
if (!allowedSourcePaths.has(resolvedPath) && !isUploadedFile) {
res
.status(403)
.json({ error: "Access denied: path not in allowed sources" });
+
return;
}
@@ -2187,15 +2536,23 @@ app.get("/api/stream-source", (req, res) => {
// path (a direct read here can miss it under the launcher's data dir).
app.get("/api/thumbnail-config", async (_req, res) => {
const r = await runCli(["thumbnail-config", "show"]);
- if (r.code !== 0) { res.json({}); return; }
+
+ if (r.code !== 0) {
+ res.json({});
+
+ return;
+ }
+
try { res.json(JSON.parse(r.stdout)); } catch { res.json({}); }
});
app.put("/api/thumbnail-config", async (req, res) => {
const tmp = join(tmpdir(), `podcli-tc-${uuidv4().slice(0, 8)}.json`);
+
try {
writeFileSync(tmp, JSON.stringify(req.body || {}), "utf-8");
const r = await runCli(["thumbnail-config", "import", tmp]);
+
if (r.code !== 0) throw new Error(stripAnsi(r.stderr || r.stdout) || "save failed");
res.json({ ok: true });
} catch (e: any) {
@@ -2207,40 +2564,70 @@ app.put("/api/thumbnail-config", async (req, res) => {
app.get("/api/thumbnail-config/export", async (_req, res) => {
const r = await runCli(["thumbnail-config", "show"]);
- if (r.code !== 0) { res.status(500).json({ error: "export failed" }); return; }
+
+ if (r.code !== 0) { res.status(500).json({
+ error: "export failed" });
+
+ return;
+ }
+
res.setHeader("Content-Disposition", 'attachment; filename="thumbnail-config.json"');
res.type("application/json").send(r.stdout);
});
app.post("/api/thumbnail-config/reset", async (_req, res) => {
const r = await runCli(["thumbnail-config", "reset"]);
- if (r.code !== 0) { res.status(500).json({ error: stripAnsi(r.stderr || r.stdout) || "reset failed" }); return; }
+
+ if (r.code !== 0) { res.status(500).json({
+ error: stripAnsi(r.stderr || r.stdout) || "reset failed" });
+
+ return;
+ }
+
res.json({ ok: true });
});
app.get("/api/image", (req, res) => {
- const raw = req.query.path as string;
- const mimes: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif" };
- const mime = raw ? mimes[extname(raw).toLowerCase()] : undefined;
- if (!mime) {
+ const raw = stringValue.safeParse(req.query.path).data;
+
+ const mimes = new Map([
+ [".png", "image/png"],
+ [".jpg", "image/jpeg"],
+ [".jpeg", "image/jpeg"],
+ [".webp", "image/webp"],
+ [".gif", "image/gif"],
+ ]);
+
+ const mime = raw ? mimes.get(extname(raw).toLowerCase()) : undefined;
+
+ if (!raw || !mime) {
res.status(403).json({ error: "unsupported type" });
+
return;
}
+
// realpath defeats symlinks pointing outside the allowed roots; home is
// excluded so the integrations/token files under it are never servable.
let resolved: string;
+
try {
resolved = realpathSync(path.resolve(raw));
} catch {
res.status(404).json({ error: "not found" });
+
return;
}
+
const allowedRoots = [paths.output, paths.working, paths.assets].map((p) => path.resolve(p));
+
if (DEMO) allowedRoots.push(path.resolve(DEMO_ASSETS_DIR));
+
if (!allowedRoots.some((root) => resolved === root || resolved.startsWith(root + path.sep))) {
res.status(403).json({ error: "access denied" });
+
return;
}
+
res.writeHead(200, { "Content-Type": mime, "Cache-Control": "no-cache" });
const stream = createReadStream(resolved);
stream.on("error", () => res.destroy());
@@ -2251,11 +2638,12 @@ registerConfigIntegrationRoutes(app, { executor, uploadDir });
// --- Transcript export (SRT/VTT) ---
app.get("/api/export-transcript", (_req, res) => {
- const format = (_req.query.format as string) || "srt";
+ const format = stringValue.safeParse(_req.query.format).data || "srt";
const transcript = uiState.transcript;
if (!transcript?.words?.length) {
res.status(400).json({ error: "No transcript available" });
+
return;
}
@@ -2264,6 +2652,7 @@ app.get("/api/export-transcript", (_req, res) => {
// Group words into subtitle lines (~8 words each)
const lineSize = 8;
const lines: Array<{ text: string; start: number; end: number }> = [];
+
for (let i = 0; i < words.length; i += lineSize) {
const chunk = words.slice(i, i + lineSize);
lines.push({
@@ -2305,13 +2694,16 @@ app.get("/api/export-transcript", (_req, res) => {
// --- Analyze audio energy ---
app.post("/api/analyze-energy", async (req, res) => {
const { video_path, segments } = req.body;
+
if (!video_path)
return res.status(400).json({ error: "video_path required" });
+
try {
const result = await executor.execute("analyze_energy", {
video_path,
segments: segments || [],
});
+
res.json(result.data || {});
} catch (err: any) {
res.status(500).json({ error: err.message });
@@ -2319,53 +2711,75 @@ app.post("/api/analyze-energy", async (req, res) => {
});
// --- Highlight reel: detect once, then iterate on moments ---
+const reelPayloadSchema = z.looseObject({
+ source: z.string().optional(),
+ sources: z.array(z.string()).optional(),
+ reel_path: z.string().optional(),
+ moments: z
+ .array(z.looseObject({ clip_path: z.string().optional(), clip_exists: z.boolean().optional() }))
+ .optional(),
+});
+
app.post("/api/reel", async (req, res) => {
try {
const result = await executor.execute("manage_reel", req.body || {});
- const data = (result.data || {}) as any;
- if (typeof data.source === "string") registerSourcePath(data.source);
- if (Array.isArray(data.sources)) {
- for (const s of data.sources) if (typeof s === "string") registerSourcePath(s);
- }
- if (typeof data.reel_path === "string") registerSourcePath(data.reel_path);
- if (Array.isArray(data.moments)) {
- for (const m of data.moments) {
- if (m && typeof m.clip_path === "string" && m.clip_exists) registerSourcePath(m.clip_path);
- }
+ const data = result.data || {};
+ const reel = reelPayloadSchema.safeParse(data).data;
+
+ if (reel?.source) registerSourcePath(reel.source);
+
+ for (const s of reel?.sources ?? []) registerSourcePath(s);
+
+ if (reel?.reel_path) registerSourcePath(reel.reel_path);
+
+ for (const m of reel?.moments ?? []) {
+ if (m.clip_path && m.clip_exists) registerSourcePath(m.clip_path);
}
+
res.json(data);
- } catch (err: any) {
- res.status(500).json({ error: err.message });
+ } catch (err: unknown) {
+ res.status(500).json({ error: errMsg(err) });
}
});
app.get("/api/reel-download", (req, res) => {
- const filePath = req.query.path as string;
+ const filePath = stringValue.safeParse(req.query.path).data;
+
if (!filePath) {
res.status(400).json({ error: "path required" });
+
return;
}
+
let resolved: string;
+
try {
resolved = realpathSync(path.resolve(filePath));
} catch {
res.status(404).json({ error: "File not found" });
+
return;
}
+
if (extname(resolved).toLowerCase() !== ".mp4" || !allowedSourcePaths.has(resolved)) {
res.status(403).json({ error: "Access denied" });
+
return;
}
+
res.download(resolved);
});
// --- Multicam: map sources, sync, cut, render one recording ---
const MULTICAM_JOB_ACTIONS = new Set(["sync", "plan", "render", "preview", "cloud", "pull"]);
+
// activity saves the session when it refreshes its cache, so it waits for jobs like any write.
const MULTICAM_WRITE_ACTIONS = new Set(["map", "cut", "set_cuts", "export", "import_timeline", "delete", "activity", ...MULTICAM_JOB_ACTIONS]);
const multicamPreviewDir = join(paths.working, "multicam");
+
// A multi-hour, multi-camera render outlasts the default one-hour task limit.
-const multicamExecutor = new PythonExecutor(8 * 3600_000);
+const multicamExecutor = createExecutor(8 * 3600_000);
+
// A job holds its session for minutes to hours and saves it when done; any
// other write in between would be overwritten, so writes wait their turn.
const multicamRunning = new Map<string, { id: string; action: string }>();
@@ -2379,6 +2793,7 @@ type MulticamPayload = {
// A render that finished with warnings says so in the job's status line, which is what job_status shows first.
function multicamDoneMessage(data: MulticamPayload | undefined): string {
const warnings = data?.outputs?.validation?.warnings || [];
+
return warnings.length ? `Done with ${warnings.length} warning(s): ${warnings.join(" ")}` : "Done";
}
@@ -2390,16 +2805,19 @@ function allowMulticamPaths(data: MulticamPayload | undefined): void {
function withActiveJob(data: MulticamPayload | undefined): MulticamPayload {
const running = data?.session_id ? multicamRunning.get(data.session_id) : undefined;
+
return running ? { ...data, active_job: running } : data || {};
}
app.post("/api/multicam", async (req, res) => {
const body = req.body || {};
const action = String(body.action || "show");
- const sessionId = typeof body.session_id === "string" ? body.session_id : "";
+ const sessionId = stringValue.safeParse(body.session_id).data ?? "";
const running = multicamRunning.get(sessionId);
+
if (running && MULTICAM_WRITE_ACTIONS.has(action)) {
res.status(409).json({ error: `This edit is busy (${running.action}). Wait for it to finish, then try again.` });
+
return;
}
@@ -2411,10 +2829,12 @@ app.post("/api/multicam", async (req, res) => {
} catch (err) {
res.status(400).json({ error: errMsg(err) });
}
+
return;
}
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "multicam",
@@ -2423,6 +2843,7 @@ app.post("/api/multicam", async (req, res) => {
message: "Starting...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
multicamRunning.set(sessionId, { id: jobId, action });
res.json({ job_id: jobId, status: "running" });
@@ -2448,15 +2869,19 @@ app.post("/api/multicam", async (req, res) => {
// Camera stills podcli made for an edit; nothing outside its working folder.
app.get("/api/multicam/image", (req, res) => {
let resolved: string | null = null;
+
try {
// Python reports resolved paths (/private/tmp on macOS), so compare real paths on both sides.
const root = realpathSync(multicamPreviewDir);
resolved = safePath(root, path.relative(root, realpathSync(String(req.query.path || ""))));
} catch {}
+
if (!resolved || extname(resolved).toLowerCase() !== ".jpg") {
res.status(404).json({ error: "Preview not found" });
+
return;
}
+
res.sendFile(resolved);
});
@@ -2464,16 +2889,21 @@ app.get("/api/multicam/image", (req, res) => {
// route can't turn a path registered elsewhere into a readable file.
app.get("/api/multicam/file", (req, res) => {
let resolved: string | null = null;
+
try {
const root = realpathSync(paths.output);
const real = realpathSync(String(req.query.path || ""));
const inside = safePath(root, path.relative(root, real));
+
if (inside && path.basename(path.dirname(inside)).endsWith("_multicam_podcli")) resolved = inside;
} catch {}
+
if (!resolved || ![".mp4", ".xml", ".fcpxml", ".wav"].includes(extname(resolved).toLowerCase())) {
res.status(403).json({ error: "Access denied" });
+
return;
}
+
res.download(resolved);
});
@@ -2489,14 +2919,23 @@ app.get("/api/encoder-info", async (_req, res) => {
// --- Speaker Detection Status ---
app.get("/api/speaker-status", (_req, res) => {
- if (DEMO) { res.json({ configured: true, setup_url: "", token_url: "" }); return; }
+ if (DEMO) { res.json({
+ configured: true, setup_url: "", token_url: "" });
+
+ return;
+ }
+
let token = process.env.HF_TOKEN || "";
+
for (const envPath of [paths.envFile, join(process.cwd(), ".env")]) {
if (token) break;
+
if (!existsSync(envPath)) continue;
const match = readFileSync(envPath, "utf-8").match(/^HF_TOKEN=(.+)$/m);
+
if (match) token = match[1].trim();
}
+
res.json({
configured: !!token,
setup_url: "https://huggingface.co/pyannote/speaker-diarization-3.1",
@@ -2516,6 +2955,7 @@ app.get("/api/presets", async (_req, res) => {
app.post("/api/presets", async (req, res) => {
const { action, name, config } = req.body;
+
try {
const result = await executor.execute("presets", { action, name, config });
res.json(result.data || {});
@@ -2527,15 +2967,18 @@ app.post("/api/presets", async (req, res) => {
// --- Assets ---
function uniqueAssetName(base: string, taken: Set<string>): string {
const slug = (base || "asset").replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+|-+$/g, "") || "asset";
+
if (!taken.has(slug)) return slug;
let i = 2;
+
while (taken.has(`${slug}-${i}`)) i++;
+
return `${slug}-${i}`;
}
app.get("/api/assets", async (req, res) => {
try {
- const items = await assetManager.list(req.query.type as string | undefined);
+ const items = await assetManager.list(stringValue.safeParse(req.query.type).data);
res.json(items);
} catch (err: unknown) {
res.status(500).json({ error: errMsg(err) });
@@ -2544,6 +2987,7 @@ app.get("/api/assets", async (req, res) => {
app.post("/api/assets/register", async (req, res) => {
const { name, path: filePath, type } = req.body;
+
try {
const asset = await assetManager.register(name, filePath, type || inferType(filePath));
broadcastSSE("assets-updated", { name });
@@ -2556,13 +3000,15 @@ app.post("/api/assets/register", async (req, res) => {
app.post("/api/assets/upload", upload.single("file"), async (req, res) => {
if (!req.file) {
res.status(400).json({ error: "No file uploaded" });
+
return;
}
+
try {
const existing = new Set((await assetManager.list()).map((a) => a.name));
- const wanted = safeName((req.body?.name as string) || basename(req.file.originalname, extname(req.file.originalname)));
+ const wanted = safeName(stringValue.safeParse(req.body?.name).data || basename(req.file.originalname, extname(req.file.originalname)));
const name = existing.has(wanted) && !req.body?.overwrite ? uniqueAssetName(wanted, existing) : wanted;
- const type = (req.body?.type as AssetType) || inferType(req.file.originalname);
+ const type = assetTypeSchema.safeParse(req.body?.type).data ?? inferType(req.file.originalname);
const asset = await assetManager.importFile(req.file.path, name, type);
broadcastSSE("assets-updated", { name });
res.json(asset);
@@ -2575,13 +3021,17 @@ app.post("/api/assets/upload", upload.single("file"), async (req, res) => {
app.post("/api/assets/url", async (req, res) => {
let url: string;
+
try {
url = await validateDownloadUrl(req.body?.url);
} catch (err: unknown) {
res.status(400).json({ error: errMsg(err) });
+
return;
}
+
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "download_video",
@@ -2590,15 +3040,16 @@ app.post("/api/assets/url", async (req, res) => {
message: "Downloading asset",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
res.json({ job_id: jobId });
(async () => {
try {
const existing = new Set((await assetManager.list()).map((a) => a.name));
- const wanted = safeName((req.body?.name as string) || basename(new URL(url).pathname) || "asset");
+ const wanted = safeName(stringValue.safeParse(req.body?.name).data || basename(new URL(url).pathname) || "asset");
const name = existing.has(wanted) ? uniqueAssetName(wanted, existing) : wanted;
- const type = req.body?.type as AssetType | undefined;
+ const type = assetTypeSchema.safeParse(req.body?.type).data;
const asset = await assetManager.importUrl(url, name, type);
job.status = "done";
job.progress = 100;
@@ -2645,16 +3096,20 @@ app.post("/api/assets/:name/rename", async (req, res) => {
app.get("/api/assets/:name/download", async (req, res) => {
try {
- // Look up by registered name only — never fall through to treating the
+ // Look up by registered name only: never fall through to treating the
// param as a filesystem path (that would allow arbitrary file reads).
const asset = (await assetManager.list()).find((a) => a.name === req.params.name);
+
if (!asset || !existsSync(asset.path)) {
res.status(404).json({ error: `Asset "${req.params.name}" not found` });
+
return;
}
+
if (req.query.dl) {
res.download(asset.path, basename(asset.path));
} else {
+ if (extname(asset.path).toLowerCase() === ".svg") res.setHeader("Content-Security-Policy", "sandbox");
res.sendFile(asset.path);
}
} catch (err: unknown) {
@@ -2687,26 +3142,29 @@ app.get("/api/sources", (_req, res) => {
const items = recentSources
.map((p) => ({ path: p, name: basename(p), exists: existsSync(p) }))
.filter((s) => s.exists);
+
res.json(items);
});
// --- Clip History ---
app.get("/api/history", async (req, res) => {
try {
- const source = req.query.source as string | undefined;
- const limit = parseInt(req.query.limit as string) || 50;
+ const source = stringValue.safeParse(req.query.source).data;
+ const limit = parseInt(stringValue.safeParse(req.query.limit).data ?? "") || 50;
+
const entries = source
? await clipsHistory.getBySource(source)
: await clipsHistory.list(limit);
+
res.json(entries);
- } catch (err: any) {
+ } catch {
res.json([]);
}
});
// Clip edits route through the Python CLI so the web UI and `podcli clips`
// share one history writer (preserves unknown fields like Phase 2 metrics).
-const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "").trim();
+const stripAnsi = (s: string) => stripVTControlCharacters(s).trim();
const RUN_PY_TIMEOUT_MS = 15 * 60_000;
@@ -2717,14 +3175,17 @@ function runPy(scriptAndArgs: string[]): Promise<{ code: number; stdout: string;
env: pythonEnv({ PODCLI_HOME: paths.home, PODCLI_DATA: paths.dataDir }),
detached: process.platform !== "win32",
});
+
let stdout = "", stderr = "";
let settled = false;
+
const finish = (result: { code: number; stdout: string; stderr: string }) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(result);
};
+
const timer = setTimeout(() => {
terminateProcessTree(proc);
finish({
@@ -2733,6 +3194,7 @@ function runPy(scriptAndArgs: string[]): Promise<{ code: number; stdout: string;
stderr: `${stderr}\nTimed out after ${RUN_PY_TIMEOUT_MS / 1000}s`.trim(),
});
}, RUN_PY_TIMEOUT_MS);
+
proc.stdout.on("data", (d) => (stdout += d));
proc.stderr.on("data", (d) => (stderr += d));
proc.on("close", (code) => finish({ code: code ?? 1, stdout, stderr }));
@@ -2744,11 +3206,13 @@ const runCli = (args: string[]) =>
runPy([join(paths.backendDir, "cli.py"), "--no-banner", ...args]);
const LOGO_POSITIONS = ["top-left", "top-right", "bottom-left", "bottom-right"] as const;
+
type LogoPosition = (typeof LOGO_POSITIONS)[number];
function logoOverlayExpr(position: string, margin = 108): string {
const x = position.endsWith("right") ? `main_w-overlay_w-${margin}` : String(margin);
const y = position.startsWith("bottom") ? `main_h-overlay_h-${margin}` : String(margin);
+
return `${x}:${y}`;
}
@@ -2757,16 +3221,19 @@ function runFfmpeg(args: string[], timeoutMs = 120_000): Promise<{ code: number;
const proc = spawn(paths.ffmpegPath, args, { detached: process.platform !== "win32" });
let stdout = "", stderr = "";
let settled = false;
+
const finish = (result: { code: number; stdout: string; stderr: string }) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(result);
};
+
const timer = setTimeout(() => {
terminateProcessTree(proc);
finish({ code: 1, stdout, stderr: `${stderr}\nTimed out after ${timeoutMs / 1000}s`.trim() });
}, timeoutMs);
+
proc.stdout.on("data", (d) => (stdout += d));
proc.stderr.on("data", (d) => (stderr += d));
proc.on("close", (code) => finish({ code: code ?? 1, stdout, stderr }));
@@ -2774,11 +3241,14 @@ function runFfmpeg(args: string[], timeoutMs = 120_000): Promise<{ code: number;
});
}
-async function resolveLogoPath(input: unknown): Promise<string | null> {
- const raw = String(input || "").trim();
+async function resolveLogoPath(input: string | undefined): Promise<string | null> {
+ const raw = (input ?? "").trim();
+
if (!raw) return null;
const resolvedLogo = await assetManager.resolve(raw);
+
if (!resolvedLogo || !existsSync(resolvedLogo)) return null;
+
return resolvedLogo;
}
@@ -2789,57 +3259,83 @@ async function bakeThumbnailCard(clipPath: string, image: string, stripStart = 0
"bake-thumbnail", clipPath, image, "--position", "start",
...(stripStart ? ["--strip-start", String(stripStart)] : []),
]);
+
return r.code === 0 ? { ok: true } : { ok: false, error: stripAnsi(r.stderr || r.stdout) };
}
app.patch("/api/clips/:id", async (req, res) => {
- if (DEMO) { res.json({ ok: true }); return; } // fixtures are read-only
+ if (DEMO) { res.json({ ok: true });
+
+ return; } // fixtures are read-only
+
const { title, caption_style, thumbnail_config } = req.body || {};
const args = ["clips", "edit", req.params.id];
+
if (title != null) args.push(`--title=${title}`);
+
if (caption_style != null) args.push("--caption-style", String(caption_style));
+
if (thumbnail_config != null) args.push("--thumbnail-config", JSON.stringify(thumbnail_config));
+
if (args.length === 3) {
res.status(400).json({ error: "nothing to update" });
+
return;
}
+
const r = await runCli(args);
+
if (r.code !== 0) {
res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "edit failed" });
+
return;
}
+
res.json({ ok: true });
});
app.delete("/api/clips/:id", async (req, res) => {
- if (DEMO) { res.json({ ok: true }); return; } // fixtures are read-only
+ if (DEMO) { res.json({ ok: true });
+
+ return; } // fixtures are read-only
+
const r = await runCli(["clips", "delete", req.params.id, "--yes"]);
+
if (r.code !== 0) {
res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "delete failed" });
+
return;
}
+
broadcastSSE("history-updated", { jobId: null, count: 1 });
res.json({ ok: true });
});
app.post("/api/clips/:id/reopen", async (req, res) => {
const r = await runCli(["clips", "reopen", req.params.id]);
+
if (r.code !== 0) {
res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "reopen failed" });
+
return;
}
+
res.json({ ok: true });
});
app.post("/api/clips/:id/thumbnail", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
+
if (!clip) {
res.status(404).json({ error: "clip not found" });
+
return;
}
+
const tc = clip.thumbnail_config || {};
- // Standalone thumbnail generation — produces variation PNGs, never touches the clip video.
+ // Standalone thumbnail generation: produces variation PNGs, never touches the clip video.
const outDir = join(paths.output, "thumbnails", String(clip.id));
+
// Free-text values ride behind "--" (positionals) or as --flag=value so a
// title starting with "-" can't be parsed as an option.
const args = [
@@ -2851,31 +3347,44 @@ app.post("/api/clips/:id/thumbnail", async (req, res) => {
"--start", String(clip.start_second),
"--end", String(clip.end_second),
];
+
if (tc.image_path) args.push("--photo", String(tc.image_path));
- else if (typeof tc.timestamp === "number") args.push("--timestamp", String(tc.timestamp));
+ else if (numberValue.safeParse(tc.timestamp).success) args.push("--timestamp", String(tc.timestamp));
+
if (tc.line1) args.push(`--line1=${tc.line1}`);
+
if (tc.line2) args.push(`--line2=${tc.line2}`);
args.push("--", tc.text || clip.title);
const r = await runCli(args);
+
if (r.code !== 0) {
res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "thumbnail failed" });
+
return;
}
+
const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));
let variations: string[] = [];
+
try { variations = JSON.parse(jsonLine || "{}").paths || []; } catch { /* no paths */ }
+
if (variations.length === 0) {
res.status(500).json({ error: "no thumbnails generated" });
+
return;
}
+
// Bake the chosen thumbnail into the clip as the opening card (stripping any prior card).
if (existsSync(clip.output_path)) {
const bake = await bakeThumbnailCard(clip.output_path, variations[0], clip.thumbnail_config?.card_seconds || 0);
+
if (!bake.ok) {
res.status(500).json({ error: `thumbnail generated but bake into clip failed: ${bake.error}` });
+
return;
}
}
+
const merged = { ...tc, preview_path: variations[0], variations, card_seconds: 1.5 };
await runCli(["clips", "edit", String(clip.id), "--thumbnail-config", JSON.stringify(merged)]);
res.json({ ok: true, preview_path: variations[0], variations });
@@ -2883,20 +3392,32 @@ app.post("/api/clips/:id/thumbnail", async (req, res) => {
app.post("/api/clips/:id/thumbnail/select", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
- if (!clip) { res.status(404).json({ error: "clip not found" }); return; }
+
+ if (!clip) { res.status(404).json({
+ error: "clip not found" });
+
+ return;
+ }
+
const tc = clip.thumbnail_config || {};
const pick = String(req.body?.path || "");
+
if (!pick || !(tc.variations || []).includes(pick) || !existsSync(pick)) {
res.status(400).json({ error: "unknown variation" });
+
return;
}
+
if (existsSync(clip.output_path)) {
const bake = await bakeThumbnailCard(clip.output_path, pick, tc.card_seconds || 0);
+
if (!bake.ok) {
res.status(500).json({ error: `bake into clip failed: ${bake.error}` });
+
return;
}
}
+
await runCli(["clips", "edit", String(clip.id), "--thumbnail-config", JSON.stringify({ ...tc, preview_path: pick, card_seconds: 1.5 })]);
res.json({ ok: true, preview_path: pick });
});
@@ -2906,19 +3427,30 @@ app.post("/api/clips/:id/thumbnail/select", async (req, res) => {
// just the title. Empty for clips rendered before these fields existed.
function thumbnailGroundingArgs(clip: { payoff?: string; context_line?: string; preview_text?: string }): string[] {
const args: string[] = [];
+
if (clip.payoff) args.push("--payoff", clip.payoff);
+
if (clip.context_line) args.push("--context-line", clip.context_line);
+
if (clip.preview_text) args.push("--preview-text", clip.preview_text);
+
return args;
}
// Candidate headline texts + face frames for the two-step thumbnail picker.
app.get("/api/clips/:id/thumbnail/options", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
- if (!clip) { res.status(404).json({ error: "clip not found" }); return; }
+
+ if (!clip) { res.status(404).json({
+ error: "clip not found" });
+
+ return;
+ }
+
const tc = clip.thumbnail_config || {};
const clamp = (v: any, d: number) => Math.min(Math.max(parseInt(String(v)) || d, 1), 8);
const outDir = join(paths.output, "thumbnails", String(clip.id), "frames");
+
const r = await runCli([
"thumbnail-options",
"--output", outDir,
@@ -2930,13 +3462,22 @@ app.get("/api/clips/:id/thumbnail/options", async (req, res) => {
...thumbnailGroundingArgs(clip),
"--", tc.text || clip.title,
]);
- if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "options failed" }); return; }
+
+ if (r.code !== 0) { res.status(400).json({
+ error: stripAnsi(r.stderr || r.stdout) || "options failed" });
+
+ return;
+ }
+
const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));
+
try {
const parsed = JSON.parse(jsonLine || "{}");
+
if (!parsed.frames?.length && (parsed.texts?.length || 0) > 0) {
- parsed.warning = "No suitable frames found in this clip — try another moment or upload a frame.";
+ parsed.warning = "No suitable frames found in this clip: try another moment or upload a frame.";
}
+
res.json(parsed);
} catch { res.status(500).json({ error: "bad options output" }); }
});
@@ -2944,58 +3485,123 @@ app.get("/api/clips/:id/thumbnail/options", async (req, res) => {
// Render one final thumbnail from a chosen frame + headline (empty lines = AI writes the text).
app.post("/api/clips/:id/thumbnail/render", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
- if (!clip) { res.status(404).json({ error: "clip not found" }); return; }
+
+ if (!clip) { res.status(404).json({
+ error: "clip not found" });
+
+ return;
+ }
+
const tc = clip.thumbnail_config || {};
const { line1, line2, frame_path, frame_info, layout, swap } = req.body || {};
+
// The pair layout takes both people from the clip itself; a frame is only
// its fallback when two people cannot be told apart.
- if (!frame_path && needsFrame(layout)) { res.status(400).json({ error: "select a frame first" }); return; }
- // Only allow frames podcli itself produced (candidate frames) or the user uploaded —
+ if (!frame_path && needsFrame(layout)) { res.status(400).json({
+ error: "select a frame first" });
+
+ return;
+ }
+
+ // Only allow frames podcli itself produced (candidate frames) or the user uploaded:
// never an arbitrary server path passed through to the renderer.
const resolvedFrame = frame_path
? resolveFrameInRoots(frame_path, [join(paths.output, "thumbnails", String(clip.id)), uploadDir])
: null;
- if (frame_path && !resolvedFrame) { res.status(400).json({ error: "invalid frame" }); return; }
+
+ if (frame_path && !resolvedFrame) { res.status(400).json({
+ error: "invalid frame" });
+
+ return;
+ }
+
const outDir = join(paths.output, "thumbnails", String(clip.id));
await mkdir(outDir, { recursive: true });
const out = join(outDir, `thumb_${uuidv4().slice(0, 8)}.png`);
+
const args = thumbnailRenderArgs({
output: out, frame: resolvedFrame, frameInfo: frame_info,
line1, line2, layout, swap: !!swap, clip,
});
+
args.push(...thumbnailGroundingArgs(clip));
args.push("--", tc.text || clip.title);
const r = await runCli(args);
- if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "render failed" }); return; }
+
+ if (r.code !== 0) { res.status(400).json({
+ error: stripAnsi(r.stderr || r.stdout) || "render failed" });
+
+ return;
+ }
+
const { path: outPath, report } = parseThumbnailRender(r.stdout);
- if (!outPath || !existsSync(outPath)) { res.status(500).json({ error: "no thumbnail produced" }); return; }
+
+ if (!outPath || !existsSync(outPath)) { res.status(500).json({
+ error: "no thumbnail produced" });
+
+ return;
+ }
+
if (clip.output_path && existsSync(clip.output_path)) {
const bake = await bakeThumbnailCard(clip.output_path, outPath, tc.card_seconds || 0);
- if (!bake.ok) { res.status(500).json({ error: `rendered but bake into clip failed: ${bake.error}` }); return; }
+
+ if (!bake.ok) { res.status(500).json({
+ error: `rendered but bake into clip failed: ${bake.error}` });
+
+ return;
+ }
}
+
const merged = {
...tc, line1: line1 || undefined, line2: line2 || undefined, preview_path: outPath, card_seconds: 1.5,
layout: report.layout, people: report.people,
};
+
const edit = await runCli(["clips", "edit", String(clip.id), "--thumbnail-config", JSON.stringify(merged)]);
- if (edit.code !== 0) { res.status(500).json({ error: stripAnsi(edit.stderr || edit.stdout) || "thumbnail metadata update failed" }); return; }
+
+ if (edit.code !== 0) { res.status(500).json({
+ error: stripAnsi(edit.stderr || edit.stdout) || "thumbnail metadata update failed" });
+
+ return;
+ }
+
res.json({ ok: true, preview_path: outPath, ...report });
});
app.get("/api/clips/:id/logo/previews", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
- if (!clip) { res.status(404).json({ error: "clip not found" }); return; }
- if (!clip.output_path || !existsSync(clip.output_path)) { res.status(400).json({ error: "rendered file missing" }); return; }
- const logo = await resolveLogoPath(req.query.logo_path);
- if (!logo) { res.status(400).json({ error: "select a logo first" }); return; }
+
+ if (!clip) { res.status(404).json({
+ error: "clip not found" });
+
+ return;
+ }
+
+ if (!clip.output_path || !existsSync(clip.output_path)) { res.status(400).json({
+ error: "rendered file missing" });
+
+ return;
+ }
+
+ const logo = await resolveLogoPath(stringValue.safeParse(req.query.logo_path).data);
+
+ if (!logo) { res.status(400).json({
+ error: "select a logo first" });
+
+ return;
+ }
+
const baseVideo = clip.logo_backup_path && existsSync(clip.logo_backup_path)
? clip.logo_backup_path
: clip.output_path;
+
const outDir = join(paths.output, "logo-previews", String(clip.id));
await mkdir(outDir, { recursive: true });
const previews = [];
+
for (const position of LOGO_POSITIONS) {
const out = join(outDir, `${position}.jpg`);
+
const r = await runFfmpeg([
"-y",
"-ss", String(Math.max(0, Math.min(1, (clip.duration || 1) / 3))),
@@ -3007,42 +3613,77 @@ app.get("/api/clips/:id/logo/previews", async (req, res) => {
"-q:v", "3",
out,
]);
+
if (r.code !== 0 || !existsSync(out)) {
res.status(400).json({ error: stripAnsi(r.stderr) || "preview failed" });
+
return;
}
+
previews.push({ position, path: out });
}
+
res.json({ previews });
});
app.post("/api/clips/:id/logo", async (req, res) => {
- if (DEMO) { res.json({ ok: true }); return; }
+ if (DEMO) { res.json({
+ ok: true });
+
+ return;
+ }
+
const clip = await clipsHistory.findById(req.params.id);
- if (!clip) { res.status(404).json({ error: "clip not found" }); return; }
- if (!clip.output_path || !existsSync(clip.output_path)) { res.status(400).json({ error: "rendered file missing" }); return; }
+
+ if (!clip) { res.status(404).json({
+ error: "clip not found" });
+
+ return;
+ }
+
+ if (!clip.output_path || !existsSync(clip.output_path)) { res.status(400).json({
+ error: "rendered file missing" });
+
+ return;
+ }
+
const action = String(req.body?.action || "apply");
+
if (action === "remove") {
const backup = clip.logo_backup_path;
+
if (!backup || !existsSync(backup)) {
res.status(400).json({ error: "no logo backup available" });
+
return;
}
+
await copyFile(backup, clip.output_path);
await clipsHistory.update(clip.id, { logo_path: "", logo_backup_path: "", logo_position: "" });
broadcastSSE("history-updated", { jobId: null, count: 1 });
res.json({ ok: true, restored_from: backup });
+
return;
}
- const logo = await resolveLogoPath(req.body?.logo_path);
- if (!logo) { res.status(400).json({ error: "select a logo first" }); return; }
- const position = LOGO_POSITIONS.includes(req.body?.logo_position) ? req.body.logo_position as LogoPosition : "top-right";
+
+ const logo = await resolveLogoPath(stringValue.safeParse(req.body?.logo_path).data);
+
+ if (!logo) { res.status(400).json({
+ error: "select a logo first" });
+
+ return;
+ }
+
+ const position: LogoPosition = z.enum(LOGO_POSITIONS).catch("top-right").parse(req.body?.logo_position);
+
const backup = clip.logo_backup_path && existsSync(clip.logo_backup_path)
? clip.logo_backup_path
: `${clip.output_path}.pre-logo.mp4`;
+
if (!existsSync(backup)) await copyFile(clip.output_path, backup);
const baseVideo = existsSync(backup) ? backup : clip.output_path;
const tmp = `${clip.output_path}.logo-${process.pid}.mp4`;
+
const r = await runFfmpeg([
"-y",
"-i", baseVideo,
@@ -3058,10 +3699,13 @@ app.post("/api/clips/:id/logo", async (req, res) => {
"-movflags", "+faststart",
tmp,
], 15 * 60_000);
+
if (r.code !== 0 || !existsSync(tmp)) {
res.status(400).json({ error: stripAnsi(r.stderr) || "logo apply failed" });
+
return;
}
+
await rename(tmp, clip.output_path);
const size = statSync(clip.output_path).size / 1024 / 1024;
await clipsHistory.update(clip.id, {
@@ -3080,72 +3724,140 @@ const thumbStudioDir = join(paths.output, "thumbnails", "studio");
// realpath both sides so a symlink planted inside an allowed root can't point
// the renderer at a file outside it.
-function resolveFrameInRoots(framePath: unknown, roots: string[]): string | null {
+function resolveFrameInRoots(framePath: string, roots: string[]): string | null {
let real: string;
+
try {
- real = realpathSync(path.resolve(String(framePath)));
+ real = realpathSync(path.resolve(framePath));
} catch {
return null;
}
+
const realRoot = (p: string) => {
try { return realpathSync(p); } catch { return resolve(p); }
};
+
const ok = roots.map(realRoot).some((root) => real === root || real.startsWith(root + path.sep));
+
return ok ? real : null;
}
app.post("/api/thumbnail-studio/options", async (req, res) => {
const { title, video_path, start, end, texts, frames } = req.body || {};
- if (!title || !String(title).trim()) { res.status(400).json({ error: "title is required" }); return; }
+
+ if (!title || !String(title).trim()) { res.status(400).json({
+ error: "title is required" });
+
+ return;
+ }
+
const clamp = (v: any, d: number) => Math.min(Math.max(parseInt(String(v)) || d, 1), 8);
+
const args = [
"thumbnail-options",
"--output", join(thumbStudioDir, "frames"),
"--texts", String(clamp(texts, 6)),
"--frames", String(clamp(frames, 6)),
];
+
if (video_path) {
// Frames come only from files the user explicitly uploaded/selected this
- // session — never an arbitrary server path passed to the extractor.
+ // session: never an arbitrary server path passed to the extractor.
let video: string;
- try { video = realpathSync(path.resolve(String(video_path))); } catch { res.status(400).json({ error: "video not found" }); return; }
- if (!allowedSourcePaths.has(video)) { res.status(400).json({ error: "unknown video, upload or select it first" }); return; }
+
+ try { video = realpathSync(path.resolve(String(video_path))); } catch { res.status(400).json({
+ error: "video not found" });
+
+ return;
+ }
+
+ if (!allowedSourcePaths.has(video)) { res.status(400).json({
+ error: "unknown video, upload or select it first" });
+
+ return;
+ }
+
args.push("--video", video);
+
if (start != null && start !== "") args.push("--start", String(Math.max(0, Number(start) || 0)));
+
if (end != null && end !== "") args.push("--end", String(Math.max(0, Number(end) || 0)));
}
+
args.push("--", String(title));
const r = await runCli(args);
- if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "options failed" }); return; }
+
+ if (r.code !== 0) { res.status(400).json({
+ error: stripAnsi(r.stderr || r.stdout) || "options failed" });
+
+ return;
+ }
+
const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));
+
try {
const parsed = JSON.parse(jsonLine || "{}");
+
if (!parsed.frames?.length && (parsed.texts?.length || 0) > 0) {
- parsed.warning = "No suitable frames found — try another moment or upload a frame.";
+ parsed.warning = "No suitable frames found: try another moment or upload a frame.";
}
+
res.json(parsed);
} catch { res.status(500).json({ error: "bad options output" }); }
});
app.post("/api/thumbnail-studio/render", async (req, res) => {
const { title, line1, line2, frame_path, frame_info } = req.body || {};
- if (!title || !String(title).trim()) { res.status(400).json({ error: "title is required" }); return; }
- if (!frame_path) { res.status(400).json({ error: "select a frame first" }); return; }
+
+ if (!title || !String(title).trim()) { res.status(400).json({
+ error: "title is required" });
+
+ return;
+ }
+
+ if (!frame_path) { res.status(400).json({
+ error: "select a frame first" });
+
+ return;
+ }
+
const resolvedFrame = resolveFrameInRoots(frame_path, [thumbStudioDir, uploadDir]);
- if (!resolvedFrame) { res.status(400).json({ error: "invalid frame" }); return; }
+
+ if (!resolvedFrame) { res.status(400).json({
+ error: "invalid frame" });
+
+ return;
+ }
+
await mkdir(thumbStudioDir, { recursive: true });
const out = join(thumbStudioDir, `thumb_${uuidv4().slice(0, 8)}.png`);
const args = ["thumbnail-render", "--frame", resolvedFrame, "--output", out];
+
if (line1) args.push(`--line1=${line1}`);
+
if (line2) args.push(`--line2=${line2}`);
+
if (frame_info) args.push("--frame-info", JSON.stringify(frame_info));
args.push("--", String(title));
const r = await runCli(args);
- if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "render failed" }); return; }
+
+ if (r.code !== 0) { res.status(400).json({
+ error: stripAnsi(r.stderr || r.stdout) || "render failed" });
+
+ return;
+ }
+
const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));
let outPath = "";
+
try { outPath = JSON.parse(jsonLine || "{}").path || ""; } catch { /* no path */ }
- if (!outPath || !existsSync(outPath)) { res.status(500).json({ error: "no thumbnail produced" }); return; }
+
+ if (!outPath || !existsSync(outPath)) { res.status(500).json({
+ error: "no thumbnail produced" });
+
+ return;
+ }
+
res.json({ ok: true, path: outPath });
});
@@ -3161,12 +3873,15 @@ app.get("/api/settings", async (_req, res) => {
});
app.post("/api/settings", async (req, res) => {
- const key = typeof req.body?.key === "string" ? req.body.key : "";
- const value = typeof req.body?.value === "string" ? req.body.value : "";
+ const key = stringValue.safeParse(req.body?.key).data ?? "";
+ const value = stringValue.safeParse(req.body?.value).data ?? "";
+
if (!key) {
res.status(400).json({ error: "key is required" });
+
return;
}
+
try {
const action = value.trim() ? "set" : "unset";
const result = await executor.execute("manage_env", { action, key, value });
@@ -3183,6 +3898,7 @@ app.get("/api/ai-cli-status", async (_req, res) => {
candidates?: Array<{ engine: string; path: string }>;
available?: boolean;
}>("ai_cli_status", {});
+
res.json(result.data ?? { available: false, candidates: [], configured: {} });
} catch (err: unknown) {
res.status(500).json({ error: errMsg(err) });
@@ -3191,7 +3907,7 @@ app.get("/api/ai-cli-status", async (_req, res) => {
app.get("/api/ai-provider-status", async (_req, res) => {
try {
- const result = await executor.execute<Record<string, unknown>>("ai_provider_status", {});
+ const result = await executor.execute<object>("ai_provider_status", {});
res.json(result.data ?? { available: false, providers: [], candidates: [] });
} catch (err: unknown) {
res.status(500).json({ error: errMsg(err) });
@@ -3208,19 +3924,33 @@ app.get("/api/youtube/config", (_req, res) => {
}
});
+const integrationsFileSchema = z.looseObject({
+ youtube: z
+ .looseObject({ client_id: z.string().optional(), client_secret: z.string().optional() })
+ .optional(),
+});
+
+type IntegrationsFile = z.infer<typeof integrationsFileSchema>;
+
app.put("/api/youtube/config", (req, res) => {
try {
- let all: Record<string, any> = {};
- try { all = JSON.parse(readFileSync(paths.integrations, "utf-8")); } catch { /* new */ }
- const yt = { ...(all.youtube || {}) };
+ let all: IntegrationsFile = {};
+
+ try { all = integrationsFileSchema.parse(JSON.parse(readFileSync(paths.integrations, "utf-8"))); } catch { /* new */ }
+
+ const yt = { ...all.youtube };
const { client_id, client_secret } = req.body || {};
+
if (client_id !== undefined) yt.client_id = client_id;
+
if (client_secret) yt.client_secret = client_secret;
all.youtube = yt;
writeFileAtomicSync(paths.integrations, JSON.stringify(all, null, 2) + "\n");
- // Holds the OAuth client secret — keep it owner-only (chmod covers the
+
+ // Holds the OAuth client secret: keep it owner-only (chmod covers the
// case where the file already existed with looser perms).
try { chmodSync(paths.integrations, 0o600); } catch { /* best effort */ }
+
res.json({ ok: true });
} catch (e: any) {
res.status(500).json({ error: e.message });
@@ -3244,19 +3974,25 @@ app.get("/api/youtube/status", async (_req, res) => {
app.post("/api/youtube/sync", async (req, res) => {
const csvPath = req.body?.csv_path;
const r = await runCli(["youtube", "sync", ...(csvPath ? ["--csv", String(csvPath)] : [])]);
+
if (r.code !== 0) {
res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "sync failed" });
+
return;
}
+
res.json({ ok: true, message: stripAnsi(r.stdout) });
});
app.post("/api/youtube/learn", async (_req, res) => {
const r = await runCli(["youtube", "learn"]);
+
if (r.code !== 0) {
res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "analysis failed" });
+
return;
}
+
res.json({ ok: true, message: stripAnsi(r.stdout) });
});
@@ -3264,27 +4000,38 @@ app.post("/api/youtube/learn", async (_req, res) => {
app.get("/api/youtube/links", async (_req, res) => {
const r = await runCli(["youtube", "link", "--json"]);
let payload: any = {};
+
try { payload = JSON.parse(r.stdout.trim().split("\n").pop() || "{}"); } catch { /* non-JSON */ }
+
if (r.code !== 0 || payload.error) {
res.status(400).json({ error: payload.error || stripAnsi(r.stderr || r.stdout) || "could not load proposals" });
+
return;
}
+
res.json({ proposals: payload.proposals || [] });
});
app.post("/api/youtube/link", async (req, res) => {
const { clip_id, video_id } = req.body || {};
+
if (!clip_id || !video_id) {
res.status(400).json({ error: "clip_id and video_id are required" });
+
return;
}
+
const r = await runCli(["youtube", "link", String(clip_id), String(video_id), "--json"]);
let payload: any = {};
+
try { payload = JSON.parse(r.stdout.trim().split("\n").pop() || "{}"); } catch { /* non-JSON */ }
+
if (r.code !== 0 || !payload.ok) {
res.status(400).json({ error: payload.error || "link failed (clip not found?)" });
+
return;
}
+
res.json({ ok: true });
});
@@ -3292,12 +4039,15 @@ app.get("/api/analytics", async (_req, res) => {
const clips = await clipsHistory.load();
const withM = clips.filter((c) => c.metrics && (c.metrics.views != null || c.metrics.retention != null));
const avg = (arr: number[]) => (arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0);
+
const agg = (keyFn: (c: any) => string) => {
const groups = new Map<string, any[]>();
+
for (const c of withM) {
- const k = keyFn(c) || "—";
+ const k = keyFn(c) || "unknown";
(groups.get(k) ?? groups.set(k, []).get(k)!).push(c);
}
+
return Array.from(groups.entries()).map(([key, cs]) => ({
key,
count: cs.length,
@@ -3306,7 +4056,8 @@ app.get("/api/analytics", async (_req, res) => {
avgCtr: +avg(cs.map((c) => c.metrics?.ctr || 0)).toFixed(1),
})).sort((a, b) => b.avgViews - a.avgViews);
};
- const lengthBucket = (d: number) => (d < 25 ? "<25s" : d < 35 ? "25–35s" : d < 45 ? "35–45s" : "45s+");
+
+ const lengthBucket = (d: number) => (d < 25 ? "<25s" : d < 35 ? "25-35s" : d < 45 ? "35-45s" : "45s+");
res.json({
published: withM.length,
total: clips.length,
@@ -3323,153 +4074,209 @@ app.get("/api/analytics", async (_req, res) => {
app.get("/api/clips/:id/source", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
+
if (!clip || !existsSync(clip.source_video)) {
res.status(404).json({ error: "source not found" });
+
return;
}
- const srcMime: Record<string, string> = { ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".mkv": "video/x-matroska", ".m4v": "video/mp4" };
- streamVideo(req, res, clip.source_video, srcMime[extname(clip.source_video).toLowerCase()] || "video/mp4");
+
+ const srcMime = new Map([
+ [".mp4", "video/mp4"],
+ [".webm", "video/webm"],
+ [".mov", "video/quicktime"],
+ [".mkv", "video/x-matroska"],
+ [".m4v", "video/mp4"],
+ ]);
+
+ streamVideo(req, res, clip.source_video, srcMime.get(extname(clip.source_video).toLowerCase()) || "video/mp4");
});
app.get("/api/clips/:id/reframe", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
- if (!clip) { res.status(404).json({ error: "clip not found" }); return; }
+
+ if (!clip) { res.status(404).json({
+ error: "clip not found" });
+
+ return;
+ }
+
res.json((await clipsHistory.loadReframe(clip.id)) || {});
});
app.get("/api/clips/:id/cuts", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
- if (!clip || !existsSync(clip.source_video)) { res.status(404).json({ error: "source not found" }); return; }
+
+ if (!clip || !existsSync(clip.source_video)) { res.status(404).json({
+ error: "source not found" });
+
+ return;
+ }
+
const start = clip.start_second;
const dur = Math.max(0.1, clip.end_second - clip.start_second);
+
// pts_time from ffmpeg scene detection is relative to -ss, not the source.
const proc = spawn(paths.ffmpegPath, [
"-ss", String(start), "-i", clip.source_video, "-t", String(dur),
"-vf", "select='gt(scene,0.3)',showinfo", "-an", "-f", "null", "-",
]);
+
let stderr = "";
proc.stderr.on("data", (d) => (stderr += d));
proc.on("close", () => {
- const cuts = [...stderr.matchAll(/pts_time:([\d.]+)/g)]
- .map((m) => +(start + parseFloat(m[1])).toFixed(3))
- .filter((t) => t > start + 0.2 && t < start + dur - 0.2);
+ const cuts = [...stderr.matchAll(/pts_time:([\d.]+)/g)].flatMap((m) => {
+ const t = +(start + parseFloat(m[1])).toFixed(3);
+
+ return t > start + 0.2 && t < start + dur - 0.2 ? [t] : [];
+ });
+
res.json({ cuts: Array.from(new Set(cuts)) });
});
proc.on("error", () => res.json({ cuts: [] }));
});
+const trimWindowSchema = z.looseObject({ inSec: z.number().optional(), outSec: z.number().optional() });
+
app.post("/api/clips/:id/rerender", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
+
if (!clip) {
res.status(404).json({ error: "clip not found" });
+
return;
}
+
// Editor sends source-absolute keyframes + trim; derive the render's clip-relative
// crop keyframes from it, and persist the editor state so reopening shows it.
- const reframe = req.body?.reframe as { keyframes?: { tAbs: number; x_pct: number }[]; inSec?: number; outSec?: number } | undefined;
- const trim = req.body?.trim as { inSec?: number; outSec?: number } | undefined;
- const startSecond = reframe && typeof reframe.inSec === "number" ? reframe.inSec
- : trim && typeof trim.inSec === "number" ? trim.inSec
- : typeof req.body?.start_second === "number" ? req.body.start_second : clip.start_second;
- const endSecond = reframe && typeof reframe.outSec === "number" ? reframe.outSec
- : trim && typeof trim.outSec === "number" ? trim.outSec
- : typeof req.body?.end_second === "number" ? req.body.end_second : clip.end_second;
+ const reframe = reframeStateSchema.safeParse(req.body?.reframe).data;
+ const trim = trimWindowSchema.safeParse(req.body?.trim).data;
+
+ const startSecond = reframe?.inSec ?? trim?.inSec ?? numberValue.safeParse(req.body?.start_second).data ?? clip.start_second;
+
+ const endSecond = reframe?.outSec ?? trim?.outSec ?? numberValue.safeParse(req.body?.end_second).data ?? clip.end_second;
+
const keyframes = reframe?.keyframes
? reframe.keyframes
.filter((k) => k.tAbs >= startSecond - 0.001 && k.tAbs <= endSecond + 0.001)
.map((k) => ({ t: +Math.max(0, k.tAbs - startSecond).toFixed(3), x_pct: k.x_pct }))
: req.body?.crop_keyframes;
+
const trimOnly = !!trim && !reframe && !Array.isArray(keyframes);
+
if (!trimOnly && (!Array.isArray(keyframes) || keyframes.length === 0)) {
res.status(400).json({ error: "keyframes required" });
+
return;
}
+
if (reframe) await clipsHistory.saveReframe(clip.id, reframe);
const recipe = (await clipsHistory.loadRecipe(clip.id)) || {};
- let allWords = (recipe.transcript_words as any[]) || (await clipsHistory.loadWords(clip.id)) || [];
+ let allWords = recipe.transcript_words ?? (await clipsHistory.loadWords(clip.id));
+
if (!allWords.length) {
// Fallback for clips rendered before recipes existed: recover words from the cached source transcript.
try {
const t = await cache.get(clip.source_video);
- if (t?.words?.length) allWords = t.words as any[];
+
+ if (t?.words?.length) allWords = t.words;
} catch { /* no cached transcript */ }
}
+
// If trimmed wider/narrower, keep only words inside the new bounds.
- const words = allWords.filter((w: any) => typeof w?.start !== "number" || (w.start >= startSecond && w.start < endSecond));
- const recipeSegments = trimOnly ? undefined : (recipe.keep_segments as ExportClip["keep_segments"]);
+ const words = allWords.filter((w) => w.start >= startSecond && w.start < endSecond);
+ const recipeSegments = trimOnly ? undefined : recipe.keep_segments;
// A trim that no longer holds the hook's passage renders without it.
- const recipeHook = recipe.hook as ClipHook | undefined;
+ const recipeHook = recipe.hook;
+ const trimOnlyCrop = recipe.crop_strategy || clip.crop_strategy || "face";
+
const hook = recipeHook && !validateHook(recipeHook, startSecond, endSecond, recipeSegments)
? recipeHook
: undefined;
+
const recipeAsset = (key: "logo_path" | "outro_path" | "intro_path") => {
const value = recipe[key];
- return typeof value === "string" && value.trim() ? value : undefined;
+
+ return value?.trim() ? value : undefined;
};
+
try {
const result = await executor.execute<ClipResult>("create_clip", {
video_path: clip.source_video,
start_second: startSecond,
end_second: endSecond,
- caption_style: req.body?.caption_style || (recipe.caption_style as string) || clip.caption_style,
- crop_strategy: trimOnly ? (recipe.crop_strategy as string) || clip.crop_strategy || "face" : "manual",
- ...(trimOnly ? {} : { crop_keyframes: keyframes }),
+ caption_style: req.body?.caption_style || recipe.caption_style || clip.caption_style,
+ crop_strategy: trimOnly ? trimOnlyCrop : "manual",
+ ...(!trimOnly && { crop_keyframes: keyframes }),
transcript_words: words,
logo_path: recipeAsset("logo_path") ?? clip.logo_path ?? null,
outro_path: recipeAsset("outro_path") ?? clip.outro_path ?? null,
intro_path: recipeAsset("intro_path") ?? clip.intro_path ?? null,
- clean_fillers: trimOnly ? false : (recipe.clean_fillers !== undefined ? recipe.clean_fillers : true),
+ clean_fillers: trimOnly ? false : (recipe.clean_fillers ?? true),
trim_opening: trimOnly ? false : undefined,
preserve_timing: trimOnly ? true : undefined,
- ...(recipeSegments ? { keep_segments: recipeSegments } : {}),
+ ...(recipeSegments && { keep_segments: recipeSegments }),
...(hook && { hook }),
title: clip.title,
output_dir: dirname(clip.output_path),
});
+
if (!result.data) throw new Error("no render output");
const outPath = result.data.output_path || clip.output_path;
- // Re-bake the chosen thumbnail card onto the fresh clip (no strip needed —
+ // Re-bake the chosen thumbnail card onto the fresh clip (no strip needed:
// create_clip always renders a cardless clip).
const tnail = clip.thumbnail_config?.preview_path;
let thumbnailBaked = false;
+
if (tnail && existsSync(tnail) && existsSync(outPath)) {
const bake = await bakeThumbnailCard(outPath, tnail);
thumbnailBaked = bake.ok;
+
if (!bake.ok) {
res.status(500).json({ error: `reframe rendered but thumbnail bake failed: ${bake.error}` });
+
return;
}
}
+
await clipsHistory.update(clip.id, {
start_second: startSecond,
end_second: endSecond,
- crop_strategy: trimOnly ? (recipe.crop_strategy as string) || clip.crop_strategy || "face" : "manual",
+ crop_strategy: trimOnly ? trimOnlyCrop : "manual",
duration: result.data.duration ?? clip.duration,
file_size_mb: result.data.file_size_mb ?? clip.file_size_mb,
output_path: outPath,
});
res.json({ ok: true, output_path: outPath, file_size_mb: result.data.file_size_mb, thumbnail_baked: thumbnailBaked });
- } catch (e: any) {
- res.status(500).json({ error: e.message });
+ } catch (e: unknown) {
+ res.status(500).json({ error: errMsg(e) });
}
});
app.post("/api/clips/:id/davinci", async (req, res) => {
const clip = await clipsHistory.findById(req.params.id);
+
if (!clip) {
res.status(404).json({ error: "clip not found" });
+
return;
}
+
if (!existsSync(clip.output_path)) {
res.status(400).json({ error: "rendered file missing" });
+
return;
}
+
const cli = join(paths.backendDir, "services", "integrations", "davinci_resolve", "cli.py");
const r = await runPy([cli, "--source", clip.output_path, `--title=${clip.title}`]);
+
if (r.code !== 0) {
res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "export failed" });
+
return;
}
+
const wrote = (r.stdout.match(/wrote:\s*(.+)/) || [])[1]?.trim();
res.json({ ok: true, path: wrote });
});
@@ -3483,19 +4290,23 @@ app.get("/api/history/check", async (req, res) => {
style = "hormozi",
crop = "speaker",
} = req.query;
+
if (!source || !start || !end) {
res.json({ duplicate: null });
+
return;
}
+
const dup = await clipsHistory.findDuplicate(
- source as string,
- parseFloat(start as string),
- parseFloat(end as string),
- style as string,
- crop as string,
+ stringValue.parse(source),
+ parseFloat(stringValue.parse(start)),
+ parseFloat(stringValue.parse(end)),
+ stringValue.parse(style),
+ stringValue.parse(crop),
);
+
res.json({ duplicate: dup });
- } catch (err: any) {
+ } catch {
res.json({ duplicate: null });
}
});
@@ -3528,15 +4339,20 @@ app.put("/api/corrections", express.json(), (req, res) => {
app.post("/api/corrections/add", express.json(), (req, res) => {
const { wrong, correct } = req.body;
+
if (!wrong || !correct) {
res.status(400).json({ error: "'wrong' and 'correct' are required" });
+
return;
}
+
try {
let corrections: Record<string, string> = {};
+
if (existsSync(correctionsPath)) {
corrections = JSON.parse(readFileSync(correctionsPath, "utf-8"));
}
+
corrections[wrong] = correct;
writeFileAtomicSync(correctionsPath, JSON.stringify(corrections, null, 2));
res.json({ ok: true, corrections });
@@ -3548,9 +4364,11 @@ app.post("/api/corrections/add", express.json(), (req, res) => {
app.delete("/api/corrections/:wrong", (req, res) => {
try {
let corrections: Record<string, string> = {};
+
if (existsSync(correctionsPath)) {
corrections = JSON.parse(readFileSync(correctionsPath, "utf-8"));
}
+
delete corrections[req.params.wrong];
writeFileAtomicSync(correctionsPath, JSON.stringify(corrections, null, 2));
res.json({ ok: true, corrections });
@@ -3564,7 +4382,7 @@ app.get("/api/knowledge", async (_req, res) => {
try {
const files = await knowledgeBase.listFiles();
res.json(files);
- } catch (err: any) {
+ } catch {
res.json([]);
}
});
@@ -3582,7 +4400,7 @@ app.post("/api/knowledge/init", async (_req, res) => {
}
});
-// Knowledge file upload (drag & drop .md files) — must be before :filename routes
+// Knowledge file upload (drag & drop .md files), must be before :filename routes
const knowledgeUpload = multer({
storage: multer.diskStorage({
destination: async (_req, _file, cb) => {
@@ -3593,6 +4411,7 @@ const knowledgeUpload = multer({
}),
fileFilter: (_req, file, cb) => {
const name = basename(file.originalname);
+
if (name.endsWith(".md") || name.endsWith(".txt")) {
cb(null, true);
} else {
@@ -3605,11 +4424,14 @@ app.post(
"/api/knowledge/upload",
knowledgeUpload.array("files", 50),
(req, res) => {
- const files = req.files as Express.Multer.File[];
+ const files = Array.isArray(req.files) ? req.files : [];
+
if (!files || files.length === 0) {
res.status(400).json({ error: "No files uploaded" });
+
return;
}
+
res.json({ uploaded: files.map((f) => f.originalname) });
},
);
@@ -3617,8 +4439,10 @@ app.post(
app.get("/api/knowledge/:filename", async (req, res) => {
if (!safePath(paths.knowledge, req.params.filename)) {
res.status(400).json({ error: "Invalid filename" });
+
return;
}
+
try {
const content = await knowledgeBase.readFile(req.params.filename);
res.json({ filename: req.params.filename, content });
@@ -3630,8 +4454,10 @@ app.get("/api/knowledge/:filename", async (req, res) => {
app.post("/api/knowledge/:filename", async (req, res) => {
if (!safePath(paths.knowledge, req.params.filename)) {
res.status(400).json({ error: "Invalid filename" });
+
return;
}
+
try {
await knowledgeBase.writeFile(req.params.filename, req.body.content);
res.json({ ok: true, filename: req.params.filename });
@@ -3643,8 +4469,10 @@ app.post("/api/knowledge/:filename", async (req, res) => {
app.delete("/api/knowledge/:filename", async (req, res) => {
if (!safePath(paths.knowledge, req.params.filename)) {
res.status(400).json({ error: "Invalid filename" });
+
return;
}
+
try {
await knowledgeBase.deleteFile(req.params.filename);
res.json({ ok: true });
@@ -3658,10 +4486,12 @@ app.get("/api/onboarding", async (_req, res) => {
const knowledge = await knowledgeBase
.status()
.catch(() => ({ templates: [], present: [], filled: [], missing: [] }));
+
const assets = await assetManager.list().catch(() => []);
const clips = await clipsHistory.load().catch(() => []);
let aiCli = false;
+
try {
const result = await executor.execute<{ available?: boolean }>("ai_cli_status", {});
aiCli = !!result.data?.available;
@@ -3693,8 +4523,10 @@ function getStateContext() {
const hasTranscript = (uiState.transcript?.words?.length ?? 0) > 0;
const hasRawTranscript = !!uiState.rawTranscriptText?.trim();
const hasSuggestions = uiState.suggestions.length > 0;
+
const selectedCount =
uiState.suggestions.length - uiState.deselectedIndices.length;
+
return {
hasVideo,
hasTranscript,
@@ -3723,7 +4555,7 @@ function buildPromptForAction(
if (action === "suggest") {
if (!ctx.hasTranscript && !ctx.hasRawTranscript) {
- // No transcript yet — prompt includes transcribe step
+ // No transcript yet: prompt includes transcribe step
if (uiState.videoPath) {
parts.push(
`Transcribe the podcast at ${uiState.videoPath} using transcribe_podcast.`,
@@ -3733,6 +4565,7 @@ function buildPromptForAction(
"Set a video path first, then transcribe it using transcribe_podcast.",
);
}
+
parts.push(
"Then find the 5-8 best viral-worthy moments and call suggest_clips.",
);
@@ -3741,10 +4574,11 @@ function buildPromptForAction(
"Use get_ui_state with include_transcript=true to read the full transcript.",
);
parts.push(
- "Find the 5-8 best viral-worthy moments — hot takes, strong opinions, funny moments, actionable advice, and emotional stories.",
+ "Find the 5-8 best viral-worthy moments, such as hot takes, strong opinions, funny moments, actionable advice, and emotional stories.",
);
parts.push("Then call suggest_clips with your suggestions.");
}
+
parts.push(`Current settings: ${settingsSummary}`);
} else if (action === "export") {
parts.push("Use get_ui_state to read the selected clips.");
@@ -3764,7 +4598,7 @@ function buildPromptForAction(
// --- MCP Prompt Hints ---
/**
- * GET /api/mcp-hints — Returns contextual MCP prompt suggestions based on current state.
+ * GET /api/mcp-hints: Returns contextual MCP prompt suggestions based on current state.
* Prompts are practical clip-generation actions, not generic help.
* Phrased generically (not Claude-specific) since any MCP client can use them.
*/
@@ -3783,7 +4617,7 @@ app.get("/api/mcp-hints", (_req, res) => {
// MCP hints only appear once there's something to work with.
if ((ctx.hasRawTranscript || ctx.hasTranscript) && !ctx.hasSuggestions) {
- // Transcript is ready — suggest clip-finding prompts
+ // Transcript is ready: suggest clip-finding prompts
hints.push(
{
prompt: "Find the 5 best viral moments from this podcast",
@@ -3870,18 +4704,21 @@ app.get("/api/mcp-hints", (_req, res) => {
});
/**
- * POST /api/generate-prompt — Build an MCP prompt for the given action using authoritative server state.
+ * POST /api/generate-prompt: Build an MCP prompt for the given action using authoritative server state.
* Body: { action: "suggest" | "export" | "restyle" }
* Returns: { prompt, action, context }
*/
app.post("/api/generate-prompt", (req, res) => {
const action = req.body.action || "suggest";
+
if (!["suggest", "export", "restyle"].includes(action)) {
res
.status(400)
.json({ error: "action must be 'suggest', 'export', or 'restyle'" });
+
return;
}
+
const prompt = buildPromptForAction(action);
const ctx = getStateContext();
res.json({ prompt, action, context: ctx });
@@ -3897,12 +4734,15 @@ app.post("/api/claude-suggest", async (req, res) => {
res
.status(400)
.json({ error: "No transcript loaded. Transcribe or import one first." });
+
return;
}
const segs = uiState.transcript?.segments;
+
if (!segs || !Array.isArray(segs) || segs.length === 0) {
res.status(400).json({ error: "No transcript segments available." });
+
return;
}
@@ -3912,6 +4752,7 @@ app.post("/api/claude-suggest", async (req, res) => {
const rendered = uiState.videoPath
? await clipsHistory.getBySource(uiState.videoPath).catch(() => [])
: [];
+
const existing_clips = [
...rendered.map((c) => ({ start_second: c.start_second, end_second: c.end_second, title: c.title })),
...uiState.suggestions.map((s) => ({ start_second: s.start_second, end_second: s.end_second, title: s.title })),
@@ -3919,14 +4760,19 @@ app.post("/api/claude-suggest", async (req, res) => {
// The backend derives laughter/reaction anchors from the audio, so it needs
// the source video, not just the segments.
- const params: Record<string, unknown> = { segments: segs, top_n, existing_clips };
const suggestVideo = uiState.filePath || uiState.videoPath;
- if (suggestVideo) params.video_path = suggestVideo;
- if (min_duration) params.min_duration = min_duration;
- if (max_duration) params.max_duration = max_duration;
- // Duration bounds are per-format, so the numbers above mean nothing without it.
- const suggestFormat = (uiState.settings as Record<string, unknown> | undefined)?.format;
- if (suggestFormat) params.format = suggestFormat;
+
+ const params = {
+ segments: segs,
+ top_n,
+ existing_clips,
+ ...(suggestVideo && { video_path: suggestVideo }),
+ ...(min_duration && { min_duration }),
+ ...(max_duration && { max_duration }),
+ // Duration bounds are per-format, so the numbers above mean nothing without it.
+ ...(uiState.settings.format && { format: uiState.settings.format }),
+ };
+
const result = await executor.execute<{ clips?: SuggestedClip[] }>(
"suggest_clips",
params,
@@ -3980,16 +4826,21 @@ app.post("/api/claude-suggest", async (req, res) => {
// --- Find user-pasted moments (paste a description/quotes, AI locates them) ---
app.post("/api/find-moment", async (req, res) => {
- const text = typeof req.body?.text === "string" ? req.body.text.trim() : "";
+ const text = (stringValue.safeParse(req.body?.text).data ?? "").trim();
+
if (!text) {
res.status(400).json({ error: "Paste a moment or description to search for." });
+
return;
}
+
const segs = uiState.transcript?.segments;
+
if (!segs || !Array.isArray(segs) || segs.length === 0) {
res
.status(400)
.json({ error: "No transcript loaded. Transcribe or import one first." });
+
return;
}
@@ -3999,6 +4850,7 @@ app.post("/api/find-moment", async (req, res) => {
end_second: s.end_second,
title: s.title,
}));
+
const result = await executor.execute<{ clips?: SuggestedClip[] }>(
"find_moment",
{ text, segments: segs, existing_clips: existing, max_results: 8 },
@@ -4007,15 +4859,19 @@ app.post("/api/find-moment", async (req, res) => {
);
const found = result.data?.clips ?? [];
+
// Append to existing suggestions, skipping anything at a range we already have.
const seen = new Set(
uiState.suggestions.map(
(s) => `${Math.round(s.start_second * 10)}-${Math.round(s.end_second * 10)}`,
),
);
+
const added: SuggestedClip[] = [];
+
for (const c of found) {
const key = `${Math.round(c.start_second * 10)}-${Math.round(c.end_second * 10)}`;
+
if (seen.has(key)) continue;
seen.add(key);
added.push({
@@ -4059,6 +4915,7 @@ app.post("/api/generate-content", async (req, res) => {
if (!clip) {
res.status(400).json({ error: "clip is required" });
+
return;
}
@@ -4072,8 +4929,10 @@ app.post("/api/generate-content", async (req, res) => {
(event) => {
if (event.partial) {
broadcastSSE("content-partial", { stream_id: clip?.id ? String(clip.id) : null, partial: event.partial });
+
return;
}
+
broadcastSSE("job-update", {
progress: event.percent,
message: event.message,
@@ -4083,14 +4942,20 @@ app.post("/api/generate-content", async (req, res) => {
const data: any = result.data || {};
// Persist onto the clip's history entry so the generated metadata survives a
- // reload — generation is expensive and was previously discarded after display.
+ // reload: generation is expensive and was previously discarded after display.
const clipId = clip?.id ? await clipsHistory.resolveId(String(clip.id)) : null;
+
if (clipId) {
const patch: Partial<ClipHistoryEntry> = {};
+
if (Array.isArray(data.titles) && data.titles.length) patch.generated_titles = data.titles;
+
if (data.description) patch.description = data.description;
+
if (data.tags) patch.tags = data.tags;
+
if (data.hashtags) patch.hashtags = data.hashtags;
+
if (Object.keys(patch).length) await clipsHistory.update(clipId, patch);
}
@@ -4113,46 +4978,61 @@ function packTranscriptText(text: string): Array<{ start: number; text: string }
const segChars = 1000;
const stride = Math.max(segChars, Math.floor(clean.length / CONTENT_MAX_SEGMENTS));
const segs: Array<{ start: number; text: string }> = [];
+
for (let off = 0; off < clean.length && segs.length < CONTENT_MAX_SEGMENTS; off += stride) {
const chunk = clean.slice(off, off + segChars).trim();
+
if (chunk) segs.push({ start: segs.length, text: chunk });
}
+
return segs;
}
function condenseSegments(segments: Array<{ start?: number; text?: string }>): Array<{ start: number; text: string }> {
- const clean = segments
- .map((s) => ({ start: Number(s.start) || 0, text: String(s.text || "").trim() }))
- .filter((s) => s.text);
+ const clean = segments.flatMap((s) => {
+ const text = String(s.text || "").trim();
+
+ return text ? [{ start: Number(s.start) || 0, text }] : [];
+ });
+
if (clean.length <= CONTENT_MAX_SEGMENTS) return clean;
const per = Math.ceil(clean.length / CONTENT_MAX_SEGMENTS);
const out: Array<{ start: number; text: string }> = [];
+
for (let i = 0; i < clean.length; i += per) {
const group = clean.slice(i, i + per);
out.push({ start: group[0].start, text: group.map((s) => s.text).join(" ").slice(0, 1200) });
}
+
return out;
}
app.post("/api/content-studio/generate", async (req, res) => {
const { title, transcript_text, mode, stream_id } = req.body || {};
let segs: Array<{ start: number; text: string }>;
- if (typeof transcript_text === "string" && transcript_text.trim()) {
- segs = packTranscriptText(transcript_text);
+
+ const pastedText = stringValue.safeParse(transcript_text).data;
+
+ if (pastedText?.trim()) {
+ segs = packTranscriptText(pastedText);
} else if (uiState.transcript?.segments?.length) {
segs = condenseSegments(uiState.transcript.segments);
} else {
res.status(400).json({ error: "paste a transcript or load an episode first" });
+
return;
}
+
const episode = mode === "episode";
const lastStart = segs.length ? segs[segs.length - 1].start : 0;
+
const clip = {
title: String(title || "").trim() || "Untitled episode",
start_second: 0,
end_second: lastStart + 60,
content_type: episode ? "full episode" : "highlight",
};
+
try {
const result = await executor.execute(
"generate_content",
@@ -4160,14 +5040,17 @@ app.post("/api/content-studio/generate", async (req, res) => {
(event) => {
if (event.partial) {
broadcastSSE("content-partial", { stream_id: stream_id || null, partial: event.partial });
+
return;
}
+
broadcastSSE("job-update", {
progress: event.percent,
message: event.message,
});
},
);
+
res.json(result.data || {});
} catch (err: any) {
res.status(500).json({
@@ -4177,23 +5060,31 @@ app.post("/api/content-studio/generate", async (req, res) => {
});
/**
- * POST /api/content-studio/custom — free-form or per-section content request.
+ * POST /api/content-studio/custom: free-form or per-section content request.
*/
app.post("/api/content-studio/custom", async (req, res) => {
const { instruction, transcript_text, mode } = req.body || {};
+
if (!instruction || !String(instruction).trim()) {
res.status(400).json({ error: "instruction is required" });
+
return;
}
+
let segs: Array<{ start: number; text: string }>;
- if (typeof transcript_text === "string" && transcript_text.trim()) {
- segs = packTranscriptText(transcript_text);
+
+ const pastedText = stringValue.safeParse(transcript_text).data;
+
+ if (pastedText?.trim()) {
+ segs = packTranscriptText(pastedText);
} else if (uiState.transcript?.segments?.length) {
segs = condenseSegments(uiState.transcript.segments);
} else {
res.status(400).json({ error: "paste a transcript or load an episode first" });
+
return;
}
+
try {
const result = await executor.execute(
"generate_custom",
@@ -4206,6 +5097,7 @@ app.post("/api/content-studio/custom", async (req, res) => {
broadcastSSE("job-update", { progress: event.percent, message: event.message });
},
);
+
res.json(result.data || {});
} catch (err: any) {
res.status(500).json({
@@ -4217,7 +5109,7 @@ app.post("/api/content-studio/custom", async (req, res) => {
// --- MCP ↔ UI Bridge Endpoints ---
/**
- * GET /api/events — Global SSE channel for real-time MCP→UI events
+ * GET /api/events: Global SSE channel for real-time MCP→UI events
*/
app.get("/api/events", (_req, res) => {
res.writeHead(200, {
@@ -4243,17 +5135,19 @@ app.get("/api/events", (_req, res) => {
_req.on("close", () => {
clearInterval(heartbeat);
const idx = sseClients.indexOf(res);
+
if (idx !== -1) sseClients.splice(idx, 1);
});
});
/**
- * GET /api/ui-state — MCP reads current UI state
+ * GET /api/ui-state: MCP reads current UI state
*/
app.get("/api/ui-state", (_req, res) => {
const selected = uiState.suggestions.filter(
- (_: unknown, i: number) => !uiState.deselectedIndices.includes(i),
+ (_, i) => !uiState.deselectedIndices.includes(i),
);
+
res.json({
videoPath: uiState.videoPath,
filePath: uiState.filePath,
@@ -4278,7 +5172,7 @@ app.get("/api/ui-state", (_req, res) => {
});
/**
- * POST /api/ui-state — UI syncs state changes to server
+ * POST /api/ui-state: UI syncs state changes to server
*/
app.post("/api/ui-state", (req, res) => {
const body = req.body;
@@ -4293,8 +5187,10 @@ app.post("/api/ui-state", (req, res) => {
body._allowClear !== true &&
!!uiState.videoPath &&
body.videoPath === "";
+
if (looksLikeMountDefaults) {
res.json({ ok: true, ignored: "stale hydration defaults" });
+
return;
}
@@ -4308,6 +5204,7 @@ app.post("/api/ui-state", (req, res) => {
body.videoPath !== undefined &&
body.videoPath !== uiState.videoPath &&
body.transcript === undefined;
+
if (videoChanged) {
uiState.transcript = null;
uiState.transcriptVideoIdentity = null;
@@ -4323,21 +5220,26 @@ app.post("/api/ui-state", (req, res) => {
uiState.videoPath = body.videoPath;
uiState.videoMissing = !!body.videoPath && !existsSync(body.videoPath);
}
+
if (body.filePath !== undefined) uiState.filePath = body.filePath;
+
if (body.transcript !== undefined) {
uiState.transcript = body.transcript;
uiState.transcriptVideoIdentity = body.transcript
? computeVideoIdentity(body.videoPath ?? uiState.videoPath ?? "")
: null;
}
+
if (body.rawTranscriptText !== undefined)
uiState.rawTranscriptText = body.rawTranscriptText;
+
if (body.silenceOriginal !== undefined) {
const original = body.silenceOriginal;
+
if (original === null) {
uiState.silenceOriginal = null;
} else if (
- typeof original?.videoPath === "string" &&
+ stringValue.safeParse(original?.videoPath).success &&
existsSync(original.videoPath) &&
Array.isArray(original?.transcript?.words)
) {
@@ -4345,6 +5247,7 @@ app.post("/api/ui-state", (req, res) => {
registerSourcePath(original.videoPath);
}
}
+
if (body.silencePlan !== undefined) {
const plan = body.silencePlan;
uiState.silencePlan = plan === null || (
@@ -4352,6 +5255,7 @@ app.post("/api/ui-state", (req, res) => {
Array.isArray(plan?.removed_ranges)
) ? plan : uiState.silencePlan;
}
+
if (body.suggestions !== undefined) {
if (body._source === "ui" && Array.isArray(body.suggestions)) {
const previousSuggestions = uiState.suggestions;
@@ -4361,15 +5265,18 @@ app.post("/api/ui-state", (req, res) => {
Math.abs(s.start_second - incoming.start_second) < 0.5 &&
Math.abs(s.end_second - incoming.end_second) < 0.5,
);
+
const existing = existingIndex >= 0 ? previousSuggestions[existingIndex] : undefined;
let merged = incoming;
+
if (!incoming.segments?.length) {
const segments = findSuggestionSegments(
previousSuggestions,
incoming.start_second,
incoming.end_second,
);
+
if (segments?.length) {
// The restored segments (and any hook) change what actually
// plays, so the duration has to be recomputed rather than
@@ -4393,6 +5300,7 @@ app.post("/api/ui-state", (req, res) => {
// exports something other than what was approved.
if (existing?.selectionHash && !uiState.deselectedIndices.includes(existingIndex)) {
const currentHash = computeSelectionHash(merged, uiState.transcript?.words);
+
if (currentHash !== existing.selectionHash) {
merged = { ...merged, selectionHash: existing.selectionHash, changedSinceSelection: true };
}
@@ -4404,41 +5312,60 @@ app.post("/api/ui-state", (req, res) => {
uiState.suggestions = body.suggestions;
}
}
+
if (body.deselectedIndices !== undefined)
uiState.deselectedIndices = body.deselectedIndices;
+
if (body.phase !== undefined) uiState.phase = body.phase;
+
if (body.results !== undefined) uiState.results = body.results;
+
if (body.energyData !== undefined) uiState.energyData = body.energyData;
+
if (body.settings) {
if (body.settings.captionStyle !== undefined)
uiState.settings.captionStyle = body.settings.captionStyle;
+
if (body.settings.cropStrategy !== undefined)
uiState.settings.cropStrategy = body.settings.cropStrategy;
+
if (body.settings.format !== undefined)
uiState.settings.format = body.settings.format;
+
if (body.settings.logoPath !== undefined)
uiState.settings.logoPath = body.settings.logoPath;
+
if (body.settings.outroPath !== undefined)
uiState.settings.outroPath = body.settings.outroPath;
+
if (body.settings.introPath !== undefined)
uiState.settings.introPath = body.settings.introPath;
+
if (body.settings.cleanFillers !== undefined)
uiState.settings.cleanFillers = body.settings.cleanFillers !== false;
+
if (["auto", "upper", "center", "lower"].includes(body.settings.captionPosition))
uiState.settings.captionPosition = body.settings.captionPosition;
+
if (body.settings.captionFontScale !== undefined)
uiState.settings.captionFontScale = Math.max(60, Math.min(160, Number(body.settings.captionFontScale) || 100));
+
if (["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"].includes(body.settings.logoPosition))
uiState.settings.logoPosition = body.settings.logoPosition;
+
if (body.settings.onboardingDismissed !== undefined)
uiState.settings.onboardingDismissed = !!body.settings.onboardingDismissed;
+
if (body.settings.silenceThreshold !== undefined)
uiState.settings.silenceThreshold = Math.max(0.25, Math.min(0.8, Number(body.settings.silenceThreshold) || 0.5));
+
if (body.settings.silenceMinPause !== undefined)
uiState.settings.silenceMinPause = Math.max(0.3, Math.min(5, Number(body.settings.silenceMinPause) || 0.65));
+
if (body.settings.silencePadding !== undefined)
uiState.settings.silencePadding = Math.max(0.02, Math.min(0.5, Number(body.settings.silencePadding) || 0.12));
}
+
uiState.lastUpdated = Date.now();
persistState();
@@ -4477,27 +5404,47 @@ function dropEnergy(clip: SuggestedClip): void {
const key =
clip.clip_id ||
`${clip.start_second.toFixed(2)}:${clip.end_second.toFixed(2)}`;
+
delete uiState.energyData[key];
}
/**
- * POST /api/suggestions/modify — mutate one suggestion in-place on the server.
+ * POST /api/suggestions/modify: mutate one suggestion in-place on the server.
* Replaces the read-modify-replace cycle MCP tools used, which lost concurrent
* edits between the GET and the wholesale POST.
* Body: { action: "update" | "delete" | "toggle", index? | clip_id?, updates?, selected? }
*/
+// A field of the wrong type is skipped, not rejected, so one bad value does not drop the whole edit.
+const ignoreWrongType = <T extends z.ZodType>(schema: T) => schema.optional().catch(undefined);
+
+const clipFieldUpdatesSchema = z.looseObject({
+ title: ignoreWrongType(z.string()),
+ start_second: ignoreWrongType(z.number()),
+ end_second: ignoreWrongType(z.number()),
+ payoff: ignoreWrongType(z.string()),
+ standalone: ignoreWrongType(z.string()),
+ context_line: ignoreWrongType(z.string()),
+ reasoning: ignoreWrongType(z.string()),
+ preview_text: ignoreWrongType(z.string()),
+ suggested_caption_style: ignoreWrongType(z.string()),
+});
+
app.post("/api/suggestions/modify", (req, res) => {
const { action = "update", clip_id, updates, selected } = req.body || {};
- let index = typeof req.body?.index === "number" ? req.body.index : -1;
+ let index = numberValue.safeParse(req.body?.index).data ?? -1;
+
if (index === -1 && clip_id) {
index = uiState.suggestions.findIndex((s) => s.clip_id === clip_id);
}
+
if (index < 0 || index >= uiState.suggestions.length) {
res.status(404).json({ error: "Clip not found", total: uiState.suggestions.length });
+
return;
}
let clip: SuggestedClip;
+
if (action === "delete") {
[clip] = uiState.suggestions.splice(index, 1);
uiState.deselectedIndices = uiState.deselectedIndices
@@ -4505,11 +5452,14 @@ app.post("/api/suggestions/modify", (req, res) => {
.map((i) => (i > index ? i - 1 : i));
dropEnergy(clip);
} else if (action === "toggle") {
- if (typeof selected !== "boolean") {
+ if (!z.boolean().safeParse(selected).success) {
res.status(400).json({ error: "selected must be a boolean for action 'toggle'" });
+
return;
}
+
clip = uiState.suggestions[index];
+
if (selected) {
uiState.deselectedIndices = uiState.deselectedIndices.filter((i) => i !== index);
// Stamp what's being approved so a later edit to the same clip can be
@@ -4520,59 +5470,81 @@ app.post("/api/suggestions/modify", (req, res) => {
if (!uiState.deselectedIndices.includes(index)) {
uiState.deselectedIndices = [...uiState.deselectedIndices, index];
}
+
delete clip.selectionHash;
delete clip.changedSinceSelection;
}
} else if (action === "update") {
const upd = updates || {};
+ const fields = clipFieldUpdatesSchema.catch({}).parse(upd);
clip = uiState.suggestions[index];
- const nextStart = typeof upd.start_second === "number" ? upd.start_second : clip.start_second;
- const nextEnd = typeof upd.end_second === "number" ? upd.end_second : clip.end_second;
+ const nextStart = fields.start_second ?? clip.start_second;
+ const nextEnd = fields.end_second ?? clip.end_second;
const rangeError = validateSuggestionRange(nextStart, nextEnd);
+
if (rangeError) {
res.status(400).json({ error: rangeError });
+
return;
}
+
const reTimed = nextStart !== clip.start_second || nextEnd !== clip.end_second;
+
// The old segments array is scoped to the old range; if left stale it
// overrides the new start/end at render time (create_clip reads
// keep_segments ahead of start_second/end_second).
const nextSegments = reTimed
? reconcileSegmentsForRange(clip.segments, clip.start_second, clip.end_second, nextStart, nextEnd)
: clip.segments;
+
const nextHook: ClipHook | undefined =
upd.hook === null ? undefined : upd.hook !== undefined ? upd.hook : clip.hook;
+
const hookError = validateHook(nextHook, nextStart, nextEnd, nextSegments);
+
if (hookError) {
res.status(400).json({
error: upd.hook === undefined
? `${hookError} The new range no longer holds this clip's hook. Pass hook: null to clear it, or a new hook.`
: hookError,
});
+
return;
}
+
// The energy score was measured over the old range.
if (reTimed) {
dropEnergy(clip);
clip.segments = nextSegments;
}
+
if (nextHook) clip.hook = { start: nextHook.start, end: nextHook.end, mode: nextHook.mode };
else delete clip.hook;
- if (typeof upd.title === "string") clip.title = upd.title;
+
+ if (fields.title !== undefined) clip.title = fields.title;
clip.start_second = nextStart;
clip.end_second = nextEnd;
- if (typeof upd.payoff === "string") clip.payoff = upd.payoff;
- if (typeof upd.standalone === "string") clip.standalone = upd.standalone;
- if (typeof upd.context_line === "string") clip.context_line = upd.context_line;
- if (typeof upd.reasoning === "string") clip.reasoning = upd.reasoning;
- if (typeof upd.preview_text === "string") clip.preview_text = upd.preview_text;
- if (typeof upd.suggested_caption_style === "string") {
- clip.suggested_caption_style = upd.suggested_caption_style;
+
+ if (fields.payoff !== undefined) clip.payoff = fields.payoff;
+
+ if (fields.standalone !== undefined) clip.standalone = fields.standalone;
+
+ if (fields.context_line !== undefined) clip.context_line = fields.context_line;
+
+ if (fields.reasoning !== undefined) clip.reasoning = fields.reasoning;
+
+ if (fields.preview_text !== undefined) clip.preview_text = fields.preview_text;
+
+ if (fields.suggested_caption_style !== undefined) {
+ clip.suggested_caption_style = fields.suggested_caption_style;
}
+
clip.duration =
Math.round(playbackDuration(clip.start_second, clip.end_second, clip.segments, clip.hook) * 10) / 10;
+
const fmtTime = (s: number) =>
`${Math.floor(s / 60)}:${Math.floor(s % 60).toString().padStart(2, "0")}`;
+
clip.timestamp_display = `${fmtTime(clip.start_second)} → ${fmtTime(clip.end_second)}`;
// Approval was for a specific render; if this edit changed any
@@ -4580,12 +5552,14 @@ app.post("/api/suggestions/modify", (req, res) => {
// silently exporting something other than what got approved.
if (clip.selectionHash && !uiState.deselectedIndices.includes(index)) {
const currentHash = computeSelectionHash(clip, uiState.transcript?.words);
+
if (currentHash !== clip.selectionHash) {
clip.changedSinceSelection = true;
}
}
} else {
res.status(400).json({ error: `Unknown action: ${action}` });
+
return;
}
@@ -4606,54 +5580,69 @@ app.post("/api/suggestions/modify", (req, res) => {
});
/**
- * POST /api/mcp/export — MCP triggers export using current UI state
+ * POST /api/mcp/export: MCP triggers export using current UI state
*/
app.post("/api/mcp/export", async (req, res) => {
// Use UI state if no explicit params provided
const videoPath =
req.body.video_path || uiState.filePath || uiState.videoPath;
+
const clips =
req.body.clips ||
uiState.suggestions.filter(
- (_: unknown, i: number) => !uiState.deselectedIndices.includes(i),
+ (_, i) => !uiState.deselectedIndices.includes(i),
);
+
const transcriptWords =
req.body.transcript_words ||
(Array.isArray(uiState.transcript?.words)
? (uiState.transcript?.words ?? [])
: []);
+
const logoPath = req.body.logo_path || uiState.settings.logoPath || null;
const outroPath = req.body.outro_path || uiState.settings.outroPath || null;
const introPath = req.body.intro_path || uiState.settings.introPath || null;
+
const captionStyle =
req.body.caption_style || uiState.settings.captionStyle || "branded";
+
const cropStrategy =
req.body.crop_strategy || uiState.settings.cropStrategy || "speaker";
+
const format =
req.body.format || uiState.settings.format || "vertical";
+
const allowAssFallback = req.body.allow_ass_fallback === true;
+
// An agent that says nothing about fillers gets the studio's toggle, so an
// export it triggers matches what the user set up there.
const cleanFillers =
req.body.clean_fillers !== undefined
? req.body.clean_fillers !== false
: uiState.settings.cleanFillers !== false;
+
const keepCaptionOverlay = req.body.keep_caption_overlay === true;
const writeCleanVariant = req.body.write_clean_variant === true;
if (!videoPath || !existsSync(videoPath)) {
res.status(400).json({ error: "Video file not found" });
+
return;
}
+
if (!clips.length) {
res.status(400).json({ error: "No clips to export" });
+
return;
}
+
for (let i = 0; i < clips.length; i++) {
const c = clips[i];
const rangeError = validateClipRange(c.start_second, c.end_second, c.format || format);
+
if (rangeError) {
res.status(400).json({ error: `Clip ${i + 1}: ${rangeError}` });
+
return;
}
}
@@ -4678,13 +5667,17 @@ app.post("/api/mcp/export", async (req, res) => {
hook: c.hook,
}),
);
+
const mcpHookError = exportHookError(styledClips);
+
if (mcpHookError) {
res.status(400).json({ error: mcpHookError });
+
return;
}
const jobId = uuidv4();
+
const job: JobState = {
id: jobId,
type: "batch_clips",
@@ -4693,6 +5686,7 @@ app.post("/api/mcp/export", async (req, res) => {
message: "Starting MCP export...",
createdAt: Date.now(),
};
+
jobs.set(jobId, job);
const historyRecorder = createBatchHistoryRecorder({
@@ -4736,12 +5730,15 @@ app.post("/api/mcp/export", async (req, res) => {
const progress = advanceProgress(job, event.percent);
job.message = event.message;
historyRecorder.recordProgress(event);
+
const clipResult = event.clip_result
? tagSubmittedClip(event.clip_result, styledClips)
: undefined;
+
if (event.stage === "clip_complete" && clipResult) {
(job.clip_results ??= []).push(clipResult);
}
+
broadcastSSE("job-update", {
jobId,
progress,
@@ -4758,6 +5755,7 @@ app.post("/api/mcp/export", async (req, res) => {
job.message = "Export complete!";
job.result = data;
uiState.results = data?.results ?? [];
+
// Record clips to history
try {
await historyRecorder.recordRemaining(result.data?.results);
@@ -4766,6 +5764,7 @@ app.post("/api/mcp/export", async (req, res) => {
err: errMsg(err),
});
}
+
setExportState("done", null);
broadcastSSE("job-complete", { jobId, result: data });
})
@@ -4787,6 +5786,7 @@ async function main() {
// Cleanup old temp files on startup (>48h)
try {
const cleaned = await fileManager.cleanupOldTasks(48);
+
if (cleaned > 0) log.info(`Cleaned up ${cleaned} old temp files`);
} catch (err) {
log.warn("Startup temp-file cleanup failed", { err: errMsg(err) });
@@ -4799,6 +5799,7 @@ async function main() {
}>("manage_config", {
action: "status",
});
+
if (status.data?.legacy_cache_pending || status.data?.legacy_presets_pending) {
await executor.execute("manage_config", { action: "migrate" });
log.info("Migrated legacy transcription cache to data/cache");
@@ -4815,18 +5816,19 @@ async function main() {
res.sendFile("index.html", { root: publicDir });
});
- // Bind to loopback by default — the studio serves local files (clips, assets,
+ // Bind to loopback by default: the studio serves local files (clips, assets,
// source video) with no auth. Set PODCLI_HOST=0.0.0.0 to expose it on the LAN.
- const HOST = process.env.PODCLI_HOST || "127.0.0.1";
- const server = app.listen(PORT, HOST, () => {
+ const server = app.listen(PORT, bindHost, () => {
log.info(`podcli running at http://localhost:${PORT}`);
});
+
server.on("error", (err: NodeJS.ErrnoException) => {
if (err.code === "EADDRINUSE") {
- log.error(`Port ${PORT} is already in use — is the studio already running? Set PODCLI_PORT to use another.`);
+ log.error(`Port ${PORT} is already in use. Is the studio already running? Set PODCLI_PORT to use another.`);
} else {
log.error("Web server failed to start", { err: err.message });
}
+
process.exit(1);
});
}
diff --git a/src/utils/atomic-file.ts b/src/utils/atomic-file.ts
index 557d8e9..7b1b3bc 100644
--- a/src/utils/atomic-file.ts
+++ b/src/utils/atomic-file.ts
@@ -10,6 +10,7 @@ function tmpPathFor(filePath: string): string {
export function writeFileAtomicSync(filePath: string, data: string): void {
const tmp = tmpPathFor(filePath);
+
try {
writeFileSync(tmp, data, "utf-8");
renameSync(tmp, filePath);
@@ -17,12 +18,14 @@ export function writeFileAtomicSync(filePath: string, data: string): void {
try {
rmSync(tmp, { force: true });
} catch {}
+
throw err;
}
}
export async function writeFileAtomic(filePath: string, data: string): Promise<void> {
const tmp = tmpPathFor(filePath);
+
try {
await writeFile(tmp, data, "utf-8");
await rename(tmp, filePath);
diff --git a/src/utils/captions.test.ts b/src/utils/captions.test.ts
index 0732876..25eb94e 100644
--- a/src/utils/captions.test.ts
+++ b/src/utils/captions.test.ts
@@ -7,6 +7,7 @@ describe("selectBestCaptionTrack", () => {
{ en: [{ ext: "vtt", url: "manual-en" }] },
{ en: [{ ext: "vtt", url: "auto-en" }] },
);
+
expect(track).toEqual({ lang: "en", kind: "manual", ext: "vtt", url: "manual-en" });
});
@@ -16,6 +17,7 @@ describe("selectBestCaptionTrack", () => {
"ka-orig": [{ ext: "vtt", url: "original-ka" }],
en: [{ ext: "vtt", url: "translated-en" }],
});
+
expect(track?.lang).toBe("ka-orig");
expect(track?.url).toBe("original-ka");
});
@@ -27,6 +29,7 @@ describe("selectBestCaptionTrack", () => {
{ ext: "json3", url: "json3-url" },
],
});
+
expect(track?.url).toBe("json3-url");
});
@@ -38,6 +41,7 @@ describe("selectBestCaptionTrack", () => {
{ ext: "ttml", url: "ttml-url" },
],
});
+
expect(track?.url).toBe("vtt-url");
});
@@ -59,6 +63,7 @@ describe("parseVtt", () => {
"second line here",
"",
].join("\n");
+
const cues = parseVtt(vtt);
expect(cues).toEqual([
{ start: 1, end: 4, text: "Hello world" },
@@ -74,6 +79,7 @@ describe("parseVtt", () => {
"<00:00:01.000><c> Hello</c><00:00:01.500><c> world</c>",
"",
].join("\n");
+
const cues = parseVtt(vtt);
expect(cues).toEqual([{ start: 1, end: 4, text: "Hello world" }]);
});
@@ -112,6 +118,7 @@ describe("cuesToWords", () => {
{ start: 0, end: 2, text: "hello world" },
{ start: 2, end: 4, text: "next sentence" },
]);
+
expect(words.map((w) => w.word)).toEqual(["hello", "world", "next", "sentence"]);
});
@@ -139,6 +146,7 @@ describe("cuesToWords", () => {
"today and I'm excited",
"&gt;&gt; Definitely.<00:00:05.680><c> Yeah.</c>",
].join("\n");
+
expect(cuesToWords(parseVtt(vtt)).map((w) => w.word)).toEqual([
"It's", "a", "great", "pleasure", "today", "and", "I'm", "excited", "Definitely.", "Yeah.",
]);
@@ -149,6 +157,7 @@ describe("cuesToWords", () => {
{ start: 0, end: 2, text: "first cue" },
{ start: 2, end: 4, text: "second cue" },
]);
+
expect(words.map((w) => w.word)).toEqual(["first", "cue", "second", "cue"]);
});
@@ -166,6 +175,7 @@ describe("parseJson3", () => {
{ tStartMs: 2080, dDurationMs: 1000, segs: [{ utf8: ">> Definitely." }] },
],
});
+
const { words, segments } = parseJson3(raw);
expect(words.map((w) => w.word)).toEqual(["It's", "a", "great", "Definitely."]);
expect(words[1].start).toBeCloseTo(0.4);
@@ -180,10 +190,12 @@ describe("parseJson3", () => {
{ tStartMs: 1000, dDurationMs: 1000, segs: [{ utf8: "Something" }, { utf8: " like", tOffsetMs: 300 }] },
],
});
+
const { words } = parseJson3(raw);
expect(words.map((w) => w.word)).toEqual(["Okay.", "Something", "like"]);
words.forEach((w, i) => {
expect(w.end).toBeGreaterThanOrEqual(w.start);
+
if (i > 0) expect(w.start).toBeGreaterThanOrEqual(words[i - 1].end);
});
});
diff --git a/src/utils/captions.ts b/src/utils/captions.ts
index bf34d4e..218b30f 100644
--- a/src/utils/captions.ts
+++ b/src/utils/captions.ts
@@ -1,3 +1,4 @@
+import { z } from "zod";
import type { WordTimestamp } from "../models/index.js";
export interface CaptionCue {
@@ -35,14 +36,18 @@ export function selectBestCaptionTrack(
): SelectedCaptionTrack | null => {
if (!dict) return null;
const langs = Object.keys(dict);
+
if (langs.length === 0) return null;
const lang = langs.find((l) => l.endsWith("-orig")) ?? langs[0];
const tracks = dict[lang];
+
if (!tracks?.length) return null;
// json3 carries a start time per word; vtt only per cue.
const best = tracks.find((t) => t.ext === "json3") ?? tracks.find((t) => t.ext === "vtt") ?? tracks[0];
+
return { lang, kind, ext: best.ext, url: best.url };
};
+
return pick(subtitles, "manual") ?? pick(automaticCaptions, "auto");
}
@@ -55,25 +60,32 @@ export function selectBestCaptionTrack(
export function parseVtt(vtt: string): CaptionCue[] {
const timeToSeconds = (t: string): number => {
const m = t.trim().match(/(?:(\d+):)?(\d+):(\d+)\.(\d+)/);
+
if (!m) return 0;
const [, h, mm, ss, ms] = m;
+
return (Number(h) || 0) * 3600 + Number(mm) * 60 + Number(ss) + Number(ms) / 1000;
};
+
const stripTags = (s: string): string => s.replace(/<[^>]*>/g, "").trim();
const blocks = vtt.replace(/\r\n/g, "\n").split(/\n\n+/);
const cues: CaptionCue[] = [];
+
for (const block of blocks) {
const lines = block.split("\n").filter((l) => l.trim().length > 0);
const timeLineIdx = lines.findIndex((l) => l.includes("-->"));
+
if (timeLineIdx === -1) continue;
const [startRaw, endRaw] = lines[timeLineIdx].split("-->");
const start = timeToSeconds(startRaw);
const end = timeToSeconds(endRaw.trim().split(/\s+/)[0] ?? endRaw);
const text = stripTags(lines.slice(timeLineIdx + 1).join(" "));
+
if (!text) continue;
cues.push({ start, end, text });
}
+
return cues;
}
@@ -85,8 +97,10 @@ export function parseVtt(vtt: string): CaptionCue[] {
*/
function cueToWords(cue: CaptionCue): WordTimestamp[] {
const words = captionTokens(cue.text);
+
if (words.length === 0) return [];
const step = (cue.end - cue.start) / words.length;
+
return words.map((word, i) => ({
word,
start: cue.start + i * step,
@@ -109,22 +123,37 @@ function cueToWords(cue: CaptionCue): WordTimestamp[] {
export function cuesToWords(cues: CaptionCue[]): WordTimestamp[] {
const kept: CaptionCue[] = [];
let tail: string[] = [];
+
for (const cue of cues) {
if (cue.end - cue.start < 0.05) continue;
const words = captionTokens(cue.text);
let overlap = Math.min(words.length, tail.length);
+
while (overlap > 0 && tail.slice(-overlap).join(" ") !== words.slice(0, overlap).join(" ")) overlap--;
const fresh = words.slice(overlap);
tail = [...tail, ...fresh].slice(-64);
+
if (fresh.length) kept.push({ ...cue, text: fresh.join(" ") });
}
+
return kept.flatMap(cueToWords);
}
-interface Json3Event {
- tStartMs?: number;
- dDurationMs?: number;
- segs?: Array<{ utf8?: string; tOffsetMs?: number }>;
+const json3Schema = z.looseObject({
+ events: z
+ .array(
+ z.looseObject({
+ tStartMs: z.number().optional(),
+ dDurationMs: z.number().optional(),
+ segs: z.array(z.looseObject({ utf8: z.string().optional(), tOffsetMs: z.number().optional() })).optional(),
+ }),
+ )
+ .optional(),
+});
+
+export interface ParsedCaptions {
+ words: WordTimestamp[];
+ segments: CaptionCue[];
}
/**
@@ -149,17 +178,20 @@ export function captionTokens(text: string): string[] {
* event before the old one closes), so words are ordered by start and each
* ends where the next begins.
*/
-export function parseJson3(raw: string): { words: WordTimestamp[]; segments: CaptionCue[] } {
- const events = (JSON.parse(raw) as { events?: Json3Event[] }).events ?? [];
+export function parseJson3(raw: string): ParsedCaptions {
+ const events = json3Schema.parse(JSON.parse(raw)).events ?? [];
const words: WordTimestamp[] = [];
const segments: CaptionCue[] = [];
+
for (const ev of events) {
const evStart = (ev.tStartMs ?? 0) / 1000;
const evEnd = evStart + (ev.dDurationMs ?? 0) / 1000;
+
const segs = (ev.segs ?? []).map((seg) => ({
tokens: captionTokens(seg.utf8 ?? ""),
start: evStart + (seg.tOffsetMs ?? 0) / 1000,
}));
+
const evWords: WordTimestamp[] = [];
segs.forEach((seg, i) => {
const segEnd = Math.max(seg.start, Math.min(segs[i + 1]?.start ?? evEnd, evEnd));
@@ -168,15 +200,19 @@ export function parseJson3(raw: string): { words: WordTimestamp[]; segments: Cap
evWords.push({ word, start: seg.start + k * step, end: seg.start + (k + 1) * step, confidence: 1 }),
);
});
+
if (!evWords.length) continue;
words.push(...evWords);
segments.push({ start: evStart, end: evEnd, text: evWords.map((w) => w.word).join(" ") });
}
+
words.sort((a, b) => a.start - b.start);
words.forEach((w, i) => {
const next = words[i + 1];
+
if (next && w.end > next.start) w.end = next.start;
});
segments.sort((a, b) => a.start - b.start);
+
return { words, segments };
}
diff --git a/src/utils/clip-hook.ts b/src/utils/clip-hook.ts
index e51c16b..e3f7d2e 100644
--- a/src/utils/clip-hook.ts
+++ b/src/utils/clip-hook.ts
@@ -28,47 +28,71 @@ const MIN_REMNANT_SECONDS = 0.1;
function bodyRanges(start: number, end: number, segments?: TimeRange[] | null): TimeRange[] {
const body = (segments ?? []).filter((s) => s.end > s.start);
+
return body.length ? body : [{ start, end }];
}
function coveringSpans(ranges: TimeRange[]): TimeRange[] {
const spans: TimeRange[] = [];
+
for (const r of [...ranges].sort((a, b) => a.start - b.start)) {
const last = spans[spans.length - 1];
+
if (last && r.start <= last.end + EDGE_TOLERANCE) last.end = Math.max(last.end, r.end);
else spans.push({ ...r });
}
+
return spans;
}
+/** A hook as it arrives from a request body, before any field is checked. */
+export type HookInput =
+ | { start?: number | string; end?: number | string; mode?: string }
+ | string
+ | null
+ | undefined;
+
+function isFiniteNumber(value: number | string | undefined): value is number {
+ return Number.isFinite(value);
+}
+
/** Returns an error message, or null when the hook is renderable (or absent). */
export function validateHook(
- hook: unknown,
+ hook: HookInput,
start: number,
end: number,
segments?: TimeRange[] | null,
): string | null {
if (hook === undefined || hook === null) return null;
- if (typeof hook !== "object") return "hook must be an object with start, end and mode";
- const { start: hs, end: he, mode } = hook as Record<string, unknown>;
- if (typeof hs !== "number" || !Number.isFinite(hs) || typeof he !== "number" || !Number.isFinite(he)) {
+
+ if (!(hook instanceof Object)) return "hook must be an object with start, end and mode";
+ const { start: hs, end: he, mode } = hook;
+
+ if (!isFiniteNumber(hs) || !isFiniteNumber(he)) {
return "hook start and end must be numbers of seconds";
}
+
if (mode !== "repeat" && mode !== "move") return 'hook mode must be "repeat" or "move"';
+
if (he <= hs) return "hook end must be greater than hook start";
const length = he - hs;
+
if (length < MIN_HOOK_SECONDS || length > MAX_HOOK_SECONDS) {
return `hook runs ${length.toFixed(1)}s. It must run between ${MIN_HOOK_SECONDS} and ${MAX_HOOK_SECONDS} seconds.`;
}
+
const inside = coveringSpans(bodyRanges(start, end, segments)).some(
(s) => s.start - EDGE_TOLERANCE <= hs && he <= s.end + EDGE_TOLERANCE,
);
+
if (!inside) {
return `hook ${hs.toFixed(2)}-${he.toFixed(2)}s is not inside the clip body. Pick a passage the clip already plays.`;
}
+
if (mode === "move" && playbackRanges(start, end, segments, { start: hs, end: he, mode }).length < 2) {
return "A move hook cannot take the whole clip. Use repeat, or widen the clip.";
}
+
return null;
}
@@ -84,10 +108,13 @@ export function playbackRanges(
hook?: ClipHook | null,
): TimeRange[] {
const body = bodyRanges(start, end, segments).map((s) => ({ start: s.start, end: s.end }));
+
if (!hook) return body;
const head = { start: hook.start, end: hook.end };
+
if (hook.mode === "repeat") return [head, ...body];
const rest: TimeRange[] = [];
+
for (const s of body) {
for (const [a, b] of [
[s.start, Math.min(s.end, hook.start)],
@@ -96,6 +123,7 @@ export function playbackRanges(
if (b - a >= MIN_REMNANT_SECONDS) rest.push({ start: a, end: b });
}
}
+
return [head, ...rest];
}
diff --git a/src/utils/clip-results.test.ts b/src/utils/clip-results.test.ts
index 18cf730..65fb9c1 100644
--- a/src/utils/clip-results.test.ts
+++ b/src/utils/clip-results.test.ts
@@ -13,6 +13,7 @@ describe("tagSubmittedClip", () => {
{ clip_index: 1, status: "success", output_path: "/out/b.mp4" },
specs,
);
+
expect(row.source_start_second).toBe(640);
expect(row.source_end_second).toBe(700);
});
@@ -24,6 +25,7 @@ describe("tagSubmittedClip", () => {
{ clip_index: 0, status: "success", start_second: 123.4, end_second: 165 },
specs,
);
+
expect(row.start_second).toBe(123.4);
expect(row.source_start_second).toBe(120);
});
@@ -39,6 +41,7 @@ describe("tagSubmittedClip", () => {
{ clip_index: 1, status: "error", error: "ffmpeg died" },
specs,
);
+
expect(row.source_start_second).toBe(640);
});
});
@@ -53,6 +56,7 @@ describe("tagSubmittedClips", () => {
{ clip_index: 1, status: "error", error: "boom" },
],
};
+
const tagged = tagSubmittedClips(data, specs);
expect(tagged?.results.map((r) => r.source_start_second)).toEqual([120, 640]);
});
diff --git a/src/utils/clip-results.ts b/src/utils/clip-results.ts
index 2624d9b..6102e37 100644
--- a/src/utils/clip-results.ts
+++ b/src/utils/clip-results.ts
@@ -1,6 +1,7 @@
import type { BatchClipsResult } from "../models/index.js";
type ClipResultRow = BatchClipsResult["results"][number];
+
export type ClipBounds = { start_second: number; end_second: number };
// Python numbers its result rows by position in the clips array it was handed,
@@ -13,9 +14,10 @@ export function tagSubmittedClip(
row: ClipResultRow,
clipSpecs?: ClipBounds[],
): ClipResultRow {
- const spec =
- typeof row.clip_index === "number" ? clipSpecs?.[row.clip_index] : undefined;
+ const spec = row.clip_index !== undefined ? clipSpecs?.[row.clip_index] : undefined;
+
if (!spec) return row;
+
return {
...row,
source_start_second: spec.start_second,
@@ -28,6 +30,7 @@ export function tagSubmittedClips(
clipSpecs?: ClipBounds[],
): BatchClipsResult | undefined {
if (!data?.results) return data;
+
return {
...data,
results: data.results.map((row) => tagSubmittedClip(row, clipSpecs)),
@@ -37,6 +40,7 @@ export function tagSubmittedClips(
// Clips render in parallel, so each worker reports its own share of the batch and
// the percentages arrive out of order. Only ever move the bar forward.
export function advanceProgress(job: { progress: number }, percent: number): number {
- if (typeof percent === "number" && percent > job.progress) job.progress = percent;
+ if (percent > job.progress) job.progress = percent;
+
return job.progress;
}
diff --git a/src/utils/clip-validation.test.ts b/src/utils/clip-validation.test.ts
index 06deb9d..41fa660 100644
--- a/src/utils/clip-validation.test.ts
+++ b/src/utils/clip-validation.test.ts
@@ -14,7 +14,7 @@ describe("validateClipRange", () => {
});
it("rejects non-numbers", () => {
- expect(validateClipRange("10" as unknown, 40)).toMatch(/must be numbers/);
+ expect(validateClipRange("10", 40)).toMatch(/must be numbers/);
expect(validateClipRange(10, NaN)).toMatch(/must be numbers/);
expect(validateClipRange(undefined, undefined)).toMatch(/must be numbers/);
});
@@ -128,6 +128,7 @@ describe("validateSuggestionContext", () => {
standalone: "that the company had just been acquired",
context_line: "Right after the acquisition:",
};
+
expect(validateSuggestionContext(needsSetup)).toMatch(/nothing renders it yet/);
const orphan = {
@@ -135,6 +136,7 @@ describe("validateSuggestionContext", () => {
preview_text: "Yeah, and that's exactly why we shut it down.",
context_line: "Why did you kill the product?",
};
+
expect(validateSuggestionContext(orphan)).toMatch(/Move start_second back/);
});
diff --git a/src/utils/clip-validation.ts b/src/utils/clip-validation.ts
index bf3b066..255d754 100644
--- a/src/utils/clip-validation.ts
+++ b/src/utils/clip-validation.ts
@@ -2,26 +2,32 @@ export function maxClipSeconds(format?: string): number {
return format === "horizontal" ? 300 : 180;
}
+/** A range bound as it arrives from a request or tool call, before it is checked. */
+export type RangeBound = number | string | null | undefined;
+
+function isFiniteBound(value: RangeBound): value is number {
+ return Number.isFinite(value);
+}
+
/** Returns an error message, or null when the range is renderable. */
export function validateClipRange(
- start: unknown,
- end: unknown,
+ start: RangeBound,
+ end: RangeBound,
format?: string,
): string | null {
- if (
- typeof start !== "number" ||
- !Number.isFinite(start) ||
- typeof end !== "number" ||
- !Number.isFinite(end)
- ) {
+ if (!isFiniteBound(start) || !isFiniteBound(end)) {
return "start_second and end_second must be numbers";
}
+
if (start < 0) return "start_second must be >= 0";
+
if (end <= start) return "end_second must be greater than start_second";
const maxDur = maxClipSeconds(format);
+
if (end - start > maxDur) {
return `Clip too long (${Math.round(end - start)}s). Max ${maxDur} seconds.`;
}
+
return null;
}
@@ -29,20 +35,19 @@ export function validateClipRange(
// renderable duration plus trim headroom.
const MAX_SUGGESTION_SECONDS = 600;
-export function validateSuggestionRange(start: unknown, end: unknown): string | null {
- if (
- typeof start !== "number" ||
- !Number.isFinite(start) ||
- typeof end !== "number" ||
- !Number.isFinite(end)
- ) {
+export function validateSuggestionRange(start: RangeBound, end: RangeBound): string | null {
+ if (!isFiniteBound(start) || !isFiniteBound(end)) {
return "start_second and end_second must be numbers";
}
+
if (start < 0) return "start_second must be >= 0";
+
if (end <= start) return "end_second must be greater than start_second";
+
if (end - start > MAX_SUGGESTION_SECONDS) {
return `Suggested range too long (${Math.round(end - start)}s). Max ${MAX_SUGGESTION_SECONDS} seconds.`;
}
+
return null;
}
@@ -53,6 +58,7 @@ export function validateSuggestionRange(start: unknown, end: unknown): string |
// ---------------------------------------------------------------------------
const MIN_PAYOFF_WORDS = 5;
+
// Japanese and Chinese do not space-delimit, so every payoff in them counts as
// one "word" however long it runs. A character floor stands in there.
const MIN_PAYOFF_CHARS = 12;
@@ -115,11 +121,13 @@ function normalize(text: string): string {
function wordCount(text: string): number {
const n = normalize(text);
+
return n ? n.split(" ").length : 0;
}
function isTooThin(payoff: string): boolean {
const normalized = normalize(payoff);
+
return normalized.includes(" ")
? wordCount(payoff) < MIN_PAYOFF_WORDS
: normalized.length < MIN_PAYOFF_CHARS;
@@ -130,43 +138,53 @@ export function isSelfContained(standalone: string): boolean {
}
/** Returns the backward-pointing opener, or null when the clip starts clean. */
-export function findOrphanOpener(previewText: unknown): string | null {
- if (typeof previewText !== "string") return null;
+export function findOrphanOpener(previewText: string | null | undefined): string | null {
+ if (!previewText) return null;
const words = normalize(previewText).split(" ").filter(Boolean);
+
if (!words.length) return null;
+
if (SELF_CONTAINED_STARTS.has(words.slice(0, 2).join(" "))) return null;
+
// "I mean" is only a stall when the sentence leads with it.
if (words[0] === "i" && words[1] === "mean") return "i mean";
+
if (words[0] === "so") {
// "that's" and "they're" have to match "that" and "they".
const next = (words[1] ?? "").replace(/'(s|d|ll|re|ve)$/, "");
+
return SO_POINTS_BACK.has(next) ? `so ${next}` : null;
}
+
return ORPHAN_OPENERS.has(words[0]) ? words[0] : null;
}
export interface SuggestionContext {
- title?: unknown;
- payoff?: unknown;
- standalone?: unknown;
- context_line?: unknown;
- preview_text?: unknown;
+ title?: string | null;
+ payoff?: string | null;
+ standalone?: string | null;
+ context_line?: string | null;
+ preview_text?: string | null;
}
/** Returns an error message, or null when the clip carries its own context. */
export function validateSuggestionContext(s: SuggestionContext): string | null {
- const payoff = typeof s.payoff === "string" ? s.payoff.trim() : "";
+ const payoff = s.payoff?.trim() ?? "";
+
if (!payoff) {
return "payoff is required: one sentence, second person, on what the viewer walks away with.";
}
+
if (isTooThin(payoff)) {
return `payoff is too thin ("${payoff}"). Write a full sentence on what the viewer walks away with.`;
}
- if (typeof s.title === "string" && normalize(s.title) === normalize(payoff)) {
+
+ if (s.title && normalize(s.title) === normalize(payoff)) {
return "payoff just restates the title. Say what the viewer gets, not what the clip is called.";
}
- const standalone = typeof s.standalone === "string" ? s.standalone.trim() : "";
+ const standalone = s.standalone?.trim() ?? "";
+
if (!standalone) {
return 'standalone is required: what the viewer must already know to follow this clip, or "nothing".';
}
@@ -184,6 +202,7 @@ export function validateSuggestionContext(s: SuggestionContext): string | null {
}
const orphan = findOrphanOpener(s.preview_text);
+
if (orphan) {
return (
`preview_text opens on "${orphan}", which points at something said before the cut. ` +
diff --git a/src/utils/errors.ts b/src/utils/errors.ts
index 06facef..b8dc1e4 100644
--- a/src/utils/errors.ts
+++ b/src/utils/errors.ts
@@ -1,6 +1,6 @@
/** Extract a human-readable message from an unknown thrown value. */
-export function errMsg(err: unknown): string {
- return err instanceof Error ? err.message : String(err);
+export function errMsg(cause: unknown): string {
+ return cause instanceof Error ? cause.message : String(cause);
}
type McpTextResult = {
@@ -9,9 +9,9 @@ type McpTextResult = {
};
/** Standard MCP error result for a caught exception. */
-export function mcpError(err: unknown): McpTextResult {
+export function mcpError(cause: unknown): McpTextResult {
return {
- content: [{ type: "text", text: `Error: ${errMsg(err)}` }],
+ content: [{ type: "text", text: `Error: ${errMsg(cause)}` }],
isError: true,
};
}
diff --git a/src/utils/full-episode-export.ts b/src/utils/full-episode-export.ts
index 09c2248..0a90392 100644
--- a/src/utils/full-episode-export.ts
+++ b/src/utils/full-episode-export.ts
@@ -1,4 +1,5 @@
import { basename, extname } from "path";
+import { z } from "zod";
export const FULL_EPISODE_CAPTION_STYLES = [
"branded",
@@ -16,21 +17,29 @@ export interface FullEpisodeProgress {
export function fullEpisodeOutputStem(videoPath: string): string {
const filename = basename(videoPath, extname(videoPath));
+
const safe = filename
.trim()
.replace(/[^a-zA-Z0-9._-]/g, "-")
.replace(/^-+|-+$/g, "");
+
return `${safe || "episode"}_full_captioned`;
}
+const progressLineSchema = z.looseObject({ percent: z.unknown(), message: z.string() });
+
export function parseFullEpisodeProgress(line: string): FullEpisodeProgress | null {
const prefix = "PODCLI_PROGRESS=";
const marker = line.indexOf(prefix);
+
if (marker < 0) return null;
+
try {
- const parsed = JSON.parse(line.slice(marker + prefix.length));
+ const parsed = progressLineSchema.parse(JSON.parse(line.slice(marker + prefix.length)));
const percent = Number(parsed.percent);
- if (!Number.isFinite(percent) || typeof parsed.message !== "string") return null;
+
+ if (!Number.isFinite(percent)) return null;
+
return {
percent: Math.max(0, Math.min(100, Math.round(percent))),
message: parsed.message,
diff --git a/src/utils/http-range.ts b/src/utils/http-range.ts
index 5ac3d0e..c7b941d 100644
--- a/src/utils/http-range.ts
+++ b/src/utils/http-range.ts
@@ -7,18 +7,24 @@ export interface ByteRange {
export function resolveByteRange(header: string, fileSize: number): ByteRange | null {
if (!Number.isSafeInteger(fileSize) || fileSize <= 0) return null;
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
+
if (!match || (!match[1] && !match[2])) return null;
if (!match[1]) {
const suffixLength = Number.parseInt(match[2], 10);
+
if (!Number.isSafeInteger(suffixLength) || suffixLength <= 0) return null;
const length = Math.min(suffixLength, fileSize);
+
return { start: fileSize - length, end: fileSize - 1 };
}
const start = Number.parseInt(match[1], 10);
const requestedEnd = match[2] ? Number.parseInt(match[2], 10) : fileSize - 1;
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(requestedEnd)) return null;
+
if (start < 0 || start >= fileSize || requestedEnd < start) return null;
+
return { start, end: Math.min(requestedEnd, fileSize - 1) };
}
diff --git a/src/utils/local-request.test.ts b/src/utils/local-request.test.ts
new file mode 100644
index 0000000..f69aaf5
--- /dev/null
+++ b/src/utils/local-request.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from "vitest";
+import { isLocalHost, rejectReason } from "./local-request.js";
+
+describe("isLocalHost", () => {
+ it("accepts loopback names with and without a port", () => {
+ for (const host of ["localhost", "localhost:3847", "127.0.0.1:3847", "[::1]:3847", "[::1]"]) {
+ expect(isLocalHost(host)).toBe(true);
+ }
+ });
+
+ it("rejects other names, including look-alikes", () => {
+ for (const host of ["evil.com", "localhost.evil.com", "127.0.0.1.evil.com:3847", "192.168.1.5:3847", "", undefined]) {
+ expect(isLocalHost(host)).toBe(false);
+ }
+ });
+});
+
+describe("rejectReason", () => {
+ const host = "localhost:3847";
+
+ it("blocks a rebound Host", () => {
+ expect(rejectReason("GET", { host: "evil.com:3847" })).toBe("Forbidden host");
+ });
+
+ it("blocks a state-changing request from a foreign origin", () => {
+ expect(rejectReason("POST", { host, origin: "https://evil.com" })).toBe("Forbidden origin");
+ expect(rejectReason("POST", { host, origin: "null" })).toBe("Forbidden origin");
+ expect(rejectReason("POST", { host, origin: "http://localhost:9999" })).toBe("Forbidden origin");
+ });
+
+ it("allows same-origin and origin-less requests", () => {
+ expect(rejectReason("POST", { host, origin: "http://localhost:3847" })).toBeNull();
+ expect(rejectReason("POST", { host })).toBeNull();
+ expect(rejectReason("GET", { host, origin: "https://evil.com" })).toBeNull();
+ });
+
+ it("skips the Host check when the studio is bound to the LAN", () => {
+ expect(rejectReason("GET", { host: "192.168.1.5:3847" }, true)).toBeNull();
+ expect(rejectReason("POST", { host: "192.168.1.5:3847", origin: "https://evil.com" }, true)).toBe("Forbidden origin");
+ });
+});
diff --git a/src/utils/local-request.ts b/src/utils/local-request.ts
new file mode 100644
index 0000000..96b729a
--- /dev/null
+++ b/src/utils/local-request.ts
@@ -0,0 +1,46 @@
+const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
+const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
+
+function hostnameOf(host: string): string | null {
+ try {
+ return new URL(`http://${host}`).hostname;
+ } catch {
+ return null;
+ }
+}
+
+/** True when a Host header names this machine. Any port is accepted. */
+export function isLocalHost(host: string | undefined): boolean {
+ if (!host) return false;
+ const name = hostnameOf(host);
+
+ return name !== null && LOCAL_HOSTNAMES.has(name);
+}
+
+/**
+ * Why a request must be refused, or null to let it through.
+ *
+ * The studio has no login, so the Host check stops DNS rebinding and the Origin
+ * check stops other websites from posting to it. A request without an Origin
+ * (curl, the MCP server's fetch) is not a browser cross-site request and passes.
+ * With allowAnyHost, an operator who bound the studio to the LAN keeps the
+ * Origin check but not the Host check.
+ */
+export function rejectReason(
+ method: string,
+ headers: { host?: string; origin?: string },
+ allowAnyHost = false,
+): string | null {
+ if (!allowAnyHost && !isLocalHost(headers.host)) return "Forbidden host";
+
+ if (SAFE_METHODS.has(method.toUpperCase()) || headers.origin === undefined) return null;
+ let originHost: string;
+
+ try {
+ originHost = new URL(headers.origin).host;
+ } catch {
+ return "Forbidden origin";
+ }
+
+ return originHost.toLowerCase() === (headers.host ?? "").toLowerCase() ? null : "Forbidden origin";
+}
diff --git a/src/utils/logger.test.ts b/src/utils/logger.test.ts
index ed08f22..3b7180c 100644
--- a/src/utils/logger.test.ts
+++ b/src/utils/logger.test.ts
@@ -3,16 +3,16 @@ import { logger, childLogger } from "./logger.js";
describe("logger", () => {
it("exposes winston-compatible levels", () => {
- expect(typeof logger.info).toBe("function");
- expect(typeof logger.warn).toBe("function");
- expect(typeof logger.error).toBe("function");
- expect(typeof logger.debug).toBe("function");
+ expect(logger.info).toBeInstanceOf(Function);
+ expect(logger.warn).toBeInstanceOf(Function);
+ expect(logger.error).toBeInstanceOf(Function);
+ expect(logger.debug).toBeInstanceOf(Function);
});
it("childLogger tags messages with the module name", () => {
const child = childLogger("test-mod");
expect(child).toBeDefined();
- expect(typeof child.info).toBe("function");
+ expect(child.info).toBeInstanceOf(Function);
});
it("respects PODCLI_LOG_LEVEL default (debug in dev)", () => {
diff --git a/src/utils/logger.ts b/src/utils/logger.ts
index 6f66a8f..a4a221e 100644
--- a/src/utils/logger.ts
+++ b/src/utils/logger.ts
@@ -17,9 +17,10 @@ export const logger = winston.createLogger({
process.env.PODCLI_LOG_JSON === "1"
? winston.format.json()
: winston.format.printf(({ timestamp, level: lvl, message, mod, ...rest }) => {
- const tag = mod ? ` [${mod as string}]` : "";
+ const tag = mod ? ` [${mod}]` : "";
const extra = Object.keys(rest).length ? ` ${JSON.stringify(rest)}` : "";
- return `${timestamp as string} ${lvl}${tag} ${message as string}${extra}`;
+
+ return `${timestamp} ${lvl}${tag} ${message}${extra}`;
}),
),
transports: [new winston.transports.Console({ stderrLevels: ["error", "warn", "info", "debug"] })],
diff --git a/src/utils/safe-path.ts b/src/utils/safe-path.ts
new file mode 100644
index 0000000..a45df7a
--- /dev/null
+++ b/src/utils/safe-path.ts
@@ -0,0 +1,12 @@
+import path from "path";
+
+/** Resolve `filename` under `base`, or null when it escapes `base`. */
+export function safePath(base: string, filename: string): string | null {
+ const root = path.resolve(base);
+ const resolved = path.resolve(base, filename);
+
+ // Compare on a path boundary so "/data/output-evil" isn't accepted as inside "/data/output".
+ if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;
+
+ return resolved;
+}
diff --git a/src/utils/selection-hash.test.ts b/src/utils/selection-hash.test.ts
index 626f434..68197b2 100644
--- a/src/utils/selection-hash.test.ts
+++ b/src/utils/selection-hash.test.ts
@@ -46,18 +46,22 @@ describe("computeSelectionHash", () => {
it("changes when segments change", () => {
const a = computeSelectionHash(clip(), words);
+
const b = computeSelectionHash(
clip({ segments: [{ start: 10, end: 15 }] }),
words,
);
+
expect(a).not.toBe(b);
});
it("changes when the transcript words inside the range change", () => {
const a = computeSelectionHash(clip(), words);
+
const editedWords = words.map((w) =>
w.word === "three" ? { ...w, word: "THREE-EDITED" } : w,
);
+
const b = computeSelectionHash(clip(), editedWords);
expect(a).not.toBe(b);
});
@@ -79,10 +83,12 @@ describe("computeSelectionHash", () => {
it("changes when a hook is added", () => {
const a = computeSelectionHash(clip(), words);
+
const b = computeSelectionHash(
{ ...clip(), hook: { start: 10, end: 12, mode: "repeat" } },
words,
);
+
expect(a).not.toBe(b);
});
diff --git a/src/utils/srt-time.ts b/src/utils/srt-time.ts
index b7793b3..594fd13 100644
--- a/src/utils/srt-time.ts
+++ b/src/utils/srt-time.ts
@@ -14,6 +14,7 @@ export function formatSrtTime(s: number): string {
totalMs -= m * 60_000;
const sec = Math.floor(totalMs / 1000);
const ms = totalMs - sec * 1000;
+
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")},${String(ms).padStart(3, "0")}`;
}
diff --git a/src/utils/thumbnail-layout.test.ts b/src/utils/thumbnail-layout.test.ts
index 589db1d..c4c1f05 100644
--- a/src/utils/thumbnail-layout.test.ts
+++ b/src/utils/thumbnail-layout.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { needsFrame, parseThumbnailRender, thumbnailRenderArgs } from "./thumbnail-layout.js";
+import { needsFrame, thumbnailRenderArgs } from "./thumbnail-layout.js";
const clip = { source_video: "/eps/ep1.mp4", start_second: 12.5, end_second: 48 };
@@ -16,6 +16,7 @@ describe("thumbnailRenderArgs", () => {
const args = thumbnailRenderArgs({
output: "/out/t.png", frame: "/f.jpg", frameInfo: { face_x_pct: 40 }, layout: "pair", clip,
});
+
expect(args).toContain("--frame");
expect(args).not.toContain("--frame-info");
expect(args).not.toContain("--swap");
@@ -25,6 +26,7 @@ describe("thumbnailRenderArgs", () => {
const args = thumbnailRenderArgs({
output: "/out/t.png", frame: "/f.jpg", frameInfo: { face_x_pct: 40 }, line1: "One", line2: "Two", clip,
});
+
expect(args).toEqual([
"thumbnail-render", "--output", "/out/t.png", "--frame", "/f.jpg",
"--line1=One", "--line2=Two", "--frame-info", '{"face_x_pct":40}',
@@ -43,24 +45,3 @@ describe("needsFrame", () => {
expect(needsFrame(undefined)).toBe(true);
});
});
-
-describe("parseThumbnailRender", () => {
- it("reads the path and which source second each face came from", () => {
- const people = [
- { side: "left", role: "guest", from: "seats", source_time: 14 },
- { side: "right", role: "host", from: "seats", source_time: 40.5 },
- ];
- const out = `progress line\n${JSON.stringify({ path: "/out/t.png", layout: "pair", people })}\n`;
- expect(parseThumbnailRender(out)).toEqual({ path: "/out/t.png", report: { layout: "pair", people } });
- });
-
- it("carries the reason a pair render fell back to one face", () => {
- const note = "Only one person is on screen in this clip. The thumbnail uses the single-face layout.";
- const out = JSON.stringify({ path: "/out/t.png", layout: "single", note });
- expect(parseThumbnailRender(out).report).toEqual({ layout: "single", note });
- });
-
- it("answers an empty path for output it cannot read", () => {
- expect(parseThumbnailRender("not json")).toEqual({ path: "", report: { layout: "single" } });
- });
-});
diff --git a/src/utils/thumbnail-layout.ts b/src/utils/thumbnail-layout.ts
index 003622e..5d559f4 100644
--- a/src/utils/thumbnail-layout.ts
+++ b/src/utils/thumbnail-layout.ts
@@ -1,7 +1,7 @@
/**
* Thumbnail layouts: one face, or two people side by side from the clip.
* backend/services/thumbnail_pair.py picks the people; this builds the
- * `thumbnail-render` call for a clip and reads back what it reported.
+ * `thumbnail-render` call for a clip. thumbnail-render-output.ts reads back what it reported.
*
* No imports, so the studio client can bundle it as is.
*/
@@ -37,7 +37,7 @@ export interface ClipThumbnailRender {
}
/** Whether a render needs a chosen frame. The pair layout takes both people from the clip. */
-export function needsFrame(layout: unknown): boolean {
+export function needsFrame(layout: string | undefined): boolean {
return layout !== "pair";
}
@@ -45,37 +45,27 @@ export function needsFrame(layout: unknown): boolean {
export function thumbnailRenderArgs(r: ClipThumbnailRender): string[] {
const pair = r.layout === "pair";
const args = ["thumbnail-render", "--output", r.output];
+
if (r.frame) args.push("--frame", r.frame);
+
if (r.layout === "pair" || r.layout === "single") args.push("--layout", r.layout);
+
if (pair) {
args.push(
"--video", r.clip.source_video,
"--start", String(r.clip.start_second),
"--end", String(r.clip.end_second),
);
+
if (r.swap) args.push("--swap");
}
+
if (r.line1) args.push(`--line1=${r.line1}`);
+
if (r.line2) args.push(`--line2=${r.line2}`);
+
// Face metadata describes the chosen frame, which a pair render does not draw.
if (r.frameInfo && !pair) args.push("--frame-info", JSON.stringify(r.frameInfo));
- return args;
-}
-/** The PNG path and layout report from the last JSON line `thumbnail-render` printed. */
-export function parseThumbnailRender(stdout: string): { path: string; report: ThumbnailLayoutReport } {
- const line = stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));
- try {
- const parsed = JSON.parse(line || "{}");
- return {
- path: typeof parsed.path === "string" ? parsed.path : "",
- report: {
- layout: parsed.layout === "pair" ? "pair" : "single",
- ...(typeof parsed.note === "string" && { note: parsed.note }),
- ...(Array.isArray(parsed.people) && { people: parsed.people as ThumbnailPerson[] }),
- },
- };
- } catch {
- return { path: "", report: { layout: "single" } };
- }
+ return args;
}
diff --git a/src/utils/thumbnail-render-output.test.ts b/src/utils/thumbnail-render-output.test.ts
new file mode 100644
index 0000000..5740ea9
--- /dev/null
+++ b/src/utils/thumbnail-render-output.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import { parseThumbnailRender } from "./thumbnail-render-output.js";
+
+describe("parseThumbnailRender", () => {
+ it("reads the path and which source second each face came from", () => {
+ const people = [
+ { side: "left", role: "guest", from: "seats", source_time: 14 },
+ { side: "right", role: "host", from: "seats", source_time: 40.5 },
+ ];
+
+ const out = `progress line\n${JSON.stringify({ path: "/out/t.png", layout: "pair", people })}\n`;
+ expect(parseThumbnailRender(out)).toEqual({ path: "/out/t.png", report: { layout: "pair", people } });
+ });
+
+ it("carries the reason a pair render fell back to one face", () => {
+ const note = "Only one person is on screen in this clip. The thumbnail uses the single-face layout.";
+ const out = JSON.stringify({ path: "/out/t.png", layout: "single", note });
+ expect(parseThumbnailRender(out).report).toEqual({ layout: "single", note });
+ });
+
+ it("answers an empty path for output it cannot read", () => {
+ expect(parseThumbnailRender("not json")).toEqual({ path: "", report: { layout: "single" } });
+ });
+});
diff --git a/src/utils/thumbnail-render-output.ts b/src/utils/thumbnail-render-output.ts
new file mode 100644
index 0000000..16165ad
--- /dev/null
+++ b/src/utils/thumbnail-render-output.ts
@@ -0,0 +1,43 @@
+import { z } from "zod";
+import type { ThumbnailLayoutReport } from "./thumbnail-layout.js";
+
+const thumbnailPersonSchema = z.object({
+ side: z.enum(["left", "right"]),
+ role: z.enum(["guest", "host"]).nullable(),
+ from: z.enum(["seats", "multicam", "image"]),
+ source_time: z.number().nullable(),
+ camera: z.string().optional(),
+ camera_time: z.number().optional(),
+});
+
+const renderOutputSchema = z.looseObject({
+ path: z.string().catch(""),
+ layout: z.string().optional(),
+ note: z.string().optional().catch(undefined),
+ people: z.array(thumbnailPersonSchema).optional().catch(undefined),
+});
+
+export interface ThumbnailRenderOutput {
+ path: string;
+ report: ThumbnailLayoutReport;
+}
+
+/** The PNG path and layout report from the last JSON line `thumbnail-render` printed. */
+export function parseThumbnailRender(stdout: string): ThumbnailRenderOutput {
+ const line = stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));
+
+ try {
+ const parsed = renderOutputSchema.parse(JSON.parse(line || "{}"));
+
+ return {
+ path: parsed.path,
+ report: {
+ layout: parsed.layout === "pair" ? "pair" : "single",
+ ...(parsed.note !== undefined && { note: parsed.note }),
+ ...(parsed.people && { people: parsed.people }),
+ },
+ };
+ } catch {
+ return { path: "", report: { layout: "single" } };
+ }
+}
diff --git a/src/utils/transcript.test.ts b/src/utils/transcript.test.ts
index 58dcc2d..7eedc4c 100644
--- a/src/utils/transcript.test.ts
+++ b/src/utils/transcript.test.ts
@@ -62,6 +62,7 @@ describe("reconcileSegmentsForRange", () => {
{ start: 0, end: 5 },
{ start: 20, end: 25 },
];
+
expect(reconcileSegmentsForRange(segments, 0, 25, 20, 25)).toBeUndefined();
});
@@ -70,6 +71,7 @@ describe("reconcileSegmentsForRange", () => {
{ start: 0, end: 10 },
{ start: 15, end: 25 },
];
+
expect(reconcileSegmentsForRange(segments, 0, 25, 5, 20)).toEqual([
{ start: 5, end: 10 },
{ start: 15, end: 20 },
@@ -89,6 +91,7 @@ describe("reconcileSegmentsForRange", () => {
{ start: 2, end: 8 },
{ start: 12, end: 18 },
];
+
expect(reconcileSegmentsForRange(segments, 2, 18, 0, 20)).toEqual([
{ start: 0, end: 8 },
{ start: 12, end: 20 },
@@ -101,6 +104,7 @@ describe("reconcileSegmentsForRange", () => {
{ start: 12, end: 18 },
{ start: 50, end: 60 }, // entirely outside the new range
];
+
expect(reconcileSegmentsForRange(segments, 2, 60, 0, 20)).toEqual([
{ start: 0, end: 8 },
{ start: 12, end: 20 },
diff --git a/src/utils/transcript.ts b/src/utils/transcript.ts
index ef1e585..b46b493 100644
--- a/src/utils/transcript.ts
+++ b/src/utils/transcript.ts
@@ -11,22 +11,25 @@ export function sliceTranscript(
end: number,
): string | undefined {
if (!words || words.length === 0) return undefined;
+
const text = words
.filter((w) => w.start >= start && w.start < end)
.map((w) => w.word)
.join(" ")
.replace(/\s+/g, " ")
.trim();
+
return text || undefined;
}
-/** Word objects spoken within [start, end] — used to re-burn captions on re-render. */
+/** Word objects spoken within [start, end]; used to re-burn captions on re-render. */
export function sliceWords(
words: WordTimestamp[] | undefined | null,
start: number,
end: number,
): WordTimestamp[] {
if (!words) return [];
+
return words.filter((w) => w.start >= start && w.start < end);
}
@@ -37,9 +40,11 @@ export function findContentType(
end: number,
): string | undefined {
if (!suggestions || suggestions.length === 0) return undefined;
+
const match = suggestions.find(
(s) => Math.abs(s.start_second - start) <= 2 && Math.abs(s.end_second - end) <= 2,
);
+
return match?.content_type;
}
@@ -64,10 +69,13 @@ export function findGroundingText(
end: number,
): { payoff?: string; context_line?: string; preview_text?: string } | undefined {
if (!suggestions || suggestions.length === 0) return undefined;
+
const match = suggestions.find(
(s) => Math.abs(s.start_second - start) <= 2 && Math.abs(s.end_second - end) <= 2,
);
+
if (!match) return undefined;
+
return { payoff: match.payoff, context_line: match.context_line, preview_text: match.preview_text };
}
@@ -110,11 +118,13 @@ export function reconcileSegmentsForRange(
const clamped = segments
.map((s) => ({ start: Math.max(s.start, nextStart), end: Math.min(s.end, nextEnd) }))
.filter((s) => s.end > s.start);
+
if (clamped.length === 0) return undefined;
if (clamped.length > 1) {
clamped[0] = { ...clamped[0], start: nextStart };
clamped[clamped.length - 1] = { ...clamped[clamped.length - 1], end: nextEnd };
+
return clamped;
}
@@ -124,6 +134,7 @@ export function reconcileSegmentsForRange(
) {
return undefined;
}
+
return clamped;
}
diff --git a/src/utils/video-identity.ts b/src/utils/video-identity.ts
index 474bacc..213ae31 100644
--- a/src/utils/video-identity.ts
+++ b/src/utils/video-identity.ts
@@ -16,6 +16,7 @@ export interface VideoIdentity {
export function computeVideoIdentity(path: string): VideoIdentity | null {
try {
const stat = statSync(path);
+
return { path, size: stat.size, mtimeMs: stat.mtimeMs };
} catch {
return null;
@@ -28,6 +29,7 @@ export function identitiesMatch(
b: VideoIdentity | null | undefined,
): boolean {
if (!a || !b) return false;
+
return a.path === b.path && a.size === b.size && a.mtimeMs === b.mtimeMs;
}
@@ -43,8 +45,11 @@ export function transcriptVideoMismatch(
): string | null {
if (!transcriptVideoIdentity) return null;
const current = computeVideoIdentity(videoPath);
+
if (!current) return null;
+
if (identitiesMatch(transcriptVideoIdentity, current)) return null;
+
return (
`Session transcript belongs to a different video than the one currently set ` +
`(${transcriptVideoIdentity.path}). Re-transcribe or re-import a transcript for ` +
diff --git a/src/utils/ytdlp-args.test.ts b/src/utils/ytdlp-args.test.ts
index 878c0d2..85a669f 100644
--- a/src/utils/ytdlp-args.test.ts
+++ b/src/utils/ytdlp-args.test.ts
@@ -53,6 +53,7 @@ describe("buildYtDlpArgs", () => {
cookiesFromBrowser: "firefox",
extractorArgs: "youtube:player_client=android",
});
+
expect(args[args.indexOf("--cookies-from-browser") + 1]).toBe("firefox");
expect(args[args.indexOf("--extractor-args") + 1]).toBe("youtube:player_client=android");
});
diff --git a/src/utils/ytdlp-args.ts b/src/utils/ytdlp-args.ts
index 6457e04..f234545 100644
--- a/src/utils/ytdlp-args.ts
+++ b/src/utils/ytdlp-args.ts
@@ -5,6 +5,7 @@
* drifted: the Python one lacked --js-runtimes. Whatever is added here reaches
* every download instead of the one that happened to be edited.
*/
+import { z } from "zod";
/** yt-dlp's SUPPORTED_BROWSERS, per yt_dlp/cookies.py. */
export const COOKIE_BROWSERS = [
@@ -21,8 +22,10 @@ export const COOKIE_BROWSERS = [
export type CookieBrowser = (typeof COOKIE_BROWSERS)[number];
+const cookieBrowserSchema = z.enum(COOKIE_BROWSERS);
+
export function isCookieBrowser(value: unknown): value is CookieBrowser {
- return typeof value === "string" && (COOKIE_BROWSERS as readonly string[]).includes(value);
+ return cookieBrowserSchema.safeParse(value).success;
}
// A bare z.string() lets a value like "--config-locations=/tmp/evil.conf" through
@@ -30,9 +33,13 @@ export function isCookieBrowser(value: unknown): value is CookieBrowser {
// positional argument, one that can point at a config carrying --exec. Only
// http(s) URLs are legitimate inputs here.
export function isHttpUrl(value: unknown): value is string {
- if (typeof value !== "string") return false;
+ const text = z.string().safeParse(value);
+
+ if (!text.success) return false;
+
try {
- const parsed = new URL(value);
+ const parsed = new URL(text.data);
+
return parsed.protocol === "http:" || parsed.protocol === "https:";
} catch {
return false;
@@ -72,7 +79,9 @@ export function buildYtDlpArgs(opts: YtDlpOptions): string[] {
args.push("--merge-output-format", "mp4");
if (opts.ffmpegLocation) args.push("--ffmpeg-location", opts.ffmpegLocation);
+
if (opts.cookiesFromBrowser) args.push("--cookies-from-browser", opts.cookiesFromBrowser);
+
// Free-text rather than an enum: YouTube rotates which clients work every few
// months, and an enum guarantees shipping a stale list.
if (opts.extractorArgs) args.push("--extractor-args", opts.extractorArgs);
@@ -84,10 +93,12 @@ export function buildYtDlpArgs(opts: YtDlpOptions): string[] {
if (opts.progressTemplate) {
args.push("--newline", "--progress", "--progress-template", opts.progressTemplate);
}
+
args.push("--print", "after_move:podcli-filepath:%(filepath)s");
// "--" forces everything after it to be read positionally, so a url that
// starts with a dash can never be parsed as another flag.
args.push("--", opts.url);
+
return args;
}
@@ -106,20 +117,25 @@ const CHANNEL_TABS = ["videos", "shorts", "streams", "playlists", "live", "podca
// (a tab, a playlist, a single video) pass through unchanged.
export function normalizeChannelUrl(url: string): string {
let parsed: URL;
+
try {
parsed = new URL(url);
} catch {
return url;
}
+
const segments = parsed.pathname.split("/").filter(Boolean);
const isChannelRoot = segments.length === 1 && segments[0].startsWith("@");
const isChannelIdRoot = segments.length === 2 && ["channel", "c", "user"].includes(segments[0]);
+
if (!isChannelRoot && !isChannelIdRoot) return url;
const lastSegment = segments.at(-1) ?? "";
+
if (CHANNEL_TABS.includes(lastSegment)) return url;
parsed.pathname = `${parsed.pathname.replace(/\/+$/, "")}/videos`;
+
return parsed.toString();
}
@@ -131,10 +147,13 @@ export function buildChannelListArgs(opts: YtDlpListOptions): string[] {
const args = ["-m", "yt_dlp"];
args.push("--ignore-config", "--no-config-locations", "--no-plugin-dirs");
args.push("--flat-playlist", "--no-warnings");
+
if (opts.limit) args.push("--playlist-end", String(opts.limit));
+
if (opts.cookiesFromBrowser) args.push("--cookies-from-browser", opts.cookiesFromBrowser);
args.push("--print", "%(.{id,title,duration,upload_date,url})j");
args.push("--", opts.channelUrl);
+
return args;
}
@@ -154,8 +173,10 @@ export function buildVideoInfoArgs(opts: YtDlpVideoInfoOptions): string[] {
// dump the first entry's info instead of erroring, silently mining the
// wrong video's captions.
args.push("--no-playlist");
+
if (opts.cookiesFromBrowser) args.push("--cookies-from-browser", opts.cookiesFromBrowser);
args.push("--dump-json", "--", opts.videoUrl);
+
return args;
}
@@ -165,13 +186,18 @@ export function extractYouTubeVideoId(url: string): string | null {
try {
const parsed = new URL(url);
const vParam = parsed.searchParams.get("v");
+
if (vParam) return vParam;
const pathMatch = parsed.pathname.match(/\/(?:shorts|embed|live)\/([^/?]+)/);
+
if (pathMatch) return pathMatch[1];
+
if (parsed.hostname === "youtu.be") {
const id = parsed.pathname.slice(1).split("/")[0];
+
return id || null;
}
+
return null;
} catch {
return null;
@@ -181,6 +207,7 @@ export function extractYouTubeVideoId(url: string): string | null {
/** Turns a yt-dlp failure into one line naming what to do about it. */
export function ytDlpHint(stderr: string): string | null {
const s = stderr.toLowerCase();
+
if (
s.includes("sign in to confirm") ||
s.includes("confirm you're not a bot") ||
@@ -188,14 +215,18 @@ export function ytDlpHint(stderr: string): string | null {
) {
return "The site asked for a signed-in session. Set PODCLI_YTDLP_BROWSER to the browser you are logged into (chrome, firefox, safari, edge, brave, chromium, opera, vivaldi, whale).";
}
+
if (s.includes("members-only") || s.includes("members only")) {
return "This is members-only. Set PODCLI_YTDLP_BROWSER to a browser signed in to an account with access.";
}
+
if (s.includes("private video")) {
return "This video is private. If it is yours, set PODCLI_YTDLP_BROWSER to a browser signed in to that account.";
}
+
if (s.includes("video unavailable") || s.includes("not available in your")) {
return "The video is unavailable from here, which is usually a region or age restriction. A signed-in browser profile via PODCLI_YTDLP_BROWSER often clears it.";
}
+
return null;
}
diff --git a/src/utils/zod-helpers.ts b/src/utils/zod-helpers.ts
new file mode 100644
index 0000000..eae224e
--- /dev/null
+++ b/src/utils/zod-helpers.ts
@@ -0,0 +1,5 @@
+import { z } from "zod";
+
+/** Reads a null from an external process as an absent value, matching an optional TypeScript field. */
+export const absentWhenNull = <T extends z.ZodType>(schema: T) =>
+ schema.nullish().transform((v) => v ?? undefined);
diff --git a/src/version.ts b/src/version.ts
index eed9051..f9e2630 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1,14 +1,21 @@
import { readFileSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
+import { z } from "zod";
+
+const packageVersionSchema = z.looseObject({ version: z.string() });
export function podcliVersion(): string {
const envVersion = process.env.PODCLI_VERSION?.trim();
+
if (envVersion) return envVersion;
try {
- const pkg = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf-8"));
- if (typeof pkg.version === "string" && pkg.version.trim()) return pkg.version;
+ const pkg = packageVersionSchema.parse(
+ JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf-8")),
+ );
+
+ if (pkg.version.trim()) return pkg.version;
} catch {
// Local dev fallback; release builds are stamped through PODCLI_VERSION.
}
diff --git a/tests/parity/.gitignore b/tests/parity/.gitignore
index 7ea24b7..8eb9824 100644
--- a/tests/parity/.gitignore
+++ b/tests/parity/.gitignore
@@ -1,4 +1,4 @@
-# Real-audio fixtures and captured baselines may contain podcast content —
+# Real-audio fixtures and captured baselines may contain podcast content:
# never commit them. The committable parity surface is the synthetic transcript,
# the goldens (*.ass.expected), and the harness code.
local/
diff --git a/tests/parity/README.md b/tests/parity/README.md
index 87ea258..03f1e20 100644
--- a/tests/parity/README.md
+++ b/tests/parity/README.md
@@ -1,4 +1,4 @@
-# Parity harness — keeping every feature correct through the native-CLI migration
+# Parity harness: keeping every feature correct through the native-CLI migration
This harness is the safety net for `plans/native-cli.md` (Go launcher, hermetic
runtimes, **whisper.cpp** replacing openai-whisper/PyTorch). Its job: prove that
@@ -13,16 +13,16 @@ import, **and** the on-disk cache; consumed by corrections, cropping, moment
selection, and captions). That seam lets correctness decompose into two layers
that are verified independently.
-### Layer 1 — everything *downstream* of the transcript JSON
+### Layer 1: everything *downstream* of the transcript JSON
Moments → crop → captions → normalize → encode. **This code does not change** in
the migration; only the runtime relocates (system → hermetic). So the rule is
absolute: a fixed transcript must yield identical output. Any difference is a
runtime *pinning* bug, never a logic change.
-- `transcript_synthetic.json` — neutral, no podcast content; packs the word-text
+- `transcript_synthetic.json`: neutral, no podcast content; packs the word-text
edge cases (leading-space token, number+symbol, punctuation, apostrophe,
whitespace-only token, zero-duration token, speaker change).
-- `test_caption_parity.py` — renders all four caption styles from that transcript
+- `test_caption_parity.py`: renders all four caption styles from that transcript
and diffs against committed goldens (`golden/*.ass.expected`). Also pins the
**word-text normalization** the whisper.cpp boundary must reproduce exactly
(the single highest-risk integration detail) and the 50ms zero-duration floor.
@@ -39,9 +39,9 @@ Intentionally update goldens after a deliberate change:
UPDATE_GOLDENS=1 venv/bin/python3 -m pytest tests/parity/test_caption_parity.py -q
```
-### Layer 2 — the engine (`audio → transcript JSON`)
+### Layer 2: the engine (`audio → transcript JSON`)
The only real change. Verified by comparing the new engine's output to a frozen
-openai-whisper baseline, with **forgiving** tolerances — because the caption
+openai-whisper baseline, with **forgiving** tolerances, because the caption
pipeline already runs in production on evenly-spaced *synthetic* word timings
(`transcript_parser.py:306`), so absolute timestamp fidelity is a quality nicety,
not a correctness requirement.
@@ -68,11 +68,11 @@ not a correctness requirement.
## Why this makes "everything still works" tractable
-- **Layer 1 is identical by construction** — pinned runtime + frozen-transcript
+- **Layer 1 is identical by construction**, pinned runtime + frozen-transcript
goldens. The boring 80% can't drift silently.
-- **Layer 2 is bounded against a floor the app already ships** — whisper.cpp only
+- **Layer 2 is bounded against a floor the app already ships**, whisper.cpp only
has to beat evenly-spaced timings, which it does trivially.
-- **The cache protects existing work** — already-transcribed videos reuse their
+- **The cache protects existing work**: already-transcribed videos reuse their
openai-whisper JSON, so they produce byte-identical output under the new binary.
- **Dual-engine release** (`--engine whisper-py`, planned) gives an instant
real-world fallback while whisper.cpp proves itself.
@@ -81,4 +81,4 @@ not a correctness requirement.
Committed: this README, `transcript_synthetic.json`, `golden/*.ass.expected`,
the harness scripts. **Never committed** (`.gitignore`): `local/` fixtures,
-`baseline/`, `candidate/` — they can contain podcast content.
+`baseline/`, `candidate/`, they can contain podcast content.
diff --git a/tests/parity/capture_baseline.py b/tests/parity/capture_baseline.py
index 2fe593e..edc527c 100644
--- a/tests/parity/capture_baseline.py
+++ b/tests/parity/capture_baseline.py
@@ -6,7 +6,7 @@ whisper.cpp, `compare.py` measures the candidate against this baseline with
explicit tolerances.
The baseline is the transcript JSON contract (`words` + `segments`) plus a
-metrics summary and the captions rendered from those real words — i.e. exactly
+metrics summary and the captions rendered from those real words, i.e. exactly
the things whisper.cpp must reproduce.
Usage:
@@ -18,7 +18,7 @@ Outputs (gitignored) under tests/parity/baseline/<stem>/:
metrics.json n_words, n_segments, duration, language, engine, model
captions_<style>.ass captions rendered from the real transcript words
-Capture this WHILE the current system still works — it is the frozen reference
+Capture this WHILE the current system still works: it is the frozen reference
everything else is measured against.
"""
@@ -93,7 +93,7 @@ def main(argv):
print(
"No fixtures. Pass media paths, or drop clips into tests/parity/local/ .\n"
"Use short representative clips (single speaker, two speakers, music-heavy, "
- "fast speech). They stay local — never committed.",
+ "fast speech). They stay local: never committed.",
file=sys.stderr,
)
return 1
diff --git a/tests/parity/compare.py b/tests/parity/compare.py
index 063a9f3..1257874 100644
--- a/tests/parity/compare.py
+++ b/tests/parity/compare.py
@@ -3,7 +3,7 @@
Layer-2 gate: bounds whisper.cpp (or any new engine) against openai-whisper
ground truth on text accuracy and word-timestamp drift. The acceptance bar is
deliberately forgiving because the caption pipeline already runs in production
-on evenly-spaced synthetic word timings (see transcript_parser.py) — absolute
+on evenly-spaced synthetic word timings (see transcript_parser.py), absolute
timestamp fidelity is a quality nicety, not a correctness requirement.
Usage:
@@ -11,7 +11,7 @@ Usage:
compares baseline/<stem>/transcript.json vs candidate/<stem>/transcript.json
venv/bin/python3 tests/parity/compare.py <baseline.json> <candidate.json>
-Exit code is nonzero if any threshold is exceeded — wire it into CI as the gate
+Exit code is nonzero if any threshold is exceeded. Wire it into CI as the gate
for the whisper.cpp swap.
"""
@@ -21,7 +21,7 @@ import sys
HERE = os.path.dirname(os.path.abspath(__file__))
-# Thresholds — tune against real fixtures, then lock in CI.
+# Thresholds: tune against real fixtures, then lock in CI.
MAX_WER = float(os.environ.get("PARITY_MAX_WER", "0.08")) # 8% word error
MAX_MEDIAN_DRIFT = float(os.environ.get("PARITY_MAX_MEDIAN_DRIFT", "0.10")) # 100ms
MAX_P95_DRIFT = float(os.environ.get("PARITY_MAX_P95_DRIFT", "0.30")) # 300ms
diff --git a/tests/parity/test_caption_parity.py b/tests/parity/test_caption_parity.py
index 3af7a9c..d04a9b8 100644
--- a/tests/parity/test_caption_parity.py
+++ b/tests/parity/test_caption_parity.py
@@ -4,11 +4,11 @@ Everything downstream of the transcript JSON contract (the `{words, segments}`
dict produced by transcribe_file / parse_speaker_transcript / JSON import /
cache) is pure code that does NOT change when we swap the transcription engine
or relocate the runtime. This test pins the most timestamp-sensitive part of
-that surface — caption (ASS) generation — against committed goldens.
+that surface: caption (ASS) generation, against committed goldens.
If a future change (whisper.cpp swap, hermetic runtime, a refactor) alters
caption output for a fixed transcript, this test fails. That is the whole point:
-the engine may change, the contract's consumers may not — silently.
+the engine may change; the contract's consumers may not, silently.
Regenerate goldens intentionally with: UPDATE_GOLDENS=1 pytest tests/parity/test_caption_parity.py
Goldens use the .ass.expected extension because *.ass is gitignored.
@@ -42,7 +42,7 @@ def _deterministic_text_widths(texts, font_name, font_size, bold, spacing=2):
so positions differ between macOS (Arial) and CI (DejaVu/Liberation) and the
goldens can never match across machines. The parity harness exists to lock
the engine-independent ASS pipeline (timing, styles, karaoke, position and
- pill geometry derived from widths) — not the host's typography — so we pin a
+ pill geometry derived from widths), not the host's typography, so we pin a
deterministic width model and the goldens become reproducible everywhere.
"""
widths = []
@@ -78,7 +78,7 @@ def _hermetic_render(monkeypatch):
"""Pin the two host-dependent inputs so goldens are reproducible everywhere.
1. Font name: caption_styles.DETECTED_FONT is resolved at import via fc-list,
- so it's "Arial" on macOS and "Liberation Sans" on CI's Ubuntu — and that
+ so it's "Arial" on macOS and "Liberation Sans" on CI's Ubuntu, and that
name is written into the ASS Style line.
2. Text widths: see _deterministic_text_widths (affects the branded style's
per-word positioning and pill geometry).
diff --git a/tests/test_ai_fallback.py b/tests/test_ai_fallback.py
index 66bf5e3..b017f45 100644
--- a/tests/test_ai_fallback.py
+++ b/tests/test_ai_fallback.py
@@ -253,7 +253,7 @@ class AIFallbackTests(unittest.TestCase):
codex_text = """TITLES (8 options, 40-60 chars, keyword-first, follow title spec):
1. Power Demand Is Exploding Fast
2. Data Centers Need Much More Energy
-TOP PICK: 1 — strongest hook
+TOP PICK: 1 \u2014 strongest hook
DESCRIPTION:
Power demand is exploding.
@@ -469,6 +469,8 @@ class AICliDiscoveryTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
prompt_file = os.path.join(tmp, "prompt.txt")
cli = os.path.join(tmp, "codex")
+ with open(prompt_file, "w", encoding="utf-8") as fh:
+ fh.write("find clips")
with mock.patch("services.ai_cli.subprocess.run") as run_mock:
run_mock.return_value = subprocess.CompletedProcess(
@@ -494,9 +496,10 @@ class AICliDiscoveryTests(unittest.TestCase):
"--sandbox", "read-only",
"--skip-git-repo-check",
"-o", prompt_file + ".out",
- "find clips",
+ "-",
],
)
+ self.assertIn("stdin", kwargs)
self.assertNotIn("--full-auto", args[0])
self.assertEqual(kwargs["cwd"], tmp)
diff --git a/tests/test_asset_store.py b/tests/test_asset_store.py
index 19626db..35e49db 100644
--- a/tests/test_asset_store.py
+++ b/tests/test_asset_store.py
@@ -1,4 +1,4 @@
-"""Tests for backend.services.asset_store — named asset registry."""
+"""Tests for backend.services.asset_store: named asset registry."""
import json
import os
diff --git a/tests/test_audio_analyzer.py b/tests/test_audio_analyzer.py
index 97c1784..d31bf78 100644
--- a/tests/test_audio_analyzer.py
+++ b/tests/test_audio_analyzer.py
@@ -68,17 +68,17 @@ class ComputeEnergyScoresTests(unittest.TestCase):
# A segment with loud + silent samples should only score off the loud ones
energy = [
{"time": 0.0, "rms_db": -20.0},
- {"time": 1.0, "rms_db": -80.0}, # silence — should be ignored
+ {"time": 1.0, "rms_db": -80.0}, # silence, should be ignored
{"time": 2.0, "rms_db": -20.0},
{"time": 3.0, "rms_db": -40.0}, # baseline context
{"time": 4.0, "rms_db": -40.0},
]
scores = aa.compute_energy_scores(energy, [{"start": 0, "end": 2}])
- # Only 2 samples contribute — -20 is above the -40 baseline → score > 0
+ # Only 2 samples contribute: -20 is above the -40 baseline → score > 0
self.assertGreater(scores[0], 0)
def test_zero_variance_energy_is_handled(self):
- # All-same energy level would cause std=0 — function must avoid div-by-zero
+ # All-same energy level would cause std=0; function must avoid div-by-zero
energy = [{"time": float(t), "rms_db": -25.0} for t in range(0, 20)]
segments = [{"start": 5, "end": 10}]
# Should not raise
diff --git a/tests/test_audio_normalize.py b/tests/test_audio_normalize.py
index ab6550a..de68b05 100644
--- a/tests/test_audio_normalize.py
+++ b/tests/test_audio_normalize.py
@@ -41,7 +41,7 @@ class ParseLoudnormStatsTests(unittest.TestCase):
self.assertEqual(data["input_tp"], "-2.0")
def test_rejects_negative_infinity_input(self):
- # -inf means silence / too-short clip — two-pass isn't meaningful
+ # -inf means silence / too-short clip; two-pass isn't meaningful
stderr = '{"input_i": "-inf", "input_tp": "-inf"}'
self.assertIsNone(an._parse_loudnorm_stats(stderr))
@@ -90,7 +90,7 @@ class NormalizeAudioTests(unittest.TestCase):
self.assertEqual(result, "/out.mp4")
apply_cmd = mocked.call_args_list[1].args[0]
joined = " ".join(apply_cmd)
- # No measured_* values — single-pass filter
+ # No measured_* values: single-pass filter
self.assertNotIn("measured_I", joined)
self.assertIn("loudnorm=I=-14.0", joined)
diff --git a/tests/test_audiogram.py b/tests/test_audiogram.py
index bca1996..9921610 100644
--- a/tests/test_audiogram.py
+++ b/tests/test_audiogram.py
@@ -1,7 +1,7 @@
"""Tests for audio-only input detection.
An episode that was never filmed used to reach `get_dimensions` and raise "No
-video stream found" — after transcription, so the expensive half of the run was
+video stream found" after transcription, so the expensive half of the run was
already paid for. These cover knowing, from the header, that there is no picture
in it, and being careful about when that is worth stopping a run over.
"""
diff --git a/tests/test_backend_stdin_encoding.py b/tests/test_backend_stdin_encoding.py
index 0f3fa2e..c8f9778 100644
--- a/tests/test_backend_stdin_encoding.py
+++ b/tests/test_backend_stdin_encoding.py
@@ -15,7 +15,7 @@ from pathlib import Path
BACKEND = Path(__file__).resolve().parent.parent / "backend"
MAIN = BACKEND / "main.py"
-TITLE = "In the end — your “shit” has to work"
+TITLE = "In the end \u2014 your “shit” has to work"
def _run_with_locale_encoding(payload: str) -> subprocess.CompletedProcess:
diff --git a/tests/test_batch_render.py b/tests/test_batch_render.py
index 446d3b9..8428254 100644
--- a/tests/test_batch_render.py
+++ b/tests/test_batch_render.py
@@ -1,4 +1,4 @@
-"""Tests for backend.main batch clip rendering — worker pool sizing, result
+"""Tests for backend.main batch clip rendering, worker pool sizing, result
ordering, and clip_complete events for both outcomes."""
import os
diff --git a/tests/test_choose_segment_tracks.py b/tests/test_choose_segment_tracks.py
index bc64242..7ebcb2e 100644
--- a/tests/test_choose_segment_tracks.py
+++ b/tests/test_choose_segment_tracks.py
@@ -1,4 +1,4 @@
-"""Tests for video_processor._choose_segment_tracks — the per-turn
+"""Tests for video_processor._choose_segment_tracks: the per-turn
face-track selector that decides which visual track represents the
active speaker for a given segment.
"""
diff --git a/tests/test_claude_suggest_helpers.py b/tests/test_claude_suggest_helpers.py
index b1cd1fd..3d1bbf7 100644
--- a/tests/test_claude_suggest_helpers.py
+++ b/tests/test_claude_suggest_helpers.py
@@ -1,7 +1,7 @@
"""Tests for pure helper functions in backend.services.claude_suggest.
These are deterministic, side-effect-free helpers that back the AI
-clip-suggestion pipeline — safe to test without mocking subprocess
+clip-suggestion pipeline: safe to test without mocking subprocess
or any external tools.
"""
@@ -96,7 +96,7 @@ class ShouldBucketTests(unittest.TestCase):
self.assertFalse(cs._should_bucket_initial_selection(segments))
def test_long_duration_buckets(self):
- # 50 minutes — over the 45 min threshold
+ # 50 minutes: over the 45 min threshold
segments = [{"start": 0, "end": 3000, "text": "x" * 100}]
self.assertTrue(cs._should_bucket_initial_selection(segments))
@@ -295,7 +295,7 @@ class ExistingShortsTests(unittest.TestCase):
)
def test_the_older_numbered_shape_still_reads(self):
- path = self._write("1. An older entry — hot take\n2. Another one — story\n")
+ path = self._write("1. An older entry \u2014 hot take\n2. Another one \u2014 story\n")
self.assertEqual(cs._load_existing_shorts(path), ["An older entry", "Another one"])
def test_a_dropped_moment_stays_available(self):
@@ -308,6 +308,24 @@ class ExistingShortsTests(unittest.TestCase):
)
self.assertEqual(cs._load_existing_shorts(path), ["Shipped one", "Queued one"])
+ def test_drop_published_removes_matching_titles_only(self):
+ path = self._write(
+ "| # | Moment | Title | Platform | Status |\n"
+ "|---|--------|-------|----------|--------|\n"
+ "| 1 | [00:01-00:30] | The pricing mistake | YouTube Shorts | published |\n"
+ )
+ clips = [
+ {"title": "The Pricing Mistake!", "start_second": 1, "end_second": 30},
+ {"title": "A different moment", "start_second": 60, "end_second": 90},
+ ]
+ kept = cs.drop_published(clips, path)
+ self.assertEqual([c["title"] for c in kept], ["A different moment"])
+
+ def test_drop_published_keeps_everything_without_a_database(self):
+ clips = [{"title": "Anything"}]
+ missing = os.path.join(self.tmp.name, "nope.md")
+ self.assertEqual(cs.drop_published(clips, missing), clips)
+
def test_unfilled_cells_are_not_titles(self):
path = self._write(
"| # | Moment | Title | Platform | Status |\n"
diff --git a/tests/test_config_bundle.py b/tests/test_config_bundle.py
index be5f61c..61c191d 100644
--- a/tests/test_config_bundle.py
+++ b/tests/test_config_bundle.py
@@ -86,9 +86,9 @@ class ConfigBundleTests(unittest.TestCase):
def test_import_rewrites_preset_and_ui_state_asset_paths(self):
# Regression: a preset/ui-state asset path stored as its literal (possibly
# symlinked, e.g. macOS /var) value must be rewritten to the new home on
- # import — otherwise it leaks the source machine's path and breaks once the
+ # import: otherwise it leaks the source machine's path and breaks once the
# source is gone. self.asset_file is the literal src path (under a tmpdir,
- # which is symlinked on macOS so raw != realpath — exactly the failure case).
+ # which is symlinked on macOS so raw != realpath, exactly the failure case).
with open(os.path.join(self.src_home, "presets", "branded.json"), "w", encoding="utf-8") as f:
json.dump({"caption_style": "branded", "logo_path": self.asset_file}, f)
with open(os.path.join(self.src_home, "ui-state.json"), "w", encoding="utf-8") as f:
diff --git a/tests/test_corrections.py b/tests/test_corrections.py
index 99f487c..a6ed382 100644
--- a/tests/test_corrections.py
+++ b/tests/test_corrections.py
@@ -1,4 +1,4 @@
-"""Tests for backend.services.corrections — word/segment replacement."""
+"""Tests for backend.services.corrections: word/segment replacement."""
import json
import os
@@ -197,7 +197,7 @@ class CorrectionsTests(unittest.TestCase):
words = [{"word": "Foo"}]
segments = [{"text": "Foo"}]
w, s = corrections.apply_corrections(words, segments)
- # Same list identity — mutated in place
+ # Same list identity: mutated in place
self.assertIs(w, words)
self.assertIs(s, segments)
diff --git a/tests/test_crop_path_golden.py b/tests/test_crop_path_golden.py
index 32c9b24..887f016 100644
--- a/tests/test_crop_path_golden.py
+++ b/tests/test_crop_path_golden.py
@@ -2,11 +2,11 @@
The helper tests next door check each piece of the tracking math in isolation.
What they cannot catch is a change that leaves every helper correct but moves
-the camera anyway — a different sampling rate, a reordered pipeline, a changed
+the camera anyway: a different sampling rate, a reordered pipeline, a changed
default. Those are exactly the changes a "pure speed optimization" makes.
So these lock the composed output: fixed detections in, exact keyframes out.
-No cv2, ffmpeg, or video files — the fixtures stand in for decoded frames.
+No cv2, ffmpeg, or video files. The fixtures stand in for decoded frames.
"""
import json
@@ -26,7 +26,7 @@ if BACKEND_ROOT not in sys.path:
from services import video_processor as vp
WIDTH, HEIGHT = 1920, 1080
-CROP_W = int(HEIGHT * (1080 / 1920)) # 607 — full-height 9:16 window
+CROP_W = int(HEIGHT * (1080 / 1920)) # 607, full-height 9:16 window
def _face(cx, fw=180):
@@ -40,7 +40,7 @@ def _two_speaker_detections(n=40, step=0.1):
class FaceSampleIndicesGoldenTests(unittest.TestCase):
"""The sampling schedule is the input to everything downstream. If a speed
- change alters it, every keyframe below shifts — so pin the exact schedule."""
+ change alters it, every keyframe below shifts, so pin the exact schedule."""
def test_30fps_schedule_is_exact(self):
idx = vp._face_sample_indices(90, 30.0)
@@ -137,7 +137,7 @@ class FaceDetectWorkersTests(unittest.TestCase):
self.assertGreaterEqual(vp._face_detect_workers(10_000), 1)
def test_short_clips_stay_serial(self):
- # A ~2s clip samples ~40 frames — not enough to repay a second detector.
+ # A ~2s clip samples ~40 frames, not enough to repay a second detector.
with mock.patch.dict(os.environ, {"PODCLI_FACE_WORKERS": ""}):
self.assertEqual(vp._face_detect_workers(0), 1)
self.assertEqual(vp._face_detect_workers(40), 1)
@@ -198,7 +198,7 @@ class DetectBatchTests(unittest.TestCase):
def test_each_detector_is_used_by_exactly_one_stride(self):
out = self._run(20, 4)
- # Frame i must be handled by detector i % 4 — deterministic striding,
+ # Frame i must be handled by detector i % 4, deterministic striding,
# so no detector is ever touched by two threads.
for i, (_, faces) in enumerate(out):
self.assertEqual(faces[0]["detector"], f"det{i % 4}")
diff --git a/tests/test_encoder.py b/tests/test_encoder.py
index 360323b..fd197b6 100644
--- a/tests/test_encoder.py
+++ b/tests/test_encoder.py
@@ -29,10 +29,6 @@ class GetEncoderFlagsTests(unittest.TestCase):
flags = encoder._get_encoder_flags("h264_amf")
self.assertIn("h264_amf", flags)
- # vaapi (Linux Intel/AMD)
- flags = encoder._get_encoder_flags("h264_vaapi")
- self.assertIn("h264_vaapi", flags)
-
# qsv (Intel QuickSync)
flags = encoder._get_encoder_flags("h264_qsv")
self.assertIn("h264_qsv", flags)
@@ -51,7 +47,7 @@ class GetEncoderFlagsTests(unittest.TestCase):
def test_all_flag_lists_start_with_c_v(self):
# Every encoder profile must specify -c:v as its first pair
for name in ["h264_videotoolbox", "h264_nvenc", "h264_amf",
- "h264_vaapi", "h264_qsv", "libx264"]:
+ "h264_qsv", "libx264"]:
flags = encoder._get_encoder_flags(name)
self.assertEqual(flags[0], "-c:v")
self.assertTrue(flags[1].startswith("h264") or flags[1] == "libx264")
@@ -68,7 +64,7 @@ class GetVideoEncodeFlagsTests(unittest.TestCase):
def test_falls_back_when_detect_encoders_raises(self):
with mock.patch.object(encoder, "detect_encoders", side_effect=RuntimeError("boom")):
flags = encoder.get_video_encode_flags()
- # Absolute fallback — must always return something usable
+ # Absolute fallback: must always return something usable
self.assertIn("libx264", flags)
self.assertIn("-crf", flags)
diff --git a/tests/test_face_track_helpers.py b/tests/test_face_track_helpers.py
index 6513890..6d9fcad 100644
--- a/tests/test_face_track_helpers.py
+++ b/tests/test_face_track_helpers.py
@@ -1,4 +1,4 @@
-"""Tests for backend.services.face_track_helpers — pure camera /
+"""Tests for backend.services.face_track_helpers: pure camera /
speaker-switch decision helpers.
"""
diff --git a/tests/test_media_probe.py b/tests/test_media_probe.py
index 1adba98..1985625 100644
--- a/tests/test_media_probe.py
+++ b/tests/test_media_probe.py
@@ -1,4 +1,4 @@
-"""Tests for backend.services.media_probe — extracted ffmpeg helpers."""
+"""Tests for backend.services.media_probe: extracted ffmpeg helpers."""
import os
import sys
@@ -92,7 +92,7 @@ class HasAudioStreamTests(unittest.TestCase):
self.assertFalse(media_probe.has_audio_stream("/fake.mp4"))
def test_assumes_yes_on_probe_failure(self):
- # Defensive default — pipeline should still try audio filters
+ # Defensive default: pipeline should still try audio filters
with mock.patch.object(
media_probe, "get_video_info", side_effect=RuntimeError("boom")
):
diff --git a/tests/test_motion_filters.py b/tests/test_motion_filters.py
index 01ceeb0..2ac965f 100644
--- a/tests/test_motion_filters.py
+++ b/tests/test_motion_filters.py
@@ -1,4 +1,4 @@
-"""Tests for backend.services.motion_filters — pure string builders."""
+"""Tests for backend.services.motion_filters: pure string builders."""
import os
import sys
@@ -165,7 +165,7 @@ class BuildMotionZoomFilterTests(unittest.TestCase):
class SimplifyKeyframesTests(unittest.TestCase):
- """Parity check against the video_processor_helpers tests — ensures
+ """Parity check against the video_processor_helpers tests; ensures
the extraction kept the same behavior."""
def test_collinear_middle_dropped(self):
diff --git a/tests/test_presets.py b/tests/test_presets.py
index 9825093..93ae782 100644
--- a/tests/test_presets.py
+++ b/tests/test_presets.py
@@ -1,4 +1,4 @@
-"""Tests for backend.presets — named show configurations."""
+"""Tests for backend.presets: named show configurations."""
import json
import os
@@ -50,7 +50,7 @@ class PresetsTests(unittest.TestCase):
self.assertEqual(loaded["whisper_model"], presets.DEFAULT_PRESET["whisper_model"])
def test_get_preset_default_returns_copy(self):
- # "default" is special — returns a fresh copy of DEFAULT_PRESET
+ # "default" is special: returns a fresh copy of DEFAULT_PRESET
d = presets.get_preset("default")
self.assertEqual(d, presets.DEFAULT_PRESET)
# Mutating the returned dict must not affect subsequent calls
diff --git a/tests/test_server_port.py b/tests/test_server_port.py
index 1944764..828394f 100644
--- a/tests/test_server_port.py
+++ b/tests/test_server_port.py
@@ -1,4 +1,4 @@
-"""Studio port resolution — must stay identical to src/config/server.ts."""
+"""Studio port resolution: must stay identical to src/config/server.ts."""
import os
import re
diff --git a/tests/test_text_utils.py b/tests/test_text_utils.py
index 066771b..1946177 100644
--- a/tests/test_text_utils.py
+++ b/tests/test_text_utils.py
@@ -58,7 +58,7 @@ def test_safe_filename_strips_characters_windows_rejects():
def test_safe_filename_drops_smart_punctuation():
- assert safe_filename("In the end — your “shit” has to work") == "In_the_end_your_shit_has_to_work"
+ assert safe_filename("In the end \u2014 your “shit” has to work") == "In_the_end_your_shit_has_to_work"
def test_safe_filename_caps_length():
@@ -66,12 +66,12 @@ def test_safe_filename_caps_length():
def test_safe_filename_has_no_leading_or_trailing_underscore():
- out = safe_filename(" — hello — ")
+ out = safe_filename(" \u2014 hello \u2014 ")
assert out == "hello"
def test_safe_filename_falls_back_when_nothing_survives():
- assert safe_filename("———") == "clip"
+ assert safe_filename("\u2014\u2014\u2014") == "clip"
assert safe_filename("") == "clip"
assert safe_filename(None) == "clip"
diff --git a/tests/test_thumbnail_html.py b/tests/test_thumbnail_html.py
index 2f29c07..58265c5 100644
--- a/tests/test_thumbnail_html.py
+++ b/tests/test_thumbnail_html.py
@@ -21,7 +21,7 @@ class ThumbnailHtmlTests(unittest.TestCase):
def test_prepare_thumbnail_lines_compacts_long_sentence_title(self):
line1, line2 = th._prepare_thumbnail_lines(
- "We build 10 megawatt data centers in 200 days — everyone is shocked",
+ "We build 10 megawatt data centers in 200 days \u2014 everyone is shocked",
)
self.assertIn("10MW", f"{line1} {line2}")
@@ -34,7 +34,7 @@ class ThumbnailHtmlTests(unittest.TestCase):
line1, line2 = th._prepare_thumbnail_lines(
title="ignored",
line1="WE BUILD 10 MEGAWATT DATA",
- line2="CENTERS IN 200 DAYS — EVERYONE IS SHOCKED",
+ line2="CENTERS IN 200 DAYS \u2014 EVERYONE IS SHOCKED",
)
self.assertLessEqual(len(line1), 24)
diff --git a/tests/test_transcript_parser.py b/tests/test_transcript_parser.py
index b99260e..2e32953 100644
--- a/tests/test_transcript_parser.py
+++ b/tests/test_transcript_parser.py
@@ -1,4 +1,4 @@
-"""Tests for backend.services.transcript_parser — format detection and parsing."""
+"""Tests for backend.services.transcript_parser: format detection and parsing."""
import json
import os
diff --git a/tests/test_transcription_engine.py b/tests/test_transcription_engine.py
index 6e470ee..68cf23a 100644
--- a/tests/test_transcription_engine.py
+++ b/tests/test_transcription_engine.py
@@ -83,7 +83,7 @@ class TranscriptionEngineTests(unittest.TestCase):
def test_whispercpp_skips_diarization_by_default(self):
# Regression: the cpp path must not attempt torch-backed diarization even
- # with the default enable_diarization=True — importing a broken torch in a
+ # with the default enable_diarization=True: importing a broken torch in a
# native runtime hard-crashes the process. Face analysis still runs.
os.environ["PODCLI_ENGINE"] = "whispercpp"
result = tr.transcribe_file(self._tmp.name, model_size="base")
diff --git a/tests/test_video_processor.py b/tests/test_video_processor.py
index 47e2bbf..c4d305f 100644
--- a/tests/test_video_processor.py
+++ b/tests/test_video_processor.py
@@ -31,7 +31,7 @@ class VideoProcessorTests(unittest.TestCase):
def test_concat_outro_uses_soft_audio_fallback_before_hard_concat(self):
# xfade attempt returns non-zero so concat_outro falls through to
- # the hardcut_soft_audio path. Patch proc_run directly — the old
+ # the hardcut_soft_audio path. Patch proc_run directly: the old
# subprocess.run mock was a no-op since the code path migrated to
# utils.proc.run.
run_fail = mock.Mock(returncode=1, stdout="", stderr="xfade unavailable")
diff --git a/tests/test_video_processor_helpers.py b/tests/test_video_processor_helpers.py
index 151bead..e9e29b2 100644
--- a/tests/test_video_processor_helpers.py
+++ b/tests/test_video_processor_helpers.py
@@ -33,7 +33,7 @@ class SimplifyKeyframesTests(unittest.TestCase):
self.assertEqual(out, [(0, 0), (10, 1000)])
def test_non_collinear_points_preserved(self):
- # (0,0), (5,800), (10,1000) — middle is far from the interpolated value
+ # (0,0), (5,800), (10,1000), middle is far from the interpolated value
keyframes = [(0, 0), (5, 800), (10, 1000)]
out = vp._simplify_keyframes(keyframes)
self.assertEqual(out, keyframes) # all preserved
@@ -58,7 +58,7 @@ class SimplifyKeyframesTests(unittest.TestCase):
class ResolveSpeakerSidesTests(unittest.TestCase):
def test_no_face_map_returns_empty(self):
- # Without a face_map, we cannot infer sides — must return empty dict
+ # Without a face_map, we cannot infer sides; must return empty dict
sides = vp._resolve_speaker_sides(
segments=[(0.0, 5.0, "SPEAKER_00")],
detections=[],
diff --git a/tools/oxlint/anti-slop/UPSTREAM.md b/tools/oxlint/anti-slop/UPSTREAM.md
new file mode 100644
index 0000000..40f4288
--- /dev/null
+++ b/tools/oxlint/anti-slop/UPSTREAM.md
@@ -0,0 +1,17 @@
+# anti-slop provenance
+
+- Source repository: https://github.com/dmmulroy/anti-slop
+- Source commit: 13909c9e07590f5a85d93c62712259fe14a883f7
+- Installer: `skills/install-anti-slop/scripts/install.mjs` from that commit, run from the repository root
+- Installed paths:
+ - `tools/oxlint/anti-slop/` (generic plugin entry point `index.ts`, `rules/`, `shared/`)
+ - `tools/oxlint/anti-slop/effect/` (opt-in Effect plugin, copied but not registered)
+ - `tools/oxlint/anti-slop/vendor/eslint-stylistic/` (vendored license and its own `UPSTREAM.md`)
+- Configuration: `.oxlintrc.json` registers `./tools/oxlint/anti-slop/index.ts` as `anti-slop` and enables all 19 generic rules at `"error"`, including the native `oxc/no-accumulating-spread`.
+- Dependencies: `oxlint` and `@oxlint/plugins`, both pinned to 1.78.0 as devDependencies.
+
+## Deviations from upstream
+
+- Plugin source: none. The copied files are unmodified.
+- Effect rules: not enabled, because `effect` is not a direct dependency.
+- Ignores: `.oxlintrc.json` adds `**/node_modules/**` and `dist/**` to the upstream agent-directory list and the plugin directory.
diff --git a/tools/oxlint/anti-slop/effect/index.ts b/tools/oxlint/anti-slop/effect/index.ts
new file mode 100644
index 0000000..55eb13d
--- /dev/null
+++ b/tools/oxlint/anti-slop/effect/index.ts
@@ -0,0 +1,21 @@
+import { eslintCompatPlugin } from "@oxlint/plugins";
+
+import { noManualEffectErrorTagRule } from "./rules/no-manual-effect-error-tag.ts";
+import { noManualTagComparisonRule } from "./rules/no-manual-tag-comparison.ts";
+import { noManualTaggedConstructionRule } from "./rules/no-manual-tagged-construction.ts";
+import { noServiceConstructorImportsRule } from "./rules/no-service-constructor-imports.ts";
+import { preferEffectMatchRule } from "./rules/prefer-effect-match.ts";
+
+/** Opt-in Oxlint rules for Effect service and Layer architecture. */
+const antiSlopEffectPlugin = eslintCompatPlugin({
+ meta: { name: "anti-slop-effect" },
+ rules: {
+ "no-manual-effect-error-tag": noManualEffectErrorTagRule,
+ "no-manual-tag-comparison": noManualTagComparisonRule,
+ "no-manual-tagged-construction": noManualTaggedConstructionRule,
+ "no-service-constructor-imports": noServiceConstructorImportsRule,
+ "prefer-effect-match": preferEffectMatchRule,
+ },
+});
+
+export default antiSlopEffectPlugin;
diff --git a/tools/oxlint/anti-slop/effect/rules/no-manual-effect-error-tag.ts b/tools/oxlint/anti-slop/effect/rules/no-manual-effect-error-tag.ts
new file mode 100644
index 0000000..daaa109
--- /dev/null
+++ b/tools/oxlint/anti-slop/effect/rules/no-manual-effect-error-tag.ts
@@ -0,0 +1,52 @@
+import { defineRule } from "@oxlint/plugins";
+
+import {
+ isInsideBroadEffectHandler,
+ isReasonTagMember,
+ isTagMember,
+ tagMemberFromComparison,
+} from "../shared/tagged-values.ts";
+
+export const noManualEffectErrorTagRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Use Effect tagged error handlers instead of manually branching on `_tag` in a catch handler.",
+ },
+ messages: {
+ tag: "Use Effect.catchTag or Effect.catchTags instead of manually discriminating a tagged error in a broad Effect catch handler.",
+ reason:
+ "Use Effect.catchReason or Effect.catchReasons instead of manually discriminating a tagged `reason` in a broad Effect catch handler.",
+ },
+ },
+ createOnce(context) {
+ return {
+ BinaryExpression(node) {
+ const tagMember = tagMemberFromComparison(node);
+ if (
+ tagMember === undefined ||
+ !isInsideBroadEffectHandler(node)
+ ) {
+ return;
+ }
+ context.report({
+ node,
+ messageId: isReasonTagMember(tagMember) ? "reason" : "tag",
+ });
+ },
+ SwitchStatement(node) {
+ if (
+ !isTagMember(node.discriminant) ||
+ !isInsideBroadEffectHandler(node)
+ ) {
+ return;
+ }
+ context.report({
+ node,
+ messageId: isReasonTagMember(node.discriminant) ? "reason" : "tag",
+ });
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/effect/rules/no-manual-tag-comparison.ts b/tools/oxlint/anti-slop/effect/rules/no-manual-tag-comparison.ts
new file mode 100644
index 0000000..868d1d2
--- /dev/null
+++ b/tools/oxlint/anti-slop/effect/rules/no-manual-tag-comparison.ts
@@ -0,0 +1,45 @@
+import { defineRule } from "@oxlint/plugins";
+
+import {
+ isInsideBroadEffectHandler,
+ isTagMember,
+ tagMemberFromComparison,
+} from "../shared/tagged-values.ts";
+
+export const noManualTagComparisonRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Use Effect Match or Predicate helpers instead of manually branching on `_tag`.",
+ },
+ messages: {
+ manualComparison:
+ "Use Match.tag/Match.tags for tagged-value branching, or Predicate.isTagged for a simple reusable predicate.",
+ manualSwitch:
+ "Use Match.value(value).pipe(Match.tag/Match.tags/Match.tagsExhaustive) or the tagged enum `$match` helper instead of switching on `_tag`.",
+ },
+ },
+ createOnce(context) {
+ return {
+ BinaryExpression(node) {
+ if (
+ tagMemberFromComparison(node) === undefined ||
+ isInsideBroadEffectHandler(node)
+ ) {
+ return;
+ }
+ context.report({ node, messageId: "manualComparison" });
+ },
+ SwitchStatement(node) {
+ if (
+ !isTagMember(node.discriminant) ||
+ isInsideBroadEffectHandler(node)
+ ) {
+ return;
+ }
+ context.report({ node, messageId: "manualSwitch" });
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/effect/rules/no-manual-tagged-construction.ts b/tools/oxlint/anti-slop/effect/rules/no-manual-tagged-construction.ts
new file mode 100644
index 0000000..382f166
--- /dev/null
+++ b/tools/oxlint/anti-slop/effect/rules/no-manual-tagged-construction.ts
@@ -0,0 +1,37 @@
+import { defineRule } from "@oxlint/plugins";
+
+import {
+ isMatchPatternObject,
+ isStringLiteral,
+ propertyName,
+} from "../shared/tagged-values.ts";
+
+export const noManualTaggedConstructionRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Construct tagged values with their existing Effect constructor instead of writing `_tag` manually.",
+ },
+ messages: {
+ manualConstruction:
+ "Use the existing Schema tagged `.make`, tagged class/error constructor, or Data.taggedEnum variant constructor instead of writing a literal `_tag` object.",
+ },
+ },
+ createOnce(context) {
+ return {
+ ObjectExpression(node) {
+ if (isMatchPatternObject(node)) return;
+ const tag = node.properties.find(
+ (property) =>
+ property.type === "Property" &&
+ propertyName(property) === "_tag" &&
+ isStringLiteral(property.value),
+ );
+ if (tag !== undefined) {
+ context.report({ node: tag, messageId: "manualConstruction" });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/effect/rules/no-service-constructor-imports.ts b/tools/oxlint/anti-slop/effect/rules/no-service-constructor-imports.ts
new file mode 100644
index 0000000..55cefb7
--- /dev/null
+++ b/tools/oxlint/anti-slop/effect/rules/no-service-constructor-imports.ts
@@ -0,0 +1,52 @@
+import { defineRule } from "@oxlint/plugins";
+
+import type { ESTree } from "@oxlint/plugins";
+
+const SERVICE_CONSTRUCTOR_NAME = /^make[A-Z]/u;
+const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
+
+function isProjectLocalImport(source: string): boolean {
+ return source.startsWith("./") || source.startsWith("../");
+}
+
+function getImportedName(specifier: ESTree.ImportSpecifier): string {
+ if (specifier.imported.type === "Identifier") return specifier.imported.name;
+ return specifier.imported.value;
+}
+
+/** Keep dependency-bearing Effect service constructors local to their owning capability modules. */
+export const noServiceConstructorImportsRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow project-local make<CapabilityName> imports outside test and spec files.",
+ },
+ messages: {
+ serviceConstructorImport:
+ 'Do not import Effect service constructor "{{name}}" into runtime code. Import the owning Layer, yield the contextual service, and allow its requirements to propagate to the composition root.',
+ },
+ },
+ create(context) {
+ const isTestFile = TEST_FILE.test(context.filename.replaceAll("\\", "/"));
+
+ return {
+ ImportDeclaration(node) {
+ if (isTestFile || !isProjectLocalImport(node.source.value)) return;
+
+ for (const specifier of node.specifiers) {
+ if (specifier.type !== "ImportSpecifier") continue;
+
+ const importedName = getImportedName(specifier);
+ if (!SERVICE_CONSTRUCTOR_NAME.test(importedName)) continue;
+
+ context.report({
+ node: specifier,
+ messageId: "serviceConstructorImport",
+ data: { name: importedName },
+ });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/effect/rules/prefer-effect-match.ts b/tools/oxlint/anti-slop/effect/rules/prefer-effect-match.ts
new file mode 100644
index 0000000..d834540
--- /dev/null
+++ b/tools/oxlint/anti-slop/effect/rules/prefer-effect-match.ts
@@ -0,0 +1,54 @@
+import { defineRule, type ESTree } from "@oxlint/plugins";
+
+const equalityOperators = new Set(["==", "===", "!=", "!=="]);
+
+export const preferEffectMatchRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Use Match from Effect for chained literal ternaries over the same value.",
+ },
+ messages: {
+ preferMatch:
+ "Use Match from Effect instead of a chained literal ternary.",
+ },
+ },
+ createOnce(context) {
+ const isLiteral = (node: ESTree.Node): boolean =>
+ node.type === "Literal" ||
+ (node.type === "TemplateLiteral" && node.expressions.length === 0);
+
+ const comparedValue = (node: ESTree.Expression): string | undefined => {
+ if (
+ node.type !== "BinaryExpression" ||
+ !equalityOperators.has(node.operator)
+ ) {
+ return undefined;
+ }
+ if (isLiteral(node.left)) return context.sourceCode.getText(node.right);
+ if (isLiteral(node.right)) return context.sourceCode.getText(node.left);
+ return undefined;
+ };
+
+ return {
+ ConditionalExpression(node) {
+ if (node.parent?.type === "ConditionalExpression") return;
+ const value = comparedValue(node.test);
+ if (value === undefined) return;
+
+ let alternate = node.alternate;
+ let literalChecks = 1;
+ while (alternate.type === "ConditionalExpression") {
+ if (comparedValue(alternate.test) !== value) return;
+ literalChecks += 1;
+ alternate = alternate.alternate;
+ }
+
+ if (literalChecks > 1) {
+ context.report({ node, messageId: "preferMatch" });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/effect/shared/tagged-values.ts b/tools/oxlint/anti-slop/effect/shared/tagged-values.ts
new file mode 100644
index 0000000..21d10a2
--- /dev/null
+++ b/tools/oxlint/anti-slop/effect/shared/tagged-values.ts
@@ -0,0 +1,97 @@
+import type { ESTree } from "@oxlint/plugins";
+
+const equalityOperators = new Set(["==", "===", "!=", "!=="]);
+const broadEffectCatchMethods = new Set(["catch", "catchAll", "catchIf"]);
+
+export const isStringLiteral = (
+ node: ESTree.Node | null | undefined,
+): node is ESTree.StringLiteral =>
+ node?.type === "Literal" && typeof node.value === "string";
+
+export const isTagMember = (
+ node: ESTree.Node | null | undefined,
+): node is ESTree.MemberExpression =>
+ node?.type === "MemberExpression" &&
+ ((!node.computed &&
+ node.property.type === "Identifier" &&
+ node.property.name === "_tag") ||
+ (node.computed &&
+ isStringLiteral(node.property) &&
+ node.property.value === "_tag"));
+
+export const tagMemberFromComparison = (
+ node: ESTree.BinaryExpression,
+): ESTree.MemberExpression | undefined => {
+ if (!equalityOperators.has(node.operator)) return undefined;
+ if (isTagMember(node.left) && isStringLiteral(node.right)) return node.left;
+ if (isTagMember(node.right) && isStringLiteral(node.left)) return node.right;
+ return undefined;
+};
+
+const isBroadEffectCatchCall = (
+ node: ESTree.Node | null | undefined,
+): node is ESTree.CallExpression =>
+ node?.type === "CallExpression" &&
+ node.callee.type === "MemberExpression" &&
+ node.callee.object.type === "Identifier" &&
+ node.callee.object.name === "Effect" &&
+ !node.callee.computed &&
+ node.callee.property.type === "Identifier" &&
+ broadEffectCatchMethods.has(node.callee.property.name);
+
+export const isInsideBroadEffectHandler = (node: ESTree.Node): boolean => {
+ let current: ESTree.Node | null | undefined = node.parent;
+ while (current !== null && current !== undefined) {
+ if (
+ current.type === "ArrowFunctionExpression" ||
+ current.type === "FunctionExpression"
+ ) {
+ return (
+ isBroadEffectCatchCall(current.parent) &&
+ current.parent.arguments.includes(current)
+ );
+ }
+ current = current.parent;
+ }
+ return false;
+};
+
+export const isReasonTagMember = (node: ESTree.MemberExpression): boolean =>
+ node.object.type === "MemberExpression" &&
+ ((!node.object.computed &&
+ node.object.property.type === "Identifier" &&
+ node.object.property.name === "reason") ||
+ (node.object.computed &&
+ isStringLiteral(node.object.property) &&
+ node.object.property.value === "reason"));
+
+export const propertyName = (
+ property: ESTree.ObjectProperty,
+): string | undefined => {
+ if (!property.computed && property.key.type === "Identifier") {
+ return property.key.name;
+ }
+ if (
+ property.key.type === "Literal" &&
+ typeof property.key.value === "string"
+ ) {
+ return property.key.value;
+ }
+ return undefined;
+};
+
+export const isMatchPatternObject = (node: ESTree.ObjectExpression): boolean => {
+ const call = node.parent;
+ if (call?.type !== "CallExpression" || !call.arguments.includes(node)) {
+ return false;
+ }
+ const callee = call.callee;
+ return (
+ callee.type === "MemberExpression" &&
+ callee.object.type === "Identifier" &&
+ callee.object.name === "Match" &&
+ !callee.computed &&
+ callee.property.type === "Identifier" &&
+ (callee.property.name === "when" || callee.property.name === "not")
+ );
+};
diff --git a/tools/oxlint/anti-slop/index.ts b/tools/oxlint/anti-slop/index.ts
new file mode 100644
index 0000000..a3876ec
--- /dev/null
+++ b/tools/oxlint/anti-slop/index.ts
@@ -0,0 +1,47 @@
+import { eslintCompatPlugin } from "@oxlint/plugins";
+
+import { noArrayFilterMapRule } from "./rules/no-array-filter-map.ts";
+import { noReduceAccumulatorCopyRule } from "./rules/no-reduce-accumulator-copy.ts";
+import { noChainedTypeAssertionsRule } from "./rules/no-chained-type-assertions.ts";
+import { noConditionalEmptyObjectSpreadRule } from "./rules/no-conditional-empty-object-spread.ts";
+import { noKnownValueWideningRule } from "./rules/no-known-value-widening.ts";
+import { noModuleMockingRule } from "./rules/no-module-mocking.ts";
+import { noObjectParametersRule } from "./rules/no-object-parameters.ts";
+import { noReflectApplyRule } from "./rules/no-reflect-apply.ts";
+import { noReflectGetRule } from "./rules/no-reflect-get.ts";
+import { noRuntimeTypeofRule } from "./rules/no-runtime-typeof.ts";
+import { noForbiddenTermInSymbolNamesRule } from "./rules/no-shape-in-symbol-names.ts";
+import { noUnknownParametersRule } from "./rules/no-unknown-parameters.ts";
+import { noUnknownReturnsRule } from "./rules/no-unknown-returns.ts";
+import { noUnknownTypeAliasesRule } from "./rules/no-unknown-type-aliases.ts";
+import { noUnsafeDictionaryTypeRule } from "./rules/no-unsafe-dictionary-type.ts";
+import { noWidenThenAssertRule } from "./rules/no-widen-then-assert.ts";
+import { requireReadableSpacingRule } from "./rules/require-readable-spacing.ts";
+import { requireSafetyCommentForTypeAssertionRule } from "./rules/require-safety-comment-for-type-assertion.ts";
+
+/** Generic Oxlint rules that reject low-evidence and low-signal implementation patterns. */
+const antiSlopPlugin = eslintCompatPlugin({
+ meta: { name: "anti-slop" },
+ rules: {
+ "no-array-filter-map": noArrayFilterMapRule,
+ "no-reduce-accumulator-copy": noReduceAccumulatorCopyRule,
+ "no-chained-type-assertions": noChainedTypeAssertionsRule,
+ "no-conditional-empty-object-spread": noConditionalEmptyObjectSpreadRule,
+ "no-known-value-widening": noKnownValueWideningRule,
+ "no-module-mocking": noModuleMockingRule,
+ "no-object-parameters": noObjectParametersRule,
+ "no-reflect-apply": noReflectApplyRule,
+ "no-reflect-get": noReflectGetRule,
+ "no-runtime-typeof": noRuntimeTypeofRule,
+ "no-unsafe-dictionary-type": noUnsafeDictionaryTypeRule,
+ "no-shape-in-symbol-names": noForbiddenTermInSymbolNamesRule,
+ "no-unknown-parameters": noUnknownParametersRule,
+ "no-unknown-returns": noUnknownReturnsRule,
+ "no-unknown-type-aliases": noUnknownTypeAliasesRule,
+ "no-widen-then-assert": noWidenThenAssertRule,
+ "require-readable-spacing": requireReadableSpacingRule,
+ "require-safety-comment-for-type-assertion": requireSafetyCommentForTypeAssertionRule,
+ },
+});
+
+export default antiSlopPlugin;
diff --git a/tools/oxlint/anti-slop/rules/no-array-filter-map.ts b/tools/oxlint/anti-slop/rules/no-array-filter-map.ts
new file mode 100644
index 0000000..dc001b3
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-array-filter-map.ts
@@ -0,0 +1,28 @@
+import { defineRule } from "@oxlint/plugins";
+
+import { arrayMethodTarget, isKnownArrayExpression, unwrapArrayExpression } from "../shared/array-method.ts";
+
+/** Reject eager array filter/map pipelines; lazy iterator helpers remain allowed. */
+export const noArrayFilterMapRule = defineRule({
+ meta: {
+ type: "suggestion",
+ docs: { description: "Disallow adjacent array filter/map passes in favor of lazy iterator helpers or a single transformation." },
+ messages: {
+ arrayFilterMap: "Avoid consecutive array `{{first}}` and `{{second}}` passes. Prefer `.values().{{first}}(...).{{second}}(...).toArray()` where iterator helpers are supported, or a single `flatMap`/mutating reducer. Preserve callback ordering, indexes, and filtering semantics.",
+ },
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ const outer = arrayMethodTarget(node.callee);
+ if (outer === null || (outer.name !== "map" && outer.name !== "filter")) return;
+ const innerCall = unwrapArrayExpression(outer.object);
+ if (innerCall.type !== "CallExpression") return;
+ const inner = arrayMethodTarget(innerCall.callee);
+ if (inner === null || inner.name !== (outer.name === "map" ? "filter" : "map")) return;
+ if (!isKnownArrayExpression(context.sourceCode, inner.object)) return;
+ context.report({ node, messageId: "arrayFilterMap", data: { first: inner.name, second: outer.name } });
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-chained-type-assertions.ts b/tools/oxlint/anti-slop/rules/no-chained-type-assertions.ts
new file mode 100644
index 0000000..0d11852
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-chained-type-assertions.ts
@@ -0,0 +1,77 @@
+import { defineRule } from "@oxlint/plugins";
+import type { ESTree } from "@oxlint/plugins";
+
+type TypeAssertionExpression = ESTree.TSAsExpression | ESTree.TSTypeAssertion;
+
+function isTypeAssertionExpression(node: ESTree.Node): node is TypeAssertionExpression {
+ return node.type === "TSAsExpression" || node.type === "TSTypeAssertion";
+}
+
+function unwrapParenthesizedExpression(expression: ESTree.Expression): ESTree.Expression {
+ let current = expression;
+ while (current.type === "ParenthesizedExpression") {
+ current = current.expression;
+ }
+ return current;
+}
+
+function isConstAssertion(node: TypeAssertionExpression): boolean {
+ const { typeAnnotation } = node;
+ return (
+ typeAnnotation.type === "TSTypeReference" &&
+ typeAnnotation.typeName.type === "Identifier" &&
+ typeAnnotation.typeName.name === "const"
+ );
+}
+
+function isOutermostAssertionInChain(node: TypeAssertionExpression): boolean {
+ let current: ESTree.Expression = node;
+ let parent = node.parent;
+
+ while (parent.type === "ParenthesizedExpression" && parent.expression === current) {
+ current = parent;
+ parent = parent.parent;
+ }
+
+ return !isTypeAssertionExpression(parent) || parent.expression !== current;
+}
+
+function isForbiddenAssertionChain(node: TypeAssertionExpression): boolean {
+ let assertionCount = 0;
+ let hasNonConstAssertion = false;
+ let current: ESTree.Expression = node;
+
+ while (isTypeAssertionExpression(current)) {
+ assertionCount += 1;
+ hasNonConstAssertion ||= !isConstAssertion(current);
+ current = unwrapParenthesizedExpression(current.expression);
+ }
+
+ return assertionCount > 1 && hasNonConstAssertion;
+}
+
+/** Disallow nested TypeScript type assertions, while permitting chains made only of const assertions. */
+export const noChainedTypeAssertionsRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow chained TypeScript as and angle-bracket assertions, including parenthesized chains.",
+ },
+ messages: {
+ chained:
+ "This assertion chain discards type evidence. Keep the original precise type, or parse untrusted input at its boundary before narrowing it.",
+ },
+ },
+ createOnce(context) {
+ const checkTypeAssertion = (node: TypeAssertionExpression) => {
+ if (!isOutermostAssertionInChain(node) || !isForbiddenAssertionChain(node)) return;
+ context.report({ node, messageId: "chained" });
+ };
+
+ return {
+ TSAsExpression: checkTypeAssertion,
+ TSTypeAssertion: checkTypeAssertion,
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-conditional-empty-object-spread.ts b/tools/oxlint/anti-slop/rules/no-conditional-empty-object-spread.ts
new file mode 100644
index 0000000..ae7248d
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-conditional-empty-object-spread.ts
@@ -0,0 +1,49 @@
+import { defineRule } from "@oxlint/plugins";
+import type { ESTree } from "@oxlint/plugins";
+
+function unwrapParentheses(node: ESTree.Expression): ESTree.Expression {
+ let current = node;
+ while (current.type === "ParenthesizedExpression") {
+ current = current.expression;
+ }
+ return current;
+}
+
+function isEmptyObjectExpression(node: ESTree.Expression): boolean {
+ return node.type === "ObjectExpression" && node.properties.length === 0;
+}
+
+function isConditionalEmptyObjectSpread(node: ESTree.Expression): boolean {
+ const conditional = unwrapParentheses(node);
+ return (
+ conditional.type === "ConditionalExpression" &&
+ (isEmptyObjectExpression(conditional.consequent) ||
+ isEmptyObjectExpression(conditional.alternate))
+ );
+}
+
+/** Ban conditional empty-object spreads without changing their omission semantics. */
+export const noConditionalEmptyObjectSpreadRule = defineRule({
+ meta: {
+ type: "suggestion",
+ docs: {
+ description:
+ "Disallow object spreads that conditionally spread an empty object to omit fields.",
+ },
+ messages: {
+ avoid:
+ "This conditional spread hides property omission behind an empty object. Build the object in separate statements and add the property only when present.",
+ },
+ },
+ createOnce(context) {
+ return {
+ SpreadElement(node) {
+ if (node.parent.type !== "ObjectExpression") return;
+
+ if (isConditionalEmptyObjectSpread(node.argument)) {
+ context.report({ node, messageId: "avoid" });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-known-value-widening.ts b/tools/oxlint/anti-slop/rules/no-known-value-widening.ts
new file mode 100644
index 0000000..0df39ab
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-known-value-widening.ts
@@ -0,0 +1,415 @@
+import { defineRule } from "@oxlint/plugins";
+
+import {
+ classifyUnsafeDictionaryValue,
+ classifyWideningTarget,
+ createTypeEnvironment,
+ isKnownEvidenceExpression,
+ type TypeEnvironment,
+ type WideningTarget,
+} from "../shared/dictionary-types.ts";
+import {
+ containsUnknownType,
+ functionParameterBindingName,
+ functionParameterTypeAnnotation,
+} from "../shared/function-parameters.ts";
+import { resolveVariable } from "../shared/scope.ts";
+
+import type { ESTree, SourceCode, Variable } from "@oxlint/plugins";
+
+type FunctionExpression = ESTree.ArrowFunctionExpression | ESTree.Function;
+
+function unwrapExpression(expression: ESTree.Expression): ESTree.Expression {
+ let current = expression;
+ while (
+ current.type === "ParenthesizedExpression" ||
+ current.type === "TSAsExpression" ||
+ current.type === "TSSatisfiesExpression" ||
+ current.type === "TSTypeAssertion" ||
+ current.type === "TSNonNullExpression"
+ ) {
+ current = current.expression;
+ }
+ return current;
+}
+
+function variableDeclarator(variable: Variable): ESTree.VariableDeclarator | null {
+ if (variable.defs.length !== 1) return null;
+ const [definition] = variable.defs;
+ return definition?.type === "Variable" && definition.node.type === "VariableDeclarator"
+ ? definition.node
+ : null;
+}
+
+function isStableConstVariable(variable: Variable, declarator: ESTree.VariableDeclarator): boolean {
+ return (
+ declarator.parent.type === "VariableDeclaration" &&
+ declarator.parent.kind === "const" &&
+ variable.references.every((reference) => reference.init || !reference.isWrite())
+ );
+}
+
+function hasKnownEvidence(
+ sourceCode: SourceCode,
+ expression: ESTree.Expression,
+ visitedVariables = new Set<Variable>(),
+): boolean {
+ if (isKnownEvidenceExpression(expression)) return true;
+ const unwrapped = unwrapExpression(expression);
+ if (unwrapped.type !== "Identifier") return false;
+ const variable = resolveVariable(sourceCode, unwrapped);
+ if (variable === null || visitedVariables.has(variable)) return false;
+ const declarator = variableDeclarator(variable);
+ if (
+ declarator === null ||
+ declarator.init === null ||
+ !isStableConstVariable(variable, declarator)
+ ) {
+ return false;
+ }
+ visitedVariables.add(variable);
+ return hasKnownEvidence(sourceCode, declarator.init, visitedVariables);
+}
+
+function isFunctionExpression(node: ESTree.Node): node is FunctionExpression {
+ return (
+ node.type === "ArrowFunctionExpression" ||
+ node.type === "FunctionDeclaration" ||
+ node.type === "FunctionExpression" ||
+ node.type === "TSDeclareFunction" ||
+ node.type === "TSEmptyBodyFunctionExpression"
+ );
+}
+
+function localFunctionForCall(
+ sourceCode: SourceCode,
+ callee: ESTree.Expression,
+): FunctionExpression | null {
+ const unwrapped = unwrapExpression(callee);
+ if (isFunctionExpression(unwrapped)) return unwrapped;
+ if (unwrapped.type !== "Identifier") return null;
+ const variable = resolveVariable(sourceCode, unwrapped);
+ if (variable === null || variable.defs.length !== 1) return null;
+ const [definition] = variable.defs;
+ if (definition === undefined) return null;
+ if (definition.type === "FunctionName" && isFunctionExpression(definition.node)) {
+ return definition.node;
+ }
+ if (definition.type !== "Variable" || definition.node.type !== "VariableDeclarator") {
+ return null;
+ }
+ const initializer = definition.node.init;
+ if (initializer === null) return null;
+ const unwrappedInitializer = unwrapExpression(initializer);
+ return isFunctionExpression(unwrappedInitializer) ? unwrappedInitializer : null;
+}
+
+function variableTypeAnnotation(
+ sourceCode: SourceCode,
+ variable: Variable,
+): ESTree.TSTypeAnnotation | null {
+ if (variable.defs.length !== 1) return null;
+ const [definition] = variable.defs;
+ if (definition === undefined) return null;
+ if (
+ definition.type === "Variable" &&
+ definition.node.type === "VariableDeclarator" &&
+ definition.node.id.type === "Identifier"
+ ) {
+ return definition.node.id.typeAnnotation ?? null;
+ }
+ if (definition.type !== "Parameter" || !isFunctionExpression(definition.node)) {
+ return null;
+ }
+ const parameter = definition.node.params.find(
+ (candidate) =>
+ functionParameterBindingName(candidate, sourceCode) === variable.name,
+ );
+ return parameter === undefined ? null : (functionParameterTypeAnnotation(parameter) ?? null);
+}
+
+function hasInformativeType(
+ type: ESTree.TSType,
+ environment: TypeEnvironment,
+): boolean {
+ return classifyUnsafeDictionaryValue(type, environment) === null;
+}
+
+function hasKnownCallArgumentEvidence(
+ sourceCode: SourceCode,
+ expression: ESTree.Expression,
+ environment: TypeEnvironment,
+ visitedVariables = new Set<Variable>(),
+): boolean {
+ if (expression.type === "ParenthesizedExpression" || expression.type === "TSNonNullExpression") {
+ return hasKnownCallArgumentEvidence(
+ sourceCode,
+ expression.expression,
+ environment,
+ visitedVariables,
+ );
+ }
+ if (expression.type === "TSAsExpression" || expression.type === "TSTypeAssertion") {
+ return hasInformativeType(expression.typeAnnotation, environment);
+ }
+ if (expression.type === "TSSatisfiesExpression") {
+ return hasKnownCallArgumentEvidence(
+ sourceCode,
+ expression.expression,
+ environment,
+ visitedVariables,
+ );
+ }
+ if (expression.type === "CallExpression") {
+ const owner = localFunctionForCall(sourceCode, expression.callee);
+ const returnType = owner?.returnType?.typeAnnotation;
+ return returnType !== undefined && hasInformativeType(returnType, environment);
+ }
+ if (expression.type !== "Identifier") return isKnownEvidenceExpression(expression);
+ const variable = resolveVariable(sourceCode, expression);
+ if (variable === null || visitedVariables.has(variable)) return false;
+ const annotation = variableTypeAnnotation(sourceCode, variable);
+ if (annotation !== null) {
+ return hasInformativeType(annotation.typeAnnotation, environment);
+ }
+ const declarator = variableDeclarator(variable);
+ if (
+ declarator === null ||
+ declarator.init === null ||
+ !isStableConstVariable(variable, declarator)
+ ) {
+ return false;
+ }
+ visitedVariables.add(variable);
+ return hasKnownCallArgumentEvidence(
+ sourceCode,
+ declarator.init,
+ environment,
+ visitedVariables,
+ );
+}
+
+function typePredicateSubjectIndex(
+ sourceCode: SourceCode,
+ owner: FunctionExpression,
+): number | null {
+ const predicate = owner.returnType?.typeAnnotation;
+ if (predicate?.type !== "TSTypePredicate" || predicate.parameterName.type !== "Identifier") {
+ return null;
+ }
+ const predicateParameterName = predicate.parameterName.name;
+ const index = owner.params.findIndex(
+ (parameter) =>
+ functionParameterBindingName(parameter, sourceCode) === predicateParameterName,
+ );
+ return index === -1 ? null : index;
+}
+
+function annotationTarget(
+ annotation: ESTree.TSTypeAnnotation | null | undefined,
+ environment: TypeEnvironment,
+): WideningTarget | null {
+ return annotation === null || annotation === undefined
+ ? null
+ : classifyWideningTarget(annotation.typeAnnotation, environment);
+}
+
+function enclosingFunction(node: ESTree.Node): FunctionExpression | null {
+ let current: ESTree.Node | null = node.parent;
+ while (current !== null && current.type !== "Program") {
+ if (
+ current.type === "ArrowFunctionExpression" ||
+ current.type === "FunctionDeclaration" ||
+ current.type === "FunctionExpression"
+ ) {
+ return current;
+ }
+ current = current.parent;
+ }
+ return null;
+}
+
+function sourceKeyName(sourceCode: SourceCode, key: ESTree.PropertyKey): string {
+ if (key.type === "Identifier" || key.type === "PrivateIdentifier") return key.name;
+ if (key.type === "Literal") return String(key.value);
+ return sourceCode.getText(key);
+}
+
+function functionName(sourceCode: SourceCode, owner: FunctionExpression | null): string {
+ if (owner === null) return "anonymous function";
+ if (owner.id !== null) return owner.id.name;
+ const parent = owner.parent;
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier")
+ return parent.id.name;
+ if (parent.type === "MethodDefinition") return sourceKeyName(sourceCode, parent.key);
+ return "anonymous function";
+}
+
+function isEmptyObjectExpression(expression: ESTree.Expression): boolean {
+ const unwrapped = unwrapExpression(expression);
+ return unwrapped.type === "ObjectExpression" && unwrapped.properties.length === 0;
+}
+
+function isDictionaryAccumulatorTarget(destination: WideningTarget): boolean {
+ return destination.kind === "open dictionary" || destination.kind === "generic container";
+}
+
+function hasParentAssertion(node: ESTree.Node): boolean {
+ return node.parent?.type === "TSAsExpression" || node.parent?.type === "TSTypeAssertion";
+}
+
+/** Detect sound syntactic cases where a known value is explicitly widened and loses evidence. */
+export const noKnownValueWideningRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow syntactically established values from flowing into explicitly broad or anonymous target types that discard useful evidence.",
+ },
+ messages: {
+ widening:
+ "The explicit {{target}} type on {{subject}} discards known type evidence. Keep inference, validate with `satisfies`, or use a named owner contract.",
+ },
+ },
+ createOnce(context) {
+ let environment: TypeEnvironment | null = null;
+
+ const reportFlow = (
+ expression: ESTree.Expression,
+ destination: WideningTarget | null,
+ subject: string,
+ ) => {
+ if (destination === null) return;
+ if (
+ isDictionaryAccumulatorTarget(destination) &&
+ isEmptyObjectExpression(expression)
+ ) {
+ return;
+ }
+ if (!hasKnownEvidence(context.sourceCode, expression)) return;
+ context.report({
+ node: expression,
+ messageId: "widening",
+ data: { subject, target: destination.kind },
+ });
+ };
+
+ const targetFromAnnotation = (annotation: ESTree.TSTypeAnnotation | null | undefined) =>
+ environment === null ? null : annotationTarget(annotation, environment);
+
+ return {
+ Program(node) {
+ environment = createTypeEnvironment(
+ node,
+ context.sourceCode.visitorKeys,
+ );
+ },
+ VariableDeclarator(node) {
+ if (node.init === null || node.id.type !== "Identifier") return;
+ reportFlow(
+ node.init,
+ targetFromAnnotation(node.id.typeAnnotation),
+ `binding \`${node.id.name}\``,
+ );
+ },
+ PropertyDefinition(node) {
+ if (node.value === null) return;
+ reportFlow(
+ node.value,
+ targetFromAnnotation(node.typeAnnotation),
+ `property \`${sourceKeyName(context.sourceCode, node.key)}\``,
+ );
+ },
+ AccessorProperty(node) {
+ if (node.value === null) return;
+ reportFlow(
+ node.value,
+ targetFromAnnotation(node.typeAnnotation),
+ `property \`${sourceKeyName(context.sourceCode, node.key)}\``,
+ );
+ },
+ AssignmentExpression(node) {
+ if (node.operator !== "=" || node.left.type !== "Identifier") return;
+ const variable = resolveVariable(context.sourceCode, node.left);
+ if (variable === null) return;
+ const declarator = variableDeclarator(variable);
+ if (declarator === null || declarator.id.type !== "Identifier") return;
+ reportFlow(
+ node.right,
+ targetFromAnnotation(declarator.id.typeAnnotation),
+ `binding \`${declarator.id.name}\``,
+ );
+ },
+ CallExpression(node) {
+ if (environment === null) return;
+ const owner = localFunctionForCall(context.sourceCode, node.callee);
+ if (owner === null) return;
+ const parameterIndex = typePredicateSubjectIndex(context.sourceCode, owner);
+ if (parameterIndex === null) return;
+ const parameter = owner.params[parameterIndex];
+ const argument = node.arguments[parameterIndex];
+ if (parameter === undefined || argument === undefined || argument.type === "SpreadElement") {
+ return;
+ }
+ const parameterAnnotation = functionParameterTypeAnnotation(parameter);
+ if (
+ parameterAnnotation === null ||
+ parameterAnnotation === undefined ||
+ !containsUnknownType(parameterAnnotation.typeAnnotation)
+ ) {
+ return;
+ }
+ if (
+ !hasKnownCallArgumentEvidence(
+ context.sourceCode,
+ argument,
+ environment,
+ )
+ ) {
+ return;
+ }
+ context.report({
+ node: argument,
+ messageId: "widening",
+ data: {
+ subject: `argument for parameter \`${functionParameterBindingName(parameter, context.sourceCode)}\` of \`${functionName(context.sourceCode, owner)}\``,
+ target: "unknown",
+ },
+ });
+ },
+ ReturnStatement(node) {
+ if (node.argument === null) return;
+ const owner = enclosingFunction(node);
+ reportFlow(
+ node.argument,
+ targetFromAnnotation(owner?.returnType),
+ `return value of \`${functionName(context.sourceCode, owner)}\``,
+ );
+ },
+ ArrowFunctionExpression(node) {
+ if (node.body.type === "BlockStatement") return;
+ reportFlow(
+ node.body,
+ targetFromAnnotation(node.returnType),
+ `return value of \`${functionName(context.sourceCode, node)}\``,
+ );
+ },
+ TSAsExpression(node) {
+ if (environment === null || hasParentAssertion(node)) return;
+ reportFlow(
+ node.expression,
+ classifyWideningTarget(node.typeAnnotation, environment),
+ "assertion",
+ );
+ },
+ TSTypeAssertion(node) {
+ if (environment === null || hasParentAssertion(node)) return;
+ reportFlow(
+ node.expression,
+ classifyWideningTarget(node.typeAnnotation, environment),
+ "assertion",
+ );
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-module-mocking.ts b/tools/oxlint/anti-slop/rules/no-module-mocking.ts
new file mode 100644
index 0000000..2d60d48
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-module-mocking.ts
@@ -0,0 +1,80 @@
+import { defineRule } from "@oxlint/plugins";
+
+import { resolveVariable } from "../shared/scope.ts";
+
+import type { ESTree, SourceCode } from "@oxlint/plugins";
+
+const moduleMockMethods = new Set(["doMock", "mock", "unstable_mockModule"]);
+
+function importedName(node: ESTree.Node): string | null {
+ if (node.type !== "ImportSpecifier") return null;
+ return node.imported.type === "Identifier" ? node.imported.name : node.imported.value;
+}
+
+function isTestFrameworkObject(
+ sourceCode: SourceCode,
+ expression: ESTree.Expression,
+): expression is ESTree.IdentifierReference {
+ if (expression.type !== "Identifier") return false;
+ if (
+ (expression.name === "vi" || expression.name === "jest") &&
+ sourceCode.isGlobalReference(expression)
+ ) {
+ return true;
+ }
+
+ const variable = resolveVariable(sourceCode, expression);
+ if (variable === null || variable.defs.length === 0) {
+ return expression.name === "vi" || expression.name === "jest";
+ }
+ return variable.defs.some((definition) => {
+ if (definition.type !== "ImportBinding" || definition.parent?.type !== "ImportDeclaration") {
+ return false;
+ }
+ const source = definition.parent.source.value;
+ const name = importedName(definition.node);
+ return (source === "vitest" && name === "vi") || (source === "@jest/globals" && name === "jest");
+ });
+}
+
+function moduleMockCall(sourceCode: SourceCode, callee: ESTree.Expression): boolean {
+ if (!("property" in callee) || !("object" in callee) || !("computed" in callee)) return false;
+ if (!isTestFrameworkObject(sourceCode, callee.object)) return false;
+ const property = callee.property;
+ const method = callee.computed
+ ? property.type === "Literal" &&
+ (property.value === "doMock" ||
+ property.value === "mock" ||
+ property.value === "unstable_mockModule")
+ ? property.value
+ : null
+ : property.type === "Identifier"
+ ? property.name
+ : null;
+ return method !== null && moduleMockMethods.has(method);
+}
+
+/** Ban test framework module mocking in favor of real dependency seams. */
+export const noModuleMockingRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow Vitest and Jest module mocking; tests must replace dependencies through real interfaces.",
+ },
+ messages: {
+ moduleMock:
+ "Replace module mocking with dependency injection through a real interface, service layer, or faithful test implementation.",
+ },
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ if (node.callee.type === "Super" || node.callee.type === "V8IntrinsicExpression") return;
+ if (moduleMockCall(context.sourceCode, node.callee)) {
+ context.report({ node, messageId: "moduleMock" });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-object-parameters.ts b/tools/oxlint/anti-slop/rules/no-object-parameters.ts
new file mode 100644
index 0000000..6589ebf
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-object-parameters.ts
@@ -0,0 +1,83 @@
+import { defineRule } from "@oxlint/plugins";
+
+import type { ESTree } from "@oxlint/plugins";
+
+import {
+ functionParameterBindingName,
+ functionParameterTypeAnnotation,
+} from "../shared/function-parameters.ts";
+import {
+ createTypeAliasEnvironment,
+ resolvedTypeMatches,
+ type TypeAliasEnvironment,
+} from "../shared/type-alias-resolution.ts";
+type ParameterOwner =
+ | ESTree.ArrowFunctionExpression
+ | ESTree.Function
+ | ESTree.TSCallSignatureDeclaration
+ | ESTree.TSConstructSignatureDeclaration
+ | ESTree.TSConstructorType
+ | ESTree.TSFunctionType
+ | ESTree.TSMethodSignature;
+
+/** Ban the broad object type on function inputs, including local aliases to object. */
+export const noObjectParametersRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow object function parameters; inputs must use an owner-provided type and be parsed at their boundary.",
+ },
+ messages: {
+ objectParameter:
+ "Parameter `{{parameter}}` uses the broad `object` type. Accept a named owner type; parse external input at its boundary before calling this function.",
+ },
+ },
+ createOnce(context) {
+ let environment: TypeAliasEnvironment | null = null;
+
+ const resolvesToObject = (type: ESTree.TSType): boolean =>
+ environment !== null &&
+ resolvedTypeMatches(type, environment, (resolved, matches) => {
+ if (resolved.type === "TSObjectKeyword") return true;
+ if (resolved.type === "TSParenthesizedType") {
+ return matches(resolved.typeAnnotation);
+ }
+ return (
+ resolved.type === "TSUnionType" && resolved.types.some(matches)
+ );
+ });
+
+ const checkParameters = (node: ParameterOwner) => {
+ for (const parameter of node.params) {
+ const annotation = functionParameterTypeAnnotation(parameter);
+ if (annotation === null || annotation === undefined) continue;
+ if (!resolvesToObject(annotation.typeAnnotation)) continue;
+ context.report({
+ node: annotation.typeAnnotation,
+ messageId: "objectParameter",
+ data: { parameter: functionParameterBindingName(parameter, context.sourceCode) },
+ });
+ }
+ };
+
+ return {
+ Program(node) {
+ environment = createTypeAliasEnvironment(
+ node,
+ context.sourceCode.visitorKeys,
+ );
+ },
+ ArrowFunctionExpression: checkParameters,
+ FunctionDeclaration: checkParameters,
+ FunctionExpression: checkParameters,
+ TSCallSignatureDeclaration: checkParameters,
+ TSConstructSignatureDeclaration: checkParameters,
+ TSConstructorType: checkParameters,
+ TSDeclareFunction: checkParameters,
+ TSEmptyBodyFunctionExpression: checkParameters,
+ TSFunctionType: checkParameters,
+ TSMethodSignature: checkParameters,
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-reduce-accumulator-copy.ts b/tools/oxlint/anti-slop/rules/no-reduce-accumulator-copy.ts
new file mode 100644
index 0000000..47d8e2c
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-reduce-accumulator-copy.ts
@@ -0,0 +1,109 @@
+import { defineRule } from "@oxlint/plugins";
+import type { ESTree, SourceCode, Variable } from "@oxlint/plugins";
+
+import {
+ arrayMethodTarget,
+ isKnownArrayExpression,
+ resolveArrayBinding,
+ unwrapArrayExpression,
+} from "../shared/array-method.ts";
+
+function enclosingReducer(node: ESTree.Node) {
+ let parent = node.parent;
+ while (parent !== null) {
+ if (parent.type === "FunctionDeclaration") return null;
+ if (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression") {
+ const callback = parent;
+ let owner: ESTree.Node | null = callback.parent;
+ while (owner !== null && unwrapArrayExpression(owner) === callback) owner = owner.parent;
+ if (owner?.type !== "CallExpression") return null;
+ const method = arrayMethodTarget(owner.callee);
+ const firstArgument = owner.arguments[0];
+ if (
+ method === null || (method.name !== "reduce" && method.name !== "reduceRight") ||
+ owner.arguments.length > 2 || firstArgument === undefined ||
+ unwrapArrayExpression(firstArgument) !== callback
+ ) return null;
+ const firstParameter = callback.params[0];
+ const accumulator = firstParameter?.type === "AssignmentPattern" ? firstParameter.left : firstParameter;
+ if (accumulator?.type !== "Identifier") return null;
+ return { callback, accumulator, initialValue: owner.arguments[1] };
+ }
+ parent = parent.parent;
+ }
+ return null;
+}
+
+function referencesAccumulator(
+ sourceCode: SourceCode,
+ node: ESTree.Node,
+ accumulator: Variable,
+ visited = new Set<Variable>(),
+): boolean {
+ const variable = resolveArrayBinding(sourceCode, node);
+ if (variable === null || visited.has(variable)) return false;
+ if (variable === accumulator) return true;
+ visited.add(variable);
+ if (variable.references.some(reference => reference.isWrite() && !reference.init)) return false;
+ for (const definition of variable.defs) {
+ if (
+ definition.type === "Variable" && definition.node.type === "VariableDeclarator" &&
+ definition.node.id.type === "Identifier" && definition.node.init !== null &&
+ definition.node.parent.type === "VariableDeclaration" && definition.node.parent.kind === "const"
+ ) {
+ return referencesAccumulator(sourceCode, definition.node.init, accumulator, visited);
+ }
+ }
+ return false;
+}
+
+function isGlobalCopyOwner(sourceCode: SourceCode, node: ESTree.Node, name: string): boolean {
+ node = unwrapArrayExpression(node);
+ if (node.type !== "Identifier" || node.name !== name) return false;
+ const variable = resolveArrayBinding(sourceCode, node);
+ return variable === null || variable.defs.length === 0;
+}
+
+/** Reject non-spread copies of reducer accumulators; pair with oxc/no-accumulating-spread. */
+export const noReduceAccumulatorCopyRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: { description: "Disallow copying growing reducer accumulators with Object.assign, Array.from, or array copy methods." },
+ messages: {
+ accumulatorCopy: "Do not copy the reducer accumulator on every iteration; growing copies can cause quadratic work. Mutate a fresh, locally owned accumulator and return it, or use an iterator pipeline/flatMap.",
+ },
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ const method = arrayMethodTarget(node.callee);
+ if (method === null) return;
+ const reducer = enclosingReducer(node);
+ if (reducer === null) return;
+ const accumulator = context.sourceCode.getDeclaredVariables(reducer.callback).find(variable =>
+ variable.identifiers.some(identifier => identifier.start === reducer.accumulator.start),
+ );
+ if (accumulator === undefined) return;
+ const isAccumulator = (expression: ESTree.Node) =>
+ referencesAccumulator(context.sourceCode, expression, accumulator);
+ let copiesAccumulator = false;
+ if (method.name === "assign" && isGlobalCopyOwner(context.sourceCode, method.object, "Object")) {
+ const target = node.arguments[0];
+ copiesAccumulator = (
+ target !== undefined && unwrapArrayExpression(target).type === "ObjectExpression" &&
+ node.arguments.slice(1).some(isAccumulator)
+ );
+ } else if (method.name === "from" && isGlobalCopyOwner(context.sourceCode, method.object, "Array")) {
+ const source = node.arguments[0];
+ copiesAccumulator = source !== undefined && isAccumulator(source);
+ } else if (["concat", "slice", "toSpliced", "toSorted", "toReversed", "with"].includes(method.name)) {
+ const initialValue = reducer.initialValue;
+ const arrayAccumulator = initialValue !== undefined &&
+ isKnownArrayExpression(context.sourceCode, initialValue);
+ copiesAccumulator = arrayAccumulator && isAccumulator(method.object);
+ }
+ if (copiesAccumulator) context.report({ node, messageId: "accumulatorCopy" });
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-reflect-apply.ts b/tools/oxlint/anti-slop/rules/no-reflect-apply.ts
new file mode 100644
index 0000000..2cc3045
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-reflect-apply.ts
@@ -0,0 +1,28 @@
+import { defineRule } from "@oxlint/plugins";
+
+import { isGlobalReflectMethodCall } from "../shared/reflect-method.ts";
+
+/** Ban Reflect.apply, which bypasses ordinary typed function calls. */
+export const noReflectApplyRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow Reflect.apply; call typed functions directly or model dynamic dispatch behind an interface.",
+ },
+ messages: {
+ reflectApply:
+ "Replace `Reflect.apply` with a typed function call. Model dynamic dispatch behind a named interface.",
+ },
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ if (node.callee.type === "Super" || node.callee.type === "V8IntrinsicExpression") return;
+ if (isGlobalReflectMethodCall(context.sourceCode, node.callee, "apply")) {
+ context.report({ node, messageId: "reflectApply" });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-reflect-get.ts b/tools/oxlint/anti-slop/rules/no-reflect-get.ts
new file mode 100644
index 0000000..cf630ec
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-reflect-get.ts
@@ -0,0 +1,28 @@
+import { defineRule } from "@oxlint/plugins";
+
+import { isGlobalReflectMethodCall } from "../shared/reflect-method.ts";
+
+/** Ban Reflect.get, which bypasses ordinary property access and useful type evidence. */
+export const noReflectGetRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow Reflect.get; use typed property access or parse dynamic input into a domain type.",
+ },
+ messages: {
+ reflectGet:
+ "Replace `Reflect.get` with typed property access. Parse dynamic input into a named domain type before reading it.",
+ },
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ if (node.callee.type === "Super" || node.callee.type === "V8IntrinsicExpression") return;
+ if (isGlobalReflectMethodCall(context.sourceCode, node.callee, "get")) {
+ context.report({ node, messageId: "reflectGet" });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-runtime-typeof.ts b/tools/oxlint/anti-slop/rules/no-runtime-typeof.ts
new file mode 100644
index 0000000..43259eb
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-runtime-typeof.ts
@@ -0,0 +1,77 @@
+import { defineRule } from "@oxlint/plugins";
+
+import type { ESTree } from "@oxlint/plugins";
+
+type RuntimeFunction = ESTree.ArrowFunctionExpression | ESTree.Function;
+
+function isRuntimeFunction(node: ESTree.Node): node is RuntimeFunction {
+ return (
+ node.type === "ArrowFunctionExpression" ||
+ node.type === "FunctionDeclaration" ||
+ node.type === "FunctionExpression"
+ );
+}
+
+function isInsideTypeGuard(node: ESTree.Node): boolean {
+ let current: ESTree.Node | null = node.parent;
+ while (current !== null && current.type !== "Program") {
+ if (isRuntimeFunction(current)) {
+ return current.returnType?.typeAnnotation.type === "TSTypePredicate";
+ }
+ current = current.parent;
+ }
+ return false;
+}
+
+/** Return whether typeof safely probes for the existence of a possibly absent binding. */
+function isExistenceProbe(node: ESTree.UnaryExpression): boolean {
+ const parent = node.parent;
+ if (parent.type !== "BinaryExpression") return false;
+ if (!["===", "!==", "==", "!="].includes(parent.operator)) return false;
+ const other = parent.left === node ? parent.right : parent.left;
+ return other.type === "Literal" && other.value === "undefined";
+}
+
+/** Disallow runtime typeof checks that narrow unparsed values instead of decoding them. */
+export const noRuntimeTypeofRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow runtime typeof checks; external values must be decoded into meaningful types at their I/O boundary.",
+ },
+ messages: {
+ runtimeTypeof:
+ "A `typeof` check narrows a representation without establishing its contract. Parse input at its I/O boundary, then branch on the domain value.",
+ },
+ schema: [
+ {
+ type: "object",
+ properties: {
+ allowInTypeGuards: { type: "boolean" },
+ },
+ additionalProperties: false,
+ },
+ ],
+ defaultOptions: [{ allowInTypeGuards: false }],
+ },
+ createOnce(context) {
+ return {
+ UnaryExpression(node) {
+ const option = context.options?.[0];
+ const allowInTypeGuards =
+ typeof option === "object" &&
+ option !== null &&
+ !Array.isArray(option) &&
+ option.allowInTypeGuards === true;
+ if (
+ node.operator === "typeof" &&
+ !isExistenceProbe(node) &&
+ (!allowInTypeGuards || !isInsideTypeGuard(node))
+ ) {
+ context.report({ node, messageId: "runtimeTypeof" });
+ }
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-shape-in-symbol-names.ts b/tools/oxlint/anti-slop/rules/no-shape-in-symbol-names.ts
new file mode 100644
index 0000000..436d2a2
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-shape-in-symbol-names.ts
@@ -0,0 +1,46 @@
+import { defineRule } from "@oxlint/plugins";
+import type { ESTree } from "@oxlint/plugins";
+
+const FORBIDDEN_SYMBOL_NAME = "shape";
+
+function containsForbiddenSymbolName(name: string): boolean {
+ return name.toLowerCase().includes(FORBIDDEN_SYMBOL_NAME);
+}
+
+/** Return whether an identifier names a statically accessed member owned by another value. */
+function isBorrowedMemberName(node: ESTree.Node): boolean {
+ const parent = node.parent;
+ if (parent === null || parent.type !== "MemberExpression") return false;
+ return parent.property === node && parent.computed === false;
+}
+
+/** Ban the case-insensitive substring "shape" in every JavaScript and TypeScript symbol name. */
+export const noForbiddenTermInSymbolNamesRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ 'Disallow the case-insensitive substring "shape" in JavaScript, TypeScript, private, and JSX symbol names.',
+ },
+ messages: {
+ forbiddenSymbolName:
+ 'Rename symbol "{{name}}" for its domain role; "shape" describes structure rather than ownership.',
+ },
+ },
+ createOnce(context) {
+ const reportForbiddenSymbolName = (node: ESTree.Node & { name: string }) => {
+ if (!containsForbiddenSymbolName(node.name) || isBorrowedMemberName(node)) return;
+ context.report({
+ node,
+ messageId: "forbiddenSymbolName",
+ data: { name: node.name },
+ });
+ };
+
+ return {
+ Identifier: reportForbiddenSymbolName,
+ PrivateIdentifier: reportForbiddenSymbolName,
+ JSXIdentifier: reportForbiddenSymbolName,
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-unknown-parameters.ts b/tools/oxlint/anti-slop/rules/no-unknown-parameters.ts
new file mode 100644
index 0000000..b4a1545
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-unknown-parameters.ts
@@ -0,0 +1,69 @@
+import { defineRule } from "@oxlint/plugins";
+import type { ESTree } from "@oxlint/plugins";
+
+import {
+ containsUnknownType,
+ functionParameterBindingName,
+ functionParameterTypeAnnotation,
+} from "../shared/function-parameters.ts";
+type ParameterOwner =
+ | ESTree.ArrowFunctionExpression
+ | ESTree.Function
+ | ESTree.TSCallSignatureDeclaration
+ | ESTree.TSConstructSignatureDeclaration
+ | ESTree.TSConstructorType
+ | ESTree.TSFunctionType
+ | ESTree.TSMethodSignature;
+
+function isTypePredicateSubject(owner: ParameterOwner, parameterName: string): boolean {
+ const predicate = owner.returnType?.typeAnnotation;
+ return (
+ predicate?.type === "TSTypePredicate" &&
+ predicate.parameterName.type === "Identifier" &&
+ predicate.parameterName.name === parameterName
+ );
+}
+
+/** Disallow unknown inputs except explicitly named error-cause enrichment. */
+export const noUnknownParametersRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow explicitly unknown function parameters except `cause` and type-predicate subjects; decode unknown input at its I/O boundary instead.",
+ },
+ messages: {
+ unknownParameter:
+ "Parameter `{{parameter}}` leaves input unparsed. Accept a named domain type; run the expected schema or parser at the I/O boundary before calling this function.",
+ },
+ },
+ createOnce(context) {
+ const checkParameters = (node: ParameterOwner) => {
+ for (const parameter of node.params) {
+ const annotation = functionParameterTypeAnnotation(parameter);
+ if (annotation === null || annotation === undefined) continue;
+ if (!containsUnknownType(annotation.typeAnnotation)) continue;
+ const name = functionParameterBindingName(parameter, context.sourceCode);
+ if (name === "cause" || isTypePredicateSubject(node, name)) continue;
+ context.report({
+ node: annotation.typeAnnotation,
+ messageId: "unknownParameter",
+ data: { parameter: name },
+ });
+ }
+ };
+
+ return {
+ ArrowFunctionExpression: checkParameters,
+ FunctionDeclaration: checkParameters,
+ FunctionExpression: checkParameters,
+ TSCallSignatureDeclaration: checkParameters,
+ TSConstructSignatureDeclaration: checkParameters,
+ TSConstructorType: checkParameters,
+ TSDeclareFunction: checkParameters,
+ TSEmptyBodyFunctionExpression: checkParameters,
+ TSFunctionType: checkParameters,
+ TSMethodSignature: checkParameters,
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-unknown-returns.ts b/tools/oxlint/anti-slop/rules/no-unknown-returns.ts
new file mode 100644
index 0000000..e1f43f8
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-unknown-returns.ts
@@ -0,0 +1,82 @@
+import { defineRule } from "@oxlint/plugins";
+
+import type { ESTree } from "@oxlint/plugins";
+
+import {
+ createTypeAliasEnvironment,
+ resolvedTypeMatches,
+ type TypeAliasEnvironment,
+} from "../shared/type-alias-resolution.ts";
+
+type FunctionWithReturnType =
+ | ESTree.ArrowFunctionExpression
+ | ESTree.Function
+ | ESTree.TSCallSignatureDeclaration
+ | ESTree.TSConstructSignatureDeclaration
+ | ESTree.TSConstructorType
+ | ESTree.TSFunctionType
+ | ESTree.TSMethodSignature;
+
+/** Ban function contracts that return unknown instead of a parsed domain type. */
+export const noUnknownReturnsRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow functions whose explicit return contract is unknown or Promise<unknown>.",
+ },
+ messages: {
+ unknownReturn:
+ "This function exposes `unknown` to its caller. Parse the value at its boundary and return a named domain type.",
+ },
+ },
+ createOnce(context) {
+ let environment: TypeAliasEnvironment | null = null;
+
+ const resolvesToUnknown = (type: ESTree.TSType): boolean =>
+ environment !== null &&
+ resolvedTypeMatches(type, environment, (resolved, matches) => {
+ if (resolved.type === "TSUnknownKeyword") return true;
+ if (resolved.type === "TSParenthesizedType") {
+ return matches(resolved.typeAnnotation);
+ }
+ if (resolved.type === "TSUnionType") return resolved.types.some(matches);
+ if (
+ resolved.type !== "TSTypeReference" ||
+ resolved.typeName.type !== "Identifier" ||
+ (resolved.typeName.name !== "Promise" &&
+ resolved.typeName.name !== "PromiseLike")
+ ) {
+ return false;
+ }
+ const value = resolved.typeArguments?.params[0];
+ return value !== undefined && matches(value);
+ });
+
+ const checkReturnType = (node: FunctionWithReturnType) => {
+ const annotation = node.returnType;
+ if (annotation === null || annotation === undefined) return;
+ if (!resolvesToUnknown(annotation.typeAnnotation)) return;
+ context.report({ node: annotation.typeAnnotation, messageId: "unknownReturn" });
+ };
+
+ return {
+ Program(node) {
+ environment = createTypeAliasEnvironment(
+ node,
+ context.sourceCode.visitorKeys,
+ );
+ },
+ ArrowFunctionExpression: checkReturnType,
+ FunctionDeclaration: checkReturnType,
+ FunctionExpression: checkReturnType,
+ TSCallSignatureDeclaration: checkReturnType,
+ TSConstructSignatureDeclaration: checkReturnType,
+ TSConstructorType: checkReturnType,
+ TSDeclareFunction: checkReturnType,
+ TSEmptyBodyFunctionExpression: checkReturnType,
+ TSFunctionType: checkReturnType,
+ TSMethodSignature: checkReturnType,
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-unknown-type-aliases.ts b/tools/oxlint/anti-slop/rules/no-unknown-type-aliases.ts
new file mode 100644
index 0000000..af5f08a
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-unknown-type-aliases.ts
@@ -0,0 +1,54 @@
+import { defineRule } from "@oxlint/plugins";
+
+import type { ESTree } from "@oxlint/plugins";
+
+import {
+ createTypeAliasEnvironment,
+ resolvedTypeMatches,
+ type TypeAliasEnvironment,
+} from "../shared/type-alias-resolution.ts";
+
+/** Ban named aliases that merely conceal TypeScript's unknown top type. */
+export const noUnknownTypeAliasesRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow type aliases whose resolved type is unknown; unknown must remain visible at an allowed boundary.",
+ },
+ messages: {
+ unknownAlias:
+ "Type alias `{{alias}}` hides `unknown`. Keep `unknown` explicit at the parsing boundary or on an allowed `cause` field; otherwise use the parsed owner type.",
+ },
+ },
+ createOnce(context) {
+ let environment: TypeAliasEnvironment | null = null;
+
+ const resolvesToUnknown = (type: ESTree.TSType): boolean =>
+ environment !== null &&
+ resolvedTypeMatches(type, environment, (resolved, matches) => {
+ if (resolved.type === "TSUnknownKeyword") return true;
+ if (resolved.type === "TSParenthesizedType") {
+ return matches(resolved.typeAnnotation);
+ }
+ return resolved.type === "TSUnionType" && resolved.types.some(matches);
+ });
+
+ return {
+ Program(node) {
+ environment = createTypeAliasEnvironment(
+ node,
+ context.sourceCode.visitorKeys,
+ );
+ },
+ TSTypeAliasDeclaration(node) {
+ if (!resolvesToUnknown(node.typeAnnotation)) return;
+ context.report({
+ node: node.id,
+ messageId: "unknownAlias",
+ data: { alias: node.id.name },
+ });
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-unsafe-dictionary-type.ts b/tools/oxlint/anti-slop/rules/no-unsafe-dictionary-type.ts
new file mode 100644
index 0000000..8cb615a
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-unsafe-dictionary-type.ts
@@ -0,0 +1,154 @@
+import { defineRule } from "@oxlint/plugins";
+
+import {
+ classifyUnsafeDictionary,
+ classifyUnsafeDictionaryValue,
+ createTypeEnvironment,
+ type TypeEnvironment,
+} from "../shared/dictionary-types.ts";
+import { visibleTypeAlias } from "../shared/type-alias-resolution.ts";
+
+import type { ESTree } from "@oxlint/plugins";
+
+const typeNodeKinds: ReadonlySet<string> = new Set([
+ "JSDocNonNullableType",
+ "JSDocNullableType",
+ "JSDocUnknownType",
+ "TSAnyKeyword",
+ "TSArrayType",
+ "TSBigIntKeyword",
+ "TSBooleanKeyword",
+ "TSConditionalType",
+ "TSConstructorType",
+ "TSFunctionType",
+ "TSImportType",
+ "TSIndexedAccessType",
+ "TSInferType",
+ "TSIntersectionType",
+ "TSIntrinsicKeyword",
+ "TSLiteralType",
+ "TSMappedType",
+ "TSNamedTupleMember",
+ "TSNeverKeyword",
+ "TSNullKeyword",
+ "TSNumberKeyword",
+ "TSObjectKeyword",
+ "TSParenthesizedType",
+ "TSStringKeyword",
+ "TSSymbolKeyword",
+ "TSTemplateLiteralType",
+ "TSThisType",
+ "TSTupleType",
+ "TSTypeLiteral",
+ "TSTypeOperator",
+ "TSTypePredicate",
+ "TSTypeQuery",
+ "TSTypeReference",
+ "TSUndefinedKeyword",
+ "TSUnionType",
+ "TSUnknownKeyword",
+ "TSVoidKeyword",
+]);
+
+function isTypeNode(node: ESTree.Node): node is ESTree.TSType {
+ return typeNodeKinds.has(node.type);
+}
+
+function typeReferenceName(type: ESTree.TSTypeReference): string | null {
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
+}
+
+function isInsideTypeAliasDeclaration(node: ESTree.Node): boolean {
+ let current: ESTree.Node | null = node.parent;
+ while (current !== null && current.type !== "Program") {
+ if (current.type === "TSTypeAliasDeclaration") return true;
+ current = current.parent;
+ }
+ return false;
+}
+
+function isPlainAliasConsumerUse(node: ESTree.TSType, environment: TypeEnvironment): boolean {
+ if (node.type !== "TSTypeReference" || node.typeArguments?.params.length) return false;
+ const name = typeReferenceName(node);
+ return (
+ name !== null &&
+ visibleTypeAlias(name, node, environment.typeAliases) !== null &&
+ !isInsideTypeAliasDeclaration(node)
+ );
+}
+
+function isInsideTypeParameterConstraint(node: ESTree.TSType): boolean {
+ let child: ESTree.Node = node;
+ let parent: ESTree.Node | null = child.parent;
+ while (parent !== null && parent.type !== "Program") {
+ if (parent.type === "TSTypeParameter" && parent.constraint === child) return true;
+ child = parent;
+ parent = child.parent;
+ }
+ return false;
+}
+
+function shouldReportType(node: ESTree.TSType, environment: TypeEnvironment): boolean {
+ if (isInsideTypeParameterConstraint(node)) return false;
+ if (isPlainAliasConsumerUse(node, environment)) return false;
+ if (classifyUnsafeDictionary(node, environment) === null) return false;
+ let current: ESTree.Node | null = node.parent;
+ while (current !== null && current.type !== "Program") {
+ if (isTypeNode(current) && classifyUnsafeDictionary(current, environment) !== null)
+ return false;
+ current = current.parent;
+ }
+ return true;
+}
+
+/** Disallow object-dictionary contracts whose direct value type is an unsafe escape hatch. */
+export const noUnsafeDictionaryTypeRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow object-dictionary contracts whose direct value type is unknown, any, object, {}, or a union/alias containing one of those escape hatches.",
+ },
+ messages: {
+ unsafeDictionary:
+ "This dictionary's {{value}} value type gives callers no concrete value contract. Use an owner/schema-derived value type; parse external payloads before insertion.",
+ },
+ },
+ createOnce(context) {
+ let environment: TypeEnvironment | null = null;
+ const report = (node: ESTree.Node, value: string) => {
+ context.report({ node, messageId: "unsafeDictionary", data: { value } });
+ };
+ const reportIfUnsafe = (node: ESTree.TSType) => {
+ if (environment === null || !shouldReportType(node, environment)) return;
+ const unsafe = classifyUnsafeDictionary(node, environment);
+ if (unsafe === null) return;
+ report(node, unsafe.unsafeValue);
+ };
+
+ return {
+ Program(node) {
+ environment = createTypeEnvironment(
+ node,
+ context.sourceCode.visitorKeys,
+ );
+ },
+ TSTypeReference: reportIfUnsafe,
+ TSTypeLiteral: reportIfUnsafe,
+ TSMappedType: reportIfUnsafe,
+ TSIndexSignature(node) {
+ if (
+ environment === null ||
+ node.typeAnnotation === null ||
+ node.parent.type === "TSTypeLiteral"
+ )
+ return;
+ const unsafe = classifyUnsafeDictionaryValue(
+ node.typeAnnotation.typeAnnotation,
+ environment,
+ );
+ if (unsafe !== null) report(node, unsafe.unsafeValue);
+ },
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/no-widen-then-assert.ts b/tools/oxlint/anti-slop/rules/no-widen-then-assert.ts
new file mode 100644
index 0000000..c5e07f7
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/no-widen-then-assert.ts
@@ -0,0 +1,366 @@
+import { defineRule } from "@oxlint/plugins";
+import type { ESTree, Variable } from "@oxlint/plugins";
+
+type BroadTypeKind = "top" | "object" | "record";
+
+type KnownValueEvidence = {
+ readonly type: ESTree.TSType | null;
+};
+
+const functionBoundaryTypes = new Set([
+ "ArrowFunctionExpression",
+ "FunctionDeclaration",
+ "FunctionExpression",
+ "TSDeclareFunction",
+ "TSEmptyBodyFunctionExpression",
+]);
+
+function unwrapExpressionParentheses(expression: ESTree.Expression): ESTree.Expression {
+ let current = expression;
+ while (current.type === "ParenthesizedExpression") current = current.expression;
+ return current;
+}
+
+function unwrapTypeParentheses(type: ESTree.TSType): ESTree.TSType {
+ let current = type;
+ while (current.type === "TSParenthesizedType") current = current.typeAnnotation;
+ return current;
+}
+
+function typeReferenceName(type: ESTree.TSTypeReference): string | null {
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
+}
+
+function isUnknownOrAnyType(type: ESTree.TSType): boolean {
+ const unwrapped = unwrapTypeParentheses(type);
+ return unwrapped.type === "TSUnknownKeyword" || unwrapped.type === "TSAnyKeyword";
+}
+
+function isBroadRecordKeyType(type: ESTree.TSType): boolean {
+ const unwrapped = unwrapTypeParentheses(type);
+ if (
+ unwrapped.type === "TSStringKeyword" ||
+ unwrapped.type === "TSNumberKeyword" ||
+ unwrapped.type === "TSSymbolKeyword"
+ ) {
+ return true;
+ }
+ if (unwrapped.type === "TSUnionType") return unwrapped.types.every(isBroadRecordKeyType);
+ return unwrapped.type === "TSTypeReference" && typeReferenceName(unwrapped) === "PropertyKey";
+}
+
+function isBroadRecordType(type: ESTree.TSType): boolean {
+ const unwrapped = unwrapTypeParentheses(type);
+
+ if (unwrapped.type === "TSTypeReference") {
+ if (typeReferenceName(unwrapped) === "Readonly") {
+ const [inner] = unwrapped.typeArguments?.params ?? [];
+ return inner !== undefined && isBroadRecordType(inner);
+ }
+
+ if (typeReferenceName(unwrapped) !== "Record") return false;
+ const parameters = unwrapped.typeArguments?.params ?? [];
+ return (
+ parameters.length === 2 &&
+ parameters[0] !== undefined &&
+ parameters[1] !== undefined &&
+ isBroadRecordKeyType(parameters[0]) &&
+ isUnknownOrAnyType(parameters[1])
+ );
+ }
+
+ if (unwrapped.type !== "TSTypeLiteral" || unwrapped.members.length !== 1) return false;
+ const [member] = unwrapped.members;
+ const [parameter] = member?.type === "TSIndexSignature" ? member.parameters : [];
+ return (
+ member?.type === "TSIndexSignature" &&
+ member.parameters.length === 1 &&
+ parameter !== undefined &&
+ isBroadRecordKeyType(parameter.typeAnnotation.typeAnnotation) &&
+ isUnknownOrAnyType(member.typeAnnotation.typeAnnotation)
+ );
+}
+
+function broadTypeKind(type: ESTree.TSType): BroadTypeKind | null {
+ const unwrapped = unwrapTypeParentheses(type);
+ if (unwrapped.type === "TSUnknownKeyword" || unwrapped.type === "TSAnyKeyword") return "top";
+ if (unwrapped.type === "TSObjectKeyword") return "object";
+ return isBroadRecordType(unwrapped) ? "record" : null;
+}
+
+function assertedExpression(
+ node: ESTree.TSAsExpression | ESTree.TSTypeAssertion,
+): ESTree.Expression {
+ return unwrapExpressionParentheses(node.expression);
+}
+
+function assertionFromExpression(
+ expression: ESTree.Expression,
+): ESTree.TSAsExpression | ESTree.TSTypeAssertion | null {
+ const unwrapped = unwrapExpressionParentheses(expression);
+ return unwrapped.type === "TSAsExpression" || unwrapped.type === "TSTypeAssertion"
+ ? unwrapped
+ : null;
+}
+
+function normalizedTypeText(sourceText: string, type: ESTree.TSType): string {
+ return sourceText.slice(type.start, type.end).replaceAll(/\s+/gu, "");
+}
+
+function typesHaveSameSyntax(
+ sourceText: string,
+ left: ESTree.TSType | null,
+ right: ESTree.TSType,
+): boolean {
+ return (
+ left !== null &&
+ normalizedTypeText(sourceText, unwrapTypeParentheses(left)) ===
+ normalizedTypeText(sourceText, unwrapTypeParentheses(right))
+ );
+}
+
+function isDefinitelyObjectType(type: ESTree.TSType): boolean {
+ const unwrapped = unwrapTypeParentheses(type);
+ switch (unwrapped.type) {
+ case "TSArrayType":
+ case "TSConstructorType":
+ case "TSFunctionType":
+ case "TSMappedType":
+ case "TSObjectKeyword":
+ case "TSTupleType":
+ return true;
+ case "TSTypeLiteral":
+ return unwrapped.members.length > 0;
+ case "TSIntersectionType":
+ return unwrapped.types.every(isDefinitelyObjectType);
+ case "TSTypeOperator":
+ return unwrapped.operator === "readonly" && isDefinitelyObjectType(unwrapped.typeAnnotation);
+ default:
+ return false;
+ }
+}
+
+function isDefinitelyNarrowerRecordType(type: ESTree.TSType): boolean {
+ const unwrapped = unwrapTypeParentheses(type);
+ if (unwrapped.type === "TSTypeLiteral") {
+ return unwrapped.members.some((member) => member.type !== "TSIndexSignature");
+ }
+
+ if (unwrapped.type !== "TSTypeReference") return false;
+ if (typeReferenceName(unwrapped) === "Readonly") {
+ const [inner] = unwrapped.typeArguments?.params ?? [];
+ return inner !== undefined && isDefinitelyNarrowerRecordType(inner);
+ }
+ if (typeReferenceName(unwrapped) !== "Record") return false;
+
+ const parameters = unwrapped.typeArguments?.params ?? [];
+ return (
+ parameters.length === 2 && parameters[1] !== undefined && !isUnknownOrAnyType(parameters[1])
+ );
+}
+
+function functionBoundary(node: ESTree.Node): ESTree.Node | null {
+ let current = node.parent;
+ while (current !== null && current.type !== "Program") {
+ if (functionBoundaryTypes.has(current.type)) return current;
+ current = current.parent;
+ }
+ return null;
+}
+
+function resolvedVariableForIdentifier(
+ scopes: readonly {
+ readonly references: readonly {
+ readonly identifier: ESTree.Node;
+ readonly resolved: Variable | null;
+ }[];
+ }[],
+ identifier: ESTree.IdentifierReference,
+): Variable | null {
+ for (const scope of scopes) {
+ const reference = scope.references.find(
+ (candidate) =>
+ candidate.identifier.start === identifier.start &&
+ candidate.identifier.end === identifier.end,
+ );
+ if (reference !== undefined) return reference.resolved;
+ }
+ return null;
+}
+
+function variableDeclarator(variable: Variable): ESTree.VariableDeclarator | null {
+ for (const definition of variable.defs) {
+ if (definition.type === "Variable" && definition.node.type === "VariableDeclarator") {
+ return definition.node;
+ }
+ }
+ return null;
+}
+
+function knownValueEvidence(
+ expression: ESTree.Expression,
+ scopes: Parameters<typeof resolvedVariableForIdentifier>[0],
+ boundary: ESTree.Node | null,
+ visitedVariables: ReadonlySet<Variable>,
+): KnownValueEvidence | null {
+ const unwrapped = unwrapExpressionParentheses(expression);
+
+ if (unwrapped.type === "TSAsExpression" || unwrapped.type === "TSTypeAssertion") {
+ if (broadTypeKind(unwrapped.typeAnnotation) !== null) return null;
+ return { type: unwrapped.typeAnnotation };
+ }
+
+ if (unwrapped.type === "Literal" || unwrapped.type === "TemplateLiteral") {
+ return { type: null };
+ }
+
+ if (
+ unwrapped.type === "ArrayExpression" ||
+ unwrapped.type === "ArrowFunctionExpression" ||
+ unwrapped.type === "ClassExpression" ||
+ unwrapped.type === "FunctionExpression" ||
+ unwrapped.type === "NewExpression" ||
+ unwrapped.type === "ObjectExpression"
+ ) {
+ return { type: null };
+ }
+
+ if (unwrapped.type !== "Identifier") return null;
+ const variable = resolvedVariableForIdentifier(scopes, unwrapped);
+ if (variable === null || visitedVariables.has(variable)) return null;
+
+ const annotatedIdentifier = variable.identifiers.find(
+ (identifier) => identifier.typeAnnotation !== null && identifier.typeAnnotation !== undefined,
+ );
+ const annotation = annotatedIdentifier?.typeAnnotation?.typeAnnotation;
+ if (annotation !== undefined && annotatedIdentifier !== undefined) {
+ if (functionBoundary(annotatedIdentifier) !== boundary || broadTypeKind(annotation) !== null) {
+ return null;
+ }
+ return { type: annotation };
+ }
+
+ const declarator = variableDeclarator(variable);
+ if (
+ declarator === null ||
+ declarator.parent.type !== "VariableDeclaration" ||
+ declarator.parent.kind !== "const" ||
+ declarator.init === null ||
+ variable.references.some((reference) => reference.isWrite() && !reference.init) ||
+ functionBoundary(declarator) !== boundary
+ ) {
+ return null;
+ }
+
+ return knownValueEvidence(
+ declarator.init,
+ scopes,
+ boundary,
+ new Set([...visitedVariables, variable]),
+ );
+}
+
+function widenedBinding(
+ variable: Variable,
+ scopes: Parameters<typeof resolvedVariableForIdentifier>[0],
+): {
+ readonly broadKind: BroadTypeKind;
+ readonly evidence: KnownValueEvidence;
+ readonly declaredAt: number;
+ readonly boundary: ESTree.Node | null;
+} | null {
+ const declarator = variableDeclarator(variable);
+ if (
+ declarator === null ||
+ declarator.parent.type !== "VariableDeclaration" ||
+ declarator.parent.kind !== "const" ||
+ declarator.id.type !== "Identifier" ||
+ declarator.init === null ||
+ variable.references.some((reference) => reference.isWrite() && !reference.init)
+ ) {
+ return null;
+ }
+
+ const boundary = functionBoundary(declarator);
+ const declaredType = declarator.id.typeAnnotation?.typeAnnotation;
+ const initializerAssertion = assertionFromExpression(declarator.init);
+ const initializerBroadKind =
+ initializerAssertion === null ? null : broadTypeKind(initializerAssertion.typeAnnotation);
+ const declaredBroadKind = declaredType === undefined ? null : broadTypeKind(declaredType);
+ const broadKind = declaredBroadKind ?? initializerBroadKind;
+ if (broadKind === null) return null;
+
+ const originalExpression =
+ initializerAssertion !== null && initializerBroadKind !== null
+ ? assertedExpression(initializerAssertion)
+ : declarator.init;
+ const evidence = knownValueEvidence(originalExpression, scopes, boundary, new Set([variable]));
+ return evidence === null ? null : { broadKind, evidence, declaredAt: declarator.end, boundary };
+}
+
+function assertionIsNarrower(
+ sourceText: string,
+ broadKind: BroadTypeKind,
+ evidence: KnownValueEvidence,
+ assertedType: ESTree.TSType,
+): boolean {
+ if (broadTypeKind(assertedType) !== null) return false;
+ if (broadKind === "top") return true;
+ if (typesHaveSameSyntax(sourceText, evidence.type, assertedType)) return true;
+ if (broadKind === "object") return isDefinitelyObjectType(assertedType);
+ return isDefinitelyNarrowerRecordType(assertedType);
+}
+
+/** Detect immutable local bindings that erase a known type and are later asserted back to a narrower type. */
+export const noWidenThenAssertRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow local const flows that explicitly widen a known value before asserting the widened binding to a narrower type.",
+ },
+ messages: {
+ widenThenAssert:
+ 'Binding "{{name}}" discards type evidence and later recreates it with an assertion. Keep the precise type from initialization through use; parse boundary input once.',
+ },
+ },
+ createOnce(context) {
+ let scopes: Parameters<typeof resolvedVariableForIdentifier>[0] = [];
+
+ const checkAssertion = (node: ESTree.TSAsExpression | ESTree.TSTypeAssertion) => {
+ const expression = assertedExpression(node);
+ if (expression.type !== "Identifier") return;
+
+ const variable = resolvedVariableForIdentifier(scopes, expression);
+ if (variable === null) return;
+ const widened = widenedBinding(variable, scopes);
+ if (
+ widened === null ||
+ node.start <= widened.declaredAt ||
+ functionBoundary(node) !== widened.boundary ||
+ !assertionIsNarrower(
+ context.sourceCode.text,
+ widened.broadKind,
+ widened.evidence,
+ node.typeAnnotation,
+ )
+ ) {
+ return;
+ }
+
+ context.report({
+ node,
+ messageId: "widenThenAssert",
+ data: { name: expression.name },
+ });
+ };
+
+ return {
+ Program() {
+ scopes = context.sourceCode.scopeManager.scopes;
+ },
+ TSAsExpression: checkAssertion,
+ TSTypeAssertion: checkAssertion,
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/rules/require-readable-spacing.ts b/tools/oxlint/anti-slop/rules/require-readable-spacing.ts
new file mode 100644
index 0000000..40735c7
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/require-readable-spacing.ts
@@ -0,0 +1,80 @@
+import type { CreateRule, ESTree, SourceCode } from "@oxlint/plugins";
+
+import createPaddingLineRule from "../vendor/eslint-stylistic/padding-line-between-statements.ts";
+
+import type { NodeTestObject } from "../vendor/eslint-stylistic/padding-line-between-statements.ts";
+
+/** A `const`/`let`/`var`/`using` declaration, optionally exported, written on one line. */
+function isSinglelineBinding(node: ESTree.Node): boolean {
+ const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : node;
+ return declaration?.type === "VariableDeclaration" && node.loc.start.line === node.loc.end.line;
+}
+
+/** Comments above a statement belong to it; a comment trailing the previous line does not. */
+function hasLeadingComment(node: ESTree.Node, sourceCode: SourceCode): boolean {
+ const previousLine = sourceCode.getTokenBefore(node)?.loc.end.line;
+ return sourceCode
+ .getCommentsBefore(node)
+ .some((comment) => comment.loc.start.line !== previousLine);
+}
+
+const singlelineBinding: NodeTestObject = {
+ test: (node) => isSinglelineBinding(node),
+};
+
+const undocumentedSinglelineBinding: NodeTestObject = {
+ test: (node, sourceCode) => isSinglelineBinding(node) && !hasLeadingComment(node, sourceCode),
+};
+
+const paddingRule = createPaddingLineRule(
+ [
+ { blankLine: "always", prev: "import", next: "*" },
+ { blankLine: "always", prev: "*", next: { selector: "Program > :not(ImportDeclaration)" } },
+ { blankLine: "always", prev: { selector: "Program > :not(ImportDeclaration)" }, next: "*" },
+ { blankLine: "always", prev: "*", next: ["function", "class", "interface", "type"] },
+ { blankLine: "always", prev: ["function", "class", "interface", "type"], next: "*" },
+ {
+ blankLine: "always",
+ prev: "*",
+ next: ["multiline-const", "multiline-let", "multiline-var", "multiline-using"],
+ },
+ {
+ blankLine: "always",
+ prev: ["multiline-const", "multiline-let", "multiline-var", "multiline-using"],
+ next: "*",
+ },
+ { blankLine: "always", prev: "*", next: ["return", "if", "switch", "try", "for", "while", "do"] },
+ { blankLine: "always", prev: "block-like", next: "*" },
+ { blankLine: "any", prev: "import", next: "import" },
+ // Consecutive single-line bindings form one group at any scope, including
+ // module scope. A binding with its own leading comment starts a new group.
+ { blankLine: "any", prev: "singleline-binding", next: "undocumented-singleline-binding" },
+ {
+ blankLine: "any",
+ prev: {
+ selector:
+ ':matches(TSDeclareFunction, ExportNamedDeclaration[declaration.type="TSDeclareFunction"])',
+ },
+ next: {
+ selector:
+ ':matches(TSDeclareFunction, FunctionDeclaration, ExportNamedDeclaration[declaration.type="TSDeclareFunction"], ExportNamedDeclaration[declaration.type="FunctionDeclaration"])',
+ },
+ },
+ ],
+ {
+ "singleline-binding": singlelineBinding,
+ "undocumented-singleline-binding": undocumentedSinglelineBinding,
+ },
+);
+
+/** Restore structural blank lines with whitespace-only fixes; keep single-line binding groups and overloads grouped. */
+export const requireReadableSpacingRule: CreateRule = {
+ ...paddingRule,
+ meta: {
+ ...paddingRule.meta,
+ docs: {
+ description: "Require readable spacing between declarations and logical statement groups.",
+ },
+ schema: [],
+ },
+};
diff --git a/tools/oxlint/anti-slop/rules/require-safety-comment-for-type-assertion.ts b/tools/oxlint/anti-slop/rules/require-safety-comment-for-type-assertion.ts
new file mode 100644
index 0000000..bfea1a2
--- /dev/null
+++ b/tools/oxlint/anti-slop/rules/require-safety-comment-for-type-assertion.ts
@@ -0,0 +1,131 @@
+import { defineRule } from "@oxlint/plugins";
+
+import type { ESTree, SourceCode } from "@oxlint/plugins";
+
+type TypeAssertion = ESTree.TSAsExpression | ESTree.TSTypeAssertion;
+
+const DEFAULT_SAFETY_MARKERS = ["SAFETY"] as const;
+
+const commentOwnerKinds = new Set([
+ "ExpressionStatement",
+ "PropertyDefinition",
+ "ReturnStatement",
+ "ThrowStatement",
+ "VariableDeclaration",
+]);
+
+function isConstAssertion(node: TypeAssertion): boolean {
+ return (
+ node.typeAnnotation.type === "TSTypeReference" &&
+ node.typeAnnotation.typeName.type === "Identifier" &&
+ node.typeAnnotation.typeName.name === "const"
+ );
+}
+
+function configuredSafetyMarkers(option: unknown): readonly string[] {
+ if (typeof option !== "object" || option === null || !("markers" in option)) {
+ return DEFAULT_SAFETY_MARKERS;
+ }
+ const configured = option.markers;
+ if (!Array.isArray(configured)) return DEFAULT_SAFETY_MARKERS;
+ const markers = configured.flatMap((marker) =>
+ typeof marker === "string" && marker.trim().length > 0 ? [marker.trim()] : [],
+ );
+ return markers.length > 0 ? markers : DEFAULT_SAFETY_MARKERS;
+}
+
+function markerPattern(markers: readonly string[]): RegExp {
+ const alternation = markers
+ .map((marker) => marker.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`))
+ .join("|");
+ return new RegExp(
+ String.raw`(?:^|[^\p{L}\p{N}_])(?:${alternation})\s*:\s*\S`,
+ "u",
+ );
+}
+
+function hasSafetyJustificationBefore(
+ sourceCode: SourceCode,
+ owner: ESTree.Node,
+ assertion: TypeAssertion,
+ pattern: RegExp,
+): boolean {
+ return sourceCode
+ .getCommentsBefore(owner)
+ .some(
+ (comment) => comment.end <= assertion.start && pattern.test(comment.value),
+ );
+}
+
+function hasSafetyComment(
+ sourceCode: SourceCode,
+ node: TypeAssertion,
+ pattern: RegExp,
+): boolean {
+ let current: ESTree.Node = node;
+ while (true) {
+ if (hasSafetyJustificationBefore(sourceCode, current, node, pattern)) return true;
+ if (commentOwnerKinds.has(current.type)) {
+ const exportDeclaration = current.parent;
+ return (
+ exportDeclaration.type === "ExportNamedDeclaration" &&
+ exportDeclaration.declaration === current &&
+ hasSafetyJustificationBefore(sourceCode, exportDeclaration, node, pattern)
+ );
+ }
+ if (current.parent.type === "Program") return false;
+ current = current.parent;
+ }
+}
+
+/** Require every non-const type assertion to state the invariant TypeScript cannot express. */
+export const requireSafetyCommentForTypeAssertionRule = defineRule({
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Require a nearby SAFETY comment for every TypeScript type assertion except const assertions.",
+ },
+ messages: {
+ missingSafetyComment:
+ "This type assertion has no `{{marker}}:` justification. State the checked invariant immediately before the assertion or its containing statement.",
+ },
+ schema: [
+ {
+ type: "object",
+ properties: {
+ markers: {
+ type: "array",
+ items: { type: "string", minLength: 1 },
+ minItems: 1,
+ uniqueItems: true,
+ },
+ },
+ additionalProperties: false,
+ },
+ ],
+ defaultOptions: [{ markers: ["SAFETY"] }],
+ },
+ createOnce(context) {
+ const patterns = new Map<string, RegExp>();
+
+ const checkAssertion = (node: TypeAssertion) => {
+ if (isConstAssertion(node)) return;
+ const markers = configuredSafetyMarkers(context.options?.[0]);
+ const patternKey = markers.join("\u0000");
+ const pattern = patterns.get(patternKey) ?? markerPattern(markers);
+ patterns.set(patternKey, pattern);
+ if (hasSafetyComment(context.sourceCode, node, pattern)) return;
+ context.report({
+ node,
+ messageId: "missingSafetyComment",
+ data: { marker: markers[0] ?? DEFAULT_SAFETY_MARKERS[0] },
+ });
+ };
+
+ return {
+ TSAsExpression: checkAssertion,
+ TSTypeAssertion: checkAssertion,
+ };
+ },
+});
diff --git a/tools/oxlint/anti-slop/shared/array-method.ts b/tools/oxlint/anti-slop/shared/array-method.ts
new file mode 100644
index 0000000..87eb9d8
--- /dev/null
+++ b/tools/oxlint/anti-slop/shared/array-method.ts
@@ -0,0 +1,94 @@
+import type { ESTree, Scope, SourceCode, Variable } from "@oxlint/plugins";
+
+/** Unwrap syntax-only wrappers when inspecting array methods and accumulator references. */
+export function unwrapArrayExpression(node: ESTree.Node): ESTree.Node {
+ while (
+ node.type === "ParenthesizedExpression" ||
+ node.type === "ChainExpression" ||
+ node.type === "TSAsExpression" ||
+ node.type === "TSTypeAssertion" ||
+ node.type === "TSNonNullExpression" ||
+ node.type === "TSSatisfiesExpression"
+ ) {
+ node = node.expression;
+ }
+ return node;
+}
+
+/** Resolve a local binding by scope, not by identifier spelling. */
+export function resolveArrayBinding(sourceCode: SourceCode, node: ESTree.Node): Variable | null {
+ node = unwrapArrayExpression(node);
+ if (node.type !== "Identifier") return null;
+ let scope: Scope | null = sourceCode.getScope(node);
+ while (scope !== null) {
+ const variable = scope.set.get(node.name);
+ if (variable !== undefined) return variable;
+ scope = scope.upper;
+ }
+ return null;
+}
+
+/** Read static method names, including computed string literals, without evaluating expressions. */
+export function arrayMethodTarget(
+ node: ESTree.Node,
+): { readonly name: string; readonly object: ESTree.Node } | null {
+ node = unwrapArrayExpression(node);
+ if (node.type !== "MemberExpression") return null;
+ const property = node.property;
+ if (!node.computed && property.type === "Identifier") {
+ return { name: property.name, object: node.object };
+ }
+ if (node.computed && property.type === "Literal" && typeof property.value === "string") {
+ return { name: property.value, object: node.object };
+ }
+ return null;
+}
+
+function isArrayAnnotation(type: ESTree.TSType): boolean {
+ if (type.type === "TSArrayType" || type.type === "TSTupleType") return true;
+ if (type.type === "TSParenthesizedType") return isArrayAnnotation(type.typeAnnotation);
+ if (type.type === "TSTypeOperator" && type.operator === "readonly") {
+ return isArrayAnnotation(type.typeAnnotation);
+ }
+ return (
+ type.type === "TSTypeReference" && type.typeName.type === "Identifier" &&
+ (type.typeName.name === "Array" || type.typeName.name === "ReadonlyArray")
+ );
+}
+
+/** Recognize local array evidence; unknown receivers and iterator pipelines are deliberately excluded. */
+export function isKnownArrayExpression(
+ sourceCode: SourceCode,
+ node: ESTree.Node,
+ visited = new Set<Variable>(),
+): boolean {
+ node = unwrapArrayExpression(node);
+ if (node.type === "ArrayExpression") return true;
+ if (node.type === "CallExpression") {
+ const method = arrayMethodTarget(node.callee);
+ return (
+ method !== null &&
+ ["map", "filter", "flatMap", "slice", "concat", "toSorted", "toReversed", "toSpliced"].includes(method.name) &&
+ isKnownArrayExpression(sourceCode, method.object, visited)
+ );
+ }
+ if (node.type !== "Identifier") return false;
+ const variable = resolveArrayBinding(sourceCode, node);
+ if (variable === null || visited.has(variable)) return false;
+ visited.add(variable);
+ if (variable.references.some(reference => reference.isWrite() && !reference.init)) return false;
+ for (const identifier of variable.identifiers) {
+ const annotation = identifier.typeAnnotation?.typeAnnotation;
+ if (annotation !== undefined) return isArrayAnnotation(annotation);
+ }
+ for (const definition of variable.defs) {
+ if (
+ definition.type === "Variable" && definition.node.type === "VariableDeclarator" &&
+ definition.node.id.type === "Identifier" && definition.node.init !== null &&
+ definition.node.parent.type === "VariableDeclaration" && definition.node.parent.kind === "const"
+ ) {
+ return isKnownArrayExpression(sourceCode, definition.node.init, visited);
+ }
+ }
+ return false;
+}
diff --git a/tools/oxlint/anti-slop/shared/dictionary-types.ts b/tools/oxlint/anti-slop/shared/dictionary-types.ts
new file mode 100644
index 0000000..8db73ff
--- /dev/null
+++ b/tools/oxlint/anti-slop/shared/dictionary-types.ts
@@ -0,0 +1,515 @@
+import type { ESTree } from "@oxlint/plugins";
+
+import {
+ createTypeAliasEnvironment,
+ hasVisibleTypeBinding,
+ visibleTypeAlias,
+ type TypeAliasEnvironment as LexicalTypeAliasEnvironment,
+} from "./type-alias-resolution.ts";
+
+const BUILT_INS = new Set([
+ "Record",
+ "Readonly",
+ "Partial",
+ "Required",
+ "Pick",
+ "Omit",
+ "PropertyKey",
+ "NonNullable",
+]);
+const TRANSPARENT_WRAPPERS = new Set(["Readonly", "Partial", "Required", "NonNullable"]);
+
+type TypeAliasEnvironment = ReadonlyMap<string, ESTree.TSType>;
+
+type ResolvedType = {
+ readonly type: ESTree.TSType;
+ readonly substitutions: TypeAliasEnvironment;
+};
+
+export type UnsafeDictionary = {
+ readonly kind: "unsafe-dictionary";
+ readonly unsafeValue: "any" | "empty-object" | "object" | "union" | "unknown";
+};
+
+export type WideningTargetKind =
+ | "anonymous object"
+ | "generic container"
+ | "object"
+ | "open dictionary"
+ | "unknown";
+
+export type WideningTarget = {
+ readonly kind: WideningTargetKind;
+};
+
+export type TypeEnvironment = {
+ readonly interfaces: ReadonlyMap<string, readonly ESTree.TSInterfaceDeclaration[]>;
+ readonly typeAliases: LexicalTypeAliasEnvironment;
+};
+
+function declaredStatement(statement: ESTree.Statement): ESTree.Node | null {
+ return statement.type === "ExportNamedDeclaration" ||
+ statement.type === "ExportDefaultDeclaration"
+ ? (statement.declaration ?? null)
+ : statement;
+}
+
+export function createTypeEnvironment(
+ program: ESTree.Program,
+ visitorKeys: Readonly<Record<string, readonly string[]>>,
+): TypeEnvironment {
+ const interfaces = new Map<string, ESTree.TSInterfaceDeclaration[]>();
+
+ for (const statement of program.body) {
+ const declaration = declaredStatement(statement);
+ if (declaration?.type !== "TSInterfaceDeclaration") continue;
+ const declarations = interfaces.get(declaration.id.name) ?? [];
+ declarations.push(declaration);
+ interfaces.set(declaration.id.name, declarations);
+ }
+
+ return {
+ interfaces,
+ typeAliases: createTypeAliasEnvironment(program, visitorKeys),
+ };
+}
+
+function typeReferenceName(type: ESTree.TSTypeReference): string | null {
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
+}
+
+function isBuiltIn(
+ name: string,
+ use: ESTree.Node,
+ environment: TypeEnvironment,
+): boolean {
+ return (
+ BUILT_INS.has(name) &&
+ !hasVisibleTypeBinding(name, use, environment.typeAliases)
+ );
+}
+
+function isUnappliedReferenceTo(type: ESTree.TSType, name: string): boolean {
+ const unwrapped = unwrapTransparentType(type);
+ return (
+ unwrapped.type === "TSTypeReference" &&
+ typeReferenceName(unwrapped) === name &&
+ (unwrapped.typeArguments === null ||
+ unwrapped.typeArguments === undefined ||
+ unwrapped.typeArguments.params.length === 0)
+ );
+}
+
+function unwrapTransparentType(type: ESTree.TSType): ESTree.TSType {
+ let current = type;
+ while (
+ current.type === "TSParenthesizedType" ||
+ (current.type === "TSTypeOperator" && current.operator === "readonly")
+ ) {
+ current = current.typeAnnotation;
+ }
+ return current;
+}
+
+function isNeverType(type: ESTree.TSType): boolean {
+ return unwrapTransparentType(type).type === "TSNeverKeyword";
+}
+
+function isEffectivelyEmptyMember(member: ESTree.TSSignature): boolean {
+ return (
+ member.type === "TSPropertySignature" &&
+ member.optional === true &&
+ member.typeAnnotation !== null &&
+ member.typeAnnotation !== undefined &&
+ isNeverType(member.typeAnnotation.typeAnnotation)
+ );
+}
+
+function isEffectivelyEmptyTypeLiteral(type: ESTree.TSTypeLiteral): boolean {
+ return type.members.length === 0 || type.members.every(isEffectivelyEmptyMember);
+}
+
+function isEffectivelyEmptyInterface(
+ declarations: readonly ESTree.TSInterfaceDeclaration[],
+): boolean {
+ if (declarations.length !== 1) return false;
+ const [type] = declarations;
+ return (
+ type !== undefined &&
+ type.extends.length === 0 &&
+ (type.body.body.length === 0 || type.body.body.every(isEffectivelyEmptyMember))
+ );
+}
+
+function resolvedSubstitutionArgument(
+ type: ESTree.TSType,
+ base: TypeAliasEnvironment,
+ resolving: ReadonlySet<string> = new Set(),
+): ESTree.TSType {
+ const unwrapped = unwrapTransparentType(type);
+ if (unwrapped.type !== "TSTypeReference") return type;
+ const name = typeReferenceName(unwrapped);
+ if (name === null || resolving.has(name)) return type;
+ const substitution = base.get(name);
+ if (substitution === undefined) return type;
+ const nextResolving = new Set(resolving);
+ nextResolving.add(name);
+ return resolvedSubstitutionArgument(substitution, base, nextResolving);
+}
+
+function aliasSubstitution(
+ alias: ESTree.TSTypeAliasDeclaration,
+ type: ESTree.TSTypeReference,
+ base: TypeAliasEnvironment,
+): TypeAliasEnvironment | null {
+ const parameters = alias.typeParameters?.params ?? [];
+ const arguments_ = type.typeArguments?.params ?? [];
+ const next = new Map(base);
+ for (const [index, parameter] of parameters.entries()) {
+ const argument = arguments_[index] ?? parameter.default;
+ if (argument === null || argument === undefined) return null;
+ next.set(parameter.name.name, resolvedSubstitutionArgument(argument, next));
+ }
+ return next;
+}
+
+function unsafeDirectValue(
+ type: ESTree.TSType,
+ environment: TypeEnvironment,
+ substitutions: TypeAliasEnvironment,
+ resolvingAliases: ReadonlySet<string>,
+): UnsafeDictionary["unsafeValue"] | null {
+ const unwrapped = unwrapTransparentType(type);
+ if (unwrapped.type === "TSUnknownKeyword") return "unknown";
+ if (unwrapped.type === "TSAnyKeyword") return "any";
+ if (unwrapped.type === "TSObjectKeyword") return "object";
+ if (unwrapped.type === "TSTypeLiteral" && isEffectivelyEmptyTypeLiteral(unwrapped))
+ return "empty-object";
+ if (unwrapped.type === "TSUnionType") {
+ return unwrapped.types.some(
+ (member) => unsafeDirectValue(member, environment, substitutions, resolvingAliases) !== null,
+ )
+ ? "union"
+ : null;
+ }
+ if (unwrapped.type === "TSIntersectionType") {
+ const unsafeMembers = unwrapped.types.map((member) =>
+ unsafeDirectValue(member, environment, substitutions, resolvingAliases),
+ );
+ if (unsafeMembers.includes("any")) return "any";
+ return unsafeMembers.length > 0 && unsafeMembers.every((member) => member !== null)
+ ? unsafeMembers[0]
+ : null;
+ }
+ if (unwrapped.type !== "TSTypeReference") return null;
+ const name = typeReferenceName(unwrapped);
+ if (name === null) return null;
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
+ const wrapped = unwrapped.typeArguments?.params[0];
+ return wrapped === undefined
+ ? null
+ : unsafeDirectValue(wrapped, environment, substitutions, resolvingAliases);
+ }
+ const substitution = substitutions.get(name);
+ if (substitution !== undefined) {
+ return isUnappliedReferenceTo(substitution, name)
+ ? null
+ : unsafeDirectValue(substitution, environment, substitutions, resolvingAliases);
+ }
+ const interfaceDeclarations = environment.interfaces.get(name);
+ if (interfaceDeclarations !== undefined) {
+ return isEffectivelyEmptyInterface(interfaceDeclarations) ? "empty-object" : null;
+ }
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
+ if (alias === null || resolvingAliases.has(name)) return null;
+ const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions);
+ if (nextSubstitutions === null) return null;
+ const nextResolving = new Set(resolvingAliases);
+ nextResolving.add(name);
+ return unsafeDirectValue(alias.typeAnnotation, environment, nextSubstitutions, nextResolving);
+}
+
+function dictionaryValueTypes(
+ type: ESTree.TSType,
+ environment: TypeEnvironment,
+ substitutions: TypeAliasEnvironment,
+ resolvingAliases: ReadonlySet<string>,
+): readonly ResolvedType[] {
+ const unwrapped = unwrapTransparentType(type);
+
+ if (unwrapped.type === "TSTypeLiteral") {
+ return unwrapped.members.flatMap((member): readonly ResolvedType[] =>
+ member.type === "TSIndexSignature" && member.typeAnnotation !== null
+ ? [{ type: member.typeAnnotation.typeAnnotation, substitutions }]
+ : [],
+ );
+ }
+
+ if (unwrapped.type === "TSMappedType") {
+ return unwrapped.typeAnnotation === null
+ ? []
+ : [{ type: unwrapped.typeAnnotation, substitutions }];
+ }
+
+ if (unwrapped.type !== "TSTypeReference") return [];
+ const name = typeReferenceName(unwrapped);
+ if (name === null) return [];
+
+ const substitution = substitutions.get(name);
+ if (substitution !== undefined) {
+ return isUnappliedReferenceTo(substitution, name)
+ ? []
+ : dictionaryValueTypes(substitution, environment, substitutions, resolvingAliases);
+ }
+
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
+ const wrapped = unwrapped.typeArguments?.params[0];
+ return wrapped === undefined
+ ? []
+ : dictionaryValueTypes(wrapped, environment, substitutions, resolvingAliases);
+ }
+
+ if (name === "Record" && isBuiltIn(name, unwrapped, environment)) {
+ const value = unwrapped.typeArguments?.params[1] ?? null;
+ return value === null ? [] : [{ type: value, substitutions }];
+ }
+
+ if (
+ (name === "Pick" || name === "Omit") &&
+ isBuiltIn(name, unwrapped, environment)
+ ) {
+ const source = unwrapped.typeArguments?.params[0];
+ return source === undefined
+ ? []
+ : dictionaryValueTypes(source, environment, substitutions, resolvingAliases);
+ }
+
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
+ if (alias === null || resolvingAliases.has(name)) return [];
+ const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions);
+ if (nextSubstitutions === null) return [];
+ const nextResolving = new Set(resolvingAliases);
+ nextResolving.add(name);
+ return dictionaryValueTypes(alias.typeAnnotation, environment, nextSubstitutions, nextResolving);
+}
+
+export function classifyUnsafeDictionaryValue(
+ valueType: ESTree.TSType,
+ environment: TypeEnvironment,
+): UnsafeDictionary | null {
+ const unsafeValue = unsafeDirectValue(valueType, environment, new Map(), new Set());
+ return unsafeValue === null ? null : { kind: "unsafe-dictionary", unsafeValue };
+}
+
+export function classifyUnsafeDictionary(
+ type: ESTree.TSType,
+ environment: TypeEnvironment,
+): UnsafeDictionary | null {
+ for (const valueType of dictionaryValueTypes(type, environment, new Map(), new Set())) {
+ const unsafeValue = unsafeDirectValue(
+ valueType.type,
+ environment,
+ valueType.substitutions,
+ new Set(),
+ );
+ if (unsafeValue !== null) return { kind: "unsafe-dictionary", unsafeValue };
+ }
+ return null;
+}
+
+export function classifyWideningTarget(
+ type: ESTree.TSType,
+ environment: TypeEnvironment,
+): WideningTarget | null {
+ const unwrapped = unwrapTransparentType(type);
+ if (unwrapped.type === "TSUnknownKeyword") return { kind: "unknown" };
+ if (unwrapped.type === "TSObjectKeyword") return { kind: "object" };
+ if (unwrapped.type === "TSTypeLiteral") {
+ return unwrapped.members.some((member) => member.type === "TSIndexSignature")
+ ? { kind: "open dictionary" }
+ : unwrapped.members.length > 0
+ ? { kind: "anonymous object" }
+ : null;
+ }
+ if (unwrapped.type === "TSMappedType") return { kind: "open dictionary" };
+ if (unwrapped.type !== "TSTypeReference") return null;
+ const name = typeReferenceName(unwrapped);
+ if (name === null) return null;
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
+ const wrapped = unwrapped.typeArguments?.params[0];
+ return wrapped === undefined ? null : classifyWideningTarget(wrapped, environment);
+ }
+ if (name === "Record" && isBuiltIn(name, unwrapped, environment)) {
+ return hasBroadRecordKey(unwrapped, environment, new Map())
+ ? { kind: "open dictionary" }
+ : null;
+ }
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
+ if (alias === null) return null;
+ if ((alias.typeParameters?.params.length ?? 0) > 0) {
+ const substitutions = aliasSubstitution(alias, unwrapped, new Map());
+ const resolved =
+ substitutions === null
+ ? null
+ : classifyAliasBroadTarget(
+ alias.typeAnnotation,
+ environment,
+ substitutions,
+ new Set([name]),
+ );
+ return resolved?.kind === "open dictionary" ? { kind: "generic container" } : null;
+ }
+ const substitutions = aliasSubstitution(alias, unwrapped, new Map());
+ if (substitutions === null) return null;
+ const resolved = classifyAliasBroadTarget(
+ alias.typeAnnotation,
+ environment,
+ substitutions,
+ new Set([name]),
+ );
+ return resolved;
+}
+
+function hasBroadRecordKey(
+ type: ESTree.TSTypeReference,
+ environment: TypeEnvironment,
+ substitutions: TypeAliasEnvironment,
+): boolean {
+ const key = type.typeArguments?.params[0];
+ return key === undefined || isBroadMappedKey(key, environment, substitutions);
+}
+
+function isBroadMappedKey(
+ type: ESTree.TSType,
+ environment: TypeEnvironment,
+ substitutions: TypeAliasEnvironment,
+ visitedAliases: ReadonlySet<string> = new Set(),
+): boolean {
+ const unwrapped = unwrapTransparentType(type);
+ if (
+ unwrapped.type === "TSStringKeyword" ||
+ unwrapped.type === "TSNumberKeyword" ||
+ unwrapped.type === "TSSymbolKeyword"
+ ) {
+ return true;
+ }
+ if (unwrapped.type === "TSUnionType") {
+ return unwrapped.types.some((member) =>
+ isBroadMappedKey(member, environment, substitutions, visitedAliases),
+ );
+ }
+ if (unwrapped.type !== "TSTypeReference") return false;
+ const name = typeReferenceName(unwrapped);
+ if (name === null) return false;
+ const substitution = substitutions.get(name);
+ if (substitution !== undefined && !isUnappliedReferenceTo(substitution, name)) {
+ return isBroadMappedKey(substitution, environment, substitutions, visitedAliases);
+ }
+ if (name === "PropertyKey" && isBuiltIn(name, unwrapped, environment)) return true;
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
+ if (
+ alias === null ||
+ (alias.typeParameters?.params.length ?? 0) > 0 ||
+ visitedAliases.has(name)
+ ) {
+ return false;
+ }
+ const nextVisited = new Set(visitedAliases);
+ nextVisited.add(name);
+ return isBroadMappedKey(alias.typeAnnotation, environment, substitutions, nextVisited);
+}
+
+function classifyAliasBroadTarget(
+ type: ESTree.TSType,
+ environment: TypeEnvironment,
+ substitutions: TypeAliasEnvironment,
+ resolvingAliases: ReadonlySet<string>,
+): WideningTarget | null {
+ const unwrapped = unwrapTransparentType(type);
+ if (unwrapped.type === "TSUnknownKeyword") return { kind: "unknown" };
+ if (unwrapped.type === "TSObjectKeyword") return { kind: "object" };
+ if (unwrapped.type === "TSTypeLiteral") {
+ return unwrapped.members.some((member) => member.type === "TSIndexSignature")
+ ? { kind: "open dictionary" }
+ : null;
+ }
+ if (unwrapped.type === "TSMappedType") {
+ return isBroadMappedKey(unwrapped.constraint, environment, substitutions)
+ ? { kind: "open dictionary" }
+ : null;
+ }
+ if (unwrapped.type !== "TSTypeReference") return null;
+ const name = typeReferenceName(unwrapped);
+ if (name === null) return null;
+ const substitution = substitutions.get(name);
+ if (substitution !== undefined) {
+ return isUnappliedReferenceTo(substitution, name)
+ ? null
+ : classifyAliasBroadTarget(
+ substitution,
+ environment,
+ substitutions,
+ resolvingAliases,
+ );
+ }
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
+ const wrapped = unwrapped.typeArguments?.params[0];
+ return wrapped === undefined
+ ? null
+ : classifyAliasBroadTarget(wrapped, environment, substitutions, resolvingAliases);
+ }
+ if (name === "Record" && isBuiltIn(name, unwrapped, environment)) {
+ return hasBroadRecordKey(unwrapped, environment, substitutions)
+ ? { kind: "open dictionary" }
+ : null;
+ }
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
+ if (alias === null || resolvingAliases.has(name)) return null;
+ const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions);
+ if (nextSubstitutions === null) return null;
+ const nextResolving = new Set(resolvingAliases);
+ nextResolving.add(name);
+ return classifyAliasBroadTarget(
+ alias.typeAnnotation,
+ environment,
+ nextSubstitutions,
+ nextResolving,
+ );
+}
+
+export function isPopulatedObjectExpression(expression: ESTree.Expression): boolean {
+ let current = expression;
+ while (
+ current.type === "ParenthesizedExpression" ||
+ current.type === "TSAsExpression" ||
+ current.type === "TSTypeAssertion" ||
+ current.type === "TSNonNullExpression"
+ ) {
+ current = current.expression;
+ }
+ return current.type === "ObjectExpression" && current.properties.length > 0;
+}
+
+export function isKnownEvidenceExpression(expression: ESTree.Expression): boolean {
+ let current = expression;
+ while (
+ current.type === "ParenthesizedExpression" ||
+ current.type === "TSAsExpression" ||
+ current.type === "TSTypeAssertion" ||
+ current.type === "TSNonNullExpression" ||
+ current.type === "TSSatisfiesExpression"
+ ) {
+ current = current.expression;
+ }
+ if (current.type === "ObjectExpression") return true;
+ return (
+ current.type === "ArrayExpression" ||
+ current.type === "ArrowFunctionExpression" ||
+ current.type === "ClassExpression" ||
+ current.type === "FunctionExpression" ||
+ current.type === "NewExpression" ||
+ current.type === "Literal" ||
+ current.type === "TemplateLiteral" ||
+ current.type === "UnaryExpression"
+ );
+}
diff --git a/tools/oxlint/anti-slop/shared/function-parameters.ts b/tools/oxlint/anti-slop/shared/function-parameters.ts
new file mode 100644
index 0000000..80de91d
--- /dev/null
+++ b/tools/oxlint/anti-slop/shared/function-parameters.ts
@@ -0,0 +1,49 @@
+import type { ESTree, SourceCode } from "@oxlint/plugins";
+
+export type FunctionParameter = ESTree.ParamPattern;
+
+/** Return whether a type is or contains TypeScript's absorbing unknown top type. */
+export function containsUnknownType(type: ESTree.TSType): boolean {
+ if (type.type === "TSUnknownKeyword") return true;
+ if (type.type === "TSParenthesizedType") return containsUnknownType(type.typeAnnotation);
+ return type.type === "TSUnionType" && type.types.some(containsUnknownType);
+}
+
+/** Return the TypeScript annotation attached to a function parameter or its wrapped binding. */
+export function functionParameterTypeAnnotation(
+ parameter: FunctionParameter,
+): ESTree.TSTypeAnnotation | null | undefined {
+ if (parameter.type === "TSParameterProperty") {
+ return functionParameterTypeAnnotation(parameter.parameter);
+ }
+ if (parameter.type === "RestElement") {
+ return parameter.typeAnnotation ?? functionParameterTypeAnnotation(parameter.argument);
+ }
+ if (parameter.type === "AssignmentPattern") {
+ return parameter.typeAnnotation ?? functionParameterTypeAnnotation(parameter.left);
+ }
+ return parameter.typeAnnotation;
+}
+
+/** Return only a function parameter's local binding, excluding its annotation and default value. */
+export function functionParameterBindingName(
+ parameter: FunctionParameter,
+ sourceCode: SourceCode,
+): string {
+ if (parameter.type === "TSParameterProperty") {
+ return functionParameterBindingName(parameter.parameter, sourceCode);
+ }
+ if (parameter.type === "AssignmentPattern") {
+ return functionParameterBindingName(parameter.left, sourceCode);
+ }
+ if (parameter.type === "RestElement") {
+ return functionParameterBindingName(parameter.argument, sourceCode);
+ }
+ if (parameter.type === "Identifier") return parameter.name;
+
+ const sourceText = sourceCode.getText(parameter);
+ const annotationStart = parameter.typeAnnotation?.start;
+ return annotationStart === undefined
+ ? sourceText
+ : sourceText.slice(0, annotationStart - parameter.start).trimEnd();
+}
diff --git a/tools/oxlint/anti-slop/shared/lexical-type-parameters.ts b/tools/oxlint/anti-slop/shared/lexical-type-parameters.ts
new file mode 100644
index 0000000..7cdb18c
--- /dev/null
+++ b/tools/oxlint/anti-slop/shared/lexical-type-parameters.ts
@@ -0,0 +1,61 @@
+import type { ESTree } from "@oxlint/plugins";
+
+type VisitorKeys = Readonly<Record<string, readonly string[]>>;
+
+function isNode(value: unknown): value is ESTree.Node {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "type" in value &&
+ typeof value.type === "string"
+ );
+}
+
+function collectInferTypeParameterNames(
+ node: ESTree.Node,
+ visitorKeys: VisitorKeys,
+ names: Set<string>,
+): void {
+ if (node.type === "TSInferType") names.add(node.typeParameter.name.name);
+ const record = node as unknown as Readonly<Record<string, unknown>>;
+ for (const key of visitorKeys[node.type] ?? []) {
+ const value = record[key];
+ if (isNode(value)) {
+ collectInferTypeParameterNames(value, visitorKeys, names);
+ continue;
+ }
+ if (!Array.isArray(value)) continue;
+ for (const child of value) {
+ if (isNode(child)) collectInferTypeParameterNames(child, visitorKeys, names);
+ }
+ }
+}
+
+/** Collect type binders that are in scope at a node and can shadow module aliases. */
+export function lexicalTypeParameterNames(
+ node: ESTree.Node,
+ visitorKeys: VisitorKeys,
+): ReadonlySet<string> {
+ const names = new Set<string>();
+ let descendant: ESTree.Node = node;
+ let current: ESTree.Node | null = node;
+ while (current !== null && current.type !== "Program") {
+ if ("typeParameters" in current) {
+ for (const parameter of current.typeParameters?.params ?? []) {
+ names.add(parameter.name.name);
+ }
+ }
+ if (
+ current.type === "TSMappedType" &&
+ (descendant === current.nameType || descendant === current.typeAnnotation)
+ ) {
+ names.add(current.key.name);
+ }
+ if (current.type === "TSConditionalType" && descendant === current.trueType) {
+ collectInferTypeParameterNames(current.extendsType, visitorKeys, names);
+ }
+ descendant = current;
+ current = current.parent;
+ }
+ return names;
+}
diff --git a/tools/oxlint/anti-slop/shared/reflect-method.ts b/tools/oxlint/anti-slop/shared/reflect-method.ts
new file mode 100644
index 0000000..43a7cfc
--- /dev/null
+++ b/tools/oxlint/anti-slop/shared/reflect-method.ts
@@ -0,0 +1,24 @@
+import { resolveVariable } from "./scope.ts";
+
+import type { ESTree, SourceCode } from "@oxlint/plugins";
+
+function isGlobalReflect(sourceCode: SourceCode, expression: ESTree.Expression): boolean {
+ if (expression.type !== "Identifier" || expression.name !== "Reflect") return false;
+ if (sourceCode.isGlobalReference(expression)) return true;
+ const variable = resolveVariable(sourceCode, expression);
+ return variable === null || variable.defs.length === 0;
+}
+
+/** Reports whether a call target names one method on the global Reflect object. */
+export function isGlobalReflectMethodCall(
+ sourceCode: SourceCode,
+ callee: ESTree.Expression,
+ methodName: string,
+): boolean {
+ if (!("property" in callee) || !("object" in callee) || !("computed" in callee)) return false;
+ if (!isGlobalReflect(sourceCode, callee.object)) return false;
+ const property = callee.property;
+ return callee.computed
+ ? property.type === "Literal" && property.value === methodName
+ : property.type === "Identifier" && property.name === methodName;
+}
diff --git a/tools/oxlint/anti-slop/shared/scope.ts b/tools/oxlint/anti-slop/shared/scope.ts
new file mode 100644
index 0000000..602414a
--- /dev/null
+++ b/tools/oxlint/anti-slop/shared/scope.ts
@@ -0,0 +1,15 @@
+import type { ESTree, Scope, SourceCode, Variable } from "@oxlint/plugins";
+
+/** Resolve an identifier to its binding by walking lexical scopes upward. */
+export function resolveVariable(
+ sourceCode: SourceCode,
+ identifier: ESTree.IdentifierReference,
+): Variable | null {
+ let scope: Scope | null = sourceCode.getScope(identifier);
+ while (scope !== null) {
+ const variable = scope.set.get(identifier.name);
+ if (variable !== undefined) return variable;
+ scope = scope.upper;
+ }
+ return null;
+}
diff --git a/tools/oxlint/anti-slop/shared/type-alias-resolution.ts b/tools/oxlint/anti-slop/shared/type-alias-resolution.ts
new file mode 100644
index 0000000..4744222
--- /dev/null
+++ b/tools/oxlint/anti-slop/shared/type-alias-resolution.ts
@@ -0,0 +1,250 @@
+import type { ESTree } from "@oxlint/plugins";
+
+import { lexicalTypeParameterNames } from "./lexical-type-parameters.ts";
+
+type VisitorKeys = Readonly<Record<string, readonly string[]>>;
+type TypeScope = ESTree.Node;
+
+type TypeBinding = {
+ readonly alias: ESTree.TSTypeAliasDeclaration | null;
+ readonly name: string;
+ readonly scope: TypeScope;
+};
+
+type Substitution = {
+ readonly substitutions: Substitutions;
+ readonly type: ESTree.TSType;
+};
+
+type Substitutions = ReadonlyMap<string, Substitution>;
+
+export type TypeAliasEnvironment = {
+ readonly aliases: readonly ESTree.TSTypeAliasDeclaration[];
+ readonly bindingsByName: ReadonlyMap<string, readonly TypeBinding[]>;
+ readonly visitorKeys: VisitorKeys;
+};
+
+export type ResolvedTypeMatcher = (
+ type: ESTree.TSType,
+ matches: (child: ESTree.TSType) => boolean,
+) => boolean;
+
+const environmentsByProgram = new WeakMap<ESTree.Program, TypeAliasEnvironment>();
+
+function isNode(value: unknown): value is ESTree.Node {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "type" in value &&
+ typeof value.type === "string"
+ );
+}
+
+function enclosingTypeScope(node: ESTree.Node): TypeScope {
+ let current: ESTree.Node | null = node.parent;
+ while (current !== null) {
+ if (
+ current.type === "Program" ||
+ current.type === "BlockStatement" ||
+ current.type === "TSModuleBlock" ||
+ current.type === "StaticBlock" ||
+ current.type === "SwitchStatement"
+ ) {
+ return current;
+ }
+ current = current.parent;
+ }
+ return node;
+}
+
+function declaredTypeBinding(node: ESTree.Node): {
+ readonly alias: ESTree.TSTypeAliasDeclaration | null;
+ readonly name: string;
+} | null {
+ if (node.type === "TSTypeAliasDeclaration") {
+ return { alias: node, name: node.id.name };
+ }
+ if (
+ node.type === "TSInterfaceDeclaration" ||
+ node.type === "TSEnumDeclaration" ||
+ node.type === "ClassDeclaration" ||
+ node.type === "ClassExpression"
+ ) {
+ return node.id === null ? null : { alias: null, name: node.id.name };
+ }
+ if (
+ node.type === "ImportSpecifier" ||
+ node.type === "ImportDefaultSpecifier" ||
+ node.type === "ImportNamespaceSpecifier"
+ ) {
+ return { alias: null, name: node.local.name };
+ }
+ return null;
+}
+
+function collectTypeBindings(
+ node: ESTree.Node,
+ visitorKeys: VisitorKeys,
+ bindingsByName: Map<string, TypeBinding[]>,
+ aliases: ESTree.TSTypeAliasDeclaration[],
+): void {
+ const declared = declaredTypeBinding(node);
+ if (declared !== null) {
+ const bindings = bindingsByName.get(declared.name) ?? [];
+ bindings.push({ ...declared, scope: enclosingTypeScope(node) });
+ bindingsByName.set(declared.name, bindings);
+ if (declared.alias !== null) aliases.push(declared.alias);
+ }
+
+ // SAFETY: Oxlint's visitor keys identify only ESTree child-node properties.
+ const fields = node as unknown as Readonly<Record<string, unknown>>;
+ for (const key of visitorKeys[node.type] ?? []) {
+ const value = fields[key];
+ if (isNode(value)) {
+ collectTypeBindings(value, visitorKeys, bindingsByName, aliases);
+ continue;
+ }
+ if (!Array.isArray(value)) continue;
+ for (const child of value) {
+ if (isNode(child)) {
+ collectTypeBindings(child, visitorKeys, bindingsByName, aliases);
+ }
+ }
+ }
+}
+
+/** Collect every lexical type alias and competing type binding in a program. */
+export function createTypeAliasEnvironment(
+ program: ESTree.Program,
+ visitorKeys: VisitorKeys,
+): TypeAliasEnvironment {
+ const cached = environmentsByProgram.get(program);
+ if (cached !== undefined) return cached;
+ const bindingsByName = new Map<string, TypeBinding[]>();
+ const aliases: ESTree.TSTypeAliasDeclaration[] = [];
+ collectTypeBindings(program, visitorKeys, bindingsByName, aliases);
+ const environment = { aliases, bindingsByName, visitorKeys };
+ environmentsByProgram.set(program, environment);
+ return environment;
+}
+
+function ancestorDistance(ancestor: ESTree.Node, node: ESTree.Node): number | null {
+ let current: ESTree.Node | null = node;
+ let distance = 0;
+ while (current !== null) {
+ if (current === ancestor) return distance;
+ current = current.parent;
+ distance += 1;
+ }
+ return null;
+}
+
+function nearestTypeBindings(
+ name: string,
+ use: ESTree.Node,
+ environment: TypeAliasEnvironment,
+): readonly TypeBinding[] {
+ const candidates = environment.bindingsByName.get(name) ?? [];
+ let nearestDistance = Number.POSITIVE_INFINITY;
+ let nearest: TypeBinding[] = [];
+ for (const candidate of candidates) {
+ const distance = ancestorDistance(candidate.scope, use);
+ if (distance === null || distance > nearestDistance) continue;
+ if (distance === nearestDistance) {
+ nearest.push(candidate);
+ continue;
+ }
+ nearestDistance = distance;
+ nearest = [candidate];
+ }
+ return nearest;
+}
+
+/** Resolve the nearest visible alias with this name, respecting lexical shadowing. */
+export function visibleTypeAlias(
+ name: string,
+ use: ESTree.Node,
+ environment: TypeAliasEnvironment,
+): ESTree.TSTypeAliasDeclaration | null {
+ if (lexicalTypeParameterNames(use, environment.visitorKeys).has(name)) return null;
+ const bindings = nearestTypeBindings(name, use, environment);
+ return bindings.length === 1 ? (bindings[0]?.alias ?? null) : null;
+}
+
+/** Return whether a local declaration shadows a built-in type at this use. */
+export function hasVisibleTypeBinding(
+ name: string,
+ use: ESTree.Node,
+ environment: TypeAliasEnvironment,
+): boolean {
+ return (
+ lexicalTypeParameterNames(use, environment.visitorKeys).has(name) ||
+ nearestTypeBindings(name, use, environment).length > 0
+ );
+}
+
+function typeReferenceName(type: ESTree.TSTypeReference): string | null {
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
+}
+
+function aliasSubstitutions(
+ alias: ESTree.TSTypeAliasDeclaration,
+ reference: ESTree.TSTypeReference,
+ base: Substitutions,
+): Substitutions | null {
+ const parameters = alias.typeParameters?.params ?? [];
+ const arguments_ = reference.typeArguments?.params ?? [];
+ const next = new Map(base);
+ for (const [index, parameter] of parameters.entries()) {
+ const explicitArgument = arguments_[index];
+ const argument = explicitArgument ?? parameter.default;
+ if (argument === null || argument === undefined) return null;
+ const argumentSubstitutions = explicitArgument === undefined ? next : base;
+ next.set(parameter.name.name, {
+ type: argument,
+ substitutions: new Map(argumentSubstitutions),
+ });
+ }
+ return next;
+}
+
+/** Match a type after resolving visible aliases and substituting their type parameters. */
+export function resolvedTypeMatches(
+ type: ESTree.TSType,
+ environment: TypeAliasEnvironment,
+ matcher: ResolvedTypeMatcher,
+): boolean {
+ const evaluate = (
+ current: ESTree.TSType,
+ substitutions: Substitutions,
+ resolvingAliases: ReadonlySet<ESTree.TSTypeAliasDeclaration>,
+ ): boolean => {
+ if (current.type === "TSTypeReference") {
+ const name = typeReferenceName(current);
+ if (name !== null) {
+ const substitution = substitutions.get(name);
+ if (substitution !== undefined && !current.typeArguments?.params.length) {
+ return evaluate(
+ substitution.type,
+ substitution.substitutions,
+ resolvingAliases,
+ );
+ }
+ const alias = visibleTypeAlias(name, current, environment);
+ if (alias !== null && !resolvingAliases.has(alias)) {
+ const nextSubstitutions = aliasSubstitutions(alias, current, substitutions);
+ if (nextSubstitutions !== null) {
+ const nextResolving = new Set(resolvingAliases);
+ nextResolving.add(alias);
+ return evaluate(alias.typeAnnotation, nextSubstitutions, nextResolving);
+ }
+ }
+ }
+ }
+ return matcher(current, (child) =>
+ evaluate(child, substitutions, resolvingAliases),
+ );
+ };
+
+ return evaluate(type, new Map(), new Set());
+}
diff --git a/tools/oxlint/anti-slop/vendor/eslint-stylistic/LICENSE b/tools/oxlint/anti-slop/vendor/eslint-stylistic/LICENSE
new file mode 100644
index 0000000..38dbc35
--- /dev/null
+++ b/tools/oxlint/anti-slop/vendor/eslint-stylistic/LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
+Copyright (c) 2023-PRESENT ESLint Stylistic contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tools/oxlint/anti-slop/vendor/eslint-stylistic/UPSTREAM.md b/tools/oxlint/anti-slop/vendor/eslint-stylistic/UPSTREAM.md
new file mode 100644
index 0000000..95d15ed
--- /dev/null
+++ b/tools/oxlint/anti-slop/vendor/eslint-stylistic/UPSTREAM.md
@@ -0,0 +1,28 @@
+# Vendored padding-line-between-statements
+
+Source: [ESLint Stylistic](https://github.com/eslint-stylistic/eslint-stylistic), commit `435c3ea0fd26a5fef9042c4b36b6e165fbbf8d08`.
+
+Copied files:
+
+- `packages/eslint-plugin/rules/padding-line-between-statements/padding-line-between-statements.ts`
+- `packages/eslint-plugin/rules/padding-line-between-statements/types.d.ts` → `padding-line-options.d.ts`
+- Root `LICENSE`, retained verbatim. Both OpenJS Foundation and ESLint Stylistic notices apply.
+
+The rule is MIT-licensed. Keep `LICENSE` with every redistributed copy, including skill assets. No Stylistic, ESLint, TypeScript-ESLint, or additional parser runtime dependency is required.
+
+## Local adaptations
+
+- Replace upstream type aliases with Oxlint's ESTree, context, token/comment, and rule types. Upstream's token type includes comments; Oxlint exposes those separately.
+- Replace `AST_NODE_TYPES` enum members with identical string literals.
+- Guard indexed reads for consuming repositories with `noUncheckedIndexedAccess`. Impossible missing AST/configuration entries raise explicit invariant errors rather than introducing new non-null assertions.
+- Replace the repository-specific `createRule` factory with `createPaddingLineRule(options, statementTypes?)`. The anti-slop wrapper supplies typed options directly; it exposes no user configuration options. The optional second argument registers caller-defined statement types, consulted before the upstream table, so a policy can match syntax the upstream matchers do not distinguish (exported bindings, comment ownership) without editing the vendored tables.
+- Implement the small required AST helper surface in `padding-line-ast.ts` using Oxlint's public source-code/token API. `isParenthesized` only needs the one-pair check used to exclude parenthesized directive strings, not the upstream general-purpose overloads.
+- Retain the upstream statement matchers, scope tracking, comment-aware insertion/removal, selector support, and diagnostic text. Upstream naming and non-null assumptions remain localized here to keep future diffs reviewable; the file is not a model for new application code.
+
+The opinionated policy lives outside this directory in `../../rules/require-readable-spacing.ts`. It adds spacing without collapsing existing blank lines. Short local bindings, consecutive imports, and adjacent overload signatures/implementation remain grouped. Spacing is syntactic, not an inference of business-logic boundaries.
+
+## Updating and verification
+
+Fetch an explicit upstream revision, compare the original rule and types against this revision, and port relevant fixes while retaining the adapters above. Update this record and preserve the license. Run `pnpm check` and `pnpm sync:skill-assets` as required by repository guidance.
+
+Focused Oxlint RuleTester cases live in `../../rules/require-readable-spacing.test.ts`; they test exact fixes, JSDoc/trailing comments, same-line statements, semicolon-free code, TypeScript exports/overloads, Effect-style generators, and upstream removal behavior. `../../rules/require-readable-spacing-cli.test.ts` verifies the exported plugin through the native Oxlint CLI on multiple files, including rejection, autofix, and repeated-fix stability. The complete upstream JS/TS test suites have not been ported; this is focused compatibility evidence, not a claim of full upstream conformance.
diff --git a/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-ast.ts b/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-ast.ts
new file mode 100644
index 0000000..10f34cc
--- /dev/null
+++ b/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-ast.ts
@@ -0,0 +1,51 @@
+// Local replacements for the upstream helper imports. See UPSTREAM.md.
+import type { ESTree, SourceCode, Token as SyntaxToken, Comment, Location } from "@oxlint/plugins";
+
+type Token = SyntaxToken | Comment;
+
+/** Line terminators recognized by the upstream padding matcher. */
+export const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]);
+
+/** Test a closing brace without treating comment text as punctuation. */
+export const isClosingBraceToken = (token: Token): boolean =>
+ token.type === "Punctuator" && token.value === "}";
+
+/** Test a semicolon without treating comment text as punctuation. */
+export const isSemicolonToken = (token: Token): boolean =>
+ token.type === "Punctuator" && token.value === ";";
+
+/** Filter the optional final semicolon when identifying block-like statements. */
+export const isNotSemicolonToken = (token: Token): boolean => !isSemicolonToken(token);
+
+/** Compare token/node boundaries, including attached comments. */
+export const isTokenOnSameLine = (left: { loc: Location }, right: { loc: Location }): boolean =>
+ left.loc.end.line === right.loc.start.line;
+
+/** Recognize declarations and expressions used by the upstream IIFE matcher. */
+export const isFunction = (node: ESTree.Node): boolean =>
+ node.type === "FunctionDeclaration" ||
+ node.type === "FunctionExpression" ||
+ node.type === "ArrowFunctionExpression";
+
+/** Preserve the upstream multiline statement heuristic. */
+export const isSingleLine = (node: ESTree.Node): boolean =>
+ node.loc.start.line === node.loc.end.line;
+
+/** Unwrap optional chaining before checking IIFE syntax. */
+export const skipChainExpression = (node: ESTree.Node): ESTree.Node =>
+ node.type === "ChainExpression" ? node.expression : node;
+
+/** Only a program or function-body expression can begin a directive prologue. */
+export const isTopLevelExpressionStatement = (
+ node: ESTree.Node,
+): node is ESTree.ExpressionStatement =>
+ node.type === "ExpressionStatement" &&
+ (node.parent.type === "Program" ||
+ (node.parent.type === "BlockStatement" && isFunction(node.parent.parent)));
+
+/** A single wrapping pair suffices to exclude a string from directive syntax. */
+export function isParenthesized(node: ESTree.Node, sourceCode: SourceCode): boolean {
+ const before = sourceCode.getTokenBefore(node);
+ const after = sourceCode.getTokenAfter(node);
+ return before?.value === "(" && after?.value === ")";
+}
diff --git a/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-between-statements.ts b/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-between-statements.ts
new file mode 100644
index 0000000..8e2c99f
--- /dev/null
+++ b/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-between-statements.ts
@@ -0,0 +1,929 @@
+// Vendored from ESLint Stylistic; see UPSTREAM.md and LICENSE in this directory.
+import type { ESTree, Context as RuleContext, SourceCode, Token as SyntaxToken, Comment, CreateRule, Location } from '@oxlint/plugins'
+type ASTNode = ESTree.Node
+type Token = SyntaxToken | Comment
+import type {
+ PaddingType,
+ SelectorOption,
+ StatementMatcher,
+} from './padding-line-options.d.ts'
+import {
+ isClosingBraceToken,
+ isFunction,
+ isNotSemicolonToken,
+ isParenthesized,
+ isSemicolonToken,
+ isSingleLine,
+ isTokenOnSameLine,
+ isTopLevelExpressionStatement,
+ LINEBREAKS,
+ skipChainExpression,
+} from './padding-line-ast.ts'
+
+const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/u
+const CJS_IMPORT = /^require\(/u
+
+/**
+ * This rule is a replica of padding-line-between-statements.
+ *
+ * Ideally we would want to extend the rule support typescript specific support.
+ * But since not all the state is exposed by the eslint and eslint has frozen stylistic rules,
+ * (see - https://eslint.org/blog/2020/05/changes-to-rules-policies for details.)
+ * we are forced to re-implement the rule here.
+ *
+ * We have tried to keep the implementation as close as possible to the eslint implementation, to make
+ * patching easier for future contributors.
+ *
+ * Reference rule - https://github.com/eslint/eslint/blob/main/lib/rules/padding-line-between-statements.js
+ */
+
+type NodeTest = (
+ node: ASTNode,
+ sourceCode: SourceCode,
+) => boolean
+
+export interface NodeTestObject {
+ test: NodeTest
+}
+
+/**
+ * A policy entry may name a caller-defined statement type (registered through
+ * `createPaddingLineRule`) anywhere the upstream statement types are accepted.
+ */
+export type PolicyStatementOption<Extra extends string = never> =
+ | StatementMatcher
+ | Extra
+ | [StatementMatcher | Extra, ...(StatementMatcher | Extra)[]]
+
+export type PolicyOptions<Extra extends string = never> = {
+ blankLine: PaddingType
+ prev: PolicyStatementOption<Extra>
+ next: PolicyStatementOption<Extra>
+}[]
+
+const LT = `[${Array.from(LINEBREAKS).join('')}]`
+const PADDING_LINE_SEQUENCE = new RegExp(
+ String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$`,
+ 'u',
+)
+
+function isSelectorOption(option: PolicyStatementOption<string>): option is SelectorOption {
+ return typeof option === 'object' && !Array.isArray(option)
+}
+
+/**
+ * Creates tester which check if a node starts with specific keyword with the
+ * appropriate AST_NODE_TYPES.
+ * @param keyword The keyword to test.
+ * @returns the created tester.
+ * @private
+ */
+function newKeywordTester(
+ type: string | string[],
+ keyword: string,
+): NodeTestObject {
+ return {
+ test(node, sourceCode): boolean {
+ const isSameKeyword = sourceCode.getFirstToken(node)?.value === keyword
+ const isSameType = Array.isArray(type)
+ ? type.includes(node.type)
+ : type === node.type
+
+ return isSameKeyword && isSameType
+ },
+ }
+}
+
+/**
+ * Creates tester which check if a node is specific type.
+ * @param type The node type to test.
+ * @returns the created tester.
+ * @private
+ */
+function newNodeTypeTester(type: string): NodeTestObject {
+ return {
+ test: (node): boolean => node.type === type,
+ }
+}
+
+/**
+ * Checks the given node is an expression statement of IIFE.
+ * @param node The node to check.
+ * @returns `true` if the node is an expression statement of IIFE.
+ * @private
+ */
+function isIIFEStatement(node: ASTNode): boolean {
+ if (node.type === 'ExpressionStatement') {
+ let expression = skipChainExpression(node.expression)
+ if (expression.type === 'UnaryExpression')
+ expression = skipChainExpression(expression.argument)
+
+ if (expression.type === 'CallExpression') {
+ let node: ASTNode = expression.callee
+ while (node.type === 'SequenceExpression') {
+ const lastExpression = node.expressions.at(-1)
+ if (lastExpression === undefined)
+ throw new Error('Padding rule invariant: sequence expression is empty')
+ node = lastExpression
+ }
+
+ return isFunction(node)
+ }
+ }
+ return false
+}
+
+/**
+ * Checks the given node is a CommonJS require statement
+ * @param node The node to check.
+ * @returns `true` if the node is a CommonJS require statement.
+ * @private
+ */
+function isCJSRequire(node: ASTNode): boolean {
+ if (node.type === 'VariableDeclaration') {
+ const declaration = node.declarations[0]
+ if (declaration?.init) {
+ let call = declaration?.init
+ while (call.type === 'MemberExpression')
+ call = call.object
+
+ if (
+ call.type === 'CallExpression'
+ && call.callee.type === 'Identifier'
+ ) {
+ return call.callee.name === 'require'
+ }
+ }
+ }
+ return false
+}
+
+/**
+ * Checks whether the given node is a block-like statement.
+ * This checks the last token of the node is the closing brace of a block.
+ * @param sourceCode The source code to get tokens.
+ * @param node The node to check.
+ * @returns `true` if the node is a block-like statement.
+ * @private
+ */
+function isBlockLikeStatement(
+ node: ASTNode,
+ sourceCode: SourceCode,
+): boolean {
+ // do-while with a block is a block-like statement.
+ if (
+ node.type === 'DoWhileStatement'
+ && node.body.type === 'BlockStatement'
+ ) {
+ return true
+ }
+
+ /**
+ * IIFE is a block-like statement specially from
+ * JSCS#disallowPaddingNewLinesAfterBlocks.
+ */
+ if (isIIFEStatement(node))
+ return true
+
+ // Checks the last token is a closing brace of blocks.
+ const lastToken = sourceCode.getLastToken(node, isNotSemicolonToken)
+ const belongingNode
+ = lastToken && isClosingBraceToken(lastToken)
+ ? sourceCode.getNodeByRangeIndex(lastToken.range[0])
+ : null
+
+ return (
+ !!belongingNode
+ && (belongingNode.type === 'BlockStatement'
+ || belongingNode.type === 'SwitchStatement')
+ )
+}
+
+/**
+ * Check whether the given node is a directive or not.
+ * @param node The node to check.
+ * @param sourceCode The source code object to get tokens.
+ * @returns `true` if the node is a directive.
+ */
+function isDirective(
+ node: ASTNode,
+ sourceCode: SourceCode,
+): boolean {
+ return (
+ isTopLevelExpressionStatement(node)
+ && node.expression.type === 'Literal'
+ && typeof node.expression.value === 'string'
+ && !isParenthesized(node.expression, sourceCode)
+ )
+}
+
+/**
+ * Check whether the given node is a part of directive prologue or not.
+ * @param node The node to check.
+ * @param sourceCode The source code object to get tokens.
+ * @returns `true` if the node is a part of directive prologue.
+ */
+function isDirectivePrologue(
+ node: ASTNode,
+ sourceCode: SourceCode,
+): boolean {
+ if (
+ isDirective(node, sourceCode)
+ && node.parent
+ && 'body' in node.parent
+ && Array.isArray(node.parent.body)
+ ) {
+ for (const sibling of node.parent.body) {
+ if (sibling === node)
+ break
+
+ if (!isDirective(sibling, sourceCode))
+ return false
+ }
+ return true
+ }
+ return false
+}
+
+/**
+ * Checks the given node is a CommonJS export statement
+ * @param node The node to check.
+ * @returns `true` if the node is a CommonJS export statement.
+ * @private
+ */
+function isCJSExport(node: ASTNode): boolean {
+ if (node.type === 'ExpressionStatement') {
+ const expression = node.expression
+ if (expression.type === 'AssignmentExpression') {
+ let left = expression.left
+ if (left.type === 'MemberExpression') {
+ while (left.object.type === 'MemberExpression')
+ left = left.object
+
+ return (
+ left.object.type === 'Identifier'
+ && (left.object.name === 'exports'
+ || (left.object.name === 'module'
+ && left.property.type === 'Identifier'
+ && left.property.name === 'exports'))
+ )
+ }
+ }
+ }
+ return false
+}
+
+/**
+ * Check whether the given node is an expression
+ * @param node The node to check.
+ * @param sourceCode The source code object to get tokens.
+ * @returns `true` if the node is an expression
+ */
+function isExpression(
+ node: ASTNode,
+ sourceCode: SourceCode,
+): boolean {
+ return (
+ node.type === 'ExpressionStatement'
+ && !isDirectivePrologue(node, sourceCode)
+ )
+}
+
+/**
+ * Gets the actual last token.
+ *
+ * If a semicolon is semicolon-less style's semicolon, this ignores it.
+ * For example:
+ *
+ * foo()
+ * ;[1, 2, 3].forEach(bar)
+ * @param sourceCode The source code to get tokens.
+ * @param node The node to get.
+ * @returns The actual last token.
+ * @private
+ */
+function getActualLastToken(
+ node: ASTNode,
+ sourceCode: SourceCode,
+): Token | null {
+ const semiToken = sourceCode.getLastToken(node)!
+ const prevToken = sourceCode.getTokenBefore(semiToken)
+ const nextToken = sourceCode.getTokenAfter(semiToken)
+ const isSemicolonLessStyle
+ = prevToken
+ && nextToken
+ && prevToken.range[0] >= node.range[0]
+ && isSemicolonToken(semiToken)
+ && !isTokenOnSameLine(prevToken, semiToken)
+ && isTokenOnSameLine(semiToken, nextToken)
+
+ return isSemicolonLessStyle ? prevToken : semiToken
+}
+
+/**
+ * This returns the concatenation of the first 2 captured strings.
+ * @param _ Unused. Whole matched string.
+ * @param trailingSpaces The trailing spaces of the first line.
+ * @param indentSpaces The indentation spaces of the last line.
+ * @returns The concatenation of trailingSpaces and indentSpaces.
+ * @private
+ */
+function replacerToRemovePaddingLines(
+ _: string,
+ trailingSpaces: string,
+ indentSpaces: string,
+): string {
+ return trailingSpaces + indentSpaces
+}
+
+function getReportLoc(node: ASTNode, sourceCode: SourceCode): Location {
+ if (isSingleLine(node))
+ return node.loc
+
+ const line = node.loc.start.line
+ const sourceLine = sourceCode.lines[line - 1]
+ if (sourceLine === undefined)
+ throw new Error('Padding rule invariant: statement source line is missing')
+
+ return {
+ start: node.loc.start,
+ end: {
+ line,
+ column: sourceLine.length,
+ },
+ }
+}
+
+/**
+ * Check and report statements for `any` configuration.
+ * It does nothing.
+ *
+ * @private
+ */
+function verifyForAny(): void {
+ // Empty
+}
+
+/**
+ * Check and report statements for `never` configuration.
+ * This autofix removes blank lines between the given 2 statements.
+ * However, if comments exist between 2 blank lines, it does not remove those
+ * blank lines automatically.
+ * @param context The rule context to report.
+ * @param _ Unused. The previous node to check.
+ * @param nextNode The next node to check.
+ * @param paddingLines The array of token pairs that blank
+ * lines exist between the pair.
+ *
+ * @private
+ */
+function verifyForNever(
+ context: RuleContext,
+ _: ASTNode,
+ nextNode: ASTNode,
+ paddingLines: [Token, Token][],
+): void {
+ if (paddingLines.length === 0)
+ return
+
+ context.report({
+ node: nextNode,
+ messageId: 'unexpectedBlankLine',
+ loc: getReportLoc(nextNode, context.sourceCode),
+ fix(fixer) {
+ if (paddingLines.length >= 2)
+ return null
+
+ const paddingPair = paddingLines[0]
+ if (paddingPair === undefined)
+ throw new Error('Padding rule invariant: reported padding pair is missing')
+ const [prevToken, nextToken] = paddingPair
+ const start = prevToken.range[1]
+ const end = nextToken.range[0]
+ const text = context
+ .sourceCode
+ .text
+ .slice(start, end)
+ .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines)
+
+ return fixer.replaceTextRange([start, end], text)
+ },
+ })
+}
+
+/**
+ * Check and report statements for `always` configuration.
+ * This autofix inserts a blank line between the given 2 statements.
+ * If the `prevNode` has trailing comments, it inserts a blank line after the
+ * trailing comments.
+ * @param context The rule context to report.
+ * @param prevNode The previous node to check.
+ * @param nextNode The next node to check.
+ * @param paddingLines The array of token pairs that blank
+ * lines exist between the pair.
+ *
+ * @private
+ */
+function verifyForAlways(
+ context: RuleContext,
+ prevNode: ASTNode,
+ nextNode: ASTNode,
+ paddingLines: [Token, Token][],
+): void {
+ if (paddingLines.length > 0)
+ return
+
+ context.report({
+ node: nextNode,
+ messageId: 'expectedBlankLine',
+ loc: getReportLoc(nextNode, context.sourceCode),
+ fix(fixer) {
+ const sourceCode = context.sourceCode
+ let prevToken = getActualLastToken(prevNode, sourceCode)!
+ const nextToken
+ = sourceCode.getFirstTokenBetween(prevToken, nextNode, {
+ includeComments: true,
+
+ /**
+ * Skip the trailing comments of the previous node.
+ * This inserts a blank line after the last trailing comment.
+ *
+ * For example:
+ *
+ * foo(); // trailing comment.
+ * // comment.
+ * bar();
+ *
+ * Get fixed to:
+ *
+ * foo(); // trailing comment.
+ *
+ * // comment.
+ * bar();
+ * @param token The token to check.
+ * @returns `true` if the token is not a trailing comment.
+ * @private
+ */
+ filter(token) {
+ if (isTokenOnSameLine(prevToken, token)) {
+ prevToken = token
+ return false
+ }
+ return true
+ },
+ })! || nextNode
+ const insertText = isTokenOnSameLine(prevToken, nextToken)
+ ? '\n\n'
+ : '\n'
+
+ return fixer.insertTextAfter(prevToken, insertText)
+ },
+ })
+}
+
+/**
+ * Types of blank lines.
+ * `any`, `never`, and `always` are defined.
+ * Those have `verify` method to check and report statements.
+ * @private
+ */
+const PaddingTypes = {
+ any: { verify: verifyForAny },
+ never: { verify: verifyForNever },
+ always: { verify: verifyForAlways },
+}
+
+const MaybeMultilineStatementType: Record<string, NodeTestObject> = {
+ 'block-like': { test: isBlockLikeStatement },
+ 'expression': { test: isExpression },
+ 'return': newKeywordTester('ReturnStatement', 'return'),
+ 'export': newKeywordTester(
+ [
+ 'ExportAllDeclaration',
+ 'ExportDefaultDeclaration',
+ 'ExportNamedDeclaration',
+ ],
+ 'export',
+ ),
+ 'var': newKeywordTester('VariableDeclaration', 'var'),
+ 'let': newKeywordTester('VariableDeclaration', 'let'),
+ 'const': newKeywordTester('VariableDeclaration', 'const'),
+ 'using': {
+ test: node => node.type === 'VariableDeclaration'
+ && (node.kind === 'using' || node.kind === 'await using'),
+ },
+ 'type': newKeywordTester('TSTypeAliasDeclaration', 'type'),
+}
+
+/**
+ * Types of statements.
+ * Those have `test` method to check it matches to the given statement.
+ * @private
+ */
+const StatementTypes: Record<string, NodeTestObject> = {
+ '*': { test: (): boolean => true },
+ 'exports': { test: isCJSExport },
+ 'require': { test: isCJSRequire },
+ 'directive': { test: isDirectivePrologue },
+ 'iife': { test: isIIFEStatement },
+
+ 'block': newNodeTypeTester('BlockStatement'),
+ 'empty': newNodeTypeTester('EmptyStatement'),
+ 'function': newNodeTypeTester('FunctionDeclaration'),
+ 'ts-method': newNodeTypeTester('TSMethodSignature'),
+
+ 'break': newKeywordTester('BreakStatement', 'break'),
+ 'case': newKeywordTester('SwitchCase', 'case'),
+ 'class': newKeywordTester('ClassDeclaration', 'class'),
+ 'continue': newKeywordTester('ContinueStatement', 'continue'),
+ 'debugger': newKeywordTester('DebuggerStatement', 'debugger'),
+ 'default': newKeywordTester(
+ ['SwitchCase', 'ExportDefaultDeclaration'],
+ 'default',
+ ),
+ 'do': newKeywordTester('DoWhileStatement', 'do'),
+ 'for': newKeywordTester(
+ [
+ 'ForStatement',
+ 'ForInStatement',
+ 'ForOfStatement',
+ ],
+ 'for',
+ ),
+ 'if': newKeywordTester('IfStatement', 'if'),
+ 'import': newKeywordTester('ImportDeclaration', 'import'),
+ 'switch': newKeywordTester('SwitchStatement', 'switch'),
+ 'throw': newKeywordTester('ThrowStatement', 'throw'),
+ 'try': newKeywordTester('TryStatement', 'try'),
+ 'while': newKeywordTester(
+ ['WhileStatement', 'DoWhileStatement'],
+ 'while',
+ ),
+ 'with': newKeywordTester('WithStatement', 'with'),
+
+ 'cjs-export': {
+ test: (node, sourceCode) => node.type === 'ExpressionStatement'
+ && node.expression.type === 'AssignmentExpression'
+ && CJS_EXPORT.test(sourceCode.getText(node.expression.left)),
+ },
+ 'cjs-import': {
+ test: (node, sourceCode) => node.type === 'VariableDeclaration'
+ && node.declarations.length > 0
+ && node.declarations[0]?.init != null
+ && CJS_IMPORT.test(sourceCode.getText(node.declarations[0].init)),
+ },
+
+ 'enum': newKeywordTester(
+ 'TSEnumDeclaration',
+ 'enum',
+ ),
+ 'interface': newKeywordTester(
+ 'TSInterfaceDeclaration',
+ 'interface',
+ ),
+ 'function-overload': newNodeTypeTester('TSDeclareFunction'),
+ ...Object.fromEntries(
+ Object.entries(MaybeMultilineStatementType)
+ .flatMap(([key, value]) => [
+ [key, value],
+ [
+ `singleline-${key}`,
+ {
+ ...value,
+ test: (node, sourceCode) => value.test(node, sourceCode) && isSingleLine(node),
+ },
+ ],
+ [
+ `multiline-${key}`,
+ {
+ ...value,
+ test: (node, sourceCode) => value.test(node, sourceCode) && !isSingleLine(node),
+ },
+ ],
+ ]),
+ ),
+}
+
+/**
+ * Build the vendored padding rule with caller-owned, typed policy options.
+ * `statementTypes` registers caller-defined statement types, looked up before
+ * the upstream table, for syntax the upstream matchers do not distinguish.
+ */
+export default function createPaddingLineRule<Extra extends string = never>(
+ options: PolicyOptions<NoInfer<Extra>>,
+ statementTypes?: Record<Extra, NodeTestObject>,
+): CreateRule {
+const customStatementTypes: Partial<Record<string, NodeTestObject>> = statementTypes ?? {}
+return {
+ meta: {
+ type: 'layout',
+ docs: {
+ description: 'Require or disallow padding lines between statements',
+ },
+ fixable: 'whitespace',
+ hasSuggestions: false,
+ // This is intentionally an array schema as you can pass 0..n config objects
+ schema: {
+ $defs: {
+ paddingType: {
+ type: 'string',
+ enum: Object.keys(PaddingTypes),
+ },
+ statementType: {
+ type: 'string',
+ enum: Object.keys(StatementTypes),
+ },
+ selectorOption: {
+ type: 'object',
+ properties: {
+ selector: {
+ type: 'string',
+ },
+ lineMode: {
+ type: 'string',
+ enum: ['any', 'singleline', 'multiline'],
+ },
+ },
+ required: ['selector'],
+ additionalProperties: false,
+ },
+ statementMatcher: {
+ anyOf: [
+ { $ref: '#/$defs/statementType' },
+ { $ref: '#/$defs/selectorOption' },
+ ],
+ },
+ statementOption: {
+ anyOf: [
+ { $ref: '#/$defs/statementMatcher' },
+ {
+ type: 'array',
+ items: { $ref: '#/$defs/statementMatcher' },
+ minItems: 1,
+ uniqueItems: true,
+ additionalItems: false,
+ },
+ ],
+ },
+ },
+ type: 'array',
+ additionalItems: false,
+ items: {
+ type: 'object',
+ properties: {
+ blankLine: { $ref: '#/$defs/paddingType' },
+ prev: { $ref: '#/$defs/statementOption' },
+ next: { $ref: '#/$defs/statementOption' },
+ },
+ additionalProperties: false,
+ required: ['blankLine', 'prev', 'next'],
+ },
+ },
+ messages: {
+ unexpectedBlankLine: 'Unexpected blank line before this statement.',
+ expectedBlankLine: 'Expected blank line before this statement.',
+ },
+ },
+ create(context) {
+ const sourceCode = context.sourceCode
+
+ const selectorMatchedNodes = new Map<string, Set<ASTNode>>()
+ const pendingPairs: { prevNode: ASTNode, nextNode: ASTNode }[] = []
+
+ function collectSelectorOption(option: PolicyStatementOption<Extra>): void {
+ if (Array.isArray(option)) {
+ for (const item of option)
+ collectSelectorOption(item)
+ return
+ }
+
+ if (!isSelectorOption(option))
+ return
+
+ selectorMatchedNodes.set(option.selector, new Set())
+ }
+
+ for (const configure of options) {
+ collectSelectorOption(configure.prev)
+ collectSelectorOption(configure.next)
+ }
+
+ type Scope = {
+ upper: Scope
+ prevNode: ASTNode | null
+ } | null
+
+ let scopeInfo: Scope = null
+
+ /**
+ * Processes to enter to new scope.
+ * This manages the current previous statement.
+ *
+ * @private
+ */
+ function enterScope(): void {
+ scopeInfo = {
+ upper: scopeInfo,
+ prevNode: null,
+ }
+ }
+
+ /**
+ * Processes to exit from the current scope.
+ *
+ * @private
+ */
+ function exitScope(): void {
+ if (scopeInfo)
+ scopeInfo = scopeInfo.upper
+ }
+
+ /**
+ * Checks whether the given node matches the given type.
+ * @param node The statement node to check.
+ * @param type The statement type to check.
+ * @returns `true` if the statement node matched the type.
+ * @private
+ */
+ function match(node: ASTNode, type: PolicyStatementOption<Extra>): boolean {
+ let innerStatementNode = node
+
+ while (innerStatementNode.type === 'LabeledStatement')
+ innerStatementNode = innerStatementNode.body
+
+ if (Array.isArray(type))
+ return type.some(match.bind(null, innerStatementNode))
+
+ if (isSelectorOption(type)) {
+ const matchedNodes = selectorMatchedNodes.get(type.selector)
+ if (!matchedNodes?.has(innerStatementNode))
+ return false
+
+ const lineMode = type.lineMode
+
+ if (lineMode === 'singleline')
+ return isSingleLine(innerStatementNode)
+ else if (lineMode === 'multiline')
+ return !isSingleLine(innerStatementNode)
+
+ return true
+ }
+ else {
+ const statementType = customStatementTypes[type] ?? StatementTypes[type]
+ if (statementType === undefined)
+ throw new Error(`Padding rule invariant: unsupported statement type ${type}`)
+ return statementType.test(innerStatementNode, sourceCode)
+ }
+ }
+
+ /**
+ * Finds the last matched configure from options.
+ * @param prevNode The previous statement to match.
+ * @param nextNode The current statement to match.
+ * @returns The tester of the last matched configure.
+ * @private
+ */
+ function getPaddingType(
+ prevNode: ASTNode,
+ nextNode: ASTNode,
+ ): (typeof PaddingTypes)[keyof typeof PaddingTypes] {
+ for (let i = options.length - 1; i >= 0; --i) {
+ const configure = options[i]
+ if (configure === undefined)
+ throw new Error('Padding rule invariant: configuration entry is missing')
+ if (
+ match(prevNode, configure.prev)
+ && match(nextNode, configure.next)
+ ) {
+ return PaddingTypes[configure.blankLine]
+ }
+ }
+ return PaddingTypes.any
+ }
+
+ /**
+ * Gets padding line sequences between the given 2 statements.
+ * Comments are separators of the padding line sequences.
+ * @param prevNode The previous statement to count.
+ * @param nextNode The current statement to count.
+ * @returns The array of token pairs.
+ * @private
+ */
+ function getPaddingLineSequences(
+ prevNode: ASTNode,
+ nextNode: ASTNode,
+ ): [Token, Token][] {
+ const pairs: [Token, Token][] = []
+ let prevToken: Token = getActualLastToken(prevNode, sourceCode)!
+
+ if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) {
+ do {
+ const token: Token = sourceCode.getTokenAfter(prevToken, {
+ includeComments: true,
+ })!
+
+ if (token.loc.start.line - prevToken.loc.end.line >= 2)
+ pairs.push([prevToken, token])
+
+ prevToken = token
+ } while (prevToken.range[0] < nextNode.range[0])
+ }
+
+ return pairs
+ }
+
+ /**
+ * Verify padding lines between the given node and the previous node.
+ * @param node The node to verify.
+ *
+ * @private
+ */
+ function verify(node: ASTNode): void {
+ if (
+ !node.parent
+ || ![
+ 'BlockStatement',
+ 'Program',
+ 'StaticBlock',
+ 'SwitchCase',
+ 'SwitchStatement',
+ 'TSInterfaceBody',
+ 'TSModuleBlock',
+ 'TSTypeLiteral',
+ ].includes(node.parent.type)
+ ) {
+ return
+ }
+
+ // Save this node as the current previous statement.
+ const prevNode = scopeInfo!.prevNode
+
+ // Verify.
+ if (prevNode)
+ pendingPairs.push({ prevNode, nextNode: node })
+
+ scopeInfo!.prevNode = node
+ }
+
+ function verifyPendingPairs(): void {
+ for (const { prevNode, nextNode } of pendingPairs) {
+ const type = getPaddingType(prevNode, nextNode)
+ const paddingLines = getPaddingLineSequences(prevNode, nextNode)
+
+ type.verify(context, prevNode, nextNode, paddingLines)
+ }
+ }
+
+ /**
+ * Verify padding lines between the given node and the previous node.
+ * Then process to enter to new scope.
+ * @param node The node to verify.
+ *
+ * @private
+ */
+ function verifyThenEnterScope(node: ASTNode): void {
+ verify(node)
+ enterScope()
+ }
+
+ const selectorMatchListeners = Object.fromEntries(
+ Array.from(selectorMatchedNodes.keys(), selector => [
+ selector,
+ (node: ASTNode): void => {
+ selectorMatchedNodes.get(selector)?.add(node)
+ },
+ ]),
+ )
+
+ return {
+ 'Program': enterScope,
+ 'Program:exit': () => {
+ verifyPendingPairs()
+ exitScope()
+ },
+ 'BlockStatement': enterScope,
+ 'BlockStatement:exit': exitScope,
+ 'SwitchStatement': enterScope,
+ 'SwitchStatement:exit': exitScope,
+ 'SwitchCase': verifyThenEnterScope,
+ 'SwitchCase:exit': exitScope,
+ 'StaticBlock': enterScope,
+ 'StaticBlock:exit': exitScope,
+
+ 'TSInterfaceBody': enterScope,
+ 'TSInterfaceBody:exit': exitScope,
+ 'TSModuleBlock': enterScope,
+ 'TSModuleBlock:exit': exitScope,
+ 'TSTypeLiteral': enterScope,
+ 'TSTypeLiteral:exit': exitScope,
+ 'TSDeclareFunction': verifyThenEnterScope,
+ 'TSDeclareFunction:exit': exitScope,
+ 'TSMethodSignature': verifyThenEnterScope,
+ 'TSMethodSignature:exit': exitScope,
+
+ ':statement': verify,
+ ...selectorMatchListeners,
+ }
+ },
+}
+}
diff --git a/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-options.d.ts b/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-options.d.ts
new file mode 100644
index 0000000..45068ec
--- /dev/null
+++ b/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-options.d.ts
@@ -0,0 +1,87 @@
+/* GENERATED, DO NOT EDIT DIRECTLY */
+
+/* @checksum: 3QCTtOH6rJM5_AGJ58rGpeEaBEfaJz17MSCxWB4X_PU */
+
+export type PaddingType = 'any' | 'never' | 'always'
+export type StatementOption =
+ | StatementMatcher
+ | [StatementMatcher, ...StatementMatcher[]]
+export type StatementMatcher =
+ | StatementType
+ | SelectorOption
+export type StatementType =
+ | '*'
+ | 'exports'
+ | 'require'
+ | 'directive'
+ | 'iife'
+ | 'block'
+ | 'empty'
+ | 'function'
+ | 'ts-method'
+ | 'break'
+ | 'case'
+ | 'class'
+ | 'continue'
+ | 'debugger'
+ | 'default'
+ | 'do'
+ | 'for'
+ | 'if'
+ | 'import'
+ | 'switch'
+ | 'throw'
+ | 'try'
+ | 'while'
+ | 'with'
+ | 'cjs-export'
+ | 'cjs-import'
+ | 'enum'
+ | 'interface'
+ | 'function-overload'
+ | 'block-like'
+ | 'singleline-block-like'
+ | 'multiline-block-like'
+ | 'expression'
+ | 'singleline-expression'
+ | 'multiline-expression'
+ | 'return'
+ | 'singleline-return'
+ | 'multiline-return'
+ | 'export'
+ | 'singleline-export'
+ | 'multiline-export'
+ | 'var'
+ | 'singleline-var'
+ | 'multiline-var'
+ | 'let'
+ | 'singleline-let'
+ | 'multiline-let'
+ | 'const'
+ | 'singleline-const'
+ | 'multiline-const'
+ | 'using'
+ | 'singleline-using'
+ | 'multiline-using'
+ | 'type'
+ | 'singleline-type'
+ | 'multiline-type'
+export type PaddingLineBetweenStatementsSchema0 = {
+ blankLine: PaddingType
+ prev: StatementOption
+ next: StatementOption
+}[]
+
+export interface SelectorOption {
+ selector: string
+ lineMode?: 'any' | 'singleline' | 'multiline'
+}
+
+export type PaddingLineBetweenStatementsRuleOptions
+ = PaddingLineBetweenStatementsSchema0
+
+export type RuleOptions
+ = PaddingLineBetweenStatementsRuleOptions
+export type MessageIds =
+ | 'unexpectedBlankLine'
+ | 'expectedBlankLine'