Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions apps/web/src/app/studio/__tests__/actions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('@/lib/github-pr-client', () => ({
createOrUpdatePullRequestsForApprovedSpecs: vi.fn(),
}));

vi.mock('next/headers', () => ({
headers: vi.fn(async () => new Headers()),
}));

vi.mock('@/lib/billing/billing-context', () => ({
resolveTrustedBillingEmail: vi.fn(async () => 'pro@example.com'),
}));

vi.mock('@/lib/billing/entitlement-store', () => ({
isProSubscriber: vi.fn(async () => true),
}));

import { openGitHubPrsForApprovedSpecs } from '@/app/studio/actions';
import { createOrUpdatePullRequestsForApprovedSpecs } from '@/lib/github-pr-client';
import { isProSubscriber } from '@/lib/billing/entitlement-store';

const mockedOpen = vi.mocked(createOrUpdatePullRequestsForApprovedSpecs);
const mockedIsPro = vi.mocked(isProSubscriber);

describe('openGitHubPrsForApprovedSpecs', () => {
const originalToken = process.env.GITHUB_TOKEN;
const originalRepo = process.env.GITHUB_REPOSITORY;

beforeEach(() => {
vi.clearAllMocks();
process.env.GITHUB_TOKEN = 'test-token';
process.env.GITHUB_REPOSITORY = 'octo/eventrelay';
});

afterEach(() => {
if (originalToken === undefined) delete process.env.GITHUB_TOKEN;
else process.env.GITHUB_TOKEN = originalToken;
if (originalRepo === undefined) delete process.env.GITHUB_REPOSITORY;
else process.env.GITHUB_REPOSITORY = originalRepo;
});

it('refuses callers without a Pro entitlement', async () => {
mockedIsPro.mockResolvedValueOnce(false);

const result = await openGitHubPrsForApprovedSpecs([
{ id: 'spec-1', title: 'Approved', body: 'Body', head: 'spec/approved', approved: true },
]);

expect(result.ok).toBe(false);
expect(result.error).toMatch(/pro subscription/i);
expect(mockedOpen).not.toHaveBeenCalled();
});

it('fails closed when no spec is approved', async () => {
const result = await openGitHubPrsForApprovedSpecs([
{ id: 'spec-1', title: 'Spec', body: 'Body', head: 'spec/one', approved: false },
]);

expect(result.ok).toBe(false);
expect(result.error).toMatch(/approve at least one spec/i);
expect(mockedOpen).not.toHaveBeenCalled();
});

it('calls the GitHub write flow with only approved specs', async () => {
mockedOpen.mockResolvedValue([
{ specId: 'spec-1', number: 10, htmlUrl: 'https://github.com/o/r/pull/10', action: 'created' },
]);

const result = await openGitHubPrsForApprovedSpecs([
{ id: 'spec-1', title: 'Approved', body: 'Body', head: 'spec/approved', approved: true },
{ id: 'spec-2', title: 'Skipped', body: 'Body', head: 'spec/skipped', approved: false },
]);

expect(result.ok).toBe(true);
expect(mockedOpen).toHaveBeenCalledWith(
[
{ id: 'spec-1', title: 'Approved', body: 'Body', head: 'spec/approved', approved: true },
],
expect.objectContaining({
owner: 'octo',
repo: 'eventrelay',
token: 'test-token',
}),
);
});

it('fails closed when GitHub integration is not configured', async () => {
delete process.env.GITHUB_TOKEN;
const result = await openGitHubPrsForApprovedSpecs([
{ id: 'spec-1', title: 'Approved', body: 'Body', head: 'spec/approved', approved: true },
]);

expect(result.ok).toBe(false);
expect(result.error).toMatch(/not configured/i);
expect(mockedOpen).not.toHaveBeenCalled();
});
});
95 changes: 95 additions & 0 deletions apps/web/src/app/studio/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
'use server';

import 'server-only';
import { headers } from 'next/headers';
import {
createOrUpdatePullRequestsForApprovedSpecs,
type ApprovedSpecPullRequestInput,
type GitHubPullRequestWriteResult,
} from '@/lib/github-pr-client';
import { resolveTrustedBillingEmail } from '@/lib/billing/billing-context';
import { isProSubscriber } from '@/lib/billing/entitlement-store';

export interface OpenGitHubPrsResult {
ok: boolean;
error?: string;
pullRequests: GitHubPullRequestWriteResult[];
}

function parseRepository(value: string): { owner: string; repo: string } | null {
const [owner, repo, ...rest] = value.trim().split('/');
if (!owner || !repo || rest.length > 0) return null;
return { owner, repo };
}

/**
* Resolve the trusted billing identity for this server action.
*
* Server actions POST to the page path, and `/studio` is intentionally public
* (see auth-paths.ts), so the middleware auth gate does *not* run here. Without
* an explicit check any anonymous visitor could invoke this action and drive
* GitHub writes with the server's GITHUB_TOKEN. We rebuild a minimal Request
* from the incoming cookies so the same trusted-identity resolution used by
* privileged API routes (session email → signed billing cookie) applies here.
*/
async function resolveActionBillingEmail(): Promise<string | null> {
const cookieHeader = (await headers()).get('cookie') ?? '';
const request = new Request('https://studio.internal/studio', {
headers: { cookie: cookieHeader },
});
return resolveTrustedBillingEmail(request);
}

