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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
/coverage
/.playwright-mcp
/artifacts/mcp-file-ingest-e2e/
/artifacts/mcp-studio-images-e2e/
/tmp

# next.js
Expand Down
2 changes: 2 additions & 0 deletions app/[locale]/(routes)/oauth/consent/oauth-consent-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ const SCOPE_TRANSLATION_KEYS: Record<DirectMcpOAuthScope, string> = {
'knowledge:search': 'knowledgeSearch',
'knowledge:read': 'knowledgeRead',
'knowledge:write': 'knowledgeWrite',
'studio:read': 'studioRead',
'studio:generate': 'studioGenerate',
'knowledge:assets': 'knowledgeAssets',
};

Expand Down
228 changes: 2 additions & 226 deletions app/api/studio/references/assets/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,107 +3,10 @@
* Lists available media files from studio outputs, studio asset references, and user uploads
*/
import { NextRequest, NextResponse } from 'next/server';
import fs from 'node:fs/promises';
import { auth } from '@/app/lib/auth';
import type { FileNode } from '@/app/lib/filesystem/workspace-files';
import { buildGenericFileTree } from '@/app/lib/filesystem/workspace-files';
import {
getStudioAssetEntityPath,
getStudioAssetsRoot,
getStudioEditsRoot,
getStudioWorkspaceVirtualRoot,
} from '@/app/lib/integrations/studio-workspace';
import { toMediaUrl, toPreviewUrl } from '@/app/lib/utils/media-url';
import { rateLimit } from '@/app/lib/utils/rate-limit';
import { db } from '@/app/lib/db';
import { studioGenerationOutputs, studioGenerations } from '@/app/lib/db/schema';
import { and, desc, eq } from 'drizzle-orm';
import { studioVisibilityCondition } from '@/app/lib/integrations/studio-scope';
import { requireStudioRequestScope } from '@/app/lib/integrations/studio-request-scope';

const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'webp', 'bmp', 'tif', 'tiff', 'gif']);
const VIDEO_EXTENSIONS = new Set(['mp4', 'mov']);
const AUDIO_EXTENSIONS = new Set(['mp3', 'wav']);
const IMAGE_GRID_PREVIEW_WIDTH = 256;
const DEFAULT_MEDIA_PREVIEW_WIDTH = 480;
type AssetKind = 'image' | 'video' | 'audio';

function getExtension(filePath: string): string {
const ext = filePath.split('.').pop();
return ext ? ext.toLowerCase() : '';
}

function walkFiles(nodes: FileNode[], list: FileNode[] = []): FileNode[] {
for (const node of nodes) {
if (node.type === 'file') {
list.push(node);
}
if (node.children?.length) {
walkFiles(node.children, list);
}
}
return list;
}

function getKind(extension: string): AssetKind | null {
if (IMAGE_EXTENSIONS.has(extension)) return 'image';
if (VIDEO_EXTENSIONS.has(extension)) return 'video';
if (AUDIO_EXTENSIONS.has(extension)) return 'audio';
return null;
}

function matchesKind(extension: string, requestedKind: AssetKind): boolean {
return getKind(extension) === requestedKind;
}

function getAssetPreviewUrl(filePath: string, kind: AssetKind, workspaceId: string): string {
if (kind === 'image') {
return toPreviewUrl(filePath, IMAGE_GRID_PREVIEW_WIDTH, { preset: 'mini', workspaceId });
}

return toPreviewUrl(filePath, DEFAULT_MEDIA_PREVIEW_WIDTH, { workspaceId });
}

interface AssetItem {
path: string;
name: string;
kind: AssetKind;
size?: number;
modified?: number;
mediaUrl: string;
previewUrl: string;
}

function isVeoGenerationOutput(outputMetadata: string | null, generationProvider: string | null, generationModel: string | null): boolean {
if (generationProvider === 'veo' && generationModel?.startsWith('veo-')) {
return true;
}

if (!outputMetadata) {
return false;
}

try {
const parsed = JSON.parse(outputMetadata) as { provider?: unknown; model?: unknown };
return parsed.provider === 'gemini' && typeof parsed.model === 'string' && parsed.model.startsWith('veo-');
} catch {
return false;
}
}

