diff --git a/docs/rea-generation-review.md b/docs/rea-generation-review.md new file mode 100644 index 00000000..d096dc4d --- /dev/null +++ b/docs/rea-generation-review.md @@ -0,0 +1,49 @@ +# REA generation review dependency + +Stacked on PR #584 / issue #583. This dependency's issue is #585. Its desktop +scope is the dedicated credential boundary and a mounted preparation-only REA +subpanel. Mobile UI is intentionally unchanged per the desktop task scope; +mobile typecheck still verifies the shared contracts. + +`minimax-video-payg` is fixed to global PAYG video. The renderer can request +status, set or clear only that slot through dedicated channels. Authorization +checks the live owning BrowserWindow's webContents and exact main frame before +reading payloads or invoking the service. Input shape is strict. Credential +reads remain lazy in main; no raw-getter IPC exists. The existing encrypted +CredentialStore and safeStorage policy are reused. The generic setter rejects +the reserved slot before store access, including array/object coercion attempts; +the generic status response omits its entry. No existing slot is migrated or +used as a fallback. Errors from the dedicated boundary are fixed public text. + +The product installs a disabled execution dependency, not a test transport. +There is no submit IPC and every injected production execution method throws +`PAID_EXECUTION_DISABLED`. Capability fields distinguish documentation date, +offline adapter implementation, production adapter availability (false), +configured credential, verified account access (false), and paid permission +(false). Storing a key does not change execution permission. Mounting the panel +does not automatically query any credential or account status. + +The panel retains originals, prepares one text-only manual shot with the exact +prompt/estimate/budget/manifest, displays the immutable returned plan and hash, +and leaves generation approval disabled. It is mounted after the existing +analysis workspace so that existing range-review behavior remains unchanged. +Source epoch/project changes retire pending results and discard late preparation +receipts. Original range imports still use the existing host's history boundary. +There is no generated preview, image reference input, local assembly or generated +timeline import in this dependency; these remain next-stage work. + +Tests use fake keys and injected services only. No real credential/status was +queried, no external paid request/upload/download was executed, and no account +access was verified. React tests mount the actual host and subpanel and test a +project switch during pending preparation, with submit and save both zero. + +The store remains bounded to 100 records. At capacity, preparation can evict only +the oldest record proven never dispatched: no task ID, no dispatch marker and no +remote action, with either pre-submit cancellation or an expired unconsumed +approval. A dispatch marker is persisted before POST. Active or valid approvals, +submitting/submitted tasks, unknown outcomes and remote IDs/results are never +evicted. Legacy ambiguous states stay protected even without the marker. Evicted +IDs are never reused, and their tokens cannot resolve a job. If all records are +protected, `JOB_LIMIT` honestly refuses new preparation. Failed replacement rolls +back the in-memory candidate. There is no clear/reset, source deletion, automatic +re-POST or renewal of an approval. diff --git a/src/main/index.ts b/src/main/index.ts index 3c126a02..177f4fce 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -6,6 +6,10 @@ import { join } from 'node:path'; import { IPC_CHANNELS } from '../shared/ipc'; import { ReaVideoAnalysisService } from './reaVideoAnalysisService'; import { registerReaAnalysisIpc } from './reaVideoAnalysisIpc'; +import { ReaGenerationJobStore } from './reaGenerationJobStore'; +import { ReaGenerationService } from './reaGenerationService'; +import { registerReaGenerationIpc } from './reaGenerationIpc'; +import { REA_VIDEO_CREDENTIAL_SLOT } from '../shared/reaGenerationApi'; import type { AppSettings, CaptureSource } from '../shared/models'; import { SourceCatalog, type RawCaptureSource } from '../shared/sourceCatalog'; import type { MediaKind } from '../shared/timelineTypes'; @@ -94,6 +98,15 @@ const reaAnalysis = new ReaVideoAnalysisService(async ({ projectId, assetId }) = const audioDetachService = new AudioDetachService({ projects: projectStore, assets: assetLibraryStore }); const exportJobStore = new ExportJobStore(); const credentialStore = new CredentialStore(app.getPath('userData')); +// No fixture transport is installed in the product. Every execution method fails closed. +const generationDisabled = async (): Promise => { throw new Error('PAID_EXECUTION_DISABLED'); }; +const reaGenerationJobs = new ReaGenerationJobStore(join(app.getPath('userData'), 'rea-generation'), { + submit: generationDisabled, query: generationDisabled, cancelQueued: generationDisabled +}); +const reaGeneration = new ReaGenerationService(credentialStore, reaGenerationJobs, async (projectId, assetId) => { + const asset = await projectStore.getAsset(projectId, assetId); + return asset?.kind === 'video' && await assetLibraryStore.getPlaybackSource(projectId, assetId) !== null; +}); const jevService = createJevService({ store: credentialStore }); const jevConfigStore = new JevConfigStore(app.getPath('userData')); let jevCredentialWindow: BrowserWindow | null = null; @@ -431,6 +444,7 @@ async function installIpcHandlers(): Promise { }); registerExportIpcHandlers(ipcMain, exportIpcService); registerReaAnalysisIpc({ service: reaAnalysis, ipcMain, getOwnWindow: () => reaAnalysisWindow }); + registerReaGenerationIpc({ service: reaGeneration, ipcMain, getOwnWindow: () => reaAnalysisWindow }); ipcMain.handle(IPC_CHANNELS.shortsStart, (_event, payload: unknown) => shortsService.start(payload)); ipcMain.handle(IPC_CHANNELS.shortsGet, (_event, payload: unknown) => shortsService.get(payload)); ipcMain.handle(IPC_CHANNELS.shortsList, (_event, payload: unknown) => shortsService.list(payload)); @@ -453,6 +467,7 @@ async function installIpcHandlers(): Promise { ipcMain.handle(IPC_CHANNELS.getProviderCredentials, async () => { try { const status = await credentialStore.getCredentialStatus(); + delete status[REA_VIDEO_CREDENTIAL_SLOT]; return ok(status); } catch (err) { return fail('UNKNOWN_ERROR', err instanceof Error ? err.message : 'Failed to retrieve credential status'); @@ -461,6 +476,7 @@ async function installIpcHandlers(): Promise { ipcMain.handle(IPC_CHANNELS.setProviderCredential, async (_event, provider: any, apiKey: string) => { if (typeof provider !== 'string') return fail('INVALID_INPUT', 'Invalid credential provider.'); + if (provider === REA_VIDEO_CREDENTIAL_SLOT) return fail('PERMISSION_DENIED', 'Use the dedicated video credential operation.'); if (provider === 'typesafe-jev') return fail('PERMISSION_DENIED', 'Use the dedicated Jev credential operation.'); try { await credentialStore.setCredential(provider, apiKey); diff --git a/src/main/reaGenerationIpc.ts b/src/main/reaGenerationIpc.ts new file mode 100644 index 00000000..db06cc70 --- /dev/null +++ b/src/main/reaGenerationIpc.ts @@ -0,0 +1,26 @@ +import type { BrowserWindow, IpcMain, IpcMainInvokeEvent } from 'electron'; +import { REA_GENERATION_CHANNELS } from '../shared/reaGenerationApi'; +import { fail, ok } from './ipcResponses'; +import type { ReaGenerationService } from './reaGenerationService'; + +export function registerReaGenerationIpc({ service, ipcMain, getOwnWindow }: { + service: Pick; + ipcMain: Pick; getOwnWindow: () => BrowserWindow | null; +}) { + for (const action of Object.keys(REA_GENERATION_CHANNELS) as (keyof typeof REA_GENERATION_CHANNELS)[]) { + ipcMain.handle(REA_GENERATION_CHANNELS[action], async (event: IpcMainInvokeEvent, payload: unknown) => { + try { + const own = getOwnWindow(); + if (!own || own.isDestroyed() || own.webContents.isDestroyed() || event.sender !== own.webContents + || !event.senderFrame || event.senderFrame !== own.webContents.mainFrame) return fail('PERMISSION_DENIED', 'Generation access denied.'); + } catch { return fail('PERMISSION_DENIED', 'Generation access denied.'); } + try { + if (action === 'status' || action === 'clearCredential') { + if (payload !== undefined) return fail('INVALID_INPUT', 'Generation request rejected.'); + return ok(await service[action]()); + } + return ok(await service[action](payload)); + } catch { return fail('INVALID_INPUT', 'Generation request rejected. No paid execution was authorized.'); } + }); + } +} diff --git a/src/main/reaGenerationJobStore.ts b/src/main/reaGenerationJobStore.ts index c83ed403..bf8e0fb0 100644 --- a/src/main/reaGenerationJobStore.ts +++ b/src/main/reaGenerationJobStore.ts @@ -8,7 +8,7 @@ import type { MinimaxVideoAdapter } from './minimaxVideoAdapter'; const recordSchema = z.strictObject({ id: z.string().uuid(), plan: reaGenerationPlanSchema, planHash: z.string().regex(/^[a-f0-9]{64}$/), approvalHash: z.string(), expiresAt: z.number().int(), state: z.enum(['awaiting-approval', 'submitting', 'outcome-unknown', 'queued', 'running', 'remote-succeeded', 'failed', 'cancelled']), - taskId: z.string().regex(/^[\w-]{1,160}$/).optional(), cancelRequested: z.boolean(), remoteAction: z.enum(['cancelled', 'deleted']).optional(), + taskId: z.string().regex(/^[\w-]{1,160}$/).optional(), dispatchStarted: z.boolean().default(false), cancelRequested: z.boolean(), remoteAction: z.enum(['cancelled', 'deleted']).optional(), pollCount: z.number().int().nonnegative(), nextPollAt: z.number().int(), deadline: z.number().int() }); type Record = z.infer; const digest = (s: string) => createHash('sha256').update(s).digest('hex'); @@ -18,7 +18,7 @@ export class ReaGenerationJobStore { private work: Promise = Promise.resolve(); private records: Record[] = []; private loaded = false; - constructor(private readonly directory: string, private readonly adapter: MinimaxVideoAdapter, private readonly now = Date.now) {} + constructor(private readonly directory: string, private readonly adapter: Pick, private readonly now = Date.now) {} private serialize(fn: () => Promise): Promise { const result = this.work.then(async () => { await this.load(); return fn(); }); this.work = result.catch(() => undefined); @@ -61,11 +61,21 @@ export class ReaGenerationJobStore { prepare(value: unknown): Promise<{ receipt: ReaGenerationReceipt; approval: string }> { const plan = freezeGenerationPlan(value); return this.serialize(async () => { - if (this.records.length >= 100) throw new Error('JOB_LIMIT'); const now = this.now(), approval = randomUUID(); + // Only records proven never dispatched can be retired. Array order is the + // persisted creation order; select the oldest eligible record deterministically. + const records = [...this.records]; + if (records.length >= 100) { + const index = records.findIndex(r => !r.taskId && !r.dispatchStarted && !r.remoteAction && + (r.state === 'cancelled' || r.state === 'awaiting-approval' && r.approvalHash.length === 64 && now >= r.expiresAt)); + if (index < 0) throw new Error('JOB_LIMIT'); + records.splice(index, 1); + } const r: Record = { id: randomUUID(), plan, planHash: generationPlanHash(plan), approvalHash: digest(approval), expiresAt: now + 300000, - state: 'awaiting-approval', cancelRequested: false, pollCount: 0, nextPollAt: now, deadline: now + 1800000 }; - this.records.push(r); await this.persist(); return { receipt: this.receipt(r), approval }; + state: 'awaiting-approval', dispatchStarted: false, cancelRequested: false, pollCount: 0, nextPollAt: now, deadline: now + 1800000 }; + records.push(r); const previous = this.records; this.records = records; + try { await this.persist(); } catch (error) { this.records = previous; throw error; } + return { receipt: this.receipt(r), approval }; }); } get(id: string, projectId: string): Promise { return this.serialize(async () => this.receipt(this.find(id, projectId))); } @@ -75,7 +85,7 @@ export class ReaGenerationJobStore { return this.serialize(async () => { const r = this.find(id, plan.projectId); if (r.state !== 'awaiting-approval' || r.cancelRequested || this.now() >= r.expiresAt || digest(approval) !== r.approvalHash || generationPlanHash(plan) !== r.planHash) throw new Error('APPROVAL_REJECTED'); - r.state = 'submitting'; r.approvalHash = ''; await this.persist(); + r.state = 'submitting'; r.dispatchStarted = true; r.approvalHash = ''; await this.persist(); try { r.taskId = await this.adapter.submit(plan, bytes); r.state = 'queued'; await this.persist(); diff --git a/src/main/reaGenerationService.ts b/src/main/reaGenerationService.ts new file mode 100644 index 00000000..da529856 --- /dev/null +++ b/src/main/reaGenerationService.ts @@ -0,0 +1,32 @@ +import { z } from 'zod'; +import { REA_VIDEO_CREDENTIAL_SLOT, type ReaGenerationCapability } from '../shared/reaGenerationApi'; +import { freezeGenerationPlan } from './reaGenerationPlan'; +import type { ReaGenerationJobStore } from './reaGenerationJobStore'; +import type { CredentialStore } from './credentialStore'; + +const scope = z.strictObject({ id: z.string().uuid(), projectId: z.string().regex(/^[\w-]{1,160}$/) }); +export class ReaGenerationService { + constructor(private readonly credentials: Pick, + private readonly jobs: ReaGenerationJobStore, + private readonly sourceExists: (projectId: string, assetId: string) => Promise) {} + async status(): Promise { + // A configured key says nothing about video access or permission to spend. + const key = await this.credentials.getCredentialValue(REA_VIDEO_CREDENTIAL_SLOT); + return { provider: REA_VIDEO_CREDENTIAL_SLOT, region: 'global', billing: 'PAYG', documentationCheckedAt: '2026-11-27', + adapterImplemented: false, offlineAdapterImplemented: true, credentialConfigured: Boolean(key?.trim()), accountAccessVerified: false, paidExecutionAllowed: false }; + } + async setCredential(payload: unknown) { + const { value } = z.strictObject({ value: z.string().min(1).max(4096).refine(v => v.trim() === v && !/[\r\n\0]/.test(v)) }).parse(payload); + await this.credentials.setCredential(REA_VIDEO_CREDENTIAL_SLOT, value); return { updated: true as const }; + } + async clearCredential() { await this.credentials.setCredential(REA_VIDEO_CREDENTIAL_SLOT, ''); return { updated: true as const }; } + async prepare(payload: unknown) { + const plan = freezeGenerationPlan(payload); + if (!await this.sourceExists(plan.projectId, plan.sourceAssetId)) throw new Error('SOURCE_UNAVAILABLE'); + // First-frame production resolution/validation is not enabled in this dependency. + if (plan.referenceImage) throw new Error('REFERENCE_UNAVAILABLE'); + const prepared = await this.jobs.prepare(plan); return { ...prepared, plan }; + } + async get(payload: unknown) { const p = scope.parse(payload); return this.jobs.get(p.id, p.projectId); } + async cancel(payload: unknown) { const p = scope.parse(payload); return this.jobs.cancel(p.id, p.projectId); } +} diff --git a/src/preload/index.ts b/src/preload/index.ts index 6b78d77b..01ad7f50 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,5 +1,6 @@ import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'; import { REA_ANALYSIS_CHANNELS, type ReaAnalysisInput, type ReaAnalysisJob, type ReaAnalysisRuntime, type ReaPrepareImportInput } from '../shared/reaVideoAnalysis'; +import { REA_GENERATION_CHANNELS, type ReaGenerationApi } from '../shared/reaGenerationApi'; import type { CuaActionSettlementAck, CuaActionSettlementTag, CuaCancelAck, CuaPrepareAck, CuaState, CuaStopResult, CuaSurfaceSnapshot } from '../shared/cua'; import type { CuaSaveCommitAck, CuaSaveReadyAck, CuaSaveReadyRequest, CuaSaveResult, CuaSaveSnapshotReport, CuaSaveSnapshotRequest } from '../shared/cuaSave'; @@ -69,7 +70,7 @@ type AssetPlaybackUrl = { readonly url: string; }; -export interface VideoToolApi extends JevCredentialApi, JevConfigApi { +export interface VideoToolApi extends JevCredentialApi, JevConfigApi, ReaGenerationApi { reaAnalysisRuntime(): Promise>; reaAnalysisStart(input: ReaAnalysisInput): Promise>; reaAnalysisGet(input: { readonly jobId: string }): Promise>; @@ -179,6 +180,12 @@ function parseUpdaterSnapshot(payload: unknown): UpdaterSnapshot | null { const videoTool: VideoToolApi = { reaAnalysisRuntime: () => ipcRenderer.invoke(REA_ANALYSIS_CHANNELS.runtime), + reaGenerationStatus: () => ipcRenderer.invoke(REA_GENERATION_CHANNELS.status), + reaGenerationSetCredential: input => ipcRenderer.invoke(REA_GENERATION_CHANNELS.setCredential, input), + reaGenerationClearCredential: () => ipcRenderer.invoke(REA_GENERATION_CHANNELS.clearCredential), + reaGenerationPrepare: input => ipcRenderer.invoke(REA_GENERATION_CHANNELS.prepare, input), + reaGenerationGet: input => ipcRenderer.invoke(REA_GENERATION_CHANNELS.get, input), + reaGenerationCancel: input => ipcRenderer.invoke(REA_GENERATION_CHANNELS.cancel, input), reaAnalysisStart: input => ipcRenderer.invoke(REA_ANALYSIS_CHANNELS.start, input), reaAnalysisGet: input => ipcRenderer.invoke(REA_ANALYSIS_CHANNELS.get, input), reaAnalysisCancel: input => ipcRenderer.invoke(REA_ANALYSIS_CHANNELS.cancel, input), diff --git a/src/renderer/components/workspace/ReaGenerationPanel.tsx b/src/renderer/components/workspace/ReaGenerationPanel.tsx new file mode 100644 index 00000000..081db066 --- /dev/null +++ b/src/renderer/components/workspace/ReaGenerationPanel.tsx @@ -0,0 +1,75 @@ +import { useEffect, useRef, useState } from 'react'; +import type { MediaAsset } from '../../../shared/timelineTypes'; +import type { ReaGenerationPlan } from '../../../shared/reaGeneration'; +import type { ReaGenerationCapability, ReaGenerationPrepared } from '../../../shared/reaGenerationApi'; + +/** Review preparation only. No submit operation is exposed by this product dependency. */ +export function ReaGenerationPanel({ projectId, sourceEpoch, assets }: { + readonly projectId: string; readonly sourceEpoch: string; readonly assets: readonly MediaAsset[]; +}) { + const [capability, setCapability] = useState(); + const [key, setKey] = useState(''); const [sourceId, setSourceId] = useState(''); const [prompt, setPrompt] = useState(''); + const [seconds, setSeconds] = useState(4); const [budget, setBudget] = useState('0.32'); + const [prepared, setPrepared] = useState(); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false); + const latestPrepared = useRef(prepared); latestPrepared.current = prepared; + const revision = useRef(0); + const identity = JSON.stringify([projectId, sourceEpoch, sourceId, prompt, seconds, budget]); + const current = useRef(identity); if (current.current !== identity) { current.current = identity; revision.current++; } + useEffect(() => { + setPrepared(undefined); setMessage(''); setBusy(false); + return () => { + revision.current++; + const previous = latestPrepared.current; + if (previous) void window.videoTool.reaGenerationCancel({ id: previous.receipt.id, projectId: previous.plan.projectId }).catch(() => undefined); + }; + }, [identity]); + useEffect(() => { setKey(''); setCapability(undefined); setSourceId(''); }, [projectId, sourceEpoch]); + const run = async (action: () => Promise) => { + const token = revision.current; setBusy(true); setMessage(''); + try { await action(); } catch { if (token === revision.current) setMessage('Request unavailable. No paid execution is enabled.'); } + finally { if (token === revision.current) setBusy(false); } + }; + const status = async () => { + const token = revision.current, response = await window.videoTool.reaGenerationStatus(); + if (token !== revision.current) return; + if (response.ok) setCapability(response.value); else setMessage(response.error.message); + }; + const prepare = async () => { + const token = revision.current, source = assets.find(a => a.id === sourceId && a.kind === 'video'); if (!source) return; + const plan: ReaGenerationPlan = { version: 1, projectId, sourceAssetId: source.id, sourceEpoch, reviewVersion: token, + shotId: 'manual-shot-1', sourceStartMs: 0, sourceEndMs: Math.max(1, Math.min(source.metadata?.durationMs ?? seconds * 1000, seconds * 1000)), prompt, + provider: 'minimax-video-payg', baseUrl: 'https://api.minimax.io', model: 'MiniMax-H3', resolution: '768P', generateAudio: false, + durationSeconds: seconds, ratio: '16:9', referenceImage: null, + estimate: { currency: 'USD', outputMicroUsdPerSecond: 80000, totalMicroUsd: seconds * 80000, budgetMicroUsd: Math.round(Number(budget) * 1_000_000), pricedAt: '2026-11-27', billingCapGuaranteed: false }, + manifest: { prompt: true, firstFrame: false, sourceVideo: false, sourceAudio: false } }; + const response = await window.videoTool.reaGenerationPrepare(plan); + if (token !== revision.current) { if (response.ok) void window.videoTool.reaGenerationCancel({ id: response.value.receipt.id, projectId }).catch(() => undefined); return; } + if (response.ok) setPrepared(response.value); else setMessage(response.error.message); + }; + return
+

REA generation review

+

Global MiniMax PAYG · MiniMax-H3 · 768P · silent · one shot. Paid execution: false. Production adapter unavailable; offline protocol tests are implemented.

+

Account access: unverified. Documentation checked: 2026-11-27. First-frame input, verified result preview, local assembly and generated timeline import are not enabled yet.

+
Dedicated video credential +

Use a global PAYG video API key. Chat, China, coding and M Plan credentials are never reused. Configuring a key does not authorize spending.

+ + + + +

Credential: {capability ? capability.credentialConfigured ? 'configured; access unverified' : 'setup required' : 'not checked'}.

+
+ +