@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,76 @@
1
+ import { useAIStudioHost } from './host-context.js';
2
+ import type { StudioTextDecisionAnswer, StudioTypedOutput } from './runtime-types.js';
3
+
4
+ type TextDecisionOutput = Extract<StudioTypedOutput, { kind: 'text-decision' }>;
5
+
6
+ function formatProbability(value: number): string {
7
+ return value.toFixed(4);
8
+ }
9
+
10
+ function barWidth(value: number): string {
11
+ return `${Math.min(100, Math.max(0, value * 100))}%`;
12
+ }
13
+
14
+ // One entry per submitted question, in submitted order. Probabilities are
15
+ // shown exactly as returned; nothing is derived from them, including the
16
+ // complement of a yes/no probability.
17
+ export function TextDecisionResultView({ output, traceId }: { readonly output: TextDecisionOutput; readonly traceId?: string }) {
18
+ const { translate: t } = useAIStudioHost();
19
+ return (
20
+ <section className="studio-result__rich" aria-label={t('StudioResults.decision.title')}>
21
+ <p className="studio-result__plain">{t('StudioResults.decision.summary', { count: output.answers.length })}</p>
22
+ <ol className="studio-decision">
23
+ {output.answers.map((answer) => <TextDecisionAnswerView key={answer.questionId} answer={answer} />)}
24
+ </ol>
25
+ {traceId ? (
26
+ <p className="studio-result__hint">
27
+ {t('StudioResults.decision.trace')} <code>{traceId}</code>
28
+ </p>
29
+ ) : null}
30
+ </section>
31
+ );
32
+ }
33
+
34
+ function TextDecisionAnswerView({ answer }: { readonly answer: StudioTextDecisionAnswer }) {
35
+ const { translate: t } = useAIStudioHost();
36
+ const rows = answer.kind === 'choice'
37
+ ? answer.probabilities.map((entry) => ({
38
+ label: entry.candidateId,
39
+ probability: entry.probability,
40
+ selected: entry.candidateId === answer.selectedCandidateId,
41
+ }))
42
+ : [{ label: t('StudioResults.decision.trueLabel'), probability: answer.trueProbability, selected: false }];
43
+ return (
44
+ <li className="studio-decision__question">
45
+ <div className="studio-decision__head">
46
+ <code className="studio-decision__id">{answer.questionId}</code>
47
+ <span className="studio-decision__kind">
48
+ {t(answer.kind === 'choice' ? 'StudioResults.decision.choice' : 'StudioResults.decision.boolean')}
49
+ </span>
50
+ </div>
51
+ <p className="studio-decision__answer">
52
+ {answer.kind === 'choice'
53
+ ? t('StudioResults.decision.selected', { candidate: answer.selectedCandidateId })
54
+ : t('StudioResults.decision.trueProbability', { probability: formatProbability(answer.trueProbability) })}
55
+ </p>
56
+ <ul
57
+ className="studio-decision__bars"
58
+ aria-label={t(answer.kind === 'choice' ? 'StudioResults.decision.candidates' : 'StudioResults.decision.trueBar')}
59
+ >
60
+ {rows.map((row) => (
61
+ <li
62
+ key={row.label}
63
+ className={row.selected ? 'studio-decision__bar studio-decision__bar--selected' : 'studio-decision__bar'}
64
+ aria-current={row.selected ? 'true' : undefined}
65
+ >
66
+ <span className="studio-decision__label">{row.label}</span>
67
+ <span className="studio-decision__track" aria-hidden="true">
68
+ <span className="studio-decision__fill" style={{ width: barWidth(row.probability) }} />
69
+ </span>
70
+ <span className="studio-decision__value">{formatProbability(row.probability)}</span>
71
+ </li>
72
+ ))}
73
+ </ul>
74
+ </li>
75
+ );
76
+ }
@@ -0,0 +1,71 @@
1
+ import { useAIStudioHost } from './host-context.js';
2
+ import type { StudioTextExchangeItem, StudioTypedOutput } from './runtime-types.js';
3
+ import { TextStudioOutputBody } from './section-ai-testing-output.js';
4
+
5
+ type TextExchangeOutput = Extract<StudioTypedOutput, { kind: 'text-exchange' }>;
6
+
7
+ // Shows every ordered item exactly as exchanged, including opaque reasoning
8
+ // continuity (by size only) and the App's tool results.
9
+ export function TextExchangeResultView({ output }: { readonly output: TextExchangeOutput }) {
10
+ const { translate: t } = useAIStudioHost();
11
+ return (
12
+ <section className="studio-result__rich" aria-label={t('StudioResults.exchange.title')}>
13
+ <p className="studio-result__plain">
14
+ {t(output.scenario === 'tool-call' ? 'StudioResults.exchange.toolScenario' : 'StudioResults.exchange.structuredScenario')}
15
+ </p>
16
+ <ol className="studio-exchange">
17
+ {output.steps.map((step, index) => (
18
+ <li key={index} className="studio-exchange__step">
19
+ <strong>
20
+ {t(step.origin === 'model' ? 'StudioResults.exchange.modelStep' : 'StudioResults.exchange.appStep', { index: index + 1 })}
21
+ {step.finishReason ? ` · ${t('StudioResults.exchange.finishReason', { reason: step.finishReason })}` : ''}
22
+ </strong>
23
+ <ol className="studio-exchange__items">
24
+ {step.items.map((item, itemIndex) => (
25
+ <li key={itemIndex}><TextExchangeItemView item={item} /></li>
26
+ ))}
27
+ </ol>
28
+ </li>
29
+ ))}
30
+ </ol>
31
+ {output.structured !== undefined ? (
32
+ <div>
33
+ <strong>{t('StudioResults.exchange.structured')}</strong>
34
+ <pre className="studio-diag__json">{JSON.stringify(output.structured, null, 2)}</pre>
35
+ </div>
36
+ ) : null}
37
+ <strong>{t('StudioResults.exchange.finalText')}</strong>
38
+ <TextStudioOutputBody text={output.text} />
39
+ </section>
40
+ );
41
+ }
42
+
43
+ function TextExchangeItemView({ item }: { readonly item: StudioTextExchangeItem }) {
44
+ const { translate: t } = useAIStudioHost();
45
+ if (item.type === 'text' || item.type === 'reasoning-summary') {
46
+ return <><span className="studio-exchange__kind">{t(item.type === 'text' ? 'StudioResults.exchange.text' : 'CapabilityTests.reasoning.summary')}</span><p className="studio-exchange__text">{item.text}</p></>;
47
+ }
48
+ if (item.type === 'reasoning-continuity') {
49
+ return (
50
+ <span className="studio-exchange__kind">
51
+ {t('StudioResults.exchange.continuity', { kind: item.carrierKind, version: item.version, bytes: item.payloadBytes })}
52
+ </span>
53
+ );
54
+ }
55
+ if (item.type === 'tool-call') {
56
+ return (
57
+ <>
58
+ <span className="studio-exchange__kind">{t('StudioResults.exchange.toolCall', { name: item.toolName, id: item.toolCallId })}</span>
59
+ <pre className="studio-diag__json">{JSON.stringify(item.arguments, null, 2)}</pre>
60
+ </>
61
+ );
62
+ }
63
+ return (
64
+ <>
65
+ <span className="studio-exchange__kind">
66
+ {t(item.isError ? 'StudioResults.exchange.toolError' : 'StudioResults.exchange.toolResult', { name: item.toolName, id: item.toolCallId })}
67
+ </span>
68
+ <pre className="studio-diag__json">{JSON.stringify(item.result, null, 2)}</pre>
69
+ </>
70
+ );
71
+ }
@@ -1,6 +1,6 @@
1
1
  import { useContext, useMemo, useState } from 'react';