async function safeBuildGenericFileTree(absoluteBasePath: string, depth: number): Promise<FileNode[]> {
try {
await fs.access(absoluteBasePath);
} catch {
await fs.mkdir(absoluteBasePath, { recursive: true });
return [];
}
try {
return await buildGenericFileTree(absoluteBasePath, '.', depth);
} catch {
return [];
}
}
import { listStudioReferenceAssets, type AssetKind } from '@/app/lib/integrations/studio-reference-assets';

export async function GET(request: NextRequest) {
const session = await auth.api.getSession({ headers: request.headers });
Expand Down Expand Up @@ -133,134 +36,7 @@ export async function GET(request: NextRequest) {
const limit = Number.isFinite(limitRaw) ? Math.max(1, Math.min(limitRaw, 500)) : 300;
const depthRaw = Number(searchParams.get('depth') || '8');
const depth = Number.isFinite(depthRaw) ? Math.max(1, Math.min(depthRaw, 12)) : 8;
const studioVisibility = studioVisibilityCondition(scope, {
workspaceId: studioGenerations.workspaceId,
createdByUserId: studioGenerations.createdByUserId,
});

if (veoOnly) {
if (requestedKind !== 'video') {
return NextResponse.json({ success: true, data: [], total: 0 });
}

const rows = await db.select({
filePath: studioGenerationOutputs.filePath,
fileName: studioGenerationOutputs.fileName,
fileSize: studioGenerationOutputs.fileSize,
mimeType: studioGenerationOutputs.mimeType,
metadata: studioGenerationOutputs.metadata,
createdAt: studioGenerationOutputs.createdAt,
provider: studioGenerations.provider,
model: studioGenerations.model,
})
.from(studioGenerationOutputs)
.innerJoin(studioGenerations, eq(studioGenerationOutputs.generationId, studioGenerations.id))
.where(and(
studioVisibility,
eq(studioGenerationOutputs.type, 'video'),
))
.orderBy(desc(studioGenerationOutputs.createdAt))
.limit(limit);

const filtered = rows
.filter((row) => row.filePath && isVeoGenerationOutput(row.metadata, row.provider, row.model))
.filter((row) => !query || row.filePath.toLowerCase().includes(query) || (row.fileName || '').toLowerCase().includes(query))
.map((row): AssetItem => ({
path: row.filePath.startsWith('studio/') ? row.filePath : `studio/outputs/${row.filePath}`,
name: row.fileName || row.filePath.split('/').pop() || row.filePath,
kind: 'video',
size: row.fileSize ?? undefined,
modified: row.createdAt?.getTime(),
mediaUrl: toMediaUrl(row.filePath, { workspaceId: scope.workspaceId }),
previewUrl: getAssetPreviewUrl(row.filePath, 'video', scope.workspaceId),
}));

return NextResponse.json({
success: true,
data: filtered,
total: filtered.length,
});
}

const outputType = requestedKind === 'audio' ? 'sound' : requestedKind;
const outputRows = await db.select({
filePath: studioGenerationOutputs.filePath,
fileName: studioGenerationOutputs.fileName,
fileSize: studioGenerationOutputs.fileSize,
createdAt: studioGenerationOutputs.createdAt,
type: studioGenerationOutputs.type,
})
.from(studioGenerationOutputs)
.innerJoin(studioGenerations, eq(studioGenerationOutputs.generationId, studioGenerations.id))
.where(and(
studioVisibility,
eq(studioGenerationOutputs.type, outputType),
))
.orderBy(desc(studioGenerationOutputs.createdAt))
.limit(limit);
// Scan aspect-ratio edits in this workspace's Studio edits directory.
const editsTree = await safeBuildGenericFileTree(getStudioEditsRoot(scope.storage), depth);
const referencesTree = await safeBuildGenericFileTree(
getStudioAssetsRoot(scope.storage) + '/references',
depth,
);

const allFiles = [
...outputRows.map((row): FileNode => ({
type: 'file',
name: row.fileName || row.filePath.split('/').pop() || row.filePath,
path: row.filePath.startsWith('studio/') ? row.filePath : `studio/outputs/${row.filePath}`,
size: row.fileSize ?? undefined,
modified: row.createdAt ? Math.floor(row.createdAt.getTime() / 1000) : undefined,
})),
...walkFiles(editsTree).map((n) => ({
...n,
path: n.path.startsWith('studio/')
? n.path
: `${getStudioWorkspaceVirtualRoot(scope.storage)}/edits/${n.path}`,
})),
...walkFiles(referencesTree).map((n) => ({
...n,
path: n.path.startsWith('studio/')
? n.path
: `${getStudioAssetEntityPath(scope.storage, 'references')}/${n.path}`,
})),
];

const filtered: AssetItem[] = [];
for (const file of allFiles) {
const ext = getExtension(file.path);
if (!matchesKind(ext, requestedKind)) {
continue;
}
const kind = getKind(ext) || requestedKind;

if (query && !file.path.toLowerCase().includes(query) && !file.name.toLowerCase().includes(query)) {
continue;
}

filtered.push({
path: file.path,
name: file.name,
kind,
size: file.size,
modified: file.modified,
mediaUrl: toMediaUrl(file.path, { workspaceId: scope.workspaceId }),
previewUrl: getAssetPreviewUrl(file.path, kind, scope.workspaceId),
});
}

filtered.sort((a, b) => {
const modifiedA = a.modified || 0;
const modifiedB = b.modified || 0;
return modifiedB - modifiedA;
});

return NextResponse.json({
success: true,
data: filtered.slice(0, limit),
total: filtered.length,
});
return NextResponse.json(await listStudioReferenceAssets(scope, { requestedKind, query, limit, depth, veoOnly }));
} catch (error) {
console.error('[API] studio/references/assets error:', error);
const message = error instanceof Error ? error.message : 'Failed to load studio reference assets';
Expand Down
11 changes: 11 additions & 0 deletions app/lib/integrations/media-reference-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,17 @@ async function readFilesystemReference(
let lastError: unknown = null;
for (const candidate of candidates) {
try {
if (ref.relativePath.startsWith('studio/organizations/') || ref.relativePath.startsWith('studio/system/')) {
const dataRoot = path.resolve(resolveCanvasDataRoot());
const studioPath = path.resolve(candidate);
if (!studioPath.startsWith(dataRoot + path.sep)) {
throw new Error('Invalid Studio reference storage path.');
}
const canonicalRoot = await fs.realpath(dataRoot);
if (await fs.realpath(studioPath) !== path.join(canonicalRoot, ref.relativePath)) {
throw new Error('Invalid Studio reference storage path.');
}
}
const stats = await fs.stat(candidate);
if (!stats.isFile()) {
throw new Error(`Not a file: ${ref.sourceId}`);
Expand Down
5 changes: 5 additions & 0 deletions app/lib/integrations/studio-generation-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export interface StudioGenerateRequest {
source_output_id?: string;
pi_session_id?: string;
extra_reference_urls?: string[];
require_all_image_references?: boolean;
video_reference_urls?: string[];
audio_reference_urls?: string[];
video_extend_source_path?: string | null;
Expand Down Expand Up @@ -1012,6 +1013,7 @@ export async function createStudioGeneration(
videoWebSearch: request.video_web_search,
videoNsfwChecker: request.video_nsfw_checker,
extraReferenceUrls: request.extra_reference_urls,
requireAllImageReferences: request.require_all_image_references,
videoReferenceUrls: request.video_reference_urls,
audioReferenceUrls: request.audio_reference_urls,
videoExtendSourcePath: request.video_extend_source_path || null,
Expand Down Expand Up @@ -1292,6 +1294,9 @@ async function executeStudioGenerationProcessing(
const extraUrls = parsedMeta.extraReferenceUrls || [];
if (extraUrls.length > 0) {
const extraImgs = await loadExtraReferenceImages(scope, extraUrls, mode === 'video' && providerId === SEEDANCE_PROVIDER_ID);
if (parsedMeta.requireAllImageReferences && extraImgs.length !== extraUrls.length) {
throw new StudioServiceError('Missing image reference', 'A requested image reference could not be loaded.', 'INVALID_REQUEST');
}
for (const img of extraImgs) {
if (!allReferenceImages.some((r) => r.imageBytes === img.imageBytes)) {
allReferenceImages.push(img);
Expand Down
23 changes: 23 additions & 0 deletions app/lib/integrations/studio-image-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Type } from 'typebox';

export const studioImageParameters = Type.Object({
prompt: Type.String({ description: 'Text description of the image to generate.' }),
product_ids: Type.Optional(Type.Array(Type.String(), { description: 'IDs of saved products to include as reference images (max 5).', maxItems: 5 })),
persona_ids: Type.Optional(Type.Array(Type.String(), { description: 'IDs of saved personas to include as reference images (max 3).', maxItems: 3 })),
style_ids: Type.Optional(Type.Array(Type.String(), { description: 'IDs of saved styles to apply as reference images (max 3).', maxItems: 3 })),
preset_id: Type.Optional(Type.String({ description: 'ID of a studio preset to apply (lighting, camera, background settings).' })),
aspect_ratio: Type.Optional(Type.String({ description: 'Aspect ratio metadata. Gemini supports 1:1 (default), 16:9, 9:16, 4:3 and 3:4. OpenAI also supports 3:2, 2:3, 4:5 and auto. For OpenAI custom sizes, image_size is authoritative and the exact ratio is derived from it.' })),
count: Type.Optional(Type.Integer({ description: 'Number of image variations. Gemini supports 1-4; OpenAI supports 1-10. Default: 1.', minimum: 1, maximum: 10 })),
provider: Type.Optional(Type.String({ description: 'Provider: gemini or openai. Default: gemini.' })),
model: Type.Optional(Type.String({ description: 'Model ID. Options: gemini-3.1-flash-image (default, best quality & features), gemini-3-pro-image (pro quality & reasoning, Nano Banana Pro), gpt-image-2.5-sunburst (best quality when provider is openai), gpt-image-2.5-flare (fast generation when provider is openai). If omitted, defaults to the best model for the selected provider.' })),
image_size: Type.Optional(Type.String({ description: 'Image resolution. Gemini: "512" (only gemini-3.1-flash), "1K", "2K", or "4K". OpenAI: "auto" or WIDTHxHEIGHT. Useful presets are 1024x1024, 1536x1024, 1024x1536, 1536x864, 864x1536, 1344x1008, 1008x1344, and 1024x1280. Custom OpenAI edges must be multiples of 16, at most 3840px, ratio at most 3:1, and total pixels between 655,360 and 8,294,400.' })),
quality: Type.Optional(Type.Union([Type.Literal('low'), Type.Literal('medium'), Type.Literal('high'), Type.Literal('xhigh'), Type.Literal('max'), Type.Literal('auto')], { description: 'Image quality. OpenAI only. Default: auto.' })),
output_format: Type.Optional(Type.Union([Type.Literal('png'), Type.Literal('jpeg'), Type.Literal('webp')], { description: 'Output format. OpenAI only. Default: png. For a transparent background, use png (recommended) or webp; jpeg does not support transparency.' })),
background: Type.Optional(Type.Union([Type.Literal('transparent'), Type.Literal('opaque'), Type.Literal('auto')], { description: 'Background treatment. OpenAI only. Default: auto. To request a transparent image, set this to transparent and set output_format to png (recommended) or webp.' })),
moderation: Type.Optional(Type.Union([Type.Literal('auto'), Type.Literal('low')], { description: 'Content moderation level. OpenAI only. Default: auto.' })),
output_compression: Type.Optional(Type.Integer({ description: 'JPEG/WebP compression from 0 to 100. OpenAI only. Default: 100; ignored for PNG.', minimum: 0, maximum: 100 })),
stream: Type.Optional(Type.Boolean({ description: 'Use the OpenAI image streaming transport and keep the final completed image. Default: false.' })),
partial_images: Type.Optional(Type.Integer({ description: 'Number of streamed partial images (0-3). Requires stream=true. Partial images incur additional image tokens; Studio persists only the final completed image.', minimum: 0, maximum: 3 })),
source_output_id: Type.Optional(Type.String({ description: 'ID of a previous Studio output to use as the base image for editing or variation. Prefer this when you have the output ID.' })),
extra_reference_urls: Type.Optional(Type.Array(Type.String(), { description: 'Reference image file paths or URLs to load as visual input for editing, variations, style matching, or image-to-image generation. Put every local reference image path here; do not only write paths in the prompt. Accepts exact workspace-scoped Studio paths returned by Studio tools, /api/studio/media/... and /api/studio/references/... URLs, products/image.png, personas/image.png, styles/image.png, workspace paths like 09_asset-library/photo.png or /api/media/09_asset-library/photo.png, plus https image URLs.' })),
});
Loading
Loading