@nimiplatform/app-tools 0.7.5 → 0.11.4

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 +56 -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 +15 -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
@@ -1,9 +1,13 @@
1
+ import { StudioJobRecoveryPanel } from './job-recovery-panel.js';
2
+ import { isStudioJobRecoveryCapability } from './job-recovery.js';
1
3
  import { Suspense, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
2
4
  import { Button, IconButton, LoadingSkeleton, nimiToast, OverlayShell, StatusBadge, Tooltip } from '@nimiplatform/kit/ui';
3
5
  import { PanelRight, SquarePen } from 'lucide-react';
4
6
  import { createBrowserDataUrlAttachmentAdapter, useChatComposer, type BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
7
+ import { notifyStudioAIConfigChanged } from './ai-config.js';
5
8
  import { useAIStudioHost } from './host-context.js';
6
9
  import type { StudioCapabilityRegistration } from './module-registration.js';
10
+ import type { StudioParameterValue } from './parameters.js';
7
11
  import type { StudioCapabilityRunResult, StudioRuntimeInspection } from './runtime-types.js';
8
12
  import { getStudioRunIntentLabel, restoreStudioCapabilityRunResult, type StudioRunConfigSnapshot, type StudioRunHistory, type StudioRunHistoryRecord } from './history.js';
9
13
  import { CapabilityRunHistory, DrawerErrorBoundary, downloadTextFile, resultPlainText, statusForCapability, type CapabilityStatus, type SectionAITestingProps } from './section-ai-testing-surface.js';
@@ -12,8 +16,12 @@ import { ScenarioJobStatus } from '@nimiplatform/sdk/runtime/generated';
12
16
  import {
13
17
  canCancelStudioCapabilityRun,
14
18
  hasStudioCapabilityRunInput,
19
+ textStudioMediaInputAvailable,
20
+ usesVerbatimStudioPrompt,
15
21
  } from './section-ai-testing-input.js';
16
22
  import { TextStudioResultState } from './section-ai-testing-result.js';
23
+ import { readStudioTextReplayMedia, readStudioLocateReplayImage } from './text-media-replay.js';
24
+ import { revealStudioAsset } from './section-ai-testing-output.js';
17
25
  import { canConfigureRunTarget, createRunConfigSnapshot, effectiveTextStudioPromptStyle, textStudioDirectiveForTarget, textStudioRunTargetIntentSummary, textStudioRuntimePrompt, useStudioRunTargetSummary, type TextStudioActiveRun } from './section-ai-testing-run.js';
18
26
  import { StudioCapabilityParameterContext, StudioHistoryLoadContext, StudioHistoryPanelContext } from './contexts.js';
19
27
 
@@ -36,7 +44,6 @@ function TextStudioShell({
36
44
  verboseConsole,
37
45
  draftPersistence,
38
46
  onOpenConfig,
39
- configOpen,
40
47
  history,
41
48
  historySelectionRequest,
42
49
  onSelectHistoryRun,
@@ -50,7 +57,6 @@ function TextStudioShell({
50
57
  verboseConsole: boolean;
51
58
  draftPersistence: boolean;
52
59
  onOpenConfig?: () => void;
53
- configOpen: boolean;
54
60
  history: StudioRunHistory | null;
55
61
  historySelectionRequest: { requestId: number; record: StudioRunHistoryRecord } | null;
56
62
  onSelectHistoryRun: (record: StudioRunHistoryRecord) => void;
@@ -75,18 +81,20 @@ function TextStudioShell({
75
81
  const [executingRun, setExecutingRun] = useState<TextStudioActiveRun | null>(null);
76
82
  const [cancelRequested, setCancelRequested] = useState(false);
77
83
  const [streamingText, setStreamingText] = useState<string | null>(null);
84
+ const [mediaInputState, setMediaInputState] = useState<'checking' | 'supported' | 'unsupported' | 'unavailable'>('checking');
78
85
  const [activeRun, setActiveRun] = useState<TextStudioActiveRun | null>(null);
79
86
  const [sessionRuns, setSessionRuns] = useState<Record<string, TextStudioActiveRun>>({});
80
87
  const historyPanel = useContext(StudioHistoryPanelContext);
81
88
  const historyCollapsed = historyPanel?.collapsed ?? true;
82
89
  const runSeqRef = useRef(0);
83
- const abortControllerRef = useRef<{ runId: string; controller: AbortController } | null>(null);
90
+ const [observationIssue, setObservationIssue] = useState(false);
91
+ const abortControllerRef = useRef<{ runId: string; controller: AbortController; observation: AbortController } | null>(null);
84
92
  const running = executingRun !== null;
85
93
  const displayingExecution = executingRun !== null && activeRun?.id === executingRun.id;
86
94
  const displayedRun = displayingExecution ? executingRun : activeRun;
87
95
  const expandedHistoryErrorRef = useRef<string | null>(null);
88
96
  const attachmentAdapter = useMemo(
89
- () => createBrowserDataUrlAttachmentAdapter({ idPrefix: 'studio-attachment', ...(capability.id === 'vision.locate' ? { maxAttachments: 1, accept: ['image/png','image/jpeg','image/webp','image/gif'] } : {}) }),
97
+ () => createBrowserDataUrlAttachmentAdapter({ idPrefix: 'studio-attachment', ...((capability.id === 'vision.locate') ? { maxAttachments: 1, accept: ['image/png','image/jpeg','image/webp','image/gif'] } : capability.id === 'text.generate' ? { maxAttachments: 1, accept: ['image/jpeg', 'audio/wav', 'audio/mpeg', 'video/mp4'] } : {}) }),
90
98
  [capability.id],
91
99
  );
92
100
  const composerState = useChatComposer<BrowserDataUrlAttachment>({
@@ -96,6 +104,25 @@ function TextStudioShell({
96
104
  onTextChange: updatePrompt,
97
105
  disabled: running,
98
106
  });
107
+ useEffect(() => {
108
+ if (capability.id !== 'text.generate') return;
109
+ let disposed = false;
110
+ let generation = 0;
111
+ const refresh = () => {
112
+ const current = ++generation;
113
+ setMediaInputState('checking');
114
+ void rendererHost.sdk.aiConfig.getSnapshot().then((snapshot) => {
115
+ if (!disposed && generation === current) {
116
+ setMediaInputState(textStudioMediaInputAvailable(snapshot, composerState.attachments[0]?.mimeType) ? 'supported' : 'unsupported');
117
+ }
118
+ }, () => {
119
+ if (!disposed && generation === current) setMediaInputState('unavailable');
120
+ });
121
+ };
122
+ refresh();
123
+ const unsubscribe = rendererHost.app.events.subscribeAIConfigRefresh(refresh);
124
+ return () => { disposed = true; generation += 1; unsubscribe(); };
125
+ }, [capability.id, rendererHost, composerState.attachments[0]?.mimeType]);
99
126
  const hasRequiredImage = capability.id !== 'vision.locate'
100
127
  || (composerState.attachments.length === 1 && composerState.attachments[0]?.kind === 'image');
101
128
  const hasActiveRun = Boolean(displayedRun);
@@ -107,10 +134,20 @@ function TextStudioShell({
107
134
  : null)
108
135
  : lastResult?.capabilityId === capability.id ? lastResult : null;
109
136
  const headerResult = hasActiveRun ? currentResult : null;
110
- const runTarget = useStudioRunTargetSummary(registration, runtime, configOpen);
137
+ const savedTextMedia = (currentResult?.ok && (currentResult.output.kind === 'text' || currentResult.output.kind === 'vision-locate') ? currentResult.output.sourceImage : undefined)
138
+ ?? displayedRun?.replayMedia;
139
+ const displayedAttachmentCount = displayedRun?.record?.runConfig?.promptControls.attachmentCount
140
+ ?? displayedRun?.attachmentCount ?? (savedTextMedia ? 1 : 0);
141
+ const textMediaReplayable = capability.id === 'vision.locate'
142
+ ? Boolean(savedTextMedia) && displayedRun?.record?.status !== 'unavailable'
143
+ : capability.id !== 'text.generate' ||
144
+ (displayedAttachmentCount === 0 && !savedTextMedia) ||
145
+ (displayedAttachmentCount <= 1 && Boolean(savedTextMedia) && displayedRun?.record?.status !== 'unavailable');
146
+ const runTarget = useStudioRunTargetSummary(registration, runtime);
111
147
  const admission = statusForCapability(registration, runTarget, headerResult, t);
112
148
  const requiresPrompt = profile.inputKind !== 'none';
113
149
  const supportsMedia = profile.supportsAttachments;
150
+ const attachmentBlocked = capability.id === 'text.generate' && composerState.attachments.length > 0 && mediaInputState !== 'supported';
114
151
  const capabilityParameters = parameterStore?.state[capability.id] ?? registration.parameters.initial();
115
152
  const effectiveCapabilityParameters = useMemo(() => registration.parameters.project(
116
153
  runTarget.source,
@@ -118,6 +155,46 @@ function TextStudioShell({
118
155
  ), [capabilityParameters, registration.parameters, runTarget.source]);
119
156
  const parameterSummary = registration.parameters.summarize(effectiveCapabilityParameters);
120
157
  const hasAlternativeInput = registration.parameters.hasAlternativeInput(capabilityParameters);
158
+ const recordedInput = registration.parameters.recordedInput;
159
+ const displayedRunPrompt = displayedRun?.prompt;
160
+ // A parameter-owned input reruns the displayed run's recorded request, which
161
+ // stays valid however the current parameters have changed since.
162
+ const displayedRunParameters = useMemo(() => {
163
+ if (!displayedRun || displayedRun.record?.status === 'unavailable' || displayedRun.record?.inputTruncated) return null;
164
+ if (registration.parameters.restoreRecordedParameters) {
165
+ return registration.parameters.restoreRecordedParameters(
166
+ displayedRun.record?.runConfig?.target.params,
167
+ displayedRun.record?.result,
168
+ displayedRunPrompt,
169
+ );
170
+ }
171
+ if (recordedInput) {
172
+ const restored = displayedRunPrompt === undefined ? null : recordedInput.decode(displayedRunPrompt);
173
+ return restored ? { ...capabilityParameters, ...restored } : null;
174
+ }
175
+ // A parameter-owned media request needs an explicit restoration rule.
176
+ // The current draft is not a source for a historical request.
177
+ return profile.requiresParameterInput ? null : capabilityParameters;
178
+ }, [displayedRun, displayedRunPrompt, recordedInput, registration.parameters, profile.requiresParameterInput, capabilityParameters]);
179
+ const displayedRunReplayable = displayedRunParameters !== null
180
+ && (!profile.requiresParameterInput || registration.parameters.hasAlternativeInput(displayedRunParameters));
181
+ const replayAssetPaths = ['sourceRelativePath', 'targetRelativePath']
182
+ .map(key => displayedRunParameters?.[key])
183
+ .filter((value): value is string => typeof value === 'string' && value.length > 0);
184
+ const replayAssetKey = JSON.stringify([displayedRun?.id, ...replayAssetPaths]);
185
+ const [replayAssets, setReplayAssets] = useState<{ key: string; available: boolean } | null>(null);
186
+ useEffect(() => {
187
+ let active = true;
188
+ if (!displayedRunReplayable || replayAssetPaths.length === 0) return;
189
+ void Promise.all(replayAssetPaths.map(relativePath => rendererHost.sdk.assets.stat(relativePath))).then(
190
+ () => { if (active) setReplayAssets({ key: replayAssetKey, available: true }); },
191
+ () => { if (active) setReplayAssets({ key: replayAssetKey, available: false }); },
192
+ );
193
+ return () => { active = false; };
194
+ }, [displayedRunReplayable, replayAssetKey, rendererHost.sdk.assets]);
195
+ const replayAssetsChecking = replayAssetPaths.length > 0 && replayAssets?.key !== replayAssetKey;
196
+ const replayAssetsAvailable = replayAssetPaths.length === 0
197
+ || (replayAssets?.key === replayAssetKey && replayAssets.available);
121
198
 
122
199
  useEffect(() => {
123
200
  const error = historyLoad?.error ?? null;
@@ -140,7 +217,7 @@ function TextStudioShell({
140
217
  }
141
218
 
142
219
  useEffect(() => {
143
- abortControllerRef.current?.controller.abort('studio-capability-changed');
220
+ abortControllerRef.current?.observation.abort('studio-capability-changed');
144
221
  abortControllerRef.current = null;
145
222
  const draft = rendererHost.app.projection.promptDraft({
146
223
  surfaceId: 'ai-capabilities',
@@ -154,50 +231,116 @@ function TextStudioShell({
154
231
  setSessionRuns({});
155
232
  setExecutingRun(null);
156
233
  setCancelRequested(false);
234
+ setObservationIssue(false);
157
235
  setStreamingText(null);
158
236
  }, [capability.id, draftPersistence, preset, rendererHost]);
159
237
 
160
- async function run(nextPrompt = prompt, nextContext = context) {
238
+ useEffect(() => () => {
239
+ runSeqRef.current += 1;
240
+ abortControllerRef.current?.observation.abort('studio-view-closed');
241
+ }, []);
242
+
243
+ // Replaying a run whose input lives in its parameters rebuilds them from the
244
+ // recorded request instead of reading the current parameters.
245
+ function runParametersFor(replayedInput: string | null): StudioParameterValue | null {
246
+ return replayedInput === null ? capabilityParameters : displayedRunParameters;
247
+ }
248
+
249
+ async function run(nextPrompt = prompt, nextContext = context, replay = false) {
161
250
  if (abortControllerRef.current) return;
162
- const displayPrompt = nextPrompt.trim();
163
- if (!hasStudioCapabilityRunInput({ requiresPrompt, prompt: displayPrompt, hasAlternativeInput })) return;
164
- if (!hasRequiredImage) return;
251
+ if (replay && !textMediaReplayable) return;
252
+ if (replay && (!displayedRunReplayable || !replayAssetsAvailable)) return;
253
+ const replayTextMedia = replay && (capability.id === 'text.generate' || capability.id === 'vision.locate');
254
+ let runAttachments = replayTextMedia ? [] : [...composerState.attachments];
255
+ const attachmentCount = supportsMedia ? (replayTextMedia ? (savedTextMedia ? 1 : displayedAttachmentCount) : runAttachments.length) : 0;
256
+ const runParameters = runParametersFor(replay ? nextPrompt : null);
257
+ if (!runParameters) return;
258
+ const runEffectiveParameters = replay && registration.parameters.restoreRecordedParameters
259
+ ? runParameters
260
+ : registration.parameters.project(runTarget.source, runParameters);
261
+ const runHasAlternativeInput = registration.parameters.hasAlternativeInput(runParameters);
262
+ // Raw document inputs retain their original whitespace so annotation
263
+ // offsets refer to the exact text the user entered. A parameter-owned input
264
+ // records its complete encoded request.
265
+ const displayPrompt = recordedInput
266
+ ? (runHasAlternativeInput ? recordedInput.encode(runEffectiveParameters) : '')
267
+ : profile.rawPrompt ? nextPrompt : nextPrompt.trim();
268
+ if (!hasStudioCapabilityRunInput({ requiresPrompt, prompt: displayPrompt, hasAlternativeInput: runHasAlternativeInput })) return;
269
+ if ((capability.id === 'music.transcribe' || capability.id === 'audio.voice.convert' || capability.id === 'audio.separate') && !runHasAlternativeInput) return;
270
+ if (profile.requiresParameterInput && !runHasAlternativeInput) return;
271
+ if (!(replay && capability.id === 'vision.locate' ? Boolean(savedTextMedia) : hasRequiredImage)) return;
165
272
  if (!runTarget.canDispatch) return;
166
273
  const runSeq = runSeqRef.current + 1;
167
274
  runSeqRef.current = runSeq;
168
275
  const abortController = new AbortController();
276
+ const observationController = new AbortController();
169
277
  const startedAt = rendererHost.clock.now();
170
278
  const pendingRun: TextStudioActiveRun = {
279
+ attachmentCount,
280
+ ...(replayTextMedia && savedTextMedia ? { replayMedia: savedTextMedia } : {}),
171
281
  id: `pending-${startedAt}`,
172
- prompt: displayPrompt || preset.prompt,
282
+ prompt: displayPrompt || (runHasAlternativeInput ? '' : preset.prompt),
173
283
  context: nextContext.trim(),
174
284
  createdAt: new Date(startedAt).toISOString(),
175
285
  result: null,
176
286
  record: null,
177
287
  error: null,
178
288
  };
179
- abortControllerRef.current = { runId: pendingRun.id, controller: abortController };
289
+ abortControllerRef.current = { runId: pendingRun.id, controller: abortController, observation: observationController };
180
290
  setActiveRun(pendingRun);
181
291
  setExecutingRun(pendingRun);
182
292
  setCancelRequested(false);
293
+ setObservationIssue(false);
294
+ const runConfig = createRunConfigSnapshot({
295
+ target: runTarget,
296
+ promptStyle: profile.controls.includes('tone') || profile.controls.includes('length')
297
+ ? effectiveTextStudioPromptStyle(runTarget) : null,
298
+ context: nextContext, attachmentCount,
299
+ requestParameters: registration.parameters.summarize(runEffectiveParameters),
300
+ });
183
301
  try {
184
302
  let result: StudioCapabilityRunResult;
185
303
  try {
304
+ if (replayTextMedia && savedTextMedia) {
305
+ try {
306
+ const readSaved = capability.id === 'vision.locate' ? readStudioLocateReplayImage : readStudioTextReplayMedia;
307
+ runAttachments = [await readSaved(rendererHost.sdk.assets, savedTextMedia, abortController.signal)];
308
+ } catch (error) {
309
+ if (abortController.signal.aborted) throw error;
310
+ throw new Error(t('Studio.profiles.textGenerate.savedMediaUnavailable'));
311
+ }
312
+ }
313
+ abortController.signal.throwIfAborted();
186
314
  const isStreaming = capability.id === 'chat.stream';
187
315
  if (isStreaming) setStreamingText('');
188
316
  const directive = textStudioDirectiveForTarget(runTarget, profile);
189
- result = await rendererHost.sdk.runCapability({
317
+ if (capability.id === 'text.generate' && runAttachments.length > 0 &&
318
+ !textStudioMediaInputAvailable(await rendererHost.sdk.aiConfig.getSnapshot(), runAttachments[0]?.mimeType)) {
319
+ result = {
320
+ ok: false, capabilityId: capability.id, reason: 'input-invalid',
321
+ message: t('Studio.profiles.textGenerate.imageTargetUnsupported'),
322
+ actionHint: t('Studio.profiles.textGenerate.imageTargetUnsupported'),
323
+ missingSurface: capability.missingSurface,
324
+ };
325
+ } else result = await rendererHost.sdk.runCapability({
190
326
  capabilityId: capability.id,
191
- prompt: capability.id === 'audio.transcribe' || capability.id === 'vision.locate'
327
+ recordedRunConfig: runConfig,
328
+ recordedCreatedAt: pendingRun.createdAt,
329
+ recordedPrompt: displayPrompt,
330
+ prompt: (capability.id === 'world.generate' && runHasAlternativeInput && !displayPrompt && !nextContext.trim()) || usesVerbatimStudioPrompt(capability.id) || profile.rawPrompt || recordedInput
192
331
  ? displayPrompt
193
332
  : textStudioRuntimePrompt(displayPrompt, nextContext, directive),
194
333
  scenarioId: preset.id,
195
334
  onPartial: isStreaming ? (text) => {
196
335
  if (runSeqRef.current === runSeq) setStreamingText(text);
197
336
  } : undefined,
198
- attachments: supportsMedia ? [...composerState.attachments] : undefined,
199
- parameters: effectiveCapabilityParameters,
337
+ attachments: supportsMedia ? runAttachments : undefined,
338
+ parameters: runEffectiveParameters,
200
339
  signal: abortController.signal,
340
+ observationSignal: observationController.signal,
341
+ onObservation: response => {
342
+ if (runSeqRef.current === runSeq) setObservationIssue(Boolean(response.observationIssue));
343
+ },
201
344
  onJobUpdate: job => {
202
345
  if (runSeqRef.current !== runSeq) return;
203
346
  const jobStatus = job.status === ScenarioJobStatus.QUEUED || job.status === ScenarioJobStatus.SUBMITTED ? 'queued' : job.status === ScenarioJobStatus.RUNNING ? 'running' : undefined;
@@ -205,25 +348,20 @@ function TextStudioShell({
205
348
  },
206
349
  });
207
350
  } catch (error) {
208
- const message = error instanceof Error ? error.message : String(error || t('NonSuccess.title.runtimeCallFailed'));
351
+ const aborted = error instanceof Error && error.name === 'AbortError';
352
+ const message = aborted ? t('Studio.profiles.textGenerate.imageStopped')
353
+ : error instanceof Error ? error.message : String(error || t('NonSuccess.title.runtimeCallFailed'));
209
354
  result = {
210
355
  ok: false,
211
356
  capabilityId: capability.id,
212
- reason: 'runtime-call-failed',
357
+ reason: aborted ? 'operation-aborted' : 'runtime-call-failed',
213
358
  message,
214
359
  actionHint: t('NonSuccess.hint.runtimeCallFailed'),
215
360
  missingSurface: capability.missingSurface,
216
361
  };
217
362
  }
218
- const runConfig = createRunConfigSnapshot({
219
- target: runTarget,
220
- promptStyle: profile.controls.includes('tone') || profile.controls.includes('length')
221
- ? effectiveTextStudioPromptStyle(runTarget)
222
- : null,
223
- context: nextContext,
224
- attachmentCount: supportsMedia ? composerState.attachments.length : 0,
225
- requestParameters: parameterSummary,
226
- });
363
+ observationController.signal.throwIfAborted();
364
+ if (result.ok) abortController.signal.throwIfAborted();
227
365
  const record = await onResult(result, displayPrompt, runConfig);
228
366
  // A result reaches the visible completed stage only after onResult has
229
367
  // finished its required custody/history work. Persistence failure throws
@@ -247,6 +385,7 @@ function TextStudioShell({
247
385
  if (abortControllerRef.current?.controller === abortController) abortControllerRef.current = null;
248
386
  setExecutingRun(null);
249
387
  setCancelRequested(false);
388
+ setObservationIssue(false);
250
389
  setStreamingText(null);
251
390
  }
252
391
  }
@@ -274,14 +413,18 @@ function TextStudioShell({
274
413
  if (currentResult.ok && currentResult.output.kind === 'artifacts') {
275
414
  const artifact = currentResult.output.firstArtifact;
276
415
  if (artifact?.relativePath) {
277
- await rendererHost.sdk.revealLocalAppAsset(artifact.relativePath);
416
+ await revealStudioAsset(rendererHost, artifact.relativePath);
278
417
  }
279
418
  return;
280
419
  }
420
+ if (currentResult.ok && currentResult.output.kind === 'text-annotation') {
421
+ await revealStudioAsset(rendererHost, currentResult.output.document.relativePath);
422
+ return;
423
+ }
281
424
  const stamp = new Date(rendererHost.clock.now()).toISOString().replace(/[:.]/g, '-');
282
425
  const text = resultPlainText(currentResult, t);
283
426
  if (!text) return;
284
- await downloadTextFile(rendererHost.app.commands, `${capability.id}-${stamp}.txt`, text);
427
+ await downloadTextFile(rendererHost, `${capability.id}-${stamp}.txt`, text);
285
428
  }
286
429
 
287
430
  // Selecting a history record is a read-only preview: it never writes the
@@ -304,6 +447,20 @@ function TextStudioShell({
304
447
  }
305
448
 
306
449
  function useHistoryRunAsDraft(record: StudioRunHistoryRecord) {
450
+ if (record.inputTruncated || record.status === 'unavailable') return;
451
+ if (registration.parameters.restoreRecordedParameters) {
452
+ const snapshot = record.runConfig?.target.params;
453
+ const restored = registration.parameters.restoreRecordedParameters(snapshot, record.result, record.prompt);
454
+ if (!restored || !parameterStore) return;
455
+ parameterStore.setParameters(capability.id, restored);
456
+ }
457
+ if (recordedInput) {
458
+ const restored = recordedInput.decode(record.prompt);
459
+ if (!restored || !parameterStore) return;
460
+ parameterStore.setParameters(capability.id, { ...capabilityParameters, ...restored });
461
+ setActiveRun(null);
462
+ return;
463
+ }
307
464
  updatePrompt(record.prompt);
308
465
  setContext(record.runConfig?.promptControls.context ?? '');
309
466
  setActiveRun(null);
@@ -323,6 +480,12 @@ function TextStudioShell({
323
480
  intentLabel={textStudioRunTargetIntentSummary(runTarget, t)}
324
481
  running={running}
325
482
  attachments={composerState.attachments}
483
+ attachmentPickerEnabled={capability.id !== 'text.generate' || mediaInputState === 'supported'}
484
+ attachmentWarning={attachmentBlocked ? t(mediaInputState === 'checking'
485
+ ? 'Studio.profiles.textGenerate.imageTargetChecking'
486
+ : mediaInputState === 'unavailable'
487
+ ? 'Studio.profiles.textGenerate.imageTargetUnknown'
488
+ : 'Studio.profiles.textGenerate.imageTargetUnsupported') : undefined}
326
489
  onOpenAttachmentPicker={composerState.openAttachmentPicker}
327
490
  onRemoveAttachment={composerState.removeAttachment}
328
491
  canDispatch={runTarget.canDispatch}
@@ -418,21 +581,26 @@ function TextStudioShell({
418
581
  admission={admission}
419
582
  intentLabel={displayedRun.record ? getStudioRunIntentLabel(displayedRun.record) : runTarget.intentLabel}
420
583
  running={displayingExecution}
421
- canRegenerate={!running && hasRequiredImage}
584
+ canRegenerate={!running && (capability.id !== 'vision.locate' || Boolean(savedTextMedia)) && textMediaReplayable && displayedRunReplayable && replayAssetsAvailable}
585
+ regenerateHint={!running && !textMediaReplayable ? t('Studio.profiles.textGenerate.savedMediaUnavailable')
586
+ : !running && replayAssetsChecking ? t('StudioShell.historyInputsChecking')
587
+ : !running && (!displayedRunReplayable || !replayAssetsAvailable) ? t('StudioShell.historyInputsUnavailable') : undefined}
422
588
  cancelRequested={displayingExecution && cancelRequested}
423
589
  streamingText={displayingExecution ? streamingText : null}
424
590
  verboseConsole={verboseConsole}
425
591
  composer={composer}
426
592
  onCopy={handleCopy}
427
593
  onDownload={handleDownload}
428
- onRegenerate={() => void run(displayedRun.prompt, displayedRun.context)}
594
+ onRegenerate={() => void run(displayedRun.prompt, displayedRun.context, true)}
429
595
  onCancel={displayingExecution && canCancelStudioCapabilityRun({
430
596
  capabilityId: capability.id,
431
597
  resultKind: profile.resultKind,
598
+ hasMediaInput: (executingRun?.attachmentCount ?? 0) > 0,
432
599
  })
433
600
  ? handleCancel
434
601
  : undefined}
435
602
  onUseAsDraft={useHistoryRunAsDraft}
603
+ onOpenIntentConfig={capability.execution === 'runtime-sdk' ? onOpenConfig : undefined}
436
604
  />
437
605
  ) : (
438
606
  <TextStudioStartState
@@ -440,6 +608,8 @@ function TextStudioShell({
440
608
  composer={composer}
441
609
  />
442
610
  )}
611
+ {displayingExecution && observationIssue ? <p role="status">{t('Music.observationIssue')}</p> : null}
612
+ {isStudioJobRecoveryCapability(capability.id) ? <StudioJobRecoveryPanel key={capability.id} capability={capability.id} disabled={running} /> : null}
443
613
  </main>
444
614
  </div>
445
615
  <CapabilityRunHistory
@@ -473,9 +643,24 @@ export function SectionAITesting({
473
643
  const { translate: t, appTitle } = useAIStudioHost();
474
644
  const capability = registration.descriptor;
475
645
  const [configOpen, setConfigOpen] = useState(false);
646
+ const rootRef = useRef<HTMLDivElement>(null);
647
+
648
+ // Mounted consumers (run target, parameter fields, recovery panels) cache
649
+ // AIConfig readiness; a drawer write happens in this window, so no focus or
650
+ // visibility change reports it.
651
+ function closeConfig() {
652
+ setConfigOpen(false);
653
+ if (rootRef.current) notifyStudioAIConfigChanged(rootRef.current);
654
+ }
655
+ // The close refresh can run before a pending write commits; the panel then
656
+ // reports the commit here. The window hears it even after this section left.
657
+ function reportCommitted() {
658
+ notifyStudioAIConfigChanged(rootRef.current ?? window);
659
+ }
476
660
 
477
661
  return (
478
662
  <div
663
+ ref={rootRef}
479
664
  className="section-ai-testing"
480
665
  data-testid={rootTestId}
481
666
  data-config-open={configOpen ? '' : undefined}
@@ -490,7 +675,6 @@ export function SectionAITesting({
490
675
  verboseConsole={verboseConsole}
491
676
  draftPersistence={draftPersistence}
492
677
  onOpenConfig={renderAIConfigPanel ? () => setConfigOpen(true) : undefined}
493
- configOpen={configOpen}
494
678
  history={history}
495
679
  historySelectionRequest={historySelectionRequest}
496
680
  onSelectHistoryRun={onSelectHistoryRun}
@@ -506,11 +690,11 @@ export function SectionAITesting({
506
690
  description={t('StudioModelConfig.drawerDescription', { appTitle })}
507
691
  panelClassName="flex flex-col"
508
692
  contentClassName="min-h-0 flex-1 overflow-y-auto p-0"
509
- onClose={() => setConfigOpen(false)}
693
+ onClose={closeConfig}
510
694
  >
511
- <DrawerErrorBoundary onClose={() => setConfigOpen(false)} translate={t}>
695
+ <DrawerErrorBoundary onClose={closeConfig} translate={t}>
512
696
  <Suspense fallback={<div className="p-5"><LoadingSkeleton lines={4} label={t('Common.loading')} /></div>}>
513
- {renderAIConfigPanel({ runtime, capabilityId: capability.capabilityContract ?? capability.id })}
697
+ {renderAIConfigPanel({ runtime, capabilityId: capability.capabilityContract ?? capability.id, onCommitted: reportCommitted })}
514
698
  </Suspense>
515
699
  </DrawerErrorBoundary>
516
700
  </OverlayShell> : null}
@@ -0,0 +1,50 @@
1
+ import {
2
+ validateNimiLocalAppTextAnnotationResult,
3
+ type NimiLocalAppAssetsClient,
4
+ type NimiLocalAppTextAnnotationResult,
5
+ } from '@nimiplatform/sdk/app';
6
+ import type { StudioManagedArtifact } from './runtime-types.js';
7
+
8
+ export const STUDIO_TEXT_ANNOTATION_DOCUMENT_MEDIA_TYPE = 'application/json';
9
+ // The SDK bounds a validated annotation result to 16 MiB of JSON.
10
+ export const STUDIO_TEXT_ANNOTATION_DOCUMENT_MAX_BYTES = 16 * 1024 * 1024;
11
+
12
+ export function encodeStudioTextAnnotationDocument(result: NimiLocalAppTextAnnotationResult): Uint8Array<ArrayBuffer> {
13
+ return new TextEncoder().encode(JSON.stringify(result));
14
+ }
15
+
16
+ export async function studioDocumentSha256(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
17
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
18
+ return `sha256:${Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
19
+ }
20
+
21
+ /**
22
+ * Reads a saved annotation document and accepts it only when its size and
23
+ * digest still match the history reference and its content is a valid typed
24
+ * annotation. A missing or altered document never renders as a saved result.
25
+ */
26
+ export async function readStudioTextAnnotationDocument(
27
+ assets: Pick<NimiLocalAppAssetsClient, 'read'>,
28
+ document: StudioManagedArtifact,
29
+ ): Promise<NimiLocalAppTextAnnotationResult> {
30
+ if (document.mediaType !== STUDIO_TEXT_ANNOTATION_DOCUMENT_MEDIA_TYPE
31
+ || document.sizeBytes < 1 || document.sizeBytes > STUDIO_TEXT_ANNOTATION_DOCUMENT_MAX_BYTES) {
32
+ throw new Error(`Saved annotation reference is invalid: ${document.relativePath}`);
33
+ }
34
+ const read = await assets.read({ relativePath: document.relativePath });
35
+ if (read.asset.sizeBytes !== document.sizeBytes || read.asset.sha256 !== document.sha256) {
36
+ throw new Error(`Saved annotation no longer matches its history record: ${document.relativePath}`);
37
+ }
38
+ const bytes = new Uint8Array(document.sizeBytes);
39
+ let offset = 0;
40
+ for await (const chunk of read.body) {
41
+ if (offset + chunk.byteLength > bytes.byteLength) throw new Error(`Saved annotation is larger than recorded: ${document.relativePath}`);
42
+ bytes.set(chunk, offset);
43
+ offset += chunk.byteLength;
44
+ }
45
+ if (offset !== bytes.byteLength) throw new Error(`Saved annotation is incomplete: ${document.relativePath}`);
46
+ if (await studioDocumentSha256(bytes) !== document.sha256) {
47
+ throw new Error(`Saved annotation digest does not match: ${document.relativePath}`);
48
+ }
49
+ return validateNimiLocalAppTextAnnotationResult(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown);
50
+ }
@@ -0,0 +1,51 @@
1
+ import { browserFilesToDataUrlAttachments, type BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
2
+ import type { NimiLocalAppAssetsClient } from '@nimiplatform/sdk/app';
3
+ import type { StudioManagedArtifact } from './runtime-types.js';
4
+ import { studioDocumentSha256 } from './text-annotation-document.js';
5
+
6
+ /** Restore the saved input, never the current composer's unrelated attachment. */
7
+ export function readStudioTextReplayMedia(assets: Pick<NimiLocalAppAssetsClient, 'read'>, source: StudioManagedArtifact, signal: AbortSignal): Promise<BrowserDataUrlAttachment> {
8
+ return readStudioOwnedReplayMedia(assets, source, signal, ['image/jpeg', 'audio/wav', 'audio/mpeg', 'video/mp4']);
9
+ }
10
+
11
+ export function readStudioLocateReplayImage(assets: Pick<NimiLocalAppAssetsClient, 'read'>, source: StudioManagedArtifact, signal: AbortSignal): Promise<BrowserDataUrlAttachment> {
12
+ return readStudioOwnedReplayMedia(assets, source, signal, ['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
13
+ }
14
+
15
+ async function readStudioOwnedReplayMedia(assets: Pick<NimiLocalAppAssetsClient, 'read'>, source: StudioManagedArtifact, signal: AbortSignal, acceptedMimeTypes: readonly string[]): Promise<BrowserDataUrlAttachment> {
16
+ if (!source.mediaType || !acceptedMimeTypes.includes(source.mediaType)
17
+ || !Number.isSafeInteger(source.sizeBytes) || source.sizeBytes < 1 || source.sizeBytes > 32 * 1024 * 1024) {
18
+ throw new Error('Saved input media is invalid');
19
+ }
20
+ signal.throwIfAborted();
21
+ const read = await assets.read({ relativePath: source.relativePath });
22
+ const bytes = new Uint8Array(source.sizeBytes);
23
+ let offset = 0;
24
+ const reader = read.body[Symbol.asyncIterator]();
25
+ try {
26
+ if (read.asset.sizeBytes !== source.sizeBytes || read.asset.sha256 !== source.sha256) {
27
+ throw new Error('Saved input media no longer matches the history record');
28
+ }
29
+ for (;;) {
30
+ signal.throwIfAborted();
31
+ const chunk = await reader.next();
32
+ if (chunk.done) break;
33
+ if (offset + chunk.value.byteLength > bytes.byteLength) throw new Error('Saved input media is larger than recorded');
34
+ bytes.set(chunk.value, offset);
35
+ offset += chunk.value.byteLength;
36
+ }
37
+ } finally {
38
+ await reader.return?.();
39
+ }
40
+ if (offset !== bytes.byteLength || await studioDocumentSha256(bytes) !== source.sha256) {
41
+ throw new Error('Saved input media is incomplete or changed');
42
+ }
43
+ signal.throwIfAborted();
44
+ const [attachment] = await browserFilesToDataUrlAttachments(
45
+ [new File([bytes], source.displayName || source.relativePath, { type: source.mediaType })],
46
+ { idPrefix: 'studio-history', accept: [source.mediaType] },
47
+ );
48
+ signal.throwIfAborted();
49
+ if (!attachment) throw new Error('Saved input media cannot be restored');
50
+ return attachment;
51
+ }
@@ -0,0 +1,17 @@
1
+ import type { NimiLocalAppClient } from '@nimiplatform/sdk/app';
2
+
3
+ type ListedVoice = Awaited<ReturnType<NimiLocalAppClient['ai']['voiceAssets']['list']>>['assets'][number];
4
+
5
+ export async function listLabVoiceAssets(client: Pick<NimiLocalAppClient['ai']['voiceAssets'], 'list'>) {
6
+ const assets: Pick<ListedVoice, 'voiceAssetId' | 'creationSource' | 'status' | 'expiresAt'>[] = [];
7
+ const cursors = new Set<string>();
8
+ let pageToken = '';
9
+ do {
10
+ if (cursors.has(pageToken)) throw new Error('VOICE_ASSET_CATALOG_CURSOR_REPEATED');
11
+ cursors.add(pageToken);
12
+ const page = await client.list({ pageSize: 100, pageToken });
13
+ assets.push(...page.assets.map(({ voiceAssetId, creationSource, status, expiresAt }) => ({ voiceAssetId, creationSource, status, expiresAt })));
14
+ pageToken = page.nextPageToken;
15
+ } while (pageToken);
16
+ return assets;
17
+ }