2
2
  import { Button, IconButton, InlineAlert, nimiToast, Popover, PopoverContent, PopoverTrigger, Tooltip } from '@nimiplatform/kit/ui';
3
- import { Check, ChevronRight, Funnel, RefreshCw, Search, Sparkles, Trash2 } from 'lucide-react';
3
+ import { Check, ChevronRight, FileX, Funnel, RefreshCw, Search, Sparkles, Trash2 } from 'lucide-react';
4
4
  import { useAIStudioHost } from './host-context.js';
5
5
  import type { StudioCapabilityRegistration } from './module-registration.js';
6
6
  import {
@@ -23,6 +23,8 @@ import {
23
23
  type StudioHistoryPanelScope,
24
24
  type StudioMediaHistoryRecord,
25
25
  } from './contexts.js';
26
+ import { studioHistoryDocumentPaths } from './history-policy.js';
27
+ import { isStoppedDirectCall } from './non-success-presentation.js';
26
28
 
27
29
  type HistoryStatusFilter = 'all' | StudioRunHistoryRecord['status'];
28
30
  type HistoryEnvironmentFilter = 'all' | 'local' | 'cloud' | 'remote-control';
@@ -245,8 +247,8 @@ export function CapabilityRunHistory({
245
247
  onSelectRun(runRecord);
246
248
  }
247
249
 
248
- function handleRemoveRecord(record: StudioRunHistoryRecord) {
249
- void historyActions?.removeRecord(record.id);
250
+ function handleRemoveRecord(record: StudioRunHistoryRecord, deleteDocument = false) {
251
+ void historyActions?.removeRecord(record.id, deleteDocument);
250
252
  }
251
253
 
252
254
  function handleRemoveMediaRecord(record: StudioMediaHistoryRecord) {
@@ -270,7 +272,8 @@ export function CapabilityRunHistory({
270
272
  const source = historySourceLabelForRun(record);
271
273
  if (record.status === 'canceled') {
272
274
  const reason = historyFailureReasonForRun(record);
273
- return [t(reason === 'operation-aborted' ? 'History.stoppedWaiting' : 'History.canceled'), intent, source, reason].filter(Boolean).join(' / ');
275
+ const stoppedLabel = reason !== 'operation-aborted' ? 'History.canceled' : isStoppedDirectCall(reason, record.capabilityId) ? 'History.stopped' : 'History.stoppedWaiting';
276
+ return [t(stoppedLabel), intent, source, reason].filter(Boolean).join(' / ');
274
277
  }
275
278
  if (record.status === 'timed-out') {
276
279
  return [t('History.timedOut'), intent, source, historyFailureReasonForRun(record)].filter(Boolean).join(' / ');
@@ -660,6 +663,19 @@ export function CapabilityRunHistory({
660
663
  />
661
664
  </Tooltip>
662
665
  ) : null}
666
+ {historyActions && studioHistoryDocumentPaths(record).length > 0 ? (
667
+ <Tooltip content={t('History.deleteRecordAndDocument')} placement="left">
668
+ <IconButton
669
+ type="button"
670
+ tone="ghost"
671
+ size="sm"
672
+ className="studio-recent__row-delete studio-recent__row-delete--document"
673
+ aria-label={t('History.deleteRecordAndDocument')}
674
+ onClick={() => handleRemoveRecord(record, true)}
675
+ icon={<FileX size={13} strokeWidth={1.9} aria-hidden="true" />}
676
+ />
677
+ </Tooltip>
678
+ ) : null}
663
679
  </li>
664
680
  );
665
681
  })}
@@ -1,4 +1,28 @@
1
1
  import type { StudioResultKind } from './module-registration.js';
2
+ import type { NimiAIConfigSnapshot } from '@nimiplatform/sdk/ai';
3
+
4
+ export function textStudioMediaInputAvailable(snapshot: NimiAIConfigSnapshot, mediaType?: string): boolean {
5
+ const required = mediaType ? mediaType.startsWith('image/') ? 'input.image' : mediaType.startsWith('audio/') ? 'input.audio' : mediaType.startsWith('video/') ? 'input.video' : '' : undefined;
6
+ if (required === '') return false;
7
+ const selection = snapshot.effectiveSelections.find((item) => item.capabilityContract === 'text.generate');
8
+ if (selection?.state !== 'ready') return false;
9
+ const resource = selection.resource;
10
+ if (resource?.oneofKind === 'cloud') {
11
+ return resource.cloud.target.state === 'ready' && (required ? resource.cloud.target.supportedFeatures.includes(required) : ['input.image', 'input.audio', 'input.video'].some((feature) => resource.cloud.target.supportedFeatures.includes(feature)));
12
+ }
13
+ if (resource?.oneofKind === 'local') {
14
+ return resource.local.state === 'ready' && (required ? resource.local.configuredFeatures.includes(required) && resource.local.implementationSupportedFeatures.includes(required) : ['input.image', 'input.audio', 'input.video'].some((feature) => resource.local.configuredFeatures.includes(feature) && resource.local.implementationSupportedFeatures.includes(feature)));
15
+ }
16
+ return false;
17
+ }
18
+
19
+ export function usesVerbatimStudioPrompt(capabilityId: string): boolean {
20
+ return capabilityId === 'audio.synthesize'
21
+ || capabilityId === 'audio.transcribe'
22
+ || capabilityId === 'voice.create'
23
+ || capabilityId === 'music.generate'
24
+ || capabilityId === 'vision.locate';
25
+ }
2
26
 
3
27
  export function hasStudioCapabilityRunInput(input: {
4
28
  requiresPrompt: boolean;
@@ -11,9 +35,14 @@ export function hasStudioCapabilityRunInput(input: {
11
35
  export function canCancelStudioCapabilityRun(input: {
12
36
  capabilityId: string;
13
37
  resultKind: StudioResultKind;
38
+ hasMediaInput?: boolean;
14
39
  }): boolean {
15
40
  return input.capabilityId === 'chat.stream'
41
+ || (input.capabilityId === 'text.generate' && input.hasMediaInput === true)
42
+ || input.resultKind === 'text-exchange'
16
43
  || input.resultKind === 'artifacts'
44
+ || input.resultKind === 'text-annotation'
45
+ || input.resultKind === 'text-decision'
17
46
  || input.resultKind === 'transcript'
18
47
  || input.resultKind === 'vision-locate'
19
48
  || input.resultKind === 'voice-asset';
@@ -0,0 +1,45 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { Button, TextareaField } from '@nimiplatform/kit/ui';
3
+ import { useAIStudioHost } from './host-context.js';
4
+ import type { StudioMusicGeneration } from './runtime-types.js';
5
+ import { downloadTextFile } from './section-ai-testing-output.js';
6
+
7
+ export function MusicGenerationNotice({ value }: { readonly value?: StudioMusicGeneration }) {
8
+ const host = useAIStudioHost();
9
+ const { translate: t } = host;
10
+ const [expanded, setExpanded] = useState(false);
11
+ const [score, setScore] = useState('');
12
+ const [error, setError] = useState('');
13
+ const scorePath = value?.generatedScore?.relativePath;
14
+ useEffect(() => {
15
+ let active = true;
16
+ setScore(''); setError('');
17
+ if (expanded && scorePath) void (async () => {
18
+ const read = await host.sdk.assets.read({ relativePath: scorePath });
19
+ if (read.asset.mediaType !== 'text/vnd.abc' || read.asset.sizeBytes > 1048576) throw new Error(t('Music.scoreTooLarge'));
20
+ const bytes = new Uint8Array(read.asset.sizeBytes);
21
+ let offset = 0;
22
+ for await (const chunk of read.body) {
23
+ if (offset + chunk.length > bytes.length) throw new Error(t('Music.scoreTooLarge'));
24
+ bytes.set(chunk, offset); offset += chunk.length;
25
+ }
26
+ if (offset !== bytes.length) throw new Error(t('Music.scoreIncomplete'));
27
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
28
+ if (active) setScore(text);
29
+ })().catch((cause: unknown) => { if (active) setError(cause instanceof Error ? cause.message : String(cause)); });
30
+ return () => { active = false; };
31
+ }, [expanded, scorePath, host, t]);
32
+ if (!value) return null;
33
+ return <div role="status" className="space-y-1 text-sm">
34
+ <p>{t(value.termination === 'model-end' ? 'Music.terminationModelEnd' : value.termination === 'budget-limit' ? 'Music.terminationBudget' : 'Music.terminationUnknown')}</p>
35
+ {value.generatedScore?.truncated ? <p>{t('Music.scoreTruncated')}</p> : null}
36
+ {scorePath ? <div className="space-y-2">
37
+ <Button onClick={() => setExpanded((current) => !current)}>{t(expanded ? 'Music.hideScore' : 'Music.viewScore')}</Button>
38
+ {expanded && score ? <>
39
+ <TextareaField value={score} readOnly textareaClassName="min-h-40 font-mono" aria-label={t('Music.generatedPlan')} />
40
+ <Button onClick={() => void downloadTextFile(host, 'generated-score.abc', score)}>{t('Music.exportScore')}</Button>
41
+ </> : null}
42
+ {error ? <p role="alert">{error}</p> : null}
43
+ </div> : null}
44
+ </div>;
45
+ }
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useState, type ReactNode } from 'react';
2
- import { Dialog, DialogContent, DialogTitle, IconButton, nimiToast, Tooltip } from '@nimiplatform/kit/ui';
2
+ import { Button, Dialog, DialogContent, DialogTitle, IconButton, nimiToast, Tooltip } from '@nimiplatform/kit/ui';
3
3
  import { Copy as CopyIcon, Download as DownloadIcon, Maximize2, X } from 'lucide-react';
4
- import { useAIStudioHost } from './host-context.js';
4
+ import { useAIStudioHost, type AIStudioHostPort, type StudioTextExportResult } from './host-context.js';
5
5
  import type { StudioCapabilityRunResult } from './runtime-types.js';
6
6
  import { openNimiLocalAppAssetMediaUrl } from '@nimiplatform/kit/shell/renderer/bridge';
7
7
  import { studioNonSuccessReasonTitle, type StudioTranslate } from './non-success-presentation.js';
@@ -17,6 +17,7 @@ export function formatTypedOutput(
17
17
  translate: StudioTranslate,
18
18
  ): string {
19
19
  const output = result.output;
20
+ if (output.kind === 'speaker-embedding') return JSON.stringify({ jobId: output.jobId, spaceId: output.spaceId, vector: output.vector }, null, 2);
20
21
  if (output.kind === 'vision-locate') return JSON.stringify({ jobId: output.jobId, ...output.result }, null, 2);
21
22
  if (output.kind === 'text') {
22
23
  return output.text || translate('StudioShell.emptyBody');
@@ -25,21 +26,62 @@ export function formatTypedOutput(
25
26
  return JSON.stringify({
26
27
  vectors: output.vectorCount,
27
28
  dimensions: output.dimensions,
29
+ // Equal dimensions do not make two vectors comparable; the space does.
30
+ spaceId: output.spaceId ?? null,
28
31
  sample: output.sample,
29
32
  totalTokens: output.totalTokens,
30
33
  }, null, 2);
31
34
  }
35
+ if (output.kind === 'text-annotation') {
36
+ return JSON.stringify({
37
+ jobId: output.jobId,
38
+ jobState: output.jobState,
39
+ language: output.language,
40
+ documentCount: output.documentCount,
41
+ tokenCount: output.tokenCount,
42
+ sentenceCount: output.sentenceCount,
43
+ document: output.document,
44
+ }, null, 2);
45
+ }
46
+ if (output.kind === 'text-exchange') {
47
+ return JSON.stringify({
48
+ scenario: output.scenario,
49
+ steps: output.steps,
50
+ ...(output.structured !== undefined ? { structured: output.structured } : {}),
51
+ text: output.text,
52
+ }, null, 2);
53
+ }
54
+ if (output.kind === 'text-decision') {
55
+ return JSON.stringify({ answers: output.answers }, null, 2);
56
+ }
57
+ if (output.kind === 'session') {
58
+ return JSON.stringify({
59
+ capabilityContract: output.capabilityContract,
60
+ startedAt: output.startedAt,
61
+ endedAt: output.endedAt,
62
+ ending: output.ending,
63
+ terminalReason: output.terminalReason,
64
+ observed: output.observed,
65
+ }, null, 2);
66
+ }
32
67
  if (output.kind === 'artifacts') {
33
68
  return JSON.stringify({
34
69
  jobId: output.jobId,
35
70
  jobState: output.jobState,
36
71
  artifactCount: output.artifactCount,
72
+ ...(output.musicGeneration ? { musicGeneration: output.musicGeneration } : {}),
73
+ ...(output.musicTranscription ? { musicTranscription: output.musicTranscription } : {}),
74
+ ...(output.voiceConversion ? { voiceConversion: output.voiceConversion } : {}),
75
+ ...(output.audioSeparation ? { audioSeparation: output.audioSeparation } : {}),
76
+ ...(output.faceSwap ? { faceSwap: output.faceSwap } : {}),
37
77
  artifacts: output.artifacts,
38
78
  firstArtifact: output.firstArtifact,
39
79
  }, null, 2);
40
80
  }
41
81
  if (output.kind === 'transcript') {
42
- return output.text || translate('StudioShell.emptyTranscript');
82
+ return output.transcription
83
+ ? JSON.stringify({ jobId: output.jobId, jobState: output.jobState, transcription: output.transcription }, null, 2)
84
+ : output.text || translate('StudioShell.emptyTranscript');
43
85
  }
44
86
  if (output.kind === 'voice-asset') {
45
87
  return JSON.stringify({
@@ -49,6 +91,10 @@ export function formatTypedOutput(
49
91
  creationSource: output.creationSource,
50
92
  assetStatus: output.assetStatus,
51
93
  voiceReference: output.voiceReference,
94
+ ...(output.preview ? { preview: output.preview } : {}),
95
+ ...(output.expiresAt ? { expiresAt: output.expiresAt } : {}),
96
+ ...(output.inputTokens !== undefined ? { inputTokens: output.inputTokens } : {}),
97
+ ...(output.outputTokens !== undefined ? { outputTokens: output.outputTokens } : {}),
52
98
  }, null, 2);
53
99
  }
54
100
  return JSON.stringify({
@@ -57,6 +103,26 @@ export function formatTypedOutput(
57
103
  }, null, 2);
58
104
  }
59
105
 
106
+ // A Job the owner already issued stays locatable after a non-success, but
107
+ // Runtime retains it only for its own retention period.
108
+ export function KnownJobNotice({ jobId }: { readonly jobId?: string }) {
109
+ const { translate: t } = useAIStudioHost();
110
+ if (!jobId) return null;
111
+ return <p className="studio-result__hint">{t('StudioResults.job.known', { jobId })}</p>;
112
+ }
113
+
114
+ export function EmbeddingResultBody({ spaceId }: { readonly spaceId?: string }) {
115
+ const { translate: t } = useAIStudioHost();
116
+ return (
117
+ <div className="studio-result__rich">
118
+ <p className="studio-result__plain">{t('StudioShell.embeddingSuccess')}</p>
119
+ <p className="studio-result__hint">
120
+ {spaceId ? t('StudioResults.embedding.space', { spaceId }) : t('StudioResults.embedding.spaceNotRecorded')}
121
+ </p>
122
+ </div>
123
+ );
124
+ }
125
+
60
126
  export function formatNonSuccessOutput(
61
127
  result: StudioCapabilityRunResult & { ok: false },
62
128
  translate: StudioTranslate,
@@ -66,6 +132,7 @@ export function formatNonSuccessOutput(
66
132
  '',
67
133
  `Capability: ${result.capabilityId}`,
68
134
  `Reason: ${result.reason}`,
135
+ result.jobId ? `Job: ${result.jobId}` : '',
69
136
  result.missingSurface ? `Missing surface: ${result.missingSurface}` : '',
70
137
  '',
71
138
  'Message:',
@@ -120,7 +187,7 @@ export function RuntimeDiagnosticsActions({
120
187
  function handleDownloadDiagnostics() {
121
188
  if (!canExport) return;
122
189
  const stamp = new Date(rendererHost.clock.now()).toISOString().replace(/[:.]/g, '-');
123
- void downloadTextFile(rendererHost.app.commands, `${filenameBase}-runtime-details-${stamp}.txt`, text);
190
+ void downloadTextFile(rendererHost, `${filenameBase}-runtime-details-${stamp}.txt`, text);
124
191
  }
125
192
  return (
126
193
  <div className="studio-diag__actions">
@@ -145,9 +212,11 @@ export function hasPreviewableArtifact(artifact?: StudioArtifactPreviewSource):
145
212
  export function ArtifactMediaPreview({
146
213
  artifact,
147
214
  fallbackLabel,
215
+ mediaLabel,
148
216
  }: {
149
217
  artifact?: StudioArtifactPreviewSource;
150
218
  fallbackLabel: string;
219
+ mediaLabel?: string;
151
220
  }) {
152
221
  const relativePath = artifact?.relativePath;
153
222
  const mimeType = artifact?.mediaType ?? '';
@@ -199,7 +268,7 @@ export function ArtifactMediaPreview({
199
268
  };
200
269
  }, [imagePreviewOpen, relativePath, t]);
201
270
  if (!hasPreviewableArtifact(artifact) || !url) return null;
202
- const label = artifact?.displayName || relativePath || fallbackLabel;
271
+ const label = mediaLabel || artifact?.displayName || relativePath || fallbackLabel;
203
272
  const isImage = branch === 'image';
204
273
  let media: ReactNode = null;
205
274
  if (isImage) {
@@ -220,7 +289,7 @@ export function ArtifactMediaPreview({
220
289
  </div>
221
290
  );
222
291
  } else if (branch === 'audio') {
223
- media = <audio controls src={url} />;
292
+ media = <audio controls src={url} aria-label={label} />;
224
293
  } else if (branch === 'video') {
225
294
  media = <video controls src={url} />;
226
295
  }
@@ -228,8 +297,10 @@ export function ArtifactMediaPreview({
228
297
  return (
229
298
  <>
230
299
  <figure className="ai-result__media" data-mime={mimeType}>
300
+ {mediaLabel ? <figcaption className="studio-result__plain">{mediaLabel}</figcaption> : null}
231
301
  {media}
232
302
  </figure>
303
+ {branch === 'audio' && artifact?.speechAlignment ? <SpeechAlignmentResultView alignment={artifact.speechAlignment} /> : null}
233
304
  {isImage ? (
234
305
  <Dialog open={imagePreviewOpen} onOpenChange={(open) => { if (!open) setImagePreviewOpen(false); }}>
235
306
  <DialogContent
@@ -255,17 +326,35 @@ export function ArtifactMediaPreview({
255
326
  );
256
327
  }
257
328
 
329
+ export function SpeechAlignmentResultView({ alignment }: { readonly alignment: NonNullable<StudioArtifactPreviewSource['speechAlignment']> }) {
330
+ const host = useAIStudioHost(), t = host.translate;
331
+ const tokens = alignment.tokens, visible = tokens.slice(0, 400);
332
+ return <section className="studio-result__rich" aria-label={t('StudioResults.alignment.title')}>
333
+ <Button size="sm" tone="secondary" onClick={() => void downloadTextFile(host, 'speech-alignment.json', JSON.stringify(alignment, null, 2))}>{t('StudioResults.alignment.exportComplete')}</Button>
334
+ <details className="studio-annotation" open>
335
+ <summary>{t(alignment.unit === 1 ? 'StudioResults.alignment.wordTimes' : 'StudioResults.alignment.charTimes', { count: tokens.length })}</summary>
336
+ <p className="studio-result__hint">{t('StudioResults.alignment.timeHint')}</p>
337
+ <table className="studio-annotation__tokens"><thead><tr><th>#</th><th>{t('StudioResults.transcript.word')}</th><th>{t('StudioResults.transcript.start')}</th><th>{t('StudioResults.transcript.end')}</th></tr></thead>
338
+ <tbody>{visible.map((token, index) => <tr key={`${index}:${token.startMs}`}><td>{index + 1}</td><td>{token.token}</td><td>{(Number(token.startMs) / 1000).toFixed(3)}</td><td>{(Number(token.endMs) / 1000).toFixed(3)}</td></tr>)}</tbody>
339
+ </table>
340
+ {visible.length < tokens.length ? <p className="studio-result__hint">{t('StudioResults.transcript.truncatedView', { shown: visible.length, total: tokens.length })}</p> : null}
341
+ </details>
342
+ </section>;
343
+ }
344
+
258
345
  export function ArtifactMediaResult({
259
346
  artifact,
260
347
  fallbackLabel,
348
+ mediaLabel,
261
349
  }: {
262
350
  artifact?: StudioArtifactPreviewSource;
263
351
  fallbackLabel: string;
352
+ mediaLabel?: string;
264
353
  }) {
265
354
  const { translate: t } = useAIStudioHost();
266
355
  const branch = studioArtifactRenderBranch(artifact);
267
356
  if (branch === 'image' || branch === 'audio' || branch === 'video') {
268
- return <ArtifactMediaPreview artifact={artifact} fallbackLabel={fallbackLabel} />;
357
+ return <ArtifactMediaPreview artifact={artifact} fallbackLabel={fallbackLabel} mediaLabel={mediaLabel} />;
269
358
  }
270
359
  return (
271
360
  <div className="studio-result__media-unavailable">
@@ -308,9 +397,42 @@ export function TextStudioOutputBody({ text }: { text: string }) {
308
397
  }
309
398
 
310
399
  export async function downloadTextFile(
311
- commands: ReturnType<typeof useAIStudioHost>['app']['commands'],
400
+ host: Pick<AIStudioHostPort, 'app' | 'translate'>,
312
401
  filename: string,
313
402
  body: string,
314
- ) {
315
- await commands.exportText({ filename, body });
403
+ ): Promise<StudioTextExportResult> {
404
+ let result: StudioTextExportResult;
405
+ try {
406
+ result = await host.app.commands.exportText({ filename, body });
407
+ } catch (error) {
408
+ result = { ok: false, error };
409
+ }
410
+ if (!result.ok) {
411
+ nimiToast.danger(host.translate('Common.exportFailed'));
412
+ } else if (!result.value.revealed) {
413
+ nimiToast.warning(host.translate('Common.exportSavedRevealFailed', { path: result.value.artifactPath }), { durationMs: 12000 });
414
+ } else {
415
+ nimiToast.success(host.translate('Common.exportSaved', { path: result.value.artifactPath }));
416
+ }
417
+ return result;
418
+ }
419
+
420
+ export async function revealStudioAsset(host: Pick<AIStudioHostPort, 'sdk' | 'translate'>, relativePath: string): Promise<boolean> {
421
+ try {
422
+ await host.sdk.revealLocalAppAsset(relativePath);
423
+ nimiToast.success(host.translate('Common.assetRevealed'));
424
+ return true;
425
+ } catch {
426
+ nimiToast.danger(host.translate('Common.assetRevealFailed', { path: relativePath }));
427
+ return false;
428
+ }
429
+ }
430
+
431
+ export function SpeakerEmbeddingResultBody({ spaceId, vector }: { readonly spaceId: string; readonly vector: readonly number[] }) {
432
+ const { translate: t } = useAIStudioHost();
433
+ return <div className="studio-result__rich">
434
+ <p>{t('StudioResults.speakerEmbedding.dimensions', { count: vector.length })}</p>
435
+ <p className="studio-result__hint">{t('StudioResults.embedding.space', { spaceId })}</p>
436
+ <p className="studio-result__hint">{t('StudioResults.speakerEmbedding.boundary')}</p>
437
+ </div>;
316
438
  }