Skip to content
Closed
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
49 changes: 49 additions & 0 deletions docs/rea-generation-review.md
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 16 additions & 0 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<never> => { 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;
Expand Down Expand Up @@ -431,6 +444,7 @@ async function installIpcHandlers(): Promise<void> {
});
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));
Expand All @@ -453,6 +467,7 @@ async function installIpcHandlers(): Promise<void> {
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');
Expand All @@ -461,6 +476,7 @@ async function installIpcHandlers(): Promise<void> {

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);
Expand Down
26 changes: 26 additions & 0 deletions src/main/reaGenerationIpc.ts
Original file line number Diff line number Diff line change
@@ -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<ReaGenerationService, keyof typeof REA_GENERATION_CHANNELS>;
ipcMain: Pick<IpcMain, 'handle'>; 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.'); }
});
}
}
22 changes: 16 additions & 6 deletions src/main/reaGenerationJobStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof recordSchema>;
const digest = (s: string) => createHash('sha256').update(s).digest('hex');
Expand All @@ -18,7 +18,7 @@ export class ReaGenerationJobStore {
private work: Promise<unknown> = 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<MinimaxVideoAdapter, 'submit' | 'query' | 'cancelQueued'>, private readonly now = Date.now) {}
private serialize<T>(fn: () => Promise<T>): Promise<T> {
const result = this.work.then(async () => { await this.load(); return fn(); });
this.work = result.catch(() => undefined);
Expand Down Expand Up @@ -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<ReaGenerationReceipt> { return this.serialize(async () => this.receipt(this.find(id, projectId))); }
Expand All @@ -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();
Expand Down
32 changes: 32 additions & 0 deletions src/main/reaGenerationService.ts
Original file line number Diff line number Diff line change
@@ -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<CredentialStore, 'getCredentialValue' | 'setCredential'>,
private readonly jobs: ReaGenerationJobStore,
private readonly sourceExists: (projectId: string, assetId: string) => Promise<boolean>) {}
async status(): Promise<ReaGenerationCapability> {
// 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); }
}
9 changes: 8 additions & 1 deletion src/preload/index.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -69,7 +70,7 @@ type AssetPlaybackUrl = {
readonly url: string;
};

export interface VideoToolApi extends JevCredentialApi, JevConfigApi {
export interface VideoToolApi extends JevCredentialApi, JevConfigApi, ReaGenerationApi {
reaAnalysisRuntime(): Promise<ApiResponse<ReaAnalysisRuntime>>;
reaAnalysisStart(input: ReaAnalysisInput): Promise<ApiResponse<ReaAnalysisJob>>;
reaAnalysisGet(input: { readonly jobId: string }): Promise<ApiResponse<ReaAnalysisJob>>;
Expand Down Expand Up @@ -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),
Expand Down
Loading
Loading