export async function openGitHubPrsForApprovedSpecs(
Comment thread
vercel[bot] marked this conversation as resolved.
specs: ApprovedSpecPullRequestInput[],
): Promise<OpenGitHubPrsResult> {
// Authorize before touching any server-side GitHub credentials. Opening PRs
// in the configured repository is a privileged, Pro-gated action — the same
// entitlement class as agent dispatch — so anonymous/free callers are refused
// before any GitHub API request is made.
const billingEmail = await resolveActionBillingEmail();
if (!(await isProSubscriber(billingEmail))) {
return {
ok: false,
error: 'Opening GitHub pull requests requires a Pro subscription. Upgrade at /pricing.',
pullRequests: [],
};
}

const approvedSpecs = specs.filter((spec) => spec.approved);
if (approvedSpecs.length === 0) {
return {
ok: false,
error: 'Approve at least one spec before opening GitHub pull requests.',
pullRequests: [],
};
}

const token = (process.env.GITHUB_TOKEN || '').trim();
const repository = parseRepository(process.env.GITHUB_REPOSITORY || '');
if (!token || !repository) {
return {
ok: false,
error: 'GitHub integration is not configured.',
pullRequests: [],
};
}

try {
const pullRequests = await createOrUpdatePullRequestsForApprovedSpecs(
approvedSpecs,
{
owner: repository.owner,
repo: repository.repo,
token,
},
);
return { ok: true, pullRequests };
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : 'Could not open GitHub pull requests.',
pullRequests: [],
};
}
}
77 changes: 74 additions & 3 deletions apps/web/src/components/OneLoopStudio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { FormEvent, useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { Download, Play, Rocket } from 'lucide-react';
import { Download, GitPullRequest, Play, Rocket } from 'lucide-react';
import { formatSeconds, parseTimestampToSeconds, extractYouTubeId } from '@/lib/timestamp';
import { applyPackStackChecks, compileLinkedSop, type LinkedSop } from '@/lib/linked-sop';
import {
Expand Down Expand Up @@ -77,6 +77,7 @@
import { CANONICAL_STUDIO_PATH } from '@/lib/auth-paths';
import type { ExtractedEvent } from '@/lib/types';
import type { VideoPackArchitecture, VideoPackArtifact } from '@/lib/video-pack-types';
import { openGitHubPrsForApprovedSpecs } from '@/app/studio/actions';

const FIXTURE = 'https://www.youtube.com/watch?v=auJzb1D-fag';

Expand All @@ -101,6 +102,15 @@
return extractYouTubeId(url) || '';
}

function toSpecBranch(videoId: string, stepId: string): string {
const slug = `${videoId || 'video'}-${stepId}`
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 48);
return `spec/${slug || 'approved'}`;
}

function mapExtractedEvents(raw: unknown[], videoId: string): ExtractedEvent[] {
return raw
.filter((item): item is Record<string, unknown> => Boolean(item) && typeof item === 'object')
Expand Down Expand Up @@ -236,6 +246,8 @@
const [deployReceiptVideoId, setDeployReceiptVideoId] = useState<string | null>(null);
const [gateReceipt, setGateReceipt] = useState<StudioGateReceiptView | null>(null);
const [completedChecks, setCompletedChecks] = useState<string[]>([]);
const [approvedSpecIds, setApprovedSpecIds] = useState<string[]>([]);
const [openingPrs, setOpeningPrs] = useState(false);
const [playerEpoch, setPlayerEpoch] = useState(0);
const [exportToast, setExportToast] = useState<{ tone: 'success' | 'error'; text: string } | null>(
null,
Expand Down Expand Up @@ -292,6 +304,7 @@

useEffect(() => {
setCompletedChecks([]);
setApprovedSpecIds([]);
setDeployReceiptUrl(null);
setDeployReceiptVideoId(null);
}, [selectedVideoId]);
Expand Down Expand Up @@ -479,7 +492,7 @@
const started = await startVideoToActions(payload);
if (!started.ok || !started.runId) {
if (started.status === 401 || started.status === 403) {
window.location.href = `/login?callbackUrl=${encodeURIComponent(CANONICAL_STUDIO_PATH)}`;

Check warning on line 495 in apps/web/src/components/OneLoopStudio.tsx

View workflow job for this annotation

GitHub Actions / lint-frontend

Do not use `window.location.href` to navigate to internal Next.js pages. Use `redirect()` in the render phase, or `useRouter().push()` in Client Components' event handlers instead. See: https://nextjs.org/docs/messages/no-location-assign-relative-destination

Check warning on line 495 in apps/web/src/components/OneLoopStudio.tsx

View workflow job for this annotation

GitHub Actions / build

Do not use `window.location.href` to navigate to internal Next.js pages. Use `redirect()` in the render phase, or `useRouter().push()` in Client Components' event handlers instead. See: https://nextjs.org/docs/messages/no-location-assign-relative-destination
return;
}
setMessage(started.error || started.message || 'Could not start Act.');
Expand Down Expand Up @@ -597,7 +610,7 @@
transcript: usableProvidedTranscript(selected?.transcript),
});
if (started.status === 401 || started.status === 403) {
window.location.href = `/login?callbackUrl=${encodeURIComponent(CANONICAL_STUDIO_PATH)}`;

Check warning on line 613 in apps/web/src/components/OneLoopStudio.tsx

View workflow job for this annotation

GitHub Actions / lint-frontend

Do not use `window.location.href` to navigate to internal Next.js pages. Use `redirect()` in the render phase, or `useRouter().push()` in Client Components' event handlers instead. See: https://nextjs.org/docs/messages/no-location-assign-relative-destination

Check warning on line 613 in apps/web/src/components/OneLoopStudio.tsx

View workflow job for this annotation

GitHub Actions / build

Do not use `window.location.href` to navigate to internal Next.js pages. Use `redirect()` in the render phase, or `useRouter().push()` in Client Components' event handlers instead. See: https://nextjs.org/docs/messages/no-location-assign-relative-destination
return;
}
if (!started.ok || !started.runId) {
Expand Down Expand Up @@ -655,6 +668,35 @@
}
};

