Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
import { isPublicErrorFacts, publicErrorCodeFromFailure, publicErrorKindForCode, safePublicErrorCode, sanitizePublicErrorFacts, type PublicErrorFacts, type OpenCreatorIssue } from '@opencreator/protocol';
import { useCallback, useMemo, useState } from 'react';
import { ApiClientError } from '../../runtime/errors.js';
import {
clearPageIssuesForSurface,
dismissPageIssue,
publishPageIssue,
resolvePageIssue
} from './page-issue-hub.js';
export type PageIssueState = {
issues: OpenCreatorIssue[];
captureOperationFailure(
operationId: string,
cause: unknown,
fallbackMessage?: string,
options?: { retryable?: boolean; risk?: 'normal' | 'paid' | 'overwrite' }
): OpenCreatorIssue;
resolveOperation(operationId: string): void;
dismissIssue(issueId: string): void;
clearIssues(): void;
};
export function usePageIssueState(surface: string): PageIssueState {
const [byOperation, setByOperation] = useState<Record<string, OpenCreatorIssue>>({});
const captureOperationFailure = useCallback((
operationId: string,
cause: unknown,
fallbackMessage = 'The operation did not complete. Try again.',
options: { retryable?: boolean; risk?: 'normal' | 'paid' | 'overwrite' } = {}
) => {
const normalized = normalizePageIssue(surface, operationId, cause, fallbackMessage);
const issue = options.retryable === true ? {
...normalized,
retryable: true,
repairActions: [{
kind: 'retry-operation' as const,
operationId,
requiresConfirmation: options.risk !== undefined && options.risk !== 'normal',
risk: options.risk ?? 'normal'
}]
} : normalized;
publishPageIssue(issue);
setByOperation(current => ({
...current,
[operationId]: mergeOccurrence(current[operationId], issue)
}));
return issue;
}, [surface]);
const resolveOperation = useCallback((operationId: string) => {
resolvePageIssue(surface, operationId);
setByOperation(current => {
if (!(operationId in current)) return current;
const next = { ...current };
delete next[operationId];
return next;
});
}, [surface]);
const dismissIssue = useCallback((issueId: string) => {
dismissPageIssue(issueId);
setByOperation(current => Object.fromEntries(
Object.entries(current).filter(([, issue]) => issue.id !== issueId)
));
}, []);
const clearIssues = useCallback(() => {
clearPageIssuesForSurface(surface);
setByOperation({});
}, [surface]);
const issues = useMemo(
() => Object.values(byOperation).sort((left, right) => right.lastOccurredAt.localeCompare(left.lastOccurredAt)),
[byOperation]
);
return { issues, captureOperationFailure, resolveOperation, dismissIssue, clearIssues };
}
export function normalizePageIssue(
surface: string,
operationId: string,
cause: unknown,
fallbackMessage: string
): OpenCreatorIssue {
if (cause instanceof ApiClientError && cause.issue !== undefined) {
const issue = cause.issue;
if (issue.scope.kind === 'creator-job') return issue;
const templateMismatch = /^Unknown creator template: ([a-z][a-z0-9-]{0,79})@(\d{1,3})$/.exec(cause.message);
if (templateMismatch !== null) {
const fingerprint = stableKey(`${surface}:${operationId}:creator_template_version_mismatch`);
return {
...issue,
diagnosticId: `OC-${fingerprint.slice(-8).toUpperCase()}`,
code: 'creator_template_version_mismatch',
scope: { kind: 'page', surface },
operation: operationId,
category: 'configuration',
summaryKey: 'issue.configuration',
fallbackMessage: `The local Runtime does not support version ${templateMismatch[2]} of the ${templateMismatch[1]} template requested by this page. The task was not created.`,
fingerprint
};
}
return {
...issue,
scope: { kind: 'page', surface },
operation: operationId,
fallbackMessage: ['操作未完成,请稍后重试。', 'The operation did not complete. Try again later.'].includes(issue.fallbackMessage)
? fallbackMessage
: issue.fallbackMessage || fallbackMessage
};
}
const now = new Date().toISOString();
const code = readCode(cause);
const kind = publicErrorKindForCode(code);
const suppliedFacts = cause !== null && typeof cause === 'object'
? (cause as { publicFacts?: PublicErrorFacts }).publicFacts : undefined;
const facts = suppliedFacts !== undefined && suppliedFacts !== null && typeof suppliedFacts === 'object'
? sanitizePublicErrorFacts(suppliedFacts) : undefined;
const network = kind === 'dns' || kind === 'connection-refused'
|| kind === 'connection-reset' || kind === 'timeout';
const confirmedKind = facts !== undefined && isPublicErrorFacts(facts) ? facts.kind : kind;
const category = network ? 'network' : confirmedKind === 'configuration' ? 'configuration'
: confirmedKind === 'validation' ? 'input' : 'execution';
const key = stableKey(`${surface}:${operationId}:${code}`);
return {
id: `page:${createId()}`,
diagnosticId: `OC-${key.slice(-8).toUpperCase()}`,
code,
scope: { kind: 'page', surface },
source: network ? 'network' : 'client',
category,
severity: 'error',
status: 'open',
operation: operationId,
summaryKey: `issue.${category}`,
summaryParams: {},
fallbackMessage,
...(facts !== undefined && isPublicErrorFacts(facts)
? { publicFacts: facts }
: kind === undefined ? {} : { publicFacts: { kind } }),
retryable: false,
repairActions: [],
fingerprint: key,
occurrenceCount: 1,
occurredAt: now,
lastOccurredAt: now
};
}
function mergeOccurrence(previous: OpenCreatorIssue | undefined, next: OpenCreatorIssue): OpenCreatorIssue {
if (previous === undefined || previous.fingerprint !== next.fingerprint) return next;
return {
...next,
id: previous.id,
diagnosticId: previous.diagnosticId,
occurredAt: previous.occurredAt,
occurrenceCount: previous.occurrenceCount + 1
};
}
function readCode(cause: unknown): string {
if (cause instanceof ApiClientError) return safePublicErrorCode(cause.code) ?? 'CLIENT_OPERATION_FAILED';
return publicErrorCodeFromFailure(cause) ?? 'CLIENT_OPERATION_FAILED';
}
function createId(): string {
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function stableKey(value: string): string {
let hash = 0x811c9dc5;
for (let index = 0; index < value.length; index += 1) {
hash ^= value.charCodeAt(index);
hash = Math.imul(hash, 0x01000193);
}
return `fnv1a-${(hash >>> 0).toString(16).padStart(8, '0')}`;
}