@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.
- package/README.md +59 -5
- package/bin/nimi-app.mjs +11 -3
- package/lib/app-access-declaration.mjs +1 -0
- package/lib/app-dependency-combinations.mjs +16 -28
- package/lib/app-doctor-update.mjs +66 -7
- package/lib/app-info.mjs +8 -1
- package/lib/app-project-lifecycle.mjs +82 -9
- package/lib/app-scaffold-capabilities.mjs +3 -3
- package/lib/app-scaffold-profiles.mjs +96 -26
- package/lib/app-scaffold.mjs +54 -7
- package/lib/canonical-capability-ids.generated.mjs +4 -0
- package/package.json +26 -25
- package/scripts/dev-shell.mjs +61 -17
- package/skills/nimi-app-lifecycle/references/acceptance.md +1 -1
- package/skills/nimi-app-lifecycle/references/adapt.md +2 -2
- package/skills/nimi-app-lifecycle/references/release.md +1 -1
- package/skills/nimi-app-lifecycle/references/upgrade-platform.md +14 -0
- package/templates/app-source/src/ai-studio-core/ai-config.ts +17 -3
- package/templates/app-source/src/ai-studio-core/ai-studio-core.css +40 -3
- package/templates/app-source/src/ai-studio-core/audio-separation-request.ts +24 -0
- package/templates/app-source/src/ai-studio-core/contexts.tsx +4 -0
- package/templates/app-source/src/ai-studio-core/history-policy.ts +395 -41
- package/templates/app-source/src/ai-studio-core/history.ts +262 -10
- package/templates/app-source/src/ai-studio-core/host-context.tsx +15 -2
- package/templates/app-source/src/ai-studio-core/index.ts +15 -4
- package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +105 -0
- package/templates/app-source/src/ai-studio-core/job-recovery.ts +224 -0
- package/templates/app-source/src/ai-studio-core/managed-result-references.ts +79 -0
- package/templates/app-source/src/ai-studio-core/messages/en.json +185 -10
- package/templates/app-source/src/ai-studio-core/messages/zh.json +185 -10
- package/templates/app-source/src/ai-studio-core/module-registration.ts +9 -1
- package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +81 -2
- package/templates/app-source/src/ai-studio-core/parameters.ts +34 -1
- package/templates/app-source/src/ai-studio-core/runtime-types.ts +124 -8
- package/templates/app-source/src/ai-studio-core/runtime.ts +218 -20
- package/templates/app-source/src/ai-studio-core/section-ai-testing-annotation-result.tsx +123 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +3 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-audio-separation-result.tsx +26 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +14 -7
- package/templates/app-source/src/ai-studio-core/section-ai-testing-decision-result.tsx +76 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +71 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +20 -4
- package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +29 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +45 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +132 -10
- package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +122 -38
- package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +4 -3
- package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +66 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +100 -22
- package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +6 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +45 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +106 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +23 -4
- package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-asset-actions.tsx +40 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-conversion-result.tsx +20 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +219 -35
- package/templates/app-source/src/ai-studio-core/text-annotation-document.ts +50 -0
- package/templates/app-source/src/ai-studio-core/text-media-replay.ts +51 -0
- package/templates/app-source/src/ai-studio-core/voice-assets.ts +17 -0
- package/templates/app-source/src/ai-studio-core/workspace.tsx +48 -6
- package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +1 -1
- package/templates/app-source/src/studio-modules/studio-create/messages/en.json +13 -1
- package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +13 -1
- package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
- package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -2
- package/templates/app-source/src/studio-modules/studio-create/registration.ts +2 -2
- package/templates/app-source/src/studio-modules/studio-create/runtime.ts +121 -3
- package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +72 -0
- package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +90 -0
- package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +16 -1
- package/templates/app-source/src/studio-modules/studio-media/index.ts +2 -0
- package/templates/app-source/src/studio-modules/studio-media/messages/en.json +225 -7
- package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +225 -7
- package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +85 -0
- package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +85 -0
- package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +64 -0
- package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +9 -26
- package/templates/app-source/src/studio-modules/studio-media/parameters.ts +170 -6
- package/templates/app-source/src/studio-modules/studio-media/registration.ts +29 -1
- package/templates/app-source/src/studio-modules/studio-media/runtime.ts +90 -6
- package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +1 -0
- package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +23 -5
- package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +132 -0
- package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +120 -0
- package/templates/app-source/src/studio-modules/studio-voice/audio-url.ts +25 -0
- package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +4 -4
- package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +4 -4
- package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +28 -0
- package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +66 -30
- package/templates/app-source/src/workbench-core/index.ts +2 -0
- package/templates/app-source/src/workbench-core/runtime-gate.tsx +102 -6
- package/templates/app-source/src/workbench-core/workbench-core.css +42 -0
- package/templates/app-source/src/workbench-core/workbench-core.tsx +69 -18
- package/templates/app-source.manifest.json +100 -0
- package/templates/default-starter/README.md +2 -1
- package/templates/default-starter/src/shell/workbench-target-adapter.ts +102 -12
- package/templates/default-starter.manifest.json +0 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
|
2
2
|
import { nimiToast } from '@nimiplatform/kit/ui';
|
|
3
3
|
|
|
4
4
|
import {
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
StudioHistoryActionsContext,
|
|
7
7
|
StudioHistoryLoadContext,
|
|
8
8
|
StudioHistoryPanelContext,
|
|
9
|
+
StudioHistoryResultContext,
|
|
9
10
|
type StudioCapabilityParameterStore,
|
|
10
11
|
type StudioHistoryActions,
|
|
11
12
|
type StudioHistoryLoadState,
|
|
@@ -34,7 +35,7 @@ export type AIStudioHistoryProjection = {
|
|
|
34
35
|
};
|
|
35
36
|
|
|
36
37
|
export type AIStudioHistoryPersistOutcome =
|
|
37
|
-
| { readonly ok: true; readonly projection: AIStudioHistoryProjection }
|
|
38
|
+
| { readonly ok: true; readonly projection: AIStudioHistoryProjection; readonly record?: StudioRunHistoryRecord }
|
|
38
39
|
| {
|
|
39
40
|
readonly ok: false;
|
|
40
41
|
readonly message: string;
|
|
@@ -113,6 +114,7 @@ export type AIStudioWorkspaceController = {
|
|
|
113
114
|
prompt: string,
|
|
114
115
|
runConfig?: StudioRunConfigSnapshot,
|
|
115
116
|
) => Promise<StudioRunHistoryRecord>;
|
|
117
|
+
readonly appendHistoryRecord: (record: StudioRunHistoryRecord) => Promise<void>;
|
|
116
118
|
readonly history: StudioRunHistory | null;
|
|
117
119
|
readonly lastResult: StudioCapabilityRunResult | null;
|
|
118
120
|
readonly historySelectionRequest: { readonly requestId: number; readonly record: StudioRunHistoryRecord } | null;
|
|
@@ -147,18 +149,53 @@ export function useAIStudioWorkspaceController({
|
|
|
147
149
|
const [historyPanel, setHistoryPanel] = useState<AIStudioHistoryPanelPreferences>(
|
|
148
150
|
historyRepository.loadPanelPreferences,
|
|
149
151
|
);
|
|
152
|
+
const currentRepository = useRef(historyRepository);
|
|
153
|
+
currentRepository.current = historyRepository;
|
|
154
|
+
const active = useRef(true);
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
active.current = true;
|
|
157
|
+
return () => { active.current = false; };
|
|
158
|
+
}, []);
|
|
150
159
|
|
|
151
160
|
const refreshHistory = useCallback(async () => {
|
|
152
161
|
try {
|
|
153
|
-
|
|
162
|
+
const next = await historyRepository.load();
|
|
163
|
+
if (!active.current || currentRepository.current !== historyRepository) return;
|
|
164
|
+
setProjection(next);
|
|
154
165
|
setHistoryIssue(null);
|
|
155
166
|
} catch (error) {
|
|
167
|
+
if (!active.current || currentRepository.current !== historyRepository) return;
|
|
156
168
|
setHistoryIssue({ kind: 'load', message: errorMessage(error, 'History load failed.') });
|
|
157
169
|
}
|
|
158
170
|
}, [historyRepository]);
|
|
159
171
|
|
|
160
172
|
useEffect(() => { void refreshHistory(); }, [refreshHistory]);
|
|
161
173
|
|
|
174
|
+
// Integration workflows already own the actual run identity and privacy
|
|
175
|
+
// policy. Commit through this repository and update the mounted workbench.
|
|
176
|
+
const appendHistoryRecord = useCallback(async (record: StudioRunHistoryRecord) => {
|
|
177
|
+
if (!active.current || currentRepository.current !== historyRepository) return;
|
|
178
|
+
try {
|
|
179
|
+
const next = await historyRepository.appendRecord(record);
|
|
180
|
+
if (!active.current || currentRepository.current !== historyRepository) return;
|
|
181
|
+
setProjection(next);
|
|
182
|
+
setHistoryIssue((current) => {
|
|
183
|
+
if (!current || current.kind === 'load') return null;
|
|
184
|
+
const records = current.records.filter((pending) => pending.id !== record.id);
|
|
185
|
+
return records.length === 0 && current.cleanupPaths.length === 0 ? null : { ...current, records };
|
|
186
|
+
});
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (active.current && currentRepository.current === historyRepository) {
|
|
189
|
+
setHistoryIssue((current) => ({
|
|
190
|
+
kind: 'save', message: errorMessage(error, 'History persistence failed.'),
|
|
191
|
+
records: [...(current?.kind === 'save' ? current.records.filter((pending) => pending.id !== record.id) : []), record],
|
|
192
|
+
cleanupPaths: current?.kind === 'save' ? current.cleanupPaths : [],
|
|
193
|
+
}));
|
|
194
|
+
}
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}, [historyRepository]);
|
|
198
|
+
|
|
162
199
|
const parameterStore = useMemo(() => ({
|
|
163
200
|
state: parameters,
|
|
164
201
|
setParameters: (capabilityId: string, value: Readonly<Record<string, unknown>>) => {
|
|
@@ -225,7 +262,7 @@ export function useAIStudioWorkspaceController({
|
|
|
225
262
|
setLastResult(result);
|
|
226
263
|
const identity = await historyRepository.nextIdentity();
|
|
227
264
|
const status = historyRepository.statusForResult?.(result);
|
|
228
|
-
const record = createStudioRunHistoryRecord({
|
|
265
|
+
const record = result.recordedHistory ?? createStudioRunHistoryRecord({
|
|
229
266
|
result,
|
|
230
267
|
prompt,
|
|
231
268
|
runId: identity.runId,
|
|
@@ -245,12 +282,14 @@ export function useAIStudioWorkspaceController({
|
|
|
245
282
|
setProjection(outcome.projection);
|
|
246
283
|
setHistoryIssue((current) => {
|
|
247
284
|
if (!current || current.kind === 'load') return null;
|
|
248
|
-
const records = current.records.filter((pending) => pending.id !== record.id
|
|
285
|
+
const records = current.records.filter((pending) => pending.id !== record.id
|
|
286
|
+
&& !(pending.capabilityId === record.capabilityId && pending.result?.ok && record.result?.ok
|
|
287
|
+
&& 'jobId' in pending.result && 'jobId' in record.result && pending.result.jobId === record.result.jobId));
|
|
249
288
|
return records.length === 0 && current.cleanupPaths.length === 0
|
|
250
289
|
? null
|
|
251
290
|
: { ...current, records };
|
|
252
291
|
});
|
|
253
|
-
return record;
|
|
292
|
+
return outcome.record ?? record;
|
|
254
293
|
}
|
|
255
294
|
if (outcome.displayFailure) {
|
|
256
295
|
const capability = registrations.find((item) => item.descriptor.id === result.capabilityId)?.descriptor;
|
|
@@ -331,6 +370,7 @@ export function useAIStudioWorkspaceController({
|
|
|
331
370
|
historyActions,
|
|
332
371
|
historyPanelState,
|
|
333
372
|
handleResult,
|
|
373
|
+
appendHistoryRecord,
|
|
334
374
|
history: projection?.runHistory ?? null,
|
|
335
375
|
lastResult,
|
|
336
376
|
historySelectionRequest,
|
|
@@ -354,6 +394,7 @@ export function AIStudioWorkspace({
|
|
|
354
394
|
<StudioHistoryLoadContext.Provider value={controller.historyLoadState}>
|
|
355
395
|
<StudioHistoryActionsContext.Provider value={controller.historyActions}>
|
|
356
396
|
<StudioHistoryPanelContext.Provider value={controller.historyPanelState}>
|
|
397
|
+
<StudioHistoryResultContext.Provider value={controller.handleResult}>
|
|
357
398
|
<SectionAITesting
|
|
358
399
|
registration={registration}
|
|
359
400
|
registrations={registrations}
|
|
@@ -369,6 +410,7 @@ export function AIStudioWorkspace({
|
|
|
369
410
|
renderAIConfigPanel={renderAIConfigPanel}
|
|
370
411
|
rootTestId={rootTestId}
|
|
371
412
|
/>
|
|
413
|
+
</StudioHistoryResultContext.Provider>
|
|
372
414
|
</StudioHistoryPanelContext.Provider>
|
|
373
415
|
</StudioHistoryActionsContext.Provider>
|
|
374
416
|
</StudioHistoryLoadContext.Provider>
|
|
@@ -6,7 +6,7 @@ export const studioCreateDescriptors = Object.freeze([
|
|
|
6
6
|
section: 'chat',
|
|
7
7
|
summary: 'Prompt → text.generate CapabilityContract → typed Runtime result.',
|
|
8
8
|
summaryKey: 'Capabilities.textGenerate.summary',
|
|
9
|
-
|
|
9
|
+
surface: 'sdk.localApp.ai.text.generateCandidate; image input uses artifacts.upload → scenario.execute:text-generate',
|
|
10
10
|
execution: 'runtime-sdk', capabilityContract: 'text.generate',
|
|
11
11
|
},
|
|
12
12
|
{
|
|
@@ -22,7 +22,17 @@
|
|
|
22
22
|
"primaryRunningLabel": "Generating…",
|
|
23
23
|
"emptyTitle": "Waiting for generation",
|
|
24
24
|
"emptyHint": "Your generated text will appear here.",
|
|
25
|
-
"footnote": "Your request will be sent to the runtime to generate content."
|
|
25
|
+
"footnote": "Your request will be sent to the runtime to generate content.",
|
|
26
|
+
"imageInvalid": "Attach one JPEG image, WAV or MP3 recording, or MP4 video for this request.",
|
|
27
|
+
"imageTargetChecking": "Checking whether the selected model accepts this media. The attachment is kept while checking.",
|
|
28
|
+
"imageTargetUnknown": "Media support could not be confirmed. The attachment is kept; reopen model settings or retry later.",
|
|
29
|
+
"imageTargetUnsupported": "The selected model does not accept this media. Remove the attachment or choose a model that supports its format.",
|
|
30
|
+
"imageTooLarge": "The selected media must be non-empty and at most 32 MiB; the selected model may have a smaller request limit.",
|
|
31
|
+
"imageStopped": "The media request was stopped. Any late result will be discarded.",
|
|
32
|
+
"imageOutputInvalid": "Runtime did not return one complete text result for this media.",
|
|
33
|
+
"imageCompleted": "Runtime completed the protected media-and-text request.",
|
|
34
|
+
"imageCompletedWithoutSource": "Runtime returned the answer, but Lab could not save the source media for History.",
|
|
35
|
+
"savedMediaUnavailable": "This run's original media cannot be restored. Retry from a history record with saved media, or start a new request and choose the file again."
|
|
26
36
|
},
|
|
27
37
|
"chatStream": {
|
|
28
38
|
"inputTitle": "Test chat streaming",
|
|
@@ -50,10 +60,12 @@
|
|
|
50
60
|
"stopPlaceholder": "One stop sequence per line",
|
|
51
61
|
"embeddingInput": "Embedding input {{index}}",
|
|
52
62
|
"embeddingInputPlaceholder": "Text to embed",
|
|
63
|
+
"embeddingDimensionsHint": "Leave blank for the model's default width. Runtime rejects this option when the selected model does not support native dimensions.",
|
|
53
64
|
"addInput": "Add input",
|
|
54
65
|
"removeInput": "Remove input {{index}}",
|
|
55
66
|
"fields": {
|
|
56
67
|
"inputs": "Embedding inputs",
|
|
68
|
+
"dimensions": "Requested output dimensions",
|
|
57
69
|
"temperature": "Temperature",
|
|
58
70
|
"topP": "Top P",
|
|
59
71
|
"maxTokens": "Max tokens",
|
|
@@ -22,7 +22,17 @@
|
|
|
22
22
|
"primaryRunningLabel": "生成中…",
|
|
23
23
|
"emptyTitle": "等待生成",
|
|
24
24
|
"emptyHint": "生成的文本会显示在这里。",
|
|
25
|
-
"footnote": "你的请求会发送到 Runtime 以生成内容。"
|
|
25
|
+
"footnote": "你的请求会发送到 Runtime 以生成内容。",
|
|
26
|
+
"imageInvalid": "请为这次请求附上一张 JPEG 图片、一段 WAV 或 MP3 录音,或一个 MP4 视频。",
|
|
27
|
+
"imageTargetChecking": "正在检查所选模型是否接受这份媒体。检查期间会保留附件。",
|
|
28
|
+
"imageTargetUnknown": "无法确认所选模型是否支持这份媒体。附件会保留;请重新打开模型设置或稍后重试。",
|
|
29
|
+
"imageTargetUnsupported": "所选模型不接受这份媒体。请移除附件,或选择支持其格式的模型。",
|
|
30
|
+
"imageTooLarge": "所选媒体必须非空,且不超过 32 MiB;实际模型可能有更小的请求限制。",
|
|
31
|
+
"imageStopped": "媒体请求已停止,不会保存后续返回的结果。",
|
|
32
|
+
"imageOutputInvalid": "Runtime 未为这份媒体返回一条完整文本结果。",
|
|
33
|
+
"imageCompleted": "Runtime 已完成受保护的媒体与文字请求。",
|
|
34
|
+
"imageCompletedWithoutSource": "Runtime 已返回回答,但 Lab 未能把原媒体保存到历史记录。",
|
|
35
|
+
"savedMediaUnavailable": "无法恢复这条记录的原媒体。请从保留原媒体的历史记录重试,或新建请求重新选择文件。"
|
|
26
36
|
},
|
|
27
37
|
"chatStream": {
|
|
28
38
|
"inputTitle": "测试聊天流式输出",
|
|
@@ -50,10 +60,12 @@
|
|
|
50
60
|
"stopPlaceholder": "每行一个停止序列",
|
|
51
61
|
"embeddingInput": "嵌入输入 {{index}}",
|
|
52
62
|
"embeddingInputPlaceholder": "要生成嵌入的文本",
|
|
63
|
+
"embeddingDimensionsHint": "留空使用模型默认维度。当前模型不支持原生维度选项时,Runtime 会拒绝请求。",
|
|
53
64
|
"addInput": "添加输入",
|
|
54
65
|
"removeInput": "移除输入 {{index}}",
|
|
55
66
|
"fields": {
|
|
56
67
|
"inputs": "嵌入输入",
|
|
68
|
+
"dimensions": "请求输出维度",
|
|
57
69
|
"temperature": "Temperature",
|
|
58
70
|
"topP": "Top P",
|
|
59
71
|
"maxTokens": "最大 Token 数",
|
|
@@ -92,8 +92,10 @@ function EmbeddingFields(props: StudioParameterPanelProps) {
|
|
|
92
92
|
const parameters = props.parameters as StudioEmbeddingParameters;
|
|
93
93
|
const values = parameters.inputs?.length ? parameters.inputs : [''];
|
|
94
94
|
const updateValues = (nextValues: string[]) => {
|
|
95
|
-
|
|
96
|
-
|
|
95
|
+
const next = { ...parameters };
|
|
96
|
+
if (nextValues.length > 1 || nextValues.some((value) => value.trim())) next.inputs = nextValues;
|
|
97
|
+
else delete next.inputs;
|
|
98
|
+
props.onChange(next);
|
|
97
99
|
};
|
|
98
100
|
const label = t('Studio.parameters.fields.inputs');
|
|
99
101
|
const fields: StudioParameterFieldDefinition[] = [{
|
|
@@ -123,6 +125,13 @@ function EmbeddingFields(props: StudioParameterPanelProps) {
|
|
|
123
125
|
</Button>
|
|
124
126
|
</div>
|
|
125
127
|
),
|
|
128
|
+
}, {
|
|
129
|
+
field: 'dimensions',
|
|
130
|
+
label: t('Studio.parameters.fields.dimensions'),
|
|
131
|
+
render: (routeDisabled) => <div>
|
|
132
|
+
<StudioNumberParameter current={parameters} field="dimensions" label={t('Studio.parameters.fields.dimensions')} onChange={props.onChange} disabled={props.disabled || routeDisabled} min={1} step={1} />
|
|
133
|
+
<small>{t('Studio.parameters.embeddingDimensionsHint')}</small>
|
|
134
|
+
</div>,
|
|
126
135
|
}];
|
|
127
136
|
return (
|
|
128
137
|
<StudioRouteAwareParameterFields
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import {
|
|
2
|
-
CLOUD_ONLY_STUDIO_PARAMETER,
|
|
3
2
|
LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
4
3
|
defineStudioParameters,
|
|
5
4
|
} from '../../ai-studio-core/parameters.js';
|
|
@@ -20,6 +19,7 @@ export type StudioTextTurnParameters = StudioTextCandidateParameters & {
|
|
|
20
19
|
|
|
21
20
|
export type StudioEmbeddingParameters = {
|
|
22
21
|
inputs?: string[];
|
|
22
|
+
dimensions?: number;
|
|
23
23
|
};
|
|
24
24
|
|
|
25
25
|
const TEXT_CANDIDATE_ROUTE_MATRIX = {
|
|
@@ -61,7 +61,7 @@ export const studioChatStreamParameters = defineStudioParameters<StudioTextTurnP
|
|
|
61
61
|
|
|
62
62
|
export const studioTextEmbedParameters = defineStudioParameters<StudioEmbeddingParameters>({
|
|
63
63
|
initial: () => ({}),
|
|
64
|
-
routeMatrix: { inputs:
|
|
64
|
+
routeMatrix: { inputs: LOCAL_AND_CLOUD_STUDIO_PARAMETER, dimensions: LOCAL_AND_CLOUD_STUDIO_PARAMETER },
|
|
65
65
|
hasAlternativeInput: (parameters) => nonEmptyEmbeddingInputs(parameters).length > 0,
|
|
66
66
|
});
|
|
67
67
|
|
|
@@ -13,10 +13,10 @@ export const studioCreateModule = Object.freeze({
|
|
|
13
13
|
descriptor: studioCreateDescriptors[0],
|
|
14
14
|
icon: Sparkles,
|
|
15
15
|
profile: {
|
|
16
|
-
|
|
16
|
+
studioTag: 'Text', inputTitleKey: 'Studio.profiles.textGenerate.inputTitle', inputPlaceholderKey: 'Studio.profiles.textGenerate.inputPlaceholder', inputKind: 'prompt', supportsAttachments: true, controls: ['tone', 'length'], primaryLabelKey: 'Studio.profiles.textGenerate.primaryLabel', primaryRunningLabelKey: 'Studio.profiles.textGenerate.primaryRunningLabel', resultTitle: 'Generated result', emptyTitleKey: 'Studio.profiles.textGenerate.emptyTitle', emptyHintKey: 'Studio.profiles.textGenerate.emptyHint', resultKind: 'text', footnoteKey: 'Studio.profiles.textGenerate.footnote',
|
|
17
17
|
},
|
|
18
18
|
preset: { id: 'acceptance-note', label: 'Acceptance note', prompt: 'Write a concise acceptance note for a Runtime-backed Nimi App that can generate helpful content.' },
|
|
19
|
-
|
|
19
|
+
runtimeMethod: 'sdk.localApp.ai.text.generateCandidate / scenario.execute:text-generate with image',
|
|
20
20
|
parameters: studioTextGenerateParameters,
|
|
21
21
|
parameterPanel: StudioCreateParameterPanel,
|
|
22
22
|
},
|
|
@@ -30,6 +30,99 @@ export const studioCreateRuntimeHandlers: StudioCapabilityRuntimeHandlers = Obje
|
|
|
30
30
|
async function runTextGenerate(context: StudioCapabilityRuntimeContext) {
|
|
31
31
|
if (!context.prompt) return inputRequired(context);
|
|
32
32
|
const parameters = context.input.parameters as StudioTextCandidateParameters | undefined;
|
|
33
|
+
const attachments = context.input.attachments ?? [];
|
|
34
|
+
if (attachments.length > 0) {
|
|
35
|
+
const image = attachments[0];
|
|
36
|
+
if (attachments.length !== 1 || !image || !['image/jpeg', 'audio/wav', 'audio/mpeg', 'video/mp4'].includes(image.mimeType)) {
|
|
37
|
+
return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('Studio.profiles.textGenerate.imageInvalid'));
|
|
38
|
+
}
|
|
39
|
+
const prefix = `data:${image.mimeType};base64,`;
|
|
40
|
+
if (!image.dataUrl.startsWith(prefix) || image.dataUrl.length > prefix.length + 4 * Math.ceil(32 * 1024 * 1024 / 3)) {
|
|
41
|
+
return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('Studio.profiles.textGenerate.imageTooLarge'));
|
|
42
|
+
}
|
|
43
|
+
if (studioRequestSignal(context)?.aborted) {
|
|
44
|
+
return context.host.nonSuccess(context.capability, 'operation-aborted', context.host.translate('Studio.profiles.textGenerate.imageStopped'));
|
|
45
|
+
}
|
|
46
|
+
let bytes: Uint8Array;
|
|
47
|
+
try {
|
|
48
|
+
bytes = Uint8Array.from(atob(image.dataUrl.slice(prefix.length)), (char) => char.charCodeAt(0));
|
|
49
|
+
} catch {
|
|
50
|
+
return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('Studio.profiles.textGenerate.imageInvalid'));
|
|
51
|
+
}
|
|
52
|
+
if (bytes.byteLength === 0 || bytes.byteLength > 32 * 1024 * 1024) {
|
|
53
|
+
return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('Studio.profiles.textGenerate.imageTooLarge'));
|
|
54
|
+
}
|
|
55
|
+
const upload = await context.host.client.ai.artifacts.upload({
|
|
56
|
+
bytes,
|
|
57
|
+
mimeType: image.mimeType as Parameters<typeof context.host.client.ai.artifacts.upload>[0]['mimeType'],
|
|
58
|
+
});
|
|
59
|
+
if (studioRequestSignal(context)?.aborted) {
|
|
60
|
+
return context.host.nonSuccess(context.capability, 'operation-aborted', context.host.translate('Studio.profiles.textGenerate.imageStopped'));
|
|
61
|
+
}
|
|
62
|
+
const response = await context.host.client.ai.scenario.execute({
|
|
63
|
+
type: 'text-generate',
|
|
64
|
+
messages: [{
|
|
65
|
+
role: 'user',
|
|
66
|
+
text: '',
|
|
67
|
+
parts: [
|
|
68
|
+
{ type: 'text', text: context.prompt },
|
|
69
|
+
{ type: 'artifact-ref', artifactId: upload.artifactId, mediaType: image.mimeType as 'image/jpeg' | 'audio/wav' | 'audio/mpeg' | 'video/mp4', displayName: image.name },
|
|
70
|
+
],
|
|
71
|
+
}],
|
|
72
|
+
...textCandidateParameters(parameters),
|
|
73
|
+
}, { signal: studioRequestSignal(context) });
|
|
74
|
+
if (studioRequestSignal(context)?.aborted) {
|
|
75
|
+
return context.host.nonSuccess(context.capability, 'operation-aborted', context.host.translate('Studio.profiles.textGenerate.imageStopped'));
|
|
76
|
+
}
|
|
77
|
+
// This one-turn image request has no follow-up turn to carry opaque state into.
|
|
78
|
+
const items = response.output.type === 'text-generate'
|
|
79
|
+
? response.output.items.filter((item) => item.type !== 'reasoning-continuity') : [];
|
|
80
|
+
const answer = items.length === 1 && items[0]?.type === 'text' ? items[0].text : '';
|
|
81
|
+
if (response.output.type !== 'text-generate' || response.output.finishReason !== 'stop' || !answer.trim()) {
|
|
82
|
+
return context.host.nonSuccess(context.capability, 'runtime-call-failed', context.host.translate('Studio.profiles.textGenerate.imageOutputInvalid'));
|
|
83
|
+
}
|
|
84
|
+
const extension = image.mimeType === 'audio/wav' ? 'wav' : image.mimeType === 'audio/mpeg' ? 'mp3' : image.mimeType === 'video/mp4' ? 'mp4' : 'jpg';
|
|
85
|
+
const relativePath = `studio/text-generate-inputs/${crypto.randomUUID()}.${extension}`;
|
|
86
|
+
let sourceImage;
|
|
87
|
+
let message = context.host.translate('Studio.profiles.textGenerate.imageCompleted');
|
|
88
|
+
try {
|
|
89
|
+
const saved = await context.host.client.storage.assets.write({
|
|
90
|
+
relativePath, body: bytes, mediaType: image.mimeType, overwrite: false,
|
|
91
|
+
});
|
|
92
|
+
if (studioRequestSignal(context)?.aborted) {
|
|
93
|
+
await context.host.client.storage.assets.remove(relativePath).catch(() => undefined);
|
|
94
|
+
return context.host.nonSuccess(context.capability, 'operation-aborted', context.host.translate('Studio.profiles.textGenerate.imageStopped'));
|
|
95
|
+
}
|
|
96
|
+
if (saved.relativePath !== relativePath || saved.sizeBytes !== bytes.byteLength ||
|
|
97
|
+
!/^sha256:[0-9a-f]{64}$/u.test(saved.sha256)) {
|
|
98
|
+
await context.host.client.storage.assets.remove(relativePath).catch(() => undefined);
|
|
99
|
+
throw new Error('saved image identity mismatch');
|
|
100
|
+
}
|
|
101
|
+
sourceImage = {
|
|
102
|
+
relativePath: saved.relativePath, mediaType: image.mimeType, sizeBytes: saved.sizeBytes,
|
|
103
|
+
sha256: saved.sha256, displayName: image.name, previewSource: 'managed-asset' as const,
|
|
104
|
+
};
|
|
105
|
+
} catch {
|
|
106
|
+
if (studioRequestSignal(context)?.aborted) {
|
|
107
|
+
return context.host.nonSuccess(context.capability, 'operation-aborted', context.host.translate('Studio.profiles.textGenerate.imageStopped'));
|
|
108
|
+
}
|
|
109
|
+
message = context.host.translate('Studio.profiles.textGenerate.imageCompletedWithoutSource');
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
ok: true as const,
|
|
113
|
+
capabilityId: context.capability.id,
|
|
114
|
+
capabilityLabel: context.capability.label,
|
|
115
|
+
message,
|
|
116
|
+
output: {
|
|
117
|
+
kind: 'text' as const,
|
|
118
|
+
text: answer,
|
|
119
|
+
finishReason: response.output.finishReason,
|
|
120
|
+
streamed: false,
|
|
121
|
+
...(sourceImage ? { sourceImage } : {}),
|
|
122
|
+
},
|
|
123
|
+
trace: response.traceId ? { traceId: response.traceId } : undefined,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
33
126
|
const result = await context.host.client.ai.text.generateCandidate({
|
|
34
127
|
messages: [{ role: 'user', text: context.prompt }],
|
|
35
128
|
...textCandidateParameters(parameters),
|
|
@@ -72,7 +165,7 @@ async function runChatStream(context: StudioCapabilityRuntimeContext) {
|
|
|
72
165
|
scenarioId: context.scenarioId,
|
|
73
166
|
surfaceId: context.host.surfaceId,
|
|
74
167
|
...(context.input.onPartial ? { onPartial: context.input.onPartial } : {}),
|
|
75
|
-
...(context
|
|
168
|
+
...(studioRequestSignal(context) ? { signal: studioRequestSignal(context) } : {}),
|
|
76
169
|
});
|
|
77
170
|
if (result.ok === false) return projectStudioRunnerNonSuccess(context, result);
|
|
78
171
|
if (result.output.kind !== 'text') {
|
|
@@ -93,13 +186,15 @@ async function runChatStream(context: StudioCapabilityRuntimeContext) {
|
|
|
93
186
|
}
|
|
94
187
|
|
|
95
188
|
async function runTextEmbed(context: StudioCapabilityRuntimeContext) {
|
|
189
|
+
const parameters = context.input.parameters as StudioEmbeddingParameters | undefined;
|
|
96
190
|
const embeddingInputs = nonEmptyEmbeddingInputs(
|
|
97
|
-
|
|
191
|
+
parameters,
|
|
98
192
|
);
|
|
99
193
|
if (!context.prompt && embeddingInputs.length === 0) return inputRequired(context);
|
|
100
194
|
const result = await context.host.client.ai.scenario.execute({
|
|
101
195
|
type: 'text-embed',
|
|
102
196
|
inputs: embeddingInputs.length > 0 ? embeddingInputs : [context.prompt],
|
|
197
|
+
...(parameters?.dimensions !== undefined ? { dimensions: parameters.dimensions } : {}),
|
|
103
198
|
});
|
|
104
199
|
if (result.output.type !== 'text-embed') {
|
|
105
200
|
return context.host.nonSuccess(
|
|
@@ -108,17 +203,29 @@ async function runTextEmbed(context: StudioCapabilityRuntimeContext) {
|
|
|
108
203
|
'Runtime embedding returned an unexpected output type.',
|
|
109
204
|
);
|
|
110
205
|
}
|
|
206
|
+
// Equal dimensions do not make vectors comparable; only the owner-reported
|
|
207
|
+
// space identifies them, so a result without it is not a reusable result.
|
|
208
|
+
const spaceId = typeof result.output.spaceId === 'string' ? result.output.spaceId.trim() : '';
|
|
209
|
+
if (!spaceId) {
|
|
210
|
+
return context.host.nonSuccess(
|
|
211
|
+
context.capability,
|
|
212
|
+
'runtime-call-failed',
|
|
213
|
+
'Runtime embedding omitted its embedding space.',
|
|
214
|
+
);
|
|
215
|
+
}
|
|
111
216
|
const first = result.output.vectors[0] ?? [];
|
|
112
217
|
return {
|
|
113
218
|
ok: true as const,
|
|
114
219
|
capabilityId: context.capability.id,
|
|
115
220
|
capabilityLabel: context.capability.label,
|
|
116
|
-
message: `Runtime completed text.embed with ${result.output.vectors.length} vector(s).`,
|
|
221
|
+
message: `Runtime completed text.embed with ${result.output.vectors.length} vector(s) in space ${spaceId}.`,
|
|
117
222
|
output: {
|
|
118
223
|
kind: 'embedding' as const,
|
|
119
224
|
vectorCount: result.output.vectors.length,
|
|
120
225
|
dimensions: first.length,
|
|
226
|
+
spaceId,
|
|
121
227
|
sample: [...first.slice(0, 8)],
|
|
228
|
+
...(result.output.usage ? { totalTokens: result.output.usage.totalTokens } : {}),
|
|
122
229
|
},
|
|
123
230
|
...(result.traceId ? { trace: { traceId: result.traceId } } : {}),
|
|
124
231
|
};
|
|
@@ -179,6 +286,7 @@ async function* streamLocalAppTextEvents(
|
|
|
179
286
|
...textSpec.input.map((message) => ({ role: 'user' as const, text: message.content })),
|
|
180
287
|
];
|
|
181
288
|
const seed = localTextSeed(textSpec.seed);
|
|
289
|
+
if (signal?.aborted) throw studioAbortError();
|
|
182
290
|
const subscription = await context.host.client.ai.text.streamTurn({
|
|
183
291
|
messages,
|
|
184
292
|
...(textSpec.temperature !== undefined ? { temperature: textSpec.temperature } : {}),
|
|
@@ -202,8 +310,12 @@ async function* streamLocalAppTextEvents(
|
|
|
202
310
|
let started = false;
|
|
203
311
|
let textItemOpened = false;
|
|
204
312
|
for await (const event of subscription) {
|
|
313
|
+
if (signal?.aborted) throw studioAbortError();
|
|
205
314
|
// This one-turn text surface has no follow-up turn to carry opaque state into.
|
|
206
315
|
if (event.type === 'reasoning-continuity') continue;
|
|
316
|
+
if (event.type === 'reasoning-summary') {
|
|
317
|
+
throw Object.assign(new Error('The text-only Studio request received an unrequested reasoning summary.'), { reasonCode: 'SDK_AI_RUNTIME_OUTPUT_INVALID' });
|
|
318
|
+
}
|
|
207
319
|
if (!started) {
|
|
208
320
|
started = true;
|
|
209
321
|
yield {
|
|
@@ -345,3 +457,9 @@ function textTurnParameters(
|
|
|
345
457
|
...(parameters.seed !== undefined ? { seed: parameters.seed } : {}),
|
|
346
458
|
};
|
|
347
459
|
}
|
|
460
|
+
|
|
461
|
+
function studioRequestSignal(context: StudioCapabilityRuntimeContext): AbortSignal | undefined {
|
|
462
|
+
if (!context.input.observationSignal) return context.input.signal;
|
|
463
|
+
if (!context.input.signal) return context.input.observationSignal;
|
|
464
|
+
return AbortSignal.any([context.input.signal, context.input.observationSignal].filter((signal): signal is AbortSignal => Boolean(signal)));
|
|
465
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from 'react';
|
|
2
|
+
import { Button } from '@nimiplatform/kit/ui';
|
|
3
|
+
import { useAIStudioHost } from '../../ai-studio-core/host-context.js';
|
|
4
|
+
import { StudioBooleanParameter, StudioNumberParameter, StudioParameterField, type StudioParameterPanelProps } from '../../ai-studio-core/parameter-fields.js';
|
|
5
|
+
import type { StudioAudioSeparateParameters } from './parameters.js';
|
|
6
|
+
|
|
7
|
+
export function AudioSeparateFields(props: StudioParameterPanelProps) {
|
|
8
|
+
const host = useAIStudioHost(); const { translate: t } = host;
|
|
9
|
+
const parameters = props.parameters as StudioAudioSeparateParameters;
|
|
10
|
+
const update = props.onChange as (next: StudioAudioSeparateParameters) => void;
|
|
11
|
+
const [ready, setReady] = useState(false);
|
|
12
|
+
const [busy, setBusy] = useState(false);
|
|
13
|
+
const [error, setError] = useState('');
|
|
14
|
+
const sourceInput = useRef<HTMLInputElement>(null);
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
let active = true;
|
|
17
|
+
// Closing the drawer and a commit can both refresh; only the newest read
|
|
18
|
+
// applies, so a slower, older snapshot never undoes a newer one.
|
|
19
|
+
let requestGeneration = 0;
|
|
20
|
+
const refresh = () => {
|
|
21
|
+
const generation = ++requestGeneration;
|
|
22
|
+
void host.sdk.aiConfig.getSnapshot().then(snapshot => {
|
|
23
|
+
if (!active || generation !== requestGeneration) return;
|
|
24
|
+
const selected = snapshot.effectiveSelections.find(item => item.capabilityContract === 'audio.separate');
|
|
25
|
+
setReady(selected?.state === 'ready');
|
|
26
|
+
setError('');
|
|
27
|
+
}).catch((cause: unknown) => { if (active && generation === requestGeneration) { setReady(false); setError(String(cause)); } });
|
|
28
|
+
};
|
|
29
|
+
refresh(); const unsubscribe = host.app.events.subscribeAIConfigRefresh(refresh);
|
|
30
|
+
return () => { active = false; unsubscribe(); };
|
|
31
|
+
}, [host]);
|
|
32
|
+
const disabled = props.disabled || busy;
|
|
33
|
+
async function importAudio(file: File) {
|
|
34
|
+
const extension = file.name.match(/\.(mp3|wav|flac)$/iu)?.[1]?.toLowerCase();
|
|
35
|
+
if (!extension || file.size < 1) { setError(t('AudioSeparate.fileInvalid')); return; }
|
|
36
|
+
const mimeType = extension === 'mp3' ? 'audio/mpeg' : extension === 'flac' ? 'audio/flac' : 'audio/wav';
|
|
37
|
+
// Do not leave the previous import executable while its replacement is
|
|
38
|
+
// still being copied. The composer requires committed input assets.
|
|
39
|
+
const { sourceRelativePath, sourceName, sourceMimeType, startSeconds, endSeconds, recoverySubmissionId, ...remaining } = parameters;
|
|
40
|
+
update(remaining);
|
|
41
|
+
setBusy(true); setError('');
|
|
42
|
+
try {
|
|
43
|
+
async function* chunks() {
|
|
44
|
+
const reader = file.stream().getReader();
|
|
45
|
+
try { while (true) { const next = await reader.read(); if (next.done) break; yield next.value; } }
|
|
46
|
+
finally { await reader.cancel(); reader.releaseLock(); }
|
|
47
|
+
}
|
|
48
|
+
const asset = await host.sdk.assets.write({ relativePath: `studio/music/imports/${crypto.randomUUID()}/source.${extension}`, body: chunks(), mediaType: mimeType, overwrite: false });
|
|
49
|
+
update({ ...remaining, sourceRelativePath: asset.relativePath, sourceName: file.name, sourceMimeType: mimeType });
|
|
50
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
51
|
+
finally { setBusy(false); }
|
|
52
|
+
}
|
|
53
|
+
return <div className="space-y-4">
|
|
54
|
+
{!ready ? <p>{t('AudioSeparate.configureInputs')}</p> : <p>{t('AudioSeparate.inputHint')}</p>}
|
|
55
|
+
<StudioParameterField label={t('AudioSeparate.source')}>
|
|
56
|
+
<input ref={sourceInput} hidden type="file" accept=".mp3,.wav,.flac" onChange={event => {
|
|
57
|
+
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (file) void importAudio(file);
|
|
58
|
+
}} />
|
|
59
|
+
<Button disabled={disabled || !ready} onClick={() => sourceInput.current?.click()}>{t(busy ? 'Music.importing' : 'AudioSeparate.chooseSource')}</Button>
|
|
60
|
+
{parameters.sourceRelativePath ? <p>{parameters.sourceName}</p> : null}
|
|
61
|
+
</StudioParameterField>
|
|
62
|
+
{ready ? <>
|
|
63
|
+
<StudioNumberParameter current={parameters} field="startSeconds" label={t('AudioSeparate.start')} onChange={update} disabled={disabled} />
|
|
64
|
+
<StudioNumberParameter current={parameters} field="endSeconds" label={t('AudioSeparate.end')} onChange={update} disabled={disabled} />
|
|
65
|
+
<p className="text-sm opacity-70">{t('AudioSeparate.rangeHint')}</p>
|
|
66
|
+
<StudioBooleanParameter current={parameters} field="includeInstrumentParts" label={t('AudioSeparate.includeInstrumentParts')} onChange={update} disabled={disabled} />
|
|
67
|
+
<p className="text-sm opacity-70">{t('AudioSeparate.instrumentPartsHint')}</p>
|
|
68
|
+
</> : null}
|
|
69
|
+
<p className="text-sm opacity-70">{t('AudioSeparate.preparationHint')}</p>
|
|
70
|
+
{error ? <p role="alert">{error}</p> : null}
|
|
71
|
+
</div>;
|
|
72
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { NimiLocalAppAudioInfo } from '@nimiplatform/sdk/app';
|
|
2
|
+
import type { NimiRuntimeScenarioJob } from '@nimiplatform/sdk/runtime';
|
|
3
|
+
import { beginStudioJobRecovery, recordedStudioScenarioJobClient, recoverStudioJobId, captureStudioJobRecoveryJobId, readStudioJobRecovery, restoreSavedStudioJobResult, saveStudioJobRecoveryResult, studioJobRecoverySignal } from '../../ai-studio-core/job-recovery.js';
|
|
4
|
+
import { createStudioScenarioJobClient, projectStudioArtifactRunnerResult, type StudioCapabilityRuntimeContext } from '../../ai-studio-core/runtime.js';
|
|
5
|
+
import type { StudioManagedArtifact } from '../../ai-studio-core/runtime-types.js';
|
|
6
|
+
import type { StudioAudioSeparateParameters } from './parameters.js';
|
|
7
|
+
|
|
8
|
+
// @nimi-authority: rule.nimi.runtime.ai-provider.audio-separation
|
|
9
|
+
export async function runAudioSeparate(context: StudioCapabilityRuntimeContext) {
|
|
10
|
+
const parameters = context.input.parameters as StudioAudioSeparateParameters | undefined;
|
|
11
|
+
const client = context.host.client; const signal = context.input.signal;
|
|
12
|
+
if (parameters?.recoverySubmissionId) {
|
|
13
|
+
const entry = (await readStudioJobRecovery(client.storage, 'audio.separate')).find(item => item.clientSubmissionId === parameters.recoverySubmissionId);
|
|
14
|
+
if (!entry?.sourceAudio) throw new Error(context.host.translate('Music.recoveryMissing'));
|
|
15
|
+
const saved = await restoreSavedStudioJobResult(entry, context.capability.label, 'audio.separate', client.storage.assets, studioJobRecoverySignal(context.input));
|
|
16
|
+
if (saved) return saved;
|
|
17
|
+
const recoveredJobId = await recoverStudioJobId(client, entry, 'audio.separate');
|
|
18
|
+
const result = await context.host.runners.audioSeparationObserve({ runtime: { ai: createStudioScenarioJobClient(context) },
|
|
19
|
+
jobId: recoveredJobId, signal: context.input.observationSignal, cancelSignal: signal, onObservation: context.input.onObservation, abortReason: context.host.abortReason, onJobUpdate: context.input.onJobUpdate });
|
|
20
|
+
const projected = await projectStudioArtifactRunnerResult({ ...context, separationSourceAudio: entry.sourceAudio,
|
|
21
|
+
separationRequest: entry.separationRequest }, result);
|
|
22
|
+
await saveStudioJobRecoveryResult(client.storage, entry.clientSubmissionId, projected, 'audio.separate');
|
|
23
|
+
return projected;
|
|
24
|
+
}
|
|
25
|
+
const invalid = () => context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('AudioSeparate.configureInputs'));
|
|
26
|
+
if (!parameters?.sourceRelativePath || !parameters.sourceMimeType) return invalid();
|
|
27
|
+
const snapshot = await client.aiConfig.get();
|
|
28
|
+
const selection = snapshot.effectiveSelections.find(item => item.capabilityContract === 'audio.separate');
|
|
29
|
+
if (selection?.state !== 'ready') return invalid();
|
|
30
|
+
const original = await client.storage.assets.stat(parameters.sourceRelativePath);
|
|
31
|
+
if (original.sizeBytes < 1 || original.mediaType !== parameters.sourceMimeType) return invalid();
|
|
32
|
+
signal?.throwIfAborted();
|
|
33
|
+
// Runtime owns decoding and the frame basis. These unary preparations cannot
|
|
34
|
+
// be interrupted by the App; cancellation abandons submission when they settle.
|
|
35
|
+
const prepared = await client.ai.artifacts.upload({ source: { kind: 'app-asset', relativePath: original.relativePath },
|
|
36
|
+
mimeType: parameters.sourceMimeType, audioPreparation: { profile: 'canonical-pcm-v1' } });
|
|
37
|
+
signal?.throwIfAborted();
|
|
38
|
+
let sourceInfo = prepared.audioInfo;
|
|
39
|
+
if (!sourceInfo || prepared.mimeType !== 'audio/wav') return invalid();
|
|
40
|
+
// The native separation implementation accepts only its declared 44100 Hz
|
|
41
|
+
// stereo domain; anything else is converted through an explicit derived
|
|
42
|
+
// preparation, never a hidden resample.
|
|
43
|
+
let separationInput = prepared;
|
|
44
|
+
if (sourceInfo.sampleRateHz !== 44100 || sourceInfo.channels !== 2) {
|
|
45
|
+
const channelMode = sourceInfo.channels === 1 ? 'MONO_TO_STEREO' as const
|
|
46
|
+
: sourceInfo.channels === 2 ? 'PRESERVE' as const : 'STEREO_TO_MONO' as const;
|
|
47
|
+
separationInput = await client.ai.artifacts.upload({ source: { kind: 'artifact', artifactId: prepared.artifactId },
|
|
48
|
+
mimeType: 'audio/wav', audioPreparation: { profile: 'canonical-pcm-v1', targetSampleRateHz: 44100, channelMode } });
|
|
49
|
+
signal?.throwIfAborted();
|
|
50
|
+
sourceInfo = separationInput.audioInfo;
|
|
51
|
+
if (!sourceInfo || sourceInfo.sampleRateHz !== 44100 || sourceInfo.channels !== 2 || sourceInfo.frameCount < 1) return invalid();
|
|
52
|
+
}
|
|
53
|
+
const sourceRangeResult = resolveRange(parameters.startSeconds, parameters.endSeconds, sourceInfo);
|
|
54
|
+
if (sourceRangeResult === 'invalid') return invalid();
|
|
55
|
+
const sourceRange = sourceRangeResult;
|
|
56
|
+
const separationRequest = sourceRange
|
|
57
|
+
? { kind: 'range' as const, startSeconds: sourceRange.startFrame / sourceInfo.sampleRateHz,
|
|
58
|
+
endSeconds: sourceRange.endFrame / sourceInfo.sampleRateHz }
|
|
59
|
+
: { kind: 'full-source' as const };
|
|
60
|
+
const adopted = await client.storage.assets.adoptArtifact({ artifactId: separationInput.artifactId,
|
|
61
|
+
relativePath: `studio/music/audio-separate-inputs/${crypto.randomUUID()}/source.wav`, overwrite: false });
|
|
62
|
+
const sourceAudio: StudioManagedArtifact = { relativePath: adopted.relativePath, mediaType: adopted.mediaType,
|
|
63
|
+
sizeBytes: adopted.sizeBytes, sha256: adopted.sha256, displayName: parameters.sourceName, previewSource: 'managed-asset' };
|
|
64
|
+
let clientSubmissionId: string;
|
|
65
|
+
try {
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
if (adopted.sizeBytes !== separationInput.sizeBytes || adopted.mediaType !== separationInput.mimeType) throw new Error('Canonical source adoption changed metadata');
|
|
68
|
+
clientSubmissionId = await beginStudioJobRecovery(client.storage, 'audio.separate', sourceAudio, undefined,
|
|
69
|
+
separationRequest, context.input.recordedRunConfig, context.input.prompt);
|
|
70
|
+
} catch (cause) { await client.storage.assets.remove(adopted.relativePath); throw cause; }
|
|
71
|
+
const scenarioClient = recordedStudioScenarioJobClient(context, clientSubmissionId, 'audio.separate');
|
|
72
|
+
const result = await context.host.runners.audioSeparate({ runtime: { ai: scenarioClient }, appId: context.host.appId,
|
|
73
|
+
mimeType: separationInput.mimeType,
|
|
74
|
+
sourceAudio: { artifactId: separationInput.artifactId, ...(sourceRange ? { range: sourceRange } : {}) },
|
|
75
|
+
...(parameters.includeInstrumentParts ? { includeInstrumentParts: true } : {}),
|
|
76
|
+
scenarioId: context.scenarioId, surfaceId: context.host.surfaceId,
|
|
77
|
+
signal, observationSignal: context.input.observationSignal, onObservation: context.input.onObservation, abortReason: context.host.abortReason,
|
|
78
|
+
onJobUpdate: context.input.onJobUpdate });
|
|
79
|
+
const projected = await projectStudioArtifactRunnerResult({ ...context, separationSourceAudio: sourceAudio, separationRequest }, result);
|
|
80
|
+
await saveStudioJobRecoveryResult(client.storage, clientSubmissionId, projected, 'audio.separate');
|
|
81
|
+
return projected;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function resolveRange(startSeconds: number | undefined, endSeconds: number | undefined, info: NimiLocalAppAudioInfo) {
|
|
85
|
+
if (startSeconds === undefined && endSeconds === undefined) return undefined;
|
|
86
|
+
const startFrame = Math.round((startSeconds ?? 0) * info.sampleRateHz);
|
|
87
|
+
const endFrame = endSeconds === undefined ? info.frameCount : Math.round(endSeconds * info.sampleRateHz);
|
|
88
|
+
if (!Number.isSafeInteger(startFrame) || !Number.isSafeInteger(endFrame) || startFrame < 0 || startFrame >= endFrame || endFrame > info.frameCount) return 'invalid';
|
|
89
|
+
return { startFrame, endFrame };
|
|
90
|
+
}
|