const openApprovedSpecsPrs = async () => {
if (!linkedSop || linkedSop.steps.length === 0) {
setMessage('Analyze a video with SOP steps before opening GitHub pull requests.');
return;
}
const sourceVideoId = getYouTubeId(selected?.url || url || '');
const specs = linkedSop.steps.map((step) => ({
id: step.id,
title: step.title,
body: [step.description || '', step.quote ? `\nQuote: ${step.quote}` : ''].join('').trim(),
head: toSpecBranch(sourceVideoId, step.id),
base: 'main',
approved: approvedSpecIds.includes(step.id),
}));
setOpeningPrs(true);
try {
const result = await openGitHubPrsForApprovedSpecs(specs);
if (!result.ok) {
setMessage(result.error || 'Could not open GitHub pull requests for approved specs.');
return;
}
setMessage(`Opened or updated ${result.pullRequests.length} GitHub pull request(s) for approved specs.`);
} catch (error) {
setMessage(error instanceof Error ? error.message : 'Could not open GitHub pull requests.');
} finally {
setOpeningPrs(false);
}
};

const transcriptStage = studioTranscriptStage({
busy: transcriptWorking,
elapsedSeconds: elapsed,
Expand Down Expand Up @@ -1008,7 +1050,9 @@
{linkedSop.steps.length === 0 && (
<li className="px-4 py-3 text-sm text-white/40">No ordered SOP in this run.</li>
)}
{linkedSop.steps.map((step) => (
{linkedSop.steps.map((step) => {
const approved = approvedSpecIds.includes(step.id);
return (
<li key={step.id} className="grid gap-1 px-4 py-3 sm:grid-cols-[7rem_1fr]">
{step.timestamp != null ? (
<button
Expand All @@ -1022,13 +1066,29 @@
<div className="font-mono text-[11px] text-white/35">{step.order}</div>
)}
<div>
<label className="mb-1 inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-white/45">
<input
type="checkbox"
checked={approved}
onChange={() =>
setApprovedSpecIds((current) =>
current.includes(step.id)
? current.filter((id) => id !== step.id)
: [...current, step.id],
)
}
className="h-3.5 w-3.5 accent-[#e8b86d]"
/>
Approved for PR
</label>
<div className="text-sm font-medium text-white">{step.title}</div>
{step.description && (
<div className="mt-0.5 text-sm text-white/55">{step.description}</div>
)}
</div>
</li>
))}
);
})}
</ol>

{stackChecks.length > 0 && (
Expand Down Expand Up @@ -1256,6 +1316,17 @@
<Rocket className="h-4 w-4" aria-hidden />
{deployBusy ? 'Attempting deploy…' : studioDeployButtonLabel(Boolean(scopedDeployReceipt))}
</button>
<button
type="button"
data-testid="studio-open-prs-button"
onClick={() => void openApprovedSpecsPrs()}
disabled={openingPrs || approvedSpecIds.length === 0}
title={approvedSpecIds.length === 0 ? 'Approve at least one SOP spec first.' : undefined}
className="inline-flex items-center gap-2 rounded-lg border border-white/15 px-4 py-2 text-sm disabled:opacity-40"
>
<GitPullRequest className="h-4 w-4" aria-hidden />
{openingPrs ? 'Opening PRs…' : `Open GitHub PRs (${approvedSpecIds.length})`}
</button>
{holdReason && (
<p className="basis-full text-xs text-[#e8b86d] sm:basis-auto sm:max-w-xl">
{holdReason}
Expand Down
Loading
Loading