@nimiplatform/app-tools 0.7.5 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +59 -5
  2. package/bin/nimi-app.mjs +11 -3
  3. package/lib/app-access-declaration.mjs +1 -0
  4. package/lib/app-dependency-combinations.mjs +16 -28
  5. package/lib/app-doctor-update.mjs +66 -7
  6. package/lib/app-info.mjs +8 -1
  7. package/lib/app-project-lifecycle.mjs +82 -9
  8. package/lib/app-scaffold-capabilities.mjs +3 -3
  9. package/lib/app-scaffold-profiles.mjs +96 -26
  10. package/lib/app-scaffold.mjs +54 -7
  11. package/lib/canonical-capability-ids.generated.mjs +4 -0
  12. package/package.json +26 -25
  13. package/scripts/dev-shell.mjs +61 -17
  14. package/skills/nimi-app-lifecycle/references/acceptance.md +1 -1
  15. package/skills/nimi-app-lifecycle/references/adapt.md +2 -2
  16. package/skills/nimi-app-lifecycle/references/release.md +1 -1
  17. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +14 -0
  18. package/templates/app-source/src/ai-studio-core/ai-config.ts +17 -3
  19. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +40 -3
  20. package/templates/app-source/src/ai-studio-core/audio-separation-request.ts +24 -0
  21. package/templates/app-source/src/ai-studio-core/contexts.tsx +4 -0
  22. package/templates/app-source/src/ai-studio-core/history-policy.ts +395 -41
  23. package/templates/app-source/src/ai-studio-core/history.ts +262 -10
  24. package/templates/app-source/src/ai-studio-core/host-context.tsx +15 -2
  25. package/templates/app-source/src/ai-studio-core/index.ts +15 -4
  26. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +105 -0
  27. package/templates/app-source/src/ai-studio-core/job-recovery.ts +224 -0
  28. package/templates/app-source/src/ai-studio-core/managed-result-references.ts +79 -0
  29. package/templates/app-source/src/ai-studio-core/messages/en.json +185 -10
  30. package/templates/app-source/src/ai-studio-core/messages/zh.json +185 -10
  31. package/templates/app-source/src/ai-studio-core/module-registration.ts +9 -1
  32. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +81 -2
  33. package/templates/app-source/src/ai-studio-core/parameters.ts +34 -1
  34. package/templates/app-source/src/ai-studio-core/runtime-types.ts +124 -8
  35. package/templates/app-source/src/ai-studio-core/runtime.ts +218 -20
  36. package/templates/app-source/src/ai-studio-core/section-ai-testing-annotation-result.tsx +123 -0
  37. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +3 -0
  38. package/templates/app-source/src/ai-studio-core/section-ai-testing-audio-separation-result.tsx +26 -0
  39. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +14 -7
  40. package/templates/app-source/src/ai-studio-core/section-ai-testing-decision-result.tsx +76 -0
  41. package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +71 -0
  42. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +20 -4
  43. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +29 -0
  44. package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +45 -0
  45. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +132 -10
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +122 -38
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +4 -3
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +66 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +100 -22
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +6 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +45 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +106 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +23 -4
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-asset-actions.tsx +40 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-conversion-result.tsx +20 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +219 -35
  57. package/templates/app-source/src/ai-studio-core/text-annotation-document.ts +50 -0
  58. package/templates/app-source/src/ai-studio-core/text-media-replay.ts +51 -0
  59. package/templates/app-source/src/ai-studio-core/voice-assets.ts +17 -0
  60. package/templates/app-source/src/ai-studio-core/workspace.tsx +48 -6
  61. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +1 -1
  62. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +13 -1
  63. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +13 -1
  64. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
  65. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -2
  66. package/templates/app-source/src/studio-modules/studio-create/registration.ts +2 -2
  67. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +121 -3
  68. package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +72 -0
  69. package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +90 -0
  70. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +16 -1
  71. package/templates/app-source/src/studio-modules/studio-media/index.ts +2 -0
  72. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +225 -7
  73. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +225 -7
  74. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +85 -0
  75. package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +85 -0
  76. package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +64 -0
  77. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +9 -26
  78. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +170 -6
  79. package/templates/app-source/src/studio-modules/studio-media/registration.ts +29 -1
  80. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +90 -6
  81. package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +1 -0
  82. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +23 -5
  83. package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +132 -0
  84. package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +120 -0
  85. package/templates/app-source/src/studio-modules/studio-voice/audio-url.ts +25 -0
  86. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +4 -4
  87. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +4 -4
  88. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +28 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +66 -30
  90. package/templates/app-source/src/workbench-core/index.ts +2 -0
  91. package/templates/app-source/src/workbench-core/runtime-gate.tsx +102 -6
  92. package/templates/app-source/src/workbench-core/workbench-core.css +42 -0
  93. package/templates/app-source/src/workbench-core/workbench-core.tsx +69 -18
  94. package/templates/app-source.manifest.json +100 -0
  95. package/templates/default-starter/README.md +2 -1
  96. package/templates/default-starter/src/shell/workbench-target-adapter.ts +102 -12
  97. package/templates/default-starter.manifest.json +0 -4
