mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
feat(video): 0.19.0 video engine (Remotion) + preview auth + render persistence (#307)
* feat(video): Phase A — VideoEngine origination spine + held-source gates
New default-off engine skeleton: opens a UX/UI authoring task (source=video, assigned to a ux-dev, LOW complexity to clear the dev-needs-subtasks guard) and materializes a held CEO-approval draft (source=video_post). Excludes video_post from all three held-source skip sites; adds the video_draft marker, six config flags, and the feature-flag entries. Origination + gate behavior unit-tested.
* refactor(orchestrator): fold _dispatch_dev_work skip chain into a helper
The per-source if/continue chain grew past xenon's --max-absolute B when the video_post held source joined it. Extract _is_non_dev_dispatch_source (every held-CEO source plus the two Board exploration sources) so the dev loop's skip is one flat call. Behavior-identical.
* feat(video): Phase B — propose_video do-tool (metadata-only, team-gated)
UX/UI dev records a video's composition ref + per-platform captions onto the authoring task's video_draft marker. Team-gated at runtime via _caller_team (Role.DEVELOPER can't tell a ux-dev from a be-dev). Resolves the caller's ACTIVE task via get_active_task_for_agent, not an oldest-first scan that would clobber a second open video task. Metadata only, no render. Wired through do_server + route + schema; added to _DEV_DO.
* feat(video): Phase D — render loop + RemotionRenderer client
Orchestrator-async _video_render_loop renders a completed authoring task's merged composition to MP4 (vertical + square) via the remotion-renderer sidecar and materializes the held video_post draft. RemotionRenderer tars the read-clone's motion/ source, POSTs it, and saves the returned MP4 bytes to a TASK-scoped local path (no shared volume; a composition is reused across videos so a composition-scoped path would clobber an earlier draft). Render failures bounded-retry (read-clone catch-up window, transient sidecar) up to a cap, then terminal-fail. Client tested vs a mock transport; loop vs a mock renderer + real DB.
* feat(video): Phase C — release / spotlight / on-demand video triggers
Three entry points open a UX/UI video-authoring task via VideoEngine.open_video_task: (1) a published release drafts a companion video — best-effort in ReleaseProposalService.approve, never fails the publish; script from the CHANGELOG via the local model with a template fallback. (2) propose_feature_spotlight gains optional wants_video/video_script — best-effort, gated on video_on_spotlight, default-off leaves the spotlight flow byte-for-byte unchanged. (3) POST /video/request (CEO-only) for an on-demand brief, with clean disabled/not_opened responses. All gated on video_engine_enabled.
* fix(video): savepoint-isolate video-task inserts (F042 poisoned session)
The best-effort try/except around open_video_task (release-publish + spotlight hooks) swallowed the Python exception, but a DBAPI error at the insert flush left the shared session must-rollback — so the caller's next commit (release finalize / request boundary) threw PendingRollbackError: the release stuck 'pending' after actually publishing, or the spotlight draft + HTTP response were lost. Wrap both inserts (open_video_task, _originate_video_post) in a begin_nested savepoint (the repo's established F042 pattern) so a DB error rolls back only the insert. open_video_task returns None (every caller already handles it); _originate_video_post propagates to the render loop's handler. Regression test: an insert FK error returns None with the session left usable. Dormant while the flags were off; armed on the NAS.
* feat(video): Phase G — motion/ package + remotion-renderer sidecar + compose
In-repo Remotion v4 motion/ package (ReleaseAnnouncement composition; calculateMetadata returns 1080x1920 vertical / 1080x1080 square from inputProps.orientation) + a credential-free remotion-renderer sidecar: untar the POSTed motion/ source, bundle (LRU-cached per source sha), selectComposition + renderMedia h264, stream the MP4 bytes back — matching the RemotionRenderer client contract. docker/remotion.Dockerfile on Debian (Chrome apt deps, build-time Chrome pre-warm, ffmpeg bundled in @remotion/renderer). Wired into both compose files (roboco_default only, shm_size 1gb, /health check) + the release publish matrix. Verified via a real local render of both cuts; the Debian docker build is the CEO's to run.
* chore(video): D-hardening — video_post source_task_id + render-loop docstring
Add a source_task_id back-reference to the video_post held-draft marker (traceability from a draft to its authoring task; also makes the render loop's two-key idempotency check wireable later). Fix the render-loop test's stale docstring ('never retried' -> bounded-retry). Both from the Phase D critic's non-blocking follow-ups.
* feat(video): Phase E1 — VideoPostService + heartbeat mutex (approve->post)
CEO-approve->post service: heartbeat-renewed Redis mutex (fail-closed, grace=ttl-2*heartbeat), re-read-in-lock double-post guard, per-platform durable commits (asyncio.shield-ed, settle-before-rollback on lock-loss), all writes inside the lock (captions validated pre-lock, applied in-lock — no stale whole-column clobber), idempotent, per-platform retry-skip. Poster interfaces (X/TikTok, mocked here). Reject + list-held-drafts. Survived 3 adversarial rounds; residual = a crash in the poster->commit window (CEO-gated low-freq, documented).
* fix(video): G-hardening — renderer leaks + Share Tech Mono brand font
Sidecar: give bundle() an explicit outDir tracked + deleted on LRU eviction (was leaking ~19MB remotion-webpack-bundle-* per source); res.on('close') cleanup so an aborted/retried download no longer leaks its remotion-out-* MP4 dir. Fonts: vendor Share Tech Mono (roboco-website brand font) as the display face (self-hosted woff2, 400-weight, headline fontWeight 700->400 to avoid faux-bold) + self-hosted Inter body — no gstatic fetch at render time (lsof-verified). Extras: composition_id whitelist (400) + Multer error middleware (400/413).
* feat(video): Phase E2 — X v2 + TikTok posters, tiktok_credentials, routes
LiveXVideoPoster (X v2 chunked media upload: init/append/finalize/STATUS-poll -> tweet w/ media_ids, OAuth1 signer reused). LiveTikTokPoster (OAuth2 inbox: init -> chunked PUT with asymmetric final chunk -> status-fetch; 401 -> refresh_token grant, rotated token persisted). tiktok_credentials Fernet singleton + migration 062 (single head). Routes: CEO approve/reject + list held drafts + write-only tiktok creds, wiring real posters into VideoPostService. Residual: a lock-loss right after a token-refresh flush can discard the rotated token (same rare CEO-gated class as the documented post->commit window).
* feat(video): Phase F — panel video-post queue + TikTok creds card + flags
video-post-queue.tsx: <video> MP4 preview with 9:16/1:1 cut switch, per-platform editable captions (280/2200 counters, over-limit disables approve), approve/reject, Request-a-video dialog. tiktok-credentials-card.tsx (4 write-only OAuth2 fields). feature-flags-card inlines TikTokCredentialsForm under video_engine_enabled. Mounted in command-center. tsc/eslint clean, 273 panel tests green. NOTE: needs the GET /video/posts/{id}/media route + mp4_paths on VideoPostResponse (folded into H) for the preview source.
* feat(video): Phase H — media route + e2e smoke + NAS arming + docs
GET /video/posts/{id}/media?cut= (CEO-gated FileResponse of the rendered MP4; closes the panel preview gap) + mp4_paths on VideoPostResponse. e2e smoke tests/e2e_smoke/test_video_pipeline.py (full flow, sidecar+X/TikTok mocked; asserts dispatcher skips, render-loop materialize, propose_video team-gate, approve idempotency). NAS arming: docker-compose.yml/.yaml ROBOCO_VIDEO_ENGINE_ENABLED/ON_RELEASE/ON_SPOTLIGHT default-on (.yaml resynced to .yml); registry stays off. CLAUDE.md video-engine section + CHANGELOG. Fixed 2 pre-existing route-test pollution leaks. Full suite 11763 passed.
* fix(video): auth-carrying preview, media route confinement, VideoPost type drift
Three fixes along the video preview path:
1. panel video preview auth: the <video> element was pointed straight at
GET /video/posts/{id}/media, but a native <video src> GET carries none
of axios's X-Agent-ID/X-Agent-Role headers — so in the default
header-trust deployment the request 401s. Fetch the cut via
videoApi.getMediaBlob (axios, responseType: blob) and drive <video>
off a URL.createObjectURL result instead. The object URL is revoked
on cut-change (the previous cut's URL) and on unmount, so neither
cut switches nor row teardown leak blob URLs.
2. backend media route confinement: GET /video/posts/{id}/media now
resolves mp4_path and refuses it with 404 when it falls outside
settings.video_output_dir. Defense-in-depth against any future
writer of mp4_paths serving files from arbitrary disk locations.
3. panel VideoPost type/comment drift: added mp4_paths to the
VideoPost interface (the committed VideoPostResponse already
carries it), and corrected the stale comment on videoMediaUrl
that claimed no route served the rendered bytes — the route has
existed since the media endpoint landed; the comment now describes
why getMediaBlob exists instead of a direct <video src>.
* Persist rendered videos to data in physical storage.
* ++
* docs(video): 0.18.0 CHANGELOG entry + RAG + map reference for video engine
- Move the video engine bullet from [Unreleased] into [0.18.0] and note
the ROBOCO_VIDEO_OUTPUT_DIR bind-mount persistence.
- Add docs/rag/architecture/video-engine.md (mirrors x-engine.md shape:
enable/disable, three triggers, render loop + sidecar, CEO gate, media
route confinement, credentials).
- Reference the video render loop in docs/map/orchestrator.md's engine list.
* chore(video): re-bump to 0.19.0 + sync registry compose defaults
Version was wrongly bumped to 0.18.0; 0.18.0 is an already-released
section. Restore its 2026-07-04 date and move the video-engine CHANGELOG
bullet into a new [0.19.0] - 2026-07-05 section above it. Bump
pyproject.toml, roboco/__init__.py, roboco/config.py (app_version),
panel/package.json, and the motion/README inputProps example to 0.19.0.
docker-compose.registry.yml: add ROBOCO_VIDEO_ENGINE_ENABLED /
_VIDEO_ON_RELEASE / _VIDEO_ON_SPOTLIGHT defaulted false (NAS arms them
true), and comment out the video-renders bind mount with a short note
so the public registry image ships video off by default. Structural
sync with docker-compose.yml maintained.
* fix(video): rate-limit /render + reflow motion/README
CodeQL flagged js/missing-rate-limiting on the renderer /render route.
The sidecar is container-network-only with one trusted caller (the
orchestrator, which renders cuts serially), so this limiter is a
retry-storm ceiling (30/min, well above legit render rate), not the
primary control. Also reflows motion/README.md hard-wrapped prose that
failed the markdown quality gate.
* fix(build): finish pnpm 11 migration + regen verb tables
The panel Docker image build failed on `pnpm install --frozen-lockfile`:
node:22-alpine's corepack resolved to its bundled pnpm 11, but
panel/package.json pinned packageManager to pnpm@10.25.0, and pnpm 11
refuses to run against that pin. The Dockerfiles were already written for
pnpm 11 (comments, CI=true, strictDepBuilds); the package.json pin was the
stale outlier. Finish the migration instead of working around it:
- panel/package.json: packageManager pnpm@10.25.0 -> pnpm@11.10.0; drop the
`pnpm` field (pnpm 11 ignores it — build approval lives in
panel/pnpm-workspace.yaml's allowBuilds). Lockfile unchanged (pnpm 11
accepts it as-is); frozen-lockfile verified.
- remotion-renderer/package.json: pin packageManager pnpm@11.10.0 for
determinism (was relying on corepack's implicit default); engines.node
>=22.13 (pnpm 11 requirement).
- docker/panel.Dockerfile + docker/remotion.Dockerfile: `corepack prepare
pnpm@11.10.0 --activate` so the build uses the pinned version explicitly
instead of trusting corepack's bundled default (which a future
node:22-alpine could change).
- .github/workflows/panel-ci.yml: Node 20 -> 22 (pnpm 11 requires
Node >=22.13; Node 20 fails the engines check).
Also regenerate agents/prompts/_generated/{developer,head_marketing,verbs}.md
— the video engine added propose_video and extended propose_feature_spotlight
(wants_video, video_script) but the verb tables weren't refreshed, failing
the foundation-check quality gate.
* chore(build): approve esbuild build script in remotion pnpm-workspace.yaml
pnpm 11 generated this file with a placeholder ('set this to true or false')
during install; resolve it to true so local dev of the renderer doesn't
re-prompt. esbuild's postinstall only verifies the prebuilt platform binary
(@esbuild/<platform> is installed as an optional dep), so approving it is
safe and silences the ERR_PNPM_IGNORED_BUILDS warning.
* fix(build): copy pnpm-workspace.yaml into panel + remotion images
pnpm 11 hard-errors with [ERR_PNPM_IGNORED_BUILDS] (exit 1) when a
dependency ships a postinstall script that isn't approved in
allowBuilds. Both Dockerfiles copied only package.json + pnpm-lock.yaml,
so the build-approval map in pnpm-workspace.yaml never made it into the
image — the remotion image build died on esbuild@0.28.1's postinstall.
Copy pnpm-workspace.yaml alongside the manifests in both images. In
panel, this also drops the --config.strictDepBuilds=false workaround:
with sharp and unrs-resolver now approved, their postinstalls run and
install the platform-specific binaries (previously skipped, leaving
sharp without its @img/sharp-* binary at runtime).
Verified locally: remotion + panel `pnpm install --frozen-lockfile`
exit 0 with the workspace file present; both exit 1 without it.
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactNode } from "react";
|
||||
import type { VideoPost } from "@/lib/api/video";
|
||||
|
||||
const { resolveApproveRef } = vi.hoisted(() => ({
|
||||
resolveApproveRef: { current: null as null | ((v: unknown) => void) },
|
||||
}));
|
||||
|
||||
const { listPosts, approve, reject, requestVideo, getMediaBlob } = vi.hoisted(
|
||||
() => ({
|
||||
listPosts: vi.fn(
|
||||
async () =>
|
||||
[
|
||||
{
|
||||
task_id: "v-1",
|
||||
source: "video_post",
|
||||
title: "Video: release v0.19.0",
|
||||
status: "pending",
|
||||
occasion: "release",
|
||||
script: "RoboCo v0.19.0 just shipped!",
|
||||
platforms: ["x", "tiktok"],
|
||||
x_caption: "RoboCo v0.19.0 is here!",
|
||||
tiktok_caption: "New RoboCo drop!",
|
||||
},
|
||||
] as VideoPost[],
|
||||
),
|
||||
// Deferred so the test can freeze the approve mid-flight.
|
||||
approve: vi.fn(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolveApproveRef.current = r as (v: unknown) => void;
|
||||
}),
|
||||
),
|
||||
reject: vi.fn(async () => ({})),
|
||||
requestVideo: vi.fn(async () => ({
|
||||
status: "opened",
|
||||
task_id: "v-2",
|
||||
detail: "Video-authoring task opened.",
|
||||
})),
|
||||
getMediaBlob: vi.fn(
|
||||
async () => new Blob(["fake-mp4-bytes"], { type: "video/mp4" }),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
videoApi: { listPosts, approve, reject, requestVideo, getMediaBlob },
|
||||
}));
|
||||
|
||||
import { VideoPostQueue } from "../video-post-queue";
|
||||
|
||||
function withQueryClient(ui: ReactNode) {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
return <QueryClientProvider client={client}>{ui}</QueryClientProvider>;
|
||||
}
|
||||
|
||||
describe("VideoPostQueue", () => {
|
||||
beforeEach(() => {
|
||||
listPosts.mockClear();
|
||||
approve.mockClear();
|
||||
reject.mockClear();
|
||||
requestVideo.mockClear();
|
||||
getMediaBlob.mockClear();
|
||||
resolveApproveRef.current = null;
|
||||
// jsdom has no Blob URL implementation. Distinct URLs per call so a
|
||||
// revoke can be asserted against the specific (stale) one it replaced.
|
||||
let objectUrlCount = 0;
|
||||
globalThis.URL.createObjectURL = vi.fn(
|
||||
() => `blob:mock-url-${++objectUrlCount}`,
|
||||
);
|
||||
globalThis.URL.revokeObjectURL = vi.fn();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders a draft with its occasion badge and both platform captions", async () => {
|
||||
render(withQueryClient(<VideoPostQueue />));
|
||||
expect(await screen.findByText("release")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByDisplayValue("RoboCo v0.19.0 is here!"),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("New RoboCo drop!")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("fetches the preview clip as a blob via axios and drives <video> off an object URL", async () => {
|
||||
render(withQueryClient(<VideoPostQueue />));
|
||||
await screen.findByText("release");
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getMediaBlob).toHaveBeenCalledWith("v-1", "vertical"),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector("video")?.getAttribute("src")).toBe(
|
||||
"blob:mock-url-1",
|
||||
),
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "1:1" }));
|
||||
await waitFor(() =>
|
||||
expect(getMediaBlob).toHaveBeenCalledWith("v-1", "square"),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector("video")?.getAttribute("src")).toBe(
|
||||
"blob:mock-url-2",
|
||||
),
|
||||
);
|
||||
// The stale cut's object URL is revoked once the new one takes over —
|
||||
// this is the leak-prevention path FIX 1 exists for.
|
||||
expect(globalThis.URL.revokeObjectURL).toHaveBeenCalledWith(
|
||||
"blob:mock-url-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("disables Approve when the edited X caption exceeds 280 characters", async () => {
|
||||
render(withQueryClient(<VideoPostQueue />));
|
||||
const textarea = await screen.findByDisplayValue("RoboCo v0.19.0 is here!");
|
||||
fireEvent.change(textarea, { target: { value: "x".repeat(281) } });
|
||||
|
||||
expect(screen.getByText("281/280")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /Approve/ }),
|
||||
).toBeDisabled();
|
||||
});
|
||||
|
||||
it("only sends captions for platforms left toggled on", async () => {
|
||||
render(withQueryClient(<VideoPostQueue />));
|
||||
await screen.findByText("release");
|
||||
|
||||
// Un-toggle TikTok — its stored caption should NOT be sent on approve.
|
||||
fireEvent.click(screen.getByLabelText("Edit TikTok caption"));
|
||||
fireEvent.click(screen.getByRole("button", { name: /Approve/ }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(approve).toHaveBeenCalledWith("v-1", {
|
||||
x_caption: "RoboCo v0.19.0 is here!",
|
||||
}),
|
||||
);
|
||||
resolveApproveRef.current?.({ status: "posted", posted: {}, detail: "ok" });
|
||||
});
|
||||
|
||||
it("rejects a draft with a reason", async () => {
|
||||
render(withQueryClient(<VideoPostQueue />));
|
||||
await screen.findByText("release");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reject" }));
|
||||
|
||||
const reasonBox = await screen.findByLabelText("Reason");
|
||||
fireEvent.change(reasonBox, { target: { value: "wrong occasion" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reject" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(reject).toHaveBeenCalledWith("v-1", "wrong occasion"),
|
||||
);
|
||||
});
|
||||
|
||||
it("requests an on-demand video with the chosen occasion, brief, and platforms", async () => {
|
||||
render(withQueryClient(<VideoPostQueue />));
|
||||
await screen.findByText("release");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Request a video/ }));
|
||||
fireEvent.change(screen.getByLabelText("Occasion"), {
|
||||
target: { value: "Founder's Day" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Brief"), {
|
||||
target: { value: "Celebrate the founding." },
|
||||
});
|
||||
// Both platforms are checked by default — leave as-is and submit.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Request" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(requestVideo).toHaveBeenCalledWith({
|
||||
occasion: "Founder's Day",
|
||||
brief: "Celebrate the founding.",
|
||||
platforms: ["x", "tiktok"],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("shows an empty-state card (with the request action) when there are no drafts", async () => {
|
||||
listPosts.mockResolvedValueOnce([]);
|
||||
render(withQueryClient(<VideoPostQueue />));
|
||||
expect(await screen.findByText(/No drafts yet/)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /Request a video/ }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import { PrReviewQueue } from "./pr-review-queue";
|
||||
import { ReleaseProposalCard } from "./release-proposal-card";
|
||||
import { PlaybookReviewQueue } from "./playbook-review-queue";
|
||||
import { XPostQueue } from "./x-post-queue";
|
||||
import { VideoPostQueue } from "./video-post-queue";
|
||||
import { RoadmapReviewQueue } from "./roadmap-review-queue";
|
||||
import { StrategySignalsPanel } from "./strategy-signals-panel";
|
||||
import type { Activity } from "./activity-item";
|
||||
@@ -125,6 +126,11 @@ export function CommandCenter() {
|
||||
<XPostQueue />
|
||||
</div>
|
||||
|
||||
{/* Video post queue (always visible — carries the on-demand request action) */}
|
||||
<div className="order-4 md:order-none">
|
||||
<VideoPostQueue />
|
||||
</div>
|
||||
|
||||
{/* Board roadmap queue (hidden when no cycle authored) */}
|
||||
<div className="order-4 md:order-none">
|
||||
<RoadmapReviewQueue />
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { videoApi } from "@/lib/api";
|
||||
import type { VideoCut, VideoPost, VideoPostExecuteResult } from "@/lib/api/video";
|
||||
import {
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { CheckCircle2, Film, Sparkles, XCircle } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const MAX_X_CAPTION_CHARS = 280;
|
||||
const MAX_TIKTOK_CAPTION_CHARS = 2200;
|
||||
const _MIN_REASON_CHARS = 4;
|
||||
|
||||
const PLATFORM_LABELS: Record<string, string> = { x: "X", tiktok: "TikTok" };
|
||||
const REQUEST_PLATFORMS = ["x", "tiktok"] as const;
|
||||
|
||||
// Only one source reaches this queue today; a function (not a literal)
|
||||
// mirrors XPostQueue's sourceMeta pattern and costs nothing to extend later.
|
||||
function sourceMeta() {
|
||||
return { label: "Video", icon: Film };
|
||||
}
|
||||
|
||||
function describeExecuteResult(result: VideoPostExecuteResult): string {
|
||||
if (result.status === "posted") return "Posted to all platforms.";
|
||||
if (result.status === "posted_partial")
|
||||
return `Posted to some platforms — ${result.detail}`;
|
||||
if (result.status === "post_failed") return `Posting failed: ${result.detail}`;
|
||||
if (result.status === "already_posted")
|
||||
return "Already posted — no-op.";
|
||||
if (result.status === "already_in_progress")
|
||||
return "A post is already in progress for this draft.";
|
||||
if (result.status === "no_platforms")
|
||||
return "This draft has no target platforms.";
|
||||
if (result.status === "lock_lost")
|
||||
return "The post lock was lost mid-upload — retry the approve.";
|
||||
if (result.status === "redis_unavailable")
|
||||
return "Redis is unavailable — can't acquire the post lock.";
|
||||
return `${result.status}: ${result.detail}`;
|
||||
}
|
||||
|
||||
// One row of the queue: an MP4 preview (9:16 / 1:1 cut switcher) + per-
|
||||
// platform editable captions + approve/reject. Mirrors XPostRow. Unchecking
|
||||
// a platform's "Edit ... caption" box leaves it disabled (shown, not sent) —
|
||||
// approve always posts every platform already in the draft; the checkbox
|
||||
// only controls whether YOUR edit overrides that platform's stored caption.
|
||||
function VideoPostRow({
|
||||
post,
|
||||
onApprove,
|
||||
onReject,
|
||||
approving,
|
||||
}: {
|
||||
post: VideoPost;
|
||||
onApprove: (
|
||||
taskId: string,
|
||||
captions: { x_caption?: string; tiktok_caption?: string },
|
||||
) => void;
|
||||
onReject: (post: VideoPost) => void;
|
||||
approving: boolean;
|
||||
}) {
|
||||
const [cut, setCut] = useState<VideoCut>("vertical");
|
||||
const [editX, setEditX] = useState(post.platforms.includes("x"));
|
||||
const [editTiktok, setEditTiktok] = useState(post.platforms.includes("tiktok"));
|
||||
const [xCaption, setXCaption] = useState(post.x_caption ?? "");
|
||||
const [tiktokCaption, setTiktokCaption] = useState(post.tiktok_caption ?? "");
|
||||
const [videoSrc, setVideoSrc] = useState<string | null>(null);
|
||||
const meta = sourceMeta();
|
||||
|
||||
// A native <video src> GET doesn't carry axios's auth headers, so fetch
|
||||
// the cut as a Blob (through axios) and drive <video> off an object URL
|
||||
// instead. Re-fetches on cut change; always revokes the previous URL.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let objectUrl: string | null = null;
|
||||
videoApi
|
||||
.getMediaBlob(post.task_id, cut)
|
||||
.then((blob) => {
|
||||
if (cancelled) return;
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
setVideoSrc(objectUrl);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setVideoSrc(null);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
};
|
||||
}, [post.task_id, cut]);
|
||||
|
||||
const xOverLimit = editX && xCaption.length > MAX_X_CAPTION_CHARS;
|
||||
const tiktokOverLimit =
|
||||
editTiktok && tiktokCaption.length > MAX_TIKTOK_CAPTION_CHARS;
|
||||
const overLimit = xOverLimit || tiktokOverLimit;
|
||||
|
||||
const handleApprove = () => {
|
||||
onApprove(post.task_id, {
|
||||
...(editX ? { x_caption: xCaption } : {}),
|
||||
...(editTiktok ? { tiktok_caption: tiktokCaption } : {}),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border p-4 transition-colors hover:bg-muted/50">
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||
<meta.icon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">{meta.label}</span>
|
||||
{post.occasion && <Badge variant="outline">{post.occasion}</Badge>}
|
||||
</div>
|
||||
|
||||
<div className="mb-3 space-y-2">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={cut === "vertical" ? "default" : "outline"}
|
||||
onClick={() => setCut("vertical")}
|
||||
>
|
||||
9:16
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={cut === "square" ? "default" : "outline"}
|
||||
onClick={() => setCut("square")}
|
||||
>
|
||||
1:1
|
||||
</Button>
|
||||
</div>
|
||||
<video
|
||||
key={`${post.task_id}-${cut}`}
|
||||
controls
|
||||
className="mx-auto max-h-96 w-full rounded-md bg-black object-contain"
|
||||
src={videoSrc ?? undefined}
|
||||
>
|
||||
Your browser does not support embedded video.
|
||||
</video>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{post.platforms.includes("x") && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={`${post.task_id}-x-edit`}
|
||||
checked={editX}
|
||||
onCheckedChange={(c) => setEditX(c === true)}
|
||||
/>
|
||||
<Label htmlFor={`${post.task_id}-x-edit`} className="text-sm">
|
||||
Edit X caption
|
||||
</Label>
|
||||
</div>
|
||||
<Textarea
|
||||
value={xCaption}
|
||||
onChange={(e) => setXCaption(e.target.value)}
|
||||
disabled={!editX}
|
||||
rows={2}
|
||||
className={xOverLimit ? "border-destructive" : undefined}
|
||||
/>
|
||||
<p
|
||||
className={`text-right text-xs ${xOverLimit ? "text-destructive" : "text-muted-foreground"}`}
|
||||
>
|
||||
{xCaption.length}/{MAX_X_CAPTION_CHARS}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{post.platforms.includes("tiktok") && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={`${post.task_id}-tiktok-edit`}
|
||||
checked={editTiktok}
|
||||
onCheckedChange={(c) => setEditTiktok(c === true)}
|
||||
/>
|
||||
<Label htmlFor={`${post.task_id}-tiktok-edit`} className="text-sm">
|
||||
Edit TikTok caption
|
||||
</Label>
|
||||
</div>
|
||||
<Textarea
|
||||
value={tiktokCaption}
|
||||
onChange={(e) => setTiktokCaption(e.target.value)}
|
||||
disabled={!editTiktok}
|
||||
rows={2}
|
||||
className={tiktokOverLimit ? "border-destructive" : undefined}
|
||||
/>
|
||||
<p
|
||||
className={`text-right text-xs ${tiktokOverLimit ? "text-destructive" : "text-muted-foreground"}`}
|
||||
>
|
||||
{tiktokCaption.length}/{MAX_TIKTOK_CAPTION_CHARS}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => onReject(post)}
|
||||
>
|
||||
<XCircle className="mr-1 h-4 w-4" />
|
||||
Reject
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
className="bg-green-600 hover:bg-green-700"
|
||||
disabled={approving || overLimit}
|
||||
onClick={handleApprove}
|
||||
>
|
||||
<CheckCircle2 className="mr-1 h-4 w-4" />
|
||||
Approve & post
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// On-demand "Request a video" dialog: occasion + brief + platforms ->
|
||||
// POST /video/request. No X equivalent — video is the only engine with an
|
||||
// on-demand trigger — so this is new, not mirrored.
|
||||
function RequestVideoDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const [occasion, setOccasion] = useState("");
|
||||
const [brief, setBrief] = useState("");
|
||||
const [platforms, setPlatforms] = useState<string[]>(["x", "tiktok"]);
|
||||
|
||||
const requestMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
videoApi.requestVideo({
|
||||
occasion: occasion.trim(),
|
||||
brief: brief.trim(),
|
||||
platforms,
|
||||
}),
|
||||
onSuccess: (result) => {
|
||||
if (result.status === "opened") {
|
||||
toast.success(result.detail);
|
||||
onOpenChange(false);
|
||||
setOccasion("");
|
||||
setBrief("");
|
||||
setPlatforms(["x", "tiktok"]);
|
||||
} else {
|
||||
toast.warning(result.detail);
|
||||
}
|
||||
},
|
||||
onError: (e) =>
|
||||
toast.error(`Request failed: ${e instanceof Error ? e.message : "error"}`),
|
||||
});
|
||||
|
||||
const togglePlatform = (platform: string) => {
|
||||
setPlatforms((prev) =>
|
||||
prev.includes(platform)
|
||||
? prev.filter((p) => p !== platform)
|
||||
: [...prev, platform],
|
||||
);
|
||||
};
|
||||
|
||||
const canSubmit =
|
||||
occasion.trim().length > 0 && brief.trim().length > 0 && platforms.length > 0;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Request a video</DialogTitle>
|
||||
<DialogDescription>
|
||||
Opens a video-authoring task for a UX/UI dev — it rides the
|
||||
normal delivery flow and the rendered clip lands back in this
|
||||
queue once rendering finishes.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="video-request-occasion">Occasion</Label>
|
||||
<Input
|
||||
id="video-request-occasion"
|
||||
placeholder="e.g. v0.19.0 launch, Founder's Day..."
|
||||
value={occasion}
|
||||
onChange={(e) => setOccasion(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="video-request-brief">Brief</Label>
|
||||
<Textarea
|
||||
id="video-request-brief"
|
||||
placeholder="What should this video cover?"
|
||||
value={brief}
|
||||
onChange={(e) => setBrief(e.target.value)}
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Platforms</Label>
|
||||
<div className="flex gap-4">
|
||||
{REQUEST_PLATFORMS.map((platform) => (
|
||||
<div key={platform} className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={`video-request-${platform}`}
|
||||
checked={platforms.includes(platform)}
|
||||
onCheckedChange={() => togglePlatform(platform)}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={`video-request-${platform}`}
|
||||
className="text-sm font-normal"
|
||||
>
|
||||
{PLATFORM_LABELS[platform]}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => requestMutation.mutate()}
|
||||
disabled={!canSubmit || requestMutation.isPending}
|
||||
>
|
||||
{requestMutation.isPending ? "Requesting..." : "Request"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// CEO queue for held video_post drafts (rendered clips from release/
|
||||
// spotlight/on-demand triggers). Hidden while loading; shows an empty-state
|
||||
// card (with the on-demand request action) when there are no drafts yet —
|
||||
// mirrors XPostQueue.
|
||||
export function VideoPostQueue({ className }: { className?: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [rejecting, setRejecting] = useState<VideoPost | null>(null);
|
||||
const [reason, setReason] = useState("");
|
||||
const [approvingId, setApprovingId] = useState<string | null>(null);
|
||||
const [requestOpen, setRequestOpen] = useState(false);
|
||||
|
||||
const { data: posts, isLoading } = useQuery({
|
||||
queryKey: ["video", "posts"],
|
||||
queryFn: () => videoApi.listPosts(),
|
||||
refetchInterval: 30000,
|
||||
});
|
||||
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({ queryKey: ["video", "posts"] });
|
||||
|
||||
const approveMutation = useMutation({
|
||||
mutationFn: ({
|
||||
taskId,
|
||||
captions,
|
||||
}: {
|
||||
taskId: string;
|
||||
captions: { x_caption?: string; tiktok_caption?: string };
|
||||
}) => videoApi.approve(taskId, captions),
|
||||
onSuccess: (result) => {
|
||||
invalidate();
|
||||
if (result.status === "posted") {
|
||||
toast.success(describeExecuteResult(result));
|
||||
} else {
|
||||
toast.warning(describeExecuteResult(result));
|
||||
}
|
||||
},
|
||||
onError: (e) =>
|
||||
toast.error(`Approve failed: ${e instanceof Error ? e.message : "error"}`),
|
||||
onSettled: () => setApprovingId(null),
|
||||
});
|
||||
|
||||
const rejectMutation = useMutation({
|
||||
mutationFn: ({ taskId, reason }: { taskId: string; reason: string }) =>
|
||||
videoApi.reject(taskId, reason),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
toast.success("Draft rejected");
|
||||
closeReject();
|
||||
},
|
||||
onError: (e) =>
|
||||
toast.error(`Reject failed: ${e instanceof Error ? e.message : "error"}`),
|
||||
});
|
||||
|
||||
const closeReject = () => {
|
||||
setRejecting(null);
|
||||
setReason("");
|
||||
};
|
||||
|
||||
const confirmReject = () => {
|
||||
if (!rejecting) return;
|
||||
if (reason.trim().length < _MIN_REASON_CHARS) {
|
||||
toast.error("Give a brief reason for rejecting");
|
||||
return;
|
||||
}
|
||||
rejectMutation.mutate({ taskId: rejecting.task_id, reason: reason.trim() });
|
||||
};
|
||||
|
||||
const handleApprove = (
|
||||
taskId: string,
|
||||
captions: { x_caption?: string; tiktok_caption?: string },
|
||||
) => {
|
||||
setApprovingId(taskId);
|
||||
approveMutation.mutate({ taskId, captions });
|
||||
};
|
||||
|
||||
if (isLoading) return null;
|
||||
|
||||
const requestButton = (
|
||||
<Button variant="outline" size="sm" onClick={() => setRequestOpen(true)}>
|
||||
<Sparkles className="mr-1 h-4 w-4" />
|
||||
Request a video
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (!posts || posts.length === 0) {
|
||||
return (
|
||||
<>
|
||||
<Card className={className}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Film className="h-5 w-5" />
|
||||
Video Post Queue
|
||||
</CardTitle>
|
||||
<CardAction>{requestButton}</CardAction>
|
||||
<CardDescription>
|
||||
Rendered clips from a release, a feature spotlight, or a request
|
||||
below land here for you to preview, edit captions, approve, or
|
||||
reject. Nothing posts on its own.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No drafts yet. Set your keys in Settings → X (Twitter) / TikTok
|
||||
Credentials and enable the video engine — or request one on
|
||||
demand above.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<RequestVideoDialog open={requestOpen} onOpenChange={setRequestOpen} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card className={className}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Film className="h-5 w-5" />
|
||||
Video Post Queue
|
||||
<Badge variant="secondary">{posts.length}</Badge>
|
||||
</CardTitle>
|
||||
<CardAction>{requestButton}</CardAction>
|
||||
<CardDescription>
|
||||
Rendered clips — preview both cuts, edit captions, approve (posts
|
||||
to the target platforms), or reject. Nothing posts on its own.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{posts.map((post) => (
|
||||
<VideoPostRow
|
||||
key={post.task_id}
|
||||
post={post}
|
||||
onApprove={handleApprove}
|
||||
onReject={setRejecting}
|
||||
approving={approvingId === post.task_id}
|
||||
/>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={!!rejecting} onOpenChange={() => closeReject()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reject draft</DialogTitle>
|
||||
<DialogDescription>
|
||||
This cancels the draft — it will not be posted. Give a brief
|
||||
reason (it is recorded).
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="video-reject-reason">Reason</Label>
|
||||
<Textarea
|
||||
id="video-reject-reason"
|
||||
placeholder="e.g. off-brand tone, wrong occasion..."
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={closeReject}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={confirmReject}
|
||||
disabled={rejectMutation.isPending}
|
||||
>
|
||||
{rejectMutation.isPending ? "Rejecting..." : "Reject"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<RequestVideoDialog open={requestOpen} onOpenChange={setRequestOpen} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
const { getCredentialsStatus, setCredentials } = vi.hoisted(() => ({
|
||||
getCredentialsStatus: vi.fn(async () => ({ has_credentials: false })),
|
||||
setCredentials: vi.fn(async () => ({ has_credentials: true })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
videoApi: { getCredentialsStatus, setCredentials },
|
||||
}));
|
||||
|
||||
import { TikTokCredentialsForm } from "../tiktok-credentials-card";
|
||||
|
||||
function withQueryClient(ui: ReactNode) {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
return <QueryClientProvider client={client}>{ui}</QueryClientProvider>;
|
||||
}
|
||||
|
||||
describe("TikTokCredentialsForm", () => {
|
||||
beforeEach(() => {
|
||||
getCredentialsStatus.mockClear();
|
||||
setCredentials.mockClear();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("shows 'no credentials configured' by default and never renders a secret", async () => {
|
||||
render(withQueryClient(<TikTokCredentialsForm />));
|
||||
expect(
|
||||
await screen.findByText("No credentials configured"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disables Save until all 4 fields are filled", async () => {
|
||||
render(withQueryClient(<TikTokCredentialsForm />));
|
||||
await screen.findByText("No credentials configured");
|
||||
const saveButton = screen.getByRole("button", { name: "Save" });
|
||||
expect(saveButton).toBeDisabled();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Client key"), {
|
||||
target: { value: "ck" },
|
||||
});
|
||||
expect(saveButton).toBeDisabled(); // still 3 unfilled
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Client secret"), {
|
||||
target: { value: "cs" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Access token"), {
|
||||
target: { value: "at" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Refresh token"), {
|
||||
target: { value: "rt" },
|
||||
});
|
||||
expect(saveButton).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it("saves all 4 secrets and clears the inputs on success", async () => {
|
||||
render(withQueryClient(<TikTokCredentialsForm />));
|
||||
await screen.findByText("No credentials configured");
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Client key"), {
|
||||
target: { value: "ck" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Client secret"), {
|
||||
target: { value: "cs" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Access token"), {
|
||||
target: { value: "at" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Refresh token"), {
|
||||
target: { value: "rt" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(setCredentials).toHaveBeenCalledWith({
|
||||
client_key: "ck",
|
||||
client_secret: "cs",
|
||||
access_token: "at",
|
||||
refresh_token: "rt",
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
(screen.getByLabelText("Client key") as HTMLInputElement).value,
|
||||
).toBe(""),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible";
|
||||
import { XCredentialsForm } from "@/components/settings/x-credentials-card";
|
||||
import { TikTokCredentialsForm } from "@/components/settings/tiktok-credentials-card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Flag, ChevronDown, ChevronRight } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
@@ -68,11 +69,18 @@ const FLAG_DESCRIPTIONS: Record<string, string> = {
|
||||
"Weekly: the Product Owner explores the company's projects and proposes a themed cycle of 3-7 roadmap items — you approve or reject each one individually; approved items land in the backlog and nothing auto-starts.",
|
||||
fable_mode_enabled:
|
||||
"Compose the Fable behavioral doctrine into every agent's system prompt and install the matching turn-discipline/honesty/verification hooks at spawn (both Claude Code and grok runtimes). Off by default; spawn path is byte-for-byte unchanged.",
|
||||
video_engine_enabled:
|
||||
"Master switch for the video-generation engine — a UX/UI dev authors a bespoke Remotion composition per trigger, then a render pass produces the 9:16/1:1 MP4 and holds it here as a draft. Even when on, distribution needs an explicit per-clip approval below; set X / TikTok credentials to post.",
|
||||
video_on_release:
|
||||
"Also open a video-authoring task when a release publishes. Off by default even with video_engine_enabled on.",
|
||||
video_on_spotlight:
|
||||
"Also open a video-authoring task when you approve a feature-spotlight draft that requests one. Off by default even with video_engine_enabled on.",
|
||||
};
|
||||
|
||||
export function FeatureFlagsCard() {
|
||||
const queryClient = useQueryClient();
|
||||
const [xCredsOpen, setXCredsOpen] = useState(false);
|
||||
const [tiktokCredsOpen, setTiktokCredsOpen] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["feature-flags"],
|
||||
@@ -124,12 +132,13 @@ export function FeatureFlagsCard() {
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
{flags.map((flag) => {
|
||||
const isXEngine = flag.key === "x_engine_enabled";
|
||||
const isVideoEngine = flag.key === "video_engine_enabled";
|
||||
return (
|
||||
<div
|
||||
key={flag.key}
|
||||
className={cn(
|
||||
"rounded-lg border p-4",
|
||||
isXEngine && "md:col-span-2",
|
||||
(isXEngine || isVideoEngine) && "md:col-span-2",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
@@ -176,6 +185,31 @@ export function FeatureFlagsCard() {
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
{isVideoEngine && (
|
||||
<Collapsible
|
||||
open={tiktokCredsOpen}
|
||||
onOpenChange={setTiktokCredsOpen}
|
||||
className="mt-3"
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full justify-between px-2 text-muted-foreground"
|
||||
>
|
||||
<span className="text-sm">TikTok credentials</span>
|
||||
{tiktokCredsOpen ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="pt-3">
|
||||
<TikTokCredentialsForm />
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { videoApi } from "@/lib/api";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Key, KeyRound, Save } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const FIELDS: Array<{
|
||||
key: "client_key" | "client_secret" | "access_token" | "refresh_token";
|
||||
label: string;
|
||||
}> = [
|
||||
{ key: "client_key", label: "Client key" },
|
||||
{ key: "client_secret", label: "Client secret" },
|
||||
{ key: "access_token", label: "Access token" },
|
||||
{ key: "refresh_token", label: "Refresh token" },
|
||||
];
|
||||
|
||||
// The CEO's one-time (or rotate) entry of the 4 OAuth2 secrets from the
|
||||
// TikTok developer app. Write-only — the stored values are never displayed
|
||||
// back, only whether they're set (mirrors x-credentials-card.tsx). Rendered
|
||||
// chrome-less so it can nest inside the video-engine feature-flag row.
|
||||
export function TikTokCredentialsForm() {
|
||||
const queryClient = useQueryClient();
|
||||
const [values, setValues] = useState({
|
||||
client_key: "",
|
||||
client_secret: "",
|
||||
access_token: "",
|
||||
refresh_token: "",
|
||||
});
|
||||
|
||||
const { data: status, isLoading } = useQuery({
|
||||
queryKey: ["video", "tiktok-credentials"],
|
||||
queryFn: () => videoApi.getCredentialsStatus(),
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: () => videoApi.setCredentials(values),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["video", "tiktok-credentials"],
|
||||
});
|
||||
setValues({
|
||||
client_key: "",
|
||||
client_secret: "",
|
||||
access_token: "",
|
||||
refresh_token: "",
|
||||
});
|
||||
toast.success("TikTok credentials saved");
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(
|
||||
`Failed to save: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const allFilled = FIELDS.every((f) => values[f.key].trim().length > 0);
|
||||
const noneFilled = FIELDS.every((f) => values[f.key].trim().length === 0);
|
||||
// A genuine save is either "set all 4" or, when something is already
|
||||
// stored, "clear all 4". All-empty with nothing stored is a true no-op.
|
||||
const canSave = allFilled || (noneFilled && !!status?.has_credentials);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The 4 OAuth2 secrets from your TikTok developer app. Stored encrypted
|
||||
server-side; agents never see them and this panel never displays them
|
||||
again once saved.
|
||||
</p>
|
||||
|
||||
<div className="flex items-center gap-2 rounded-md border p-3">
|
||||
{status?.has_credentials ? (
|
||||
<>
|
||||
<Key className="h-4 w-4 text-green-500" />
|
||||
<span className="text-sm text-green-600 dark:text-green-400">
|
||||
Credentials are set
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<KeyRound className="h-4 w-4 text-amber-500" />
|
||||
<span className="text-sm text-amber-600 dark:text-amber-400">
|
||||
{isLoading ? "Checking..." : "No credentials configured"}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{FIELDS.map((field) => (
|
||||
<div key={field.key} className="space-y-2">
|
||||
<Label htmlFor={`tiktok-cred-${field.key}`}>
|
||||
{status?.has_credentials ? `Replace ${field.label}` : field.label}
|
||||
</Label>
|
||||
<Input
|
||||
id={`tiktok-cred-${field.key}`}
|
||||
type="password"
|
||||
value={values[field.key]}
|
||||
onChange={(e) =>
|
||||
setValues((prev) => ({ ...prev, [field.key]: e.target.value }))
|
||||
}
|
||||
placeholder="••••••••••••"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Set all 4 to save (or rotate); leave all 4 blank and save to clear.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={() => saveMutation.mutate()}
|
||||
disabled={saveMutation.isPending || !canSave}
|
||||
>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{saveMutation.isPending ? "Saving..." : "Save"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user