@@ -0,0 +1,105 @@
1
+ import { useContext, useEffect, useRef, useState } from 'react';
2
+ import { StudioHistoryResultContext, StudioHistoryPanelContext } from './contexts.js';
3
+ import { Button } from '@nimiplatform/kit/ui';
4
+ import { useAIStudioHost } from './host-context.js';
5
+ import type { StudioCapabilityRunResult } from './runtime-types.js';
6
+ import { forgetStudioJobRecovery, readStudioJobRecovery, type StudioJobRecoveryEntry, type StudioJobRecoveryCapability } from './job-recovery.js';
7
+
8
+ export function StudioJobRecoveryPanel({ disabled, capability = 'music.generate' }: { readonly disabled: boolean; readonly capability?: StudioJobRecoveryCapability }) {
9
+ const host = useAIStudioHost();
10
+ const { translate: t } = host;
11
+ const commitResult = useContext(StudioHistoryResultContext);
12
+ const historyPanel = useContext(StudioHistoryPanelContext);
13
+ const [entries, setEntries] = useState<readonly StudioJobRecoveryEntry[]>([]);
14
+ const [error, setError] = useState('');
15
+ const [busy, setBusy] = useState(false);
16
+ const [result, setResult] = useState<StudioCapabilityRunResult | null>(null);
17
+ const panel = useRef<HTMLDetailsElement | null>(null);
18
+ const abort = useRef<AbortController | null>(null);
19
+ const observation = useRef<AbortController | null>(null);
20
+ const snapshotSequence = useRef(0);
21
+ const [observationIssue, setObservationIssue] = useState(false);
22
+ useEffect(() => () => observation.current?.abort(), [capability]);
23
+ async function refresh() {
24
+ const sequence = ++snapshotSequence.current;
25
+ const next = await readStudioJobRecovery(host.sdk.storage, capability);
26
+ if (sequence === snapshotSequence.current) { setEntries(next); }
27
+ }
28
+ useEffect(() => {
29
+ let active = true;
30
+ const load = () => {
31
+ const sequence = ++snapshotSequence.current;
32
+ void readStudioJobRecovery(host.sdk.storage, capability).then((value) => {
33
+ if (!active || sequence !== snapshotSequence.current) return;
34
+ setEntries(value);
35
+ setResult(previous => {
36
+ if (!previous?.ok || !('jobId' in previous.output)) return previous;
37
+ const jobId = previous.output.jobId;
38
+ return value.some(entry => entry.result?.ok && 'jobId' in entry.result
39
+ && entry.result.jobId === jobId) ? previous : null;
40
+ });
41
+ })
42
+ .catch((cause: unknown) => { if (active && sequence === snapshotSequence.current) setError(cause instanceof Error ? cause.message : String(cause)); });
43
+ };
44
+ load();
45
+ const unsubscribe = host.app.events.subscribeAIConfigRefresh(load);
46
+ return () => { active = false; snapshotSequence.current++; unsubscribe(); };
47
+ }, [host, disabled, capability, historyPanel?.imageRecords]);
48
+ async function recover(entry: StudioJobRecoveryEntry) {
49
+ if (observation.current) return;
50
+ const controller = new AbortController(); abort.current = controller;
51
+ const view = new AbortController(); observation.current = view;
52
+ setBusy(true); setError(''); setResult(null); setObservationIssue(false);
53
+ try {
54
+ const next = await host.sdk.runCapability({ capabilityId: capability, prompt: '', signal: controller.signal, observationSignal: view.signal,
55
+ onObservation: response => { if (!view.signal.aborted) setObservationIssue(Boolean(response.observationIssue)); },
56
+ parameters: { recoverySubmissionId: entry.clientSubmissionId } });
57
+ view.signal.throwIfAborted();
58
+ if (next.ok) {
59
+ controller.signal.throwIfAborted();
60
+ if (!commitResult) throw new Error(t('Music.historyOwnerUnavailable'));
61
+ await commitResult(next, entry.prompt ?? '', entry.runConfig);
62
+ }
63
+ if (view.signal.aborted) return;
64
+ setResult(next);
65
+ if (next.ok && panel.current) panel.current.open = false;
66
+ await refresh();
67
+ } catch (cause) {
68
+ if (view.signal.aborted) return;
69
+ const record = cause && typeof cause === 'object' ? cause as { reasonCode?: unknown; code?: unknown } : null;
70
+ const code = String(record?.reasonCode ?? record?.code ?? '').toLowerCase().replaceAll('-', '_');
71
+ setError(code === 'not_found'
72
+ ? t('Music.recoveryJobNotFound') : cause instanceof Error ? cause.message : String(cause));
73
+ }
74
+ finally { if (observation.current === view) { abort.current = null; observation.current = null; if (!view.signal.aborted) setBusy(false); } }
75
+ }
76
+ if (!entries.length && !error) return null;
77
+ const summaryState = busy ? t('Music.recovering')
78
+ : error || (result && !result.ok) ? t('Music.recoveryNeedsAttention')
79
+ : result?.ok ? t('Music.recovered') : '';
80
+ return <details ref={panel} className="studio-recovery" aria-label={t('Music.recoveryTitle')}>
81
+ <summary>
82
+ {t('Music.recoveryTitle')} <span>({entries.length})</span>
83
+ {summaryState ? <span className="studio-recovery__state" role="status" title={summaryState}>{summaryState}</span> : null}
84
+ </summary>
85
+ <div className="studio-recovery__body">
86
+ <p className="text-sm opacity-70">{t('Music.recoveryHint')}</p>
87
+ <div className="max-h-48 space-y-2 overflow-y-auto">
88
+ {[...entries].reverse().map((entry) => <div key={entry.clientSubmissionId} className="flex flex-wrap items-center gap-2">
89
+ <time dateTime={entry.createdAt}>{new Date(entry.createdAt).toLocaleString(host.locale)}</time>
90
+ <Button disabled={disabled || busy} onClick={() => void recover(entry)}>{t(entry.result ? 'Music.openSaved' : 'Music.recover')}</Button>
91
+ <Button disabled={disabled || busy} onClick={() => void forgetStudioJobRecovery(host.sdk.storage, entry.clientSubmissionId, capability).then(() => {
92
+ setResult(null); setError(''); return refresh();
93
+ })
94
+ .catch((cause: unknown) => setError(cause instanceof Error ? cause.message : String(cause)))}>{t('Music.forgetRecord')}</Button>
95
+ </div>)}
96
+ </div>
97
+ {busy ? <div className="flex items-center gap-2"><span>{t('Music.recovering')}</span><Button onClick={() => abort.current?.abort()}>{t('Music.cancelJob')}</Button></div> : null}
98
+ {error ? <p role="alert">{error}</p> : null}
99
+ {result && !result.ok ? <p role="alert">{result.diagnostics?.reasonCode === 'NOT_FOUND'
100
+ ? t('Music.recoveryJobNotFound') : result.message}</p> : null}
101
+ {observationIssue && busy ? <p role="status">{t('Music.observationIssue')}</p> : null}
102
+ {result?.ok ? <p role="status">{t('Music.recovered')}</p> : null}
103
+ </div>
104
+ </details>;
105
+ }
@@ -0,0 +1,224 @@
1
+ import { ScenarioType, VisionLocateGeometry } from '@nimiplatform/sdk/runtime/generated';
2
+ import { isJsonObject } from '@nimiplatform/sdk/types';
3
+ import type { NimiLocalAppClient } from '@nimiplatform/sdk/app';
4
+ import type { JsonValue } from '@nimiplatform/sdk/types';
5
+ import { createStudioRunHistoryResultSnapshot, restoreStudioCapabilityRunResult, type StudioRunHistoryResultSnapshot } from './history.js';
6
+ import { validateManagedArtifact, validateStudioHistoryResult, validateRunConfig, validateFaceSwapHistory } from './history-policy.js';
7
+ import type { StudioRunConfigSnapshot } from './history.js';
8
+ import { studioResultAssetPaths, studioResultAssetReferences, verifyStudioManagedAsset } from './managed-result-references.js';
9
+ import type { StudioAudioSeparationRequest, StudioCapabilityRunResult, StudioManagedArtifact } from './runtime-types.js';
10
+ import { isAudioSeparationRequest } from './audio-separation-request.js';
11
+
12
+ type Storage = Pick<NimiLocalAppClient['storage'], 'readJson' | 'writeJson'>;
13
+ export type StudioJobRecoveryEntry = {
14
+ readonly details?: StudioJobRecoveryDetails;
15
+ readonly clientSubmissionId: string;
16
+ readonly createdAt: string;
17
+ readonly message?: string;
18
+ readonly result?: StudioRunHistoryResultSnapshot;
19
+ readonly sourceAudio?: StudioManagedArtifact;
20
+ readonly targetAudio?: StudioManagedArtifact;
21
+ readonly jobId?: string;
22
+ readonly separationRequest?: StudioAudioSeparationRequest;
23
+ readonly prompt?: string;
24
+ readonly runConfig?: StudioRunConfigSnapshot;
25
+ };
26
+ export type StudioJobRecoveryCapability = keyof typeof paths;
27
+ export type StudioJobRecoveryDetails = {
28
+ readonly sourceImage?: StudioManagedArtifact;
29
+ readonly scenarioType: import('@nimiplatform/sdk/runtime/generated').ScenarioType;
30
+ readonly expectedVision?: { readonly imageArtifactId: string; readonly geometry: import('@nimiplatform/sdk/runtime/generated').VisionLocateGeometry };
31
+ readonly creationSource?: 'reference-audio' | 'text-description';
32
+ readonly timestamps?: boolean;
33
+ readonly texts?: readonly string[];
34
+ readonly faceSwap?: import('./runtime-types.js').StudioFaceSwap;
35
+ };
36
+ const paths = { 'audio.speaker.embed': 'studio/speaker-embedding-recovery.json', 'image.generate': 'studio/image-recovery.json', 'video.generate': 'studio/video-recovery.json', 'audio.synthesize': 'studio/speech-recovery.json', 'audio.transcribe': 'studio/transcript-recovery.json', 'voice.create': 'studio/voice-recovery.json', 'vision.locate': 'studio/locate-recovery.json', 'text.annotate': 'studio/annotation-recovery.json', 'image.face_swap': 'studio/image-face-recovery.json', 'video.face_swap': 'studio/video-face-recovery.json', 'music.generate': 'studio/music-recovery.json', 'music.transcribe': 'studio/music-transcription-recovery.json', 'audio.voice.convert': 'studio/voice-convert-recovery.json', 'audio.separate': 'studio/audio-separation-recovery.json' };
37
+ let mutationTail: Promise<unknown> = Promise.resolve();
38
+
39
+ export async function readStudioJobRecovery(storage: Storage, capability: StudioJobRecoveryCapability = 'music.generate'): Promise<readonly StudioJobRecoveryEntry[]> {
40
+ let value: unknown;
41
+ try { value = (await storage.readJson(paths[capability])).value; }
42
+ catch (cause) {
43
+ const error = cause as { reasonCode?: string; code?: string };
44
+ const code = String(error?.reasonCode ?? error?.code ?? '').toLowerCase().replaceAll('-', '_');
45
+ if (code === 'not_found' || code === 'app_storage_entry_not_found') return [];
46
+ throw cause;
47
+ }
48
+ if (!Array.isArray(value)) throw new Error('Invalid saved task recovery entries');
49
+ const ids = new Set<string>();
50
+ for (const item of value) {
51
+ if (!item || typeof item !== 'object' || typeof item.clientSubmissionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(item.clientSubmissionId)
52
+ || ids.has(item.clientSubmissionId) || typeof item.createdAt !== 'string' || !Number.isFinite(Date.parse(item.createdAt))
53
+ || Object.keys(item).some((key) => !['clientSubmissionId', 'createdAt', 'message', 'result', 'prompt', 'runConfig', 'jobId', 'details',
54
+ ...(capability === 'music.generate' ? [] : ['sourceAudio']),
55
+ ...(capability === 'audio.voice.convert' ? ['targetAudio'] : []),
56
+ ...(capability === 'audio.separate' ? ['separationRequest'] : [])].includes(key))) throw new Error('Invalid saved task recovery entry');
57
+ ids.add(item.clientSubmissionId);
58
+ if (item.details !== undefined) validateRecoveryDetails(item.details);
59
+ if (item.prompt !== undefined && typeof item.prompt !== 'string') throw new Error('Invalid saved task prompt');
60
+ if (item.runConfig !== undefined) {
61
+ validateRunConfig(item.runConfig, 'task recovery request');
62
+ if (item.runConfig.target.capabilityId !== capability) throw new Error('Task recovery request has a different capability');
63
+ }
64
+ if (item.separationRequest !== undefined && !isAudioSeparationRequest(item.separationRequest)) throw new Error('Invalid saved separation request');
65
+ if (item.jobId !== undefined
66
+ && (typeof item.jobId !== 'string' || item.jobId.length < 1 || item.jobId.length > 256 || item.jobId !== item.jobId.trim())) throw new Error('Invalid saved task recovery entry');
67
+ if (['music.transcribe', 'audio.voice.convert', 'audio.separate'].includes(capability)) validateManagedArtifact(item.sourceAudio, 'task recovery source');
68
+ if (capability === 'audio.voice.convert' && item.targetAudio !== undefined) validateManagedArtifact(item.targetAudio, 'voice conversion recovery target');
69
+ if (item.result !== undefined) {
70
+ validateStudioHistoryResult(item.result, 'task recovery');
71
+ const complete = capability === 'music.transcribe' ? item.result.musicTranscription
72
+ : capability === 'audio.voice.convert' ? item.result.voiceConversion
73
+ : capability === 'audio.separate' ? item.result.audioSeparation : capability === 'music.generate' ? item.result.musicGeneration : true;
74
+ if (!item.result.ok || !complete || typeof item.message !== 'string') throw new Error('Incomplete saved task result');
75
+ const savedRequest = capability === 'audio.separate' ? item.result.audioSeparation?.request : undefined;
76
+ if (savedRequest && item.separationRequest && (savedRequest.kind !== item.separationRequest.kind
77
+ || savedRequest.startSeconds !== item.separationRequest.startSeconds
78
+ || savedRequest.endSeconds !== item.separationRequest.endSeconds)) throw new Error('Saved separation request conflicts with its result');
79
+ }
80
+ }
81
+ return value as StudioJobRecoveryEntry[];
82
+ }
83
+
84
+ async function mutate(storage: Storage, update: (entries: readonly StudioJobRecoveryEntry[]) => StudioJobRecoveryEntry[], capability: StudioJobRecoveryCapability) {
85
+ const next = mutationTail.then(async () => {
86
+ const entries = update(await readStudioJobRecovery(storage, capability));
87
+ // This is bounded recovery storage, not business-history retention. Never
88
+ // discard an unindexed result to make room for a newer author action.
89
+ if (new TextEncoder().encode(JSON.stringify(entries)).length > 240 * 1024) {
90
+ throw new Error('Task recovery storage is full; explicitly remove completed recovery entries after verifying their saved history.');
91
+ }
92
+ await storage.writeJson(paths[capability], JSON.parse(JSON.stringify(entries)) as JsonValue);
93
+ });
94
+ mutationTail = next.catch(() => undefined);
95
+ await next;
96
+ }
97
+
98
+ export async function beginStudioJobRecovery(storage: Storage, capability: StudioJobRecoveryCapability = 'music.generate', sourceAudio?: StudioManagedArtifact, targetAudio?: StudioManagedArtifact, separationRequest?: StudioAudioSeparationRequest, runConfig?: StudioRunConfigSnapshot, prompt?: string, details?: StudioJobRecoveryDetails): Promise<string> {
99
+ if (['music.transcribe', 'audio.voice.convert', 'audio.separate'].includes(capability)) validateManagedArtifact(sourceAudio, 'task recovery source');
100
+ if (targetAudio !== undefined) validateManagedArtifact(targetAudio, 'voice conversion recovery target');
101
+ if (separationRequest !== undefined && (capability !== 'audio.separate' || !isAudioSeparationRequest(separationRequest))) throw new Error('Invalid separation request');
102
+ if (details) validateRecoveryDetails(details);
103
+ const clientSubmissionId = crypto.randomUUID();
104
+ await mutate(storage, (entries) => [...entries, { clientSubmissionId, createdAt: new Date().toISOString(), ...(sourceAudio ? { sourceAudio } : {}), ...(targetAudio ? { targetAudio } : {}), ...(separationRequest ? { separationRequest } : {}), ...(runConfig ? { runConfig } : {}), ...(prompt === undefined ? {} : { prompt }), ...(details ? { details } : {}) }], capability);
105
+ return clientSubmissionId;
106
+ }
107
+
108
+ export async function captureStudioJobRecoveryJobId(storage: Storage, id: string, jobId: string, capability: StudioJobRecoveryCapability = 'music.generate') {
109
+ if (!jobId || jobId.length > 256 || jobId !== jobId.trim()) throw new Error('Invalid task recovery job identity');
110
+ await mutate(storage, (entries) => {
111
+ const current = entries.find(entry => entry.clientSubmissionId === id);
112
+ if (!current || (current.jobId && current.jobId !== jobId)) throw new Error('Saved action has a different Job identity');
113
+ return entries.map(entry => entry.clientSubmissionId === id ? { ...entry, jobId } : entry);
114
+ }, capability);
115
+ }
116
+
117
+ export async function saveStudioJobRecoveryResult(storage: Storage, id: string, result: StudioCapabilityRunResult, capability: StudioJobRecoveryCapability = 'music.generate') {
118
+ if (!result.ok) return;
119
+ if (result.capabilityId !== capability) throw new Error('Saved result belongs to a different capability');
120
+ if (['music.generate', 'music.transcribe', 'audio.voice.convert', 'audio.separate'].includes(capability) && result.output.kind !== 'artifacts') throw new Error('Recovery requires the complete adopted result');
121
+ const media = result.output.kind === 'artifacts' ? result.output : undefined;
122
+ const complete = capability === 'music.transcribe' ? media?.musicTranscription
123
+ : capability === 'audio.voice.convert' ? media?.voiceConversion
124
+ : capability === 'audio.separate' ? media?.audioSeparation : capability === 'music.generate' ? media?.musicGeneration : true;
125
+ if (!complete) throw new Error('Task recovery requires the complete adopted result');
126
+ const snapshot = createStudioRunHistoryResultSnapshot(result);
127
+ await mutate(storage, (entries) => {
128
+ const entry = entries.find(item => item.clientSubmissionId === id);
129
+ if (!entry || !('jobId' in result.output) || (entry.jobId && entry.jobId !== result.output.jobId)) throw new Error('Saved result does not belong to the recorded action');
130
+ return entries.map((entry) => entry.clientSubmissionId === id ? { ...entry, message: result.message, result: snapshot } : entry);
131
+ }, capability);
132
+ }
133
+
134
+ export async function forgetStudioJobRecovery(storage: Storage, id: string, capability: StudioJobRecoveryCapability = 'music.generate') {
135
+ await mutate(storage, (entries) => entries.filter((entry) => entry.clientSubmissionId !== id), capability);
136
+ }
137
+
138
+ export async function restoreSavedStudioJobResult(entry: StudioJobRecoveryEntry, label: string, capability: StudioJobRecoveryCapability,
139
+ assets: Pick<NimiLocalAppClient['storage']['assets'], 'read'>, signal?: AbortSignal): Promise<StudioCapabilityRunResult | null> {
140
+ if (!entry.result) return null;
141
+ await verifySavedStudioJobAssets(entry, assets, signal);
142
+ signal?.throwIfAborted();
143
+ const result = restoreStudioCapabilityRunResult({ capabilityId: capability, result: entry.result, message: entry.message ?? '' }, () => label);
144
+ if (capability === 'audio.separate' && entry.separationRequest && result?.ok && result.output.kind === 'artifacts' && result.output.audioSeparation) {
145
+ return { ...result, output: { ...result.output,
146
+ audioSeparation: { ...result.output.audioSeparation, request: entry.separationRequest } } };
147
+ }
148
+ return result;
149
+ }
150
+
151
+ export async function verifySavedStudioJobAssets(entry: StudioJobRecoveryEntry,
152
+ assets: Pick<NimiLocalAppClient['storage']['assets'], 'read'>, signal?: AbortSignal): Promise<void> {
153
+ if (!entry.result) return;
154
+ const refs = studioResultAssetReferences(entry.result);
155
+ for (const path of studioResultAssetPaths(entry.result)) {
156
+ const references = refs.filter(ref => ref.relativePath === path);
157
+ const expected: { relativePath: string; sha256?: string; sizeBytes?: number; mediaType?: string } = { relativePath: path };
158
+ for (const ref of references) {
159
+ for (const key of ['sha256', 'sizeBytes', 'mediaType'] as const) {
160
+ const value = ref[key];
161
+ if (value === undefined) continue;
162
+ if ((key === 'sizeBytes' ? typeof value !== 'number' : typeof value !== 'string') || (expected[key] !== undefined && expected[key] !== value)) throw new Error('Saved asset roles disagree');
163
+ Object.assign(expected, { [key]: value });
164
+ }
165
+ }
166
+ await verifyStudioManagedAsset(assets, expected, signal);
167
+ }
168
+ }
169
+
170
+ /** Submit only after beginStudioJobRecovery has durably recorded this action. */
171
+ export function recordedStudioScenarioJobClient(context: import('./runtime.js').StudioCapabilityRuntimeContext,
172
+ clientSubmissionId: string, capability: StudioJobRecoveryCapability) {
173
+ const api = context.host.client.ai;
174
+ return context.host.createScenarioJobClient({ ...api, scenarioJobs: { ...api.scenarioJobs,
175
+ async submit(spec, options) {
176
+ context.input.observationSignal?.throwIfAborted();
177
+ context.input.signal?.throwIfAborted();
178
+ const entry = (await readStudioJobRecovery(context.host.client.storage, capability)).find(item => item.clientSubmissionId === clientSubmissionId);
179
+ if (!entry || entry.jobId) throw new Error('The recorded action is missing or already submitted');
180
+ context.input.observationSignal?.throwIfAborted();
181
+ context.input.signal?.throwIfAborted();
182
+ const response = await api.scenarioJobs.submit(spec, { ...options, clientSubmissionId });
183
+ await captureStudioJobRecoveryJobId(context.host.client.storage, clientSubmissionId, response.job.jobId, capability);
184
+ return response;
185
+ },
186
+ } });
187
+ }
188
+
189
+ export async function recoverStudioJobId(client: NimiLocalAppClient, entry: StudioJobRecoveryEntry, capability: StudioJobRecoveryCapability): Promise<string> {
190
+ const response = entry.jobId ? await client.ai.scenarioJobs.get(entry.jobId) : await client.ai.scenarioJobs.lookupSubmission(entry.clientSubmissionId);
191
+ await captureStudioJobRecoveryJobId(client.storage, entry.clientSubmissionId, response.job.jobId, capability);
192
+ return response.job.jobId;
193
+ }
194
+
195
+ export function isStudioJobRecoveryCapability(value: string): value is StudioJobRecoveryCapability {
196
+ return Object.hasOwn(paths, value);
197
+ }
198
+
199
+ function validateRecoveryDetails(value: unknown): asserts value is StudioJobRecoveryDetails {
200
+ const fail = () => { throw new Error('Saved task inputs are invalid'); };
201
+ if (!isJsonObject(value) || Object.keys(value).some(key => !['scenarioType', 'sourceImage', 'expectedVision', 'creationSource', 'timestamps', 'texts', 'faceSwap'].includes(key))
202
+ || typeof value.scenarioType !== 'number' || value.scenarioType <= 0 || !Object.values(ScenarioType).includes(value.scenarioType)) return fail();
203
+ if (value.expectedVision !== undefined || value.sourceImage !== undefined) {
204
+ if (value.scenarioType !== ScenarioType.VISION_LOCATE || !isJsonObject(value.expectedVision)
205
+ || Object.keys(value.expectedVision).some(key => !['imageArtifactId', 'geometry'].includes(key))
206
+ || typeof value.expectedVision.imageArtifactId !== 'string' || !value.expectedVision.imageArtifactId.trim()
207
+ || ![VisionLocateGeometry.BOX, VisionLocateGeometry.POINT].includes(Number(value.expectedVision.geometry))) return fail();
208
+ validateManagedArtifact(value.sourceImage, 'saved Locate image');
209
+ }
210
+ if (value.creationSource !== undefined && (value.scenarioType !== ScenarioType.VOICE_CREATE || !['reference-audio', 'text-description'].includes(String(value.creationSource)))) return fail();
211
+ if (value.timestamps !== undefined && (value.scenarioType !== ScenarioType.SPEECH_TRANSCRIBE || typeof value.timestamps !== 'boolean')) return fail();
212
+ if (value.texts !== undefined && (value.scenarioType !== ScenarioType.TEXT_ANNOTATE || !Array.isArray(value.texts) || !value.texts.length || value.texts.length > 64 || value.texts.some(text => typeof text !== 'string'))) return fail();
213
+ if (value.faceSwap !== undefined) {
214
+ if (![ScenarioType.IMAGE_FACE_SWAP, ScenarioType.VIDEO_FACE_SWAP].includes(value.scenarioType)) return fail();
215
+ validateFaceSwapHistory(value.faceSwap, 'saved face replacement');
216
+ }
217
+ }
218
+
219
+ export const studioJobRecoveryCapabilities = Object.freeze(Object.keys(paths) as StudioJobRecoveryCapability[]);
220
+
221
+ /** Local result work stops for either view disposal or the current user action. */
222
+ export function studioJobRecoverySignal(input: { readonly signal?: AbortSignal; readonly observationSignal?: AbortSignal }): AbortSignal {
223
+ return AbortSignal.any([input.signal, input.observationSignal].filter((value): value is AbortSignal => Boolean(value)));
224
+ }
@@ -0,0 +1,79 @@
1
+ import type { StudioManagedArtifact } from './runtime-types.js';
2
+
3
+ /** App-owned references from the submitted inputs and every saved output role. */
4
+ export function studioResultAssetReferences(value: unknown): readonly Record<string, unknown>[] {
5
+ if (!value || typeof value !== 'object' || (value as { ok?: unknown }).ok === false) return [];
6
+ const result = value as Record<string, unknown>;
7
+ const references: Record<string, unknown>[] = [];
8
+ const add = (item: unknown) => {
9
+ if (item && typeof item === 'object' && typeof (item as Record<string, unknown>).relativePath === 'string') {
10
+ references.push(item as Record<string, unknown>);
11
+ }
12
+ };
13
+ const nested = (key: string) => result[key] && typeof result[key] === 'object' ? result[key] as Record<string, unknown> : {};
14
+ add(result.sourceImage); add(result.preview); add(result.document);
15
+ add(result.firstArtifact);
16
+ if (Array.isArray(result.artifacts)) result.artifacts.forEach(add);
17
+ const transcription = nested('musicTranscription');
18
+ add(transcription.sourceAudio);
19
+ if (Array.isArray(transcription.scores)) transcription.scores.forEach(add);
20
+ const separation = nested('audioSeparation');
21
+ add(separation.sourceAudio); add(separation.vocals); add(separation.background);
22
+ if (Array.isArray(separation.instrumentParts)) separation.instrumentParts.forEach(part => add(part?.artifact));
23
+ const conversion = nested('voiceConversion');
24
+ add(conversion.sourceVocal); add(conversion.targetVoice); add(conversion.vocal);
25
+ const generation = nested('musicGeneration');
26
+ add(generation.generatedScore);
27
+ if (typeof generation.mixRelativePath === 'string') add({ relativePath: generation.mixRelativePath });
28
+ return references;
29
+ }
30
+
31
+ export function studioResultAssetPaths(value: unknown): string[] {
32
+ return [...new Set(studioResultAssetReferences(value).map(item => item.relativePath as string))];
33
+ }
34
+
35
+ export function studioWorldInputSource(p: Readonly<Record<string, unknown>>): StudioManagedArtifact | undefined {
36
+ if (!['ordinary', 'equirectangular-360'].includes(String(p.inputMode)) || typeof p.sourceRelativePath !== 'string' ||
37
+ !/^world-tour\/inputs\/[0-9a-f-]+\.(png|jpg|webp)$/u.test(p.sourceRelativePath) ||
38
+ !Number.isSafeInteger(p.sourceSizeBytes) || Number(p.sourceSizeBytes) < 1 || Number(p.sourceSizeBytes) > 20_000_000 ||
39
+ typeof p.sourceSHA256 !== 'string' || !/^sha256:[0-9a-f]{64}$/u.test(p.sourceSHA256) ||
40
+ !['image/png', 'image/jpeg', 'image/webp'].includes(String(p.sourceMediaType)) ||
41
+ !Number.isSafeInteger(p.sourceWidth) || !Number.isSafeInteger(p.sourceHeight) || Number(p.sourceWidth) < 1 || Number(p.sourceHeight) < 1 ||
42
+ (p.inputMode === 'equirectangular-360' && p.sourceWidth !== 2 * Number(p.sourceHeight))) return undefined;
43
+ return { relativePath: p.sourceRelativePath, mediaType: String(p.sourceMediaType), sizeBytes: Number(p.sourceSizeBytes),
44
+ sha256: p.sourceSHA256, displayName: String(p.sourceName || ''), previewSource: 'managed-asset' };
45
+ }
46
+
47
+ /** The admitted full reader verifies the owner digest; exhaust it to observe all
48
+ * integrity/retention failures, without retaining media bytes in renderer memory. */
49
+ export async function verifyStudioManagedAsset(
50
+ assets: Pick<import('@nimiplatform/sdk/app').NimiLocalAppAssetsClient, 'read'>,
51
+ expected: { readonly relativePath: string; readonly sha256?: string; readonly sizeBytes?: number; readonly mediaType?: string },
52
+ signal?: AbortSignal,
53
+ ): Promise<void> {
54
+ signal?.throwIfAborted();
55
+ const read = await assets.read({ relativePath: expected.relativePath });
56
+ const iterator = read.body[Symbol.asyncIterator]();
57
+ let size = 0;
58
+ let closing: Promise<unknown> | undefined;
59
+ const close = () => closing ??= Promise.resolve().then(() => iterator.return?.());
60
+ const abort = () => { void close().catch(() => undefined); };
61
+ signal?.addEventListener('abort', abort, { once: true });
62
+ try {
63
+ signal?.throwIfAborted();
64
+ if (read.asset.relativePath !== expected.relativePath || read.range.offset !== 0 || read.range.length !== read.asset.sizeBytes
65
+ || (expected.sha256 !== undefined && read.asset.sha256 !== expected.sha256)
66
+ || (expected.sizeBytes !== undefined && read.asset.sizeBytes !== expected.sizeBytes)
67
+ || (expected.mediaType !== undefined && read.asset.mediaType !== expected.mediaType)) throw new Error('Saved asset no longer matches its result');
68
+ for (;;) {
69
+ signal?.throwIfAborted();
70
+ const next = await iterator.next();
71
+ signal?.throwIfAborted();
72
+ if (next.done) break;
73
+ size += next.value.byteLength;
74
+ if (size > read.asset.sizeBytes) throw new Error('Saved asset is larger than recorded');
75
+ }
76
+ if (size !== read.asset.sizeBytes) throw new Error('Saved asset is incomplete');
77
+ signal?.throwIfAborted();
78
+ } finally { signal?.removeEventListener('abort', abort); await close(); }
79
+ }