@nimiplatform/app-tools 0.16.0-rc.15 → 0.16.0-rc.18

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 (84) hide show
  1. package/README.md +5 -42
  2. package/bin/nimi-app.mjs +25 -6
  3. package/lib/app-dependency-combinations.mjs +1 -0
  4. package/lib/app-doctor-update.mjs +8 -6
  5. package/lib/app-info.mjs +39 -19
  6. package/lib/app-lifecycle-guidance.mjs +1 -1
  7. package/lib/app-pack.mjs +4 -1
  8. package/lib/app-project-lifecycle.mjs +32 -12
  9. package/lib/app-resources.mjs +36 -0
  10. package/lib/app-scaffold-profiles.mjs +1 -1
  11. package/lib/app-scaffold.mjs +11 -13
  12. package/lib/index.mjs +7 -0
  13. package/lib/public-storefront.mjs +327 -0
  14. package/lib/storefront-media.mjs +8 -4
  15. package/lib/storefront-pack.mjs +152 -0
  16. package/lib/storefront-release-verification.mjs +31 -0
  17. package/lib/storefront-source.mjs +161 -0
  18. package/lib/web-coordination.mjs +4 -1
  19. package/lib/web-scaffold.mjs +3 -3
  20. package/package.json +9 -6
  21. package/scripts/sync-app-source.mjs +5 -12
  22. package/skills/nimi-app-lifecycle/SKILL.md +1 -0
  23. package/skills/nimi-app-lifecycle/references/storefront.md +28 -0
  24. package/templates/app-source/src/ai-studio-core/ai-config.ts +12 -0
  25. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +138 -117
  26. package/templates/app-source/src/ai-studio-core/history.ts +10 -8
  27. package/templates/app-source/src/ai-studio-core/host-context.tsx +1 -0
  28. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +15 -10
  29. package/templates/app-source/src/ai-studio-core/job-recovery.ts +505 -115
  30. package/templates/app-source/src/ai-studio-core/messages/en.json +55 -9
  31. package/templates/app-source/src/ai-studio-core/messages/zh.json +55 -9
  32. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +8 -2
  33. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +2 -0
  34. package/templates/app-source/src/ai-studio-core/parameters.ts +5 -4
  35. package/templates/app-source/src/ai-studio-core/run-target.ts +12 -1
  36. package/templates/app-source/src/ai-studio-core/runtime-types.ts +3 -0
  37. package/templates/app-source/src/ai-studio-core/runtime.ts +50 -12
  38. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +6 -7
  39. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +88 -27
  40. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +33 -0
  41. package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +2 -2
  42. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +10 -3
  43. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +6 -4
  44. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +121 -40
  45. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +34 -8
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +16 -2
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +18 -7
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +1 -1
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +78 -9
  50. package/templates/app-source/src/ai-studio-core/text-media-replay.ts +2 -1
  51. package/templates/app-source/src/ai-studio-core/workspace.tsx +138 -3
  52. package/templates/app-source/src/product-modules/agent-center/index.tsx +19 -3
  53. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -3
  54. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +19 -3
  55. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +12 -7
  56. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +48 -20
  57. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +2 -2
  58. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +2 -2
  59. package/templates/app-source/src/studio-modules/studio-create/registration.ts +1 -1
  60. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +11 -19
  61. package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +7 -4
  62. package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +14 -10
  63. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +3 -1
  64. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +3 -1
  65. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +6 -5
  66. package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +19 -11
  67. package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +14 -10
  68. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +54 -16
  69. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +22 -9
  70. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +19 -10
  71. package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +12 -6
  72. package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +11 -9
  73. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +5 -0
  74. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +5 -0
  75. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +18 -7
  76. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +28 -4
  77. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +12 -8
  78. package/templates/app-source/src/workbench-core/runtime-gate.tsx +171 -44
  79. package/templates/app-source/src/workbench-core/workbench-core.css +226 -23
  80. package/templates/app-source/src/workbench-core/workbench-core.tsx +5 -5
  81. package/templates/app-source.manifest.json +2 -2
  82. package/templates/default-starter/NIMI_APP.md +11 -3
  83. package/templates/default-starter.manifest.json +2 -2
  84. package/templates/storefront-release.yml +97 -0
@@ -9,9 +9,10 @@ import { TextExchangeResultView } from './section-ai-testing-exchange-result.js'
9
9
  import { TextDecisionResultView } from './section-ai-testing-decision-result.js';
10
10
  import { FaceSwapNotice, SessionSummaryView } from './section-ai-testing-session-result.js';
11
11
  import { useEffect, useState, type ReactNode } from 'react';
12
- import { Button, EmptyState, IconButton, StatusBadge, Surface, Tooltip } from '@nimiplatform/kit/ui';
12
+ import { Button, EmptyState, IconButton, ProgressIndicator, StatusBadge, Surface, Tooltip } from '@nimiplatform/kit/ui';
13
13
  import { AlertTriangle, ChevronRight, Clock, Copy as CopyIcon, Download as DownloadIcon, FileText, FolderOpen, Loader2, RefreshCw, SlidersHorizontal, Sparkles, Square } from 'lucide-react';
14
14
  import { useAIStudioHost } from './host-context.js';
15
+ import type { StudioJobProgress } from './section-ai-testing-run.js';
15
16
  import { VisionLocateResultView } from './section-ai-testing-vision-result.js';
16
17
  import type { StudioCapabilityRunResult } from './runtime-types.js';
17
18
  import type { StudioCapabilityDescriptor, StudioCapabilityRegistration } from './module-registration.js';
@@ -31,7 +32,7 @@ function ReadyBody({ result }: { result: StudioCapabilityRunResult & { ok: true
31
32
  if (output.kind === 'text') {
32
33
  return <div className="studio-result__rich">
33
34
  {output.sourceImage ? <ArtifactMediaPreview artifact={output.sourceImage} fallbackLabel={output.sourceImage.displayName || output.sourceImage.relativePath} /> : null}
34
- <TextStudioOutputBody text={output.text} />
35
+ <TextStudioOutputBody text={output.text} finishReason={output.finishReason} />
35
36
  </div>;
36
37
  }
37
38
  if (output.kind === 'transcript') {
@@ -207,7 +208,9 @@ export function StudioResult({
207
208
  intentLabel,
208
209
  requestSettings,
209
210
  streamingText,
211
+ jobId,
210
212
  jobStatus,
213
+ jobProgress,
211
214
  verboseConsole,
212
215
  onCopy,
213
216
  onDownload,
@@ -225,7 +228,9 @@ export function StudioResult({
225
228
  intentLabel?: string;
226
229
  requestSettings?: ReactNode;
227
230
  streamingText?: string | null;
231
+ jobId?: string;
228
232
  jobStatus?: 'queued' | 'running';
233
+ jobProgress?: StudioJobProgress;
229
234
  verboseConsole: boolean;
230
235
  onCopy: () => void;
231
236
  onDownload: () => void;
@@ -365,20 +370,41 @@ export function StudioResult({
365
370
  let body: ReactNode;
366
371
  if (running) {
367
372
  const hasStream = typeof streamingText === 'string';
373
+ const hasKnownProgress = Boolean(!hasStream && jobProgress && jobProgress.totalSteps > 0);
368
374
  body = (
369
375
  <div className="studio-result__pending">
370
376
  <div className="studio-result__pending-line">
371
377
  <Loader2 size={15} aria-hidden="true" className="studio-spin" />
372
378
  <span>{cancelRequested
373
379
  ? t('Studio.result.pendingCancel')
380
+ : jobStatus ? t(`Studio.result.jobStatus.${jobStatus}`)
374
381
  : capability.id === 'music.transcribe' ? t('Transcription.running')
375
382
  : capability.id === 'audio.voice.convert' ? t('VoiceConvert.running')
376
383
  : capability.id === 'audio.separate' ? t('AudioSeparate.running')
377
- : capability.id === 'vision.locate' && jobStatus ? t(`VisionLocate.${jobStatus}`)
378
384
  : profile.pendingLabelKey
379
385
  ? t(profile.pendingLabelKey)
380
386
  : hasStream ? t('Studio.result.pendingStreaming') : t('Studio.result.pendingRuntime')}</span>
381
387
  </div>
388
+ {jobId ? <p>{t('Studio.result.jobLabel')} <code>{jobId}</code></p> : null}
389
+ {jobId && !hasKnownProgress && !hasStream ? <ProgressIndicator indeterminate data-testid="studio-job-progress" aria-label={t('Studio.result.progressLabel')} /> : null}
390
+ {hasKnownProgress && jobProgress ? (
391
+ <div className="studio-result__progress" data-testid="studio-job-progress">
392
+ <ProgressIndicator
393
+ value={jobProgress.percent}
394
+ max={100}
395
+ showValue
396
+ aria-label={t('Studio.result.progressLabel')}
397
+ aria-valuetext={jobProgress.totalSteps > 0
398
+ ? t('Studio.result.progressSteps', { current: jobProgress.currentStep, total: jobProgress.totalSteps })
399
+ : `${jobProgress.percent}%`}
400
+ />
401
+ {jobProgress.totalSteps > 0 ? (
402
+ <span className="studio-result__progress-steps">
403
+ {t('Studio.result.progressSteps', { current: jobProgress.currentStep, total: jobProgress.totalSteps })}
404
+ </span>
405
+ ) : null}
406
+ </div>
407
+ ) : null}
382
408
  {hasStream ? <div className="studio-result__text studio-result__text--stream" aria-live="polite">{streamingText || '...'}</div> : null}
383
409
  </div>
384
410
  );
@@ -390,8 +416,8 @@ export function StudioResult({
390
416
  <span>{statusTitle}</span>
391
417
  </div>
392
418
  <p>{studioNonSuccessReasonUserMessage(operationAborted.reason, t, capability.id)}</p>
393
- <p className="studio-result__hint">{studioNonSuccessReasonUserAction(operationAborted.reason, t, capability.id)}</p>
394
- <KnownJobNotice jobId={operationAborted.jobId} />
419
+ <p className="studio-result__hint">{studioNonSuccessReasonUserAction(operationAborted.reason, t, capability.id, operationAborted.diagnostics)}</p>
420
+ <KnownJobNotice jobId={operationAborted.jobId} recoveryCleanupUnconfirmed={operationAborted.recoveryCleanupUnconfirmed} />
395
421
  </div>
396
422
  );
397
423
  } else if (canceled) {
@@ -403,7 +429,7 @@ export function StudioResult({
403
429
  </div>
404
430
  <p>{studioNonSuccessReasonUserMessage(canceled.reason, t)}</p>
405
431
  <p className="studio-result__hint">{studioNonSuccessReasonUserAction(canceled.reason, t)}</p>
406
- <KnownJobNotice jobId={canceled.jobId} />
432
+ <KnownJobNotice jobId={canceled.jobId} recoveryCleanupUnconfirmed={canceled.recoveryCleanupUnconfirmed} />
407
433
  </div>
408
434
  );
409
435
  } else if (timedOut) {
@@ -415,7 +441,7 @@ export function StudioResult({
415
441
  </div>
416
442
  <p>{studioNonSuccessReasonUserMessage(timedOut.reason, t)}</p>
417
443
  <p className="studio-result__hint">{studioNonSuccessReasonUserAction(timedOut.reason, t)}</p>
418
- <KnownJobNotice jobId={timedOut.jobId} />
444
+ <KnownJobNotice jobId={timedOut.jobId} recoveryCleanupUnconfirmed={timedOut.recoveryCleanupUnconfirmed} />
419
445
  </div>
420
446
  );
421
447
  } else if (blocked) {
@@ -439,7 +465,7 @@ export function StudioResult({
439
465
  {t('NonSuccess.openAIConfig')}
440
466
  </Button>
441
467
  ) : null}
442
- <KnownJobNotice jobId={blocked.jobId} />
468
+ <KnownJobNotice jobId={blocked.jobId} recoveryCleanupUnconfirmed={blocked.recoveryCleanupUnconfirmed} />
443
469
  </div>
444
470
  );
445
471
  } else if (ready) {
@@ -3,7 +3,7 @@ import { Button } from '@nimiplatform/kit/ui';
3
3
  import { useAIStudioHost } from './host-context.js';
4
4
  import { downloadTextFile, TextStudioOutputBody } from './section-ai-testing-output.js';
5
5
 
6
- const MAX_VISIBLE_WORDS = 400;
6
+ const MAX_VISIBLE_ROWS = 400;
7
7
 
8
8
  export function SpeechTranscriptResultView({
9
9
  text,
@@ -14,8 +14,9 @@ export function SpeechTranscriptResultView({
14
14
  }) {
15
15
  const host = useAIStudioHost();
16
16
  const { translate: t } = host;
17
+ const diarization = transcription?.diarization;
17
18
  const words = transcription?.words ?? [];
18
- const visibleWords = words.slice(0, MAX_VISIBLE_WORDS);
19
+ const visibleWords = words.slice(0, MAX_VISIBLE_ROWS);
19
20
  return (
20
21
  <section className="studio-result__rich" aria-label={t('StudioResults.transcript.title')}>
21
22
  <TextStudioOutputBody text={text} />
@@ -27,6 +28,19 @@ export function SpeechTranscriptResultView({
27
28
  </Button>
28
29
  ) : null}
29
30
  {transcription?.language ? <p className="studio-result__hint">{t('StudioResults.transcript.detectedLanguage', { language: transcription.language })}</p> : null}
31
+ {diarization?.status === 'no-speakers' ? <p>{t('StudioResults.transcript.noSpeakers')}</p> : null}
32
+ {diarization?.status === 'diarized' ? (
33
+ <details className="studio-annotation" open>
34
+ <summary>{t('StudioResults.transcript.speakerIntervals', { count: diarization.intervals.length })}</summary>
35
+ <table className="studio-annotation__tokens">
36
+ <thead><tr><th>{t('StudioResults.transcript.speaker')}</th><th>{t('StudioResults.transcript.start')}</th><th>{t('StudioResults.transcript.end')}</th></tr></thead>
37
+ <tbody>{diarization.intervals.slice(0, MAX_VISIBLE_ROWS).map((interval, index) => (
38
+ <tr key={index}><td>{interval.speakerId}</td><td>{interval.startSeconds.toFixed(3)}</td><td>{interval.endSeconds.toFixed(3)}</td></tr>
39
+ ))}</tbody>
40
+ </table>
41
+ {diarization.intervals.length > MAX_VISIBLE_ROWS ? <p>{t('StudioResults.transcript.moreIntervals', { count: MAX_VISIBLE_ROWS })}</p> : null}
42
+ </details>
43
+ ) : null}
30
44
  {words.length > 0 ? (
31
45
  <details className="studio-annotation" open>
32
46
  <summary>{t('StudioResults.transcript.wordTimes', { count: words.length })}</summary>
@@ -103,19 +103,30 @@ export function MusicTranscriptionNotice({ value, recordId }: { readonly value?:
103
103
  end: (value.inputRange.endFrame / value.sourceInfo.sampleRateHz).toFixed(3), hz: value.sourceInfo.sampleRateHz })}</p>
104
104
  <ArtifactMediaResult artifact={value.sourceAudio} fallbackLabel={t('Transcription.source')} />
105
105
  <div className="flex flex-wrap gap-2">
106
- {value.scores.map(score => <Button key={score.relativePath} onClick={() => {
107
- choose(score.relativePath);
108
- }}>{t(`Transcription.parts.${score.part}`)} · {score.format.toUpperCase()}</Button>)}
109
- {timelinePath ? <Button onClick={() => choose(timelinePath)}>{t('Transcription.timeline')}</Button> : null}
106
+ {value.scores.map(score => <Button
107
+ key={score.relativePath}
108
+ size="sm"
109
+ tone={selected === score.relativePath ? 'primary' : 'secondary'}
110
+ aria-pressed={selected === score.relativePath}
111
+ onClick={() => { choose(score.relativePath); }}
112
+ >{t(`Transcription.parts.${score.part}`)} · {score.format.toUpperCase()}</Button>)}
113
+ {timelinePath ? <Button
114
+ size="sm"
115
+ tone={selected === timelinePath ? 'primary' : 'secondary'}
116
+ aria-pressed={selected === timelinePath}
117
+ onClick={() => choose(timelinePath)}
118
+ >{t('Transcription.timeline')}</Button> : null}
110
119
  </div>
111
120
  {file?.midi ? <div className="space-y-2">
112
121
  <p>{t('Transcription.midiTimeBasis', { start: (value.inputRange.startFrame / value.sourceInfo.sampleRateHz).toFixed(3) })}</p>
113
- <Button disabled={exporting === sourceKey} onClick={() => void exportSelected()}>{t('Transcription.exportMidi')}</Button>
114
- <Button onClick={() => void revealSelected()}>{t('Transcription.showFile')}</Button>
122
+ <div className="flex flex-wrap gap-2">
123
+ <Button size="sm" disabled={exporting === sourceKey} onClick={() => void exportSelected()}>{t('Transcription.exportMidi')}</Button>
124
+ <Button size="sm" tone="secondary" onClick={() => void revealSelected()}>{t('Transcription.showFile')}</Button>
125
+ </div>
115
126
  </div> : null}
116
127
  {body ? <>
117
128
  <TextareaField value={body} readOnly textareaClassName="min-h-48 max-h-96 font-mono" aria-label={t('Transcription.result')} />
118
- <Button disabled={exporting === sourceKey} onClick={() => void exportSelected()}>{t('Transcription.export')}</Button>
129
+ <Button size="sm" disabled={exporting === sourceKey} onClick={() => void exportSelected()}>{t('Transcription.export')}</Button>
119
130
  </> : null}
120
131
  {exportedPath ? <p>{t('Transcription.exported', { path: exportedPath })}</p> : null}
121
132
  {error ? <p role="alert">{error}</p> : null}
@@ -34,7 +34,7 @@ export function VisionLocateResultView({ output }: { output: Extract<StudioTyped
34
34
  {location.type === 'box' ? <rect x={location.x1*width} y={location.y1*height} width={(location.x2-location.x1)*width} height={(location.y2-location.y1)*height} vectorEffect="non-scaling-stroke" /> : <circle cx={location.x*width} cy={location.y*height} r={Math.max(width,height)*0.007} vectorEffect="non-scaling-stroke" />}
35
35
  </g>)}
36
36
  </svg>
37
- </div> : <p>{t('VisionLocate.previewUnavailable')}</p>}
37
+ </div> : <p role="status">{t(source && !imageFailed ? 'Common.loading' : 'VisionLocate.previewUnavailable')}</p>}
38
38
  <figcaption>{t(locations.length ? 'VisionLocate.found' : 'VisionLocate.noMatch', { count: locations.length })}</figcaption>
39
39
  <details><summary>{t('VisionLocate.coordinates')}</summary><pre>{JSON.stringify({ imageArtifactId, width, height, locations }, null, 2)}</pre></details>
40
40
  </figure>;
@@ -14,6 +14,7 @@ import { CapabilityRunHistory, DrawerErrorBoundary, downloadTextFile, resultPlai
14
14
  import { TextStudioComposer, TextStudioStartState } from './section-ai-testing-composer.js';
15
15
  import { ScenarioJobStatus } from '@nimiplatform/sdk/runtime/generated';
16
16
  import {
17
+ STUDIO_TEXT_MEDIA_MIMES,
17
18
  canCancelStudioCapabilityRun,
18
19
  hasStudioCapabilityRunInput,
19
20
  textStudioMediaInputAvailable,
@@ -104,12 +105,13 @@ function TextStudioShell({
104
105
  const runSeqRef = useRef(0);
105
106
  const [observationIssue, setObservationIssue] = useState(false);
106
107
  const abortControllerRef = useRef<{ runId: string; controller: AbortController; observation: AbortController } | null>(null);
108
+ const submittingRef = useRef(false);
107
109
  const running = executingRun !== null;
108
110
  const displayingExecution = executingRun !== null && activeRun?.id === executingRun.id;
109
111
  const displayedRun = displayingExecution ? executingRun : activeRun;
110
112
  const expandedHistoryErrorRef = useRef<string | null>(null);
111
113
  const attachmentAdapter = useMemo(
112
- () => 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'] } : {}) }),
114
+ () => 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: [...STUDIO_TEXT_MEDIA_MIMES] } : {}) }),
113
115
  [capability.id],
114
116
  );
115
117
  const composerState = useChatComposer<BrowserDataUrlAttachment>({
@@ -156,7 +158,7 @@ function TextStudioShell({
156
158
  const parameterSummary = registration.parameters.summarize(effectiveCapabilityParameters);
157
159
  const hasAlternativeInput = registration.parameters.hasAlternativeInput(effectiveCapabilityParameters);
158
160
  const promptEnabled = profile.inputKind !== 'url' || runtime?.mode !== 'remote-app';
159
- const inputIssueKey = registration.parameters.requiredInputIssue?.(effectiveCapabilityParameters);
161
+ const inputIssueKey = registration.parameters.requiredInputIssue?.(effectiveCapabilityParameters, runTarget.effectiveSelection, prompt);
160
162
  const recordedInput = registration.parameters.recordedInput;
161
163
  const displayedRunPrompt = displayedRun?.prompt;
162
164
  // A parameter-owned input reruns the displayed run's recorded request, which
@@ -273,7 +275,7 @@ function TextStudioShell({
273
275
  }
274
276
 
275
277
  async function run(nextPrompt = prompt, nextContext = context, replay = false) {
276
- if (abortControllerRef.current) return;
278
+ if (abortControllerRef.current || submittingRef.current) return;
277
279
  if (!replay && inputPreparationsRef.current.has(capability.id)) return;
278
280
  if (replay && !textMediaReplayable) return;
279
281
  if (replay && (!displayedRunReplayable || !replayAssetsAvailable)) return;
@@ -285,7 +287,7 @@ function TextStudioShell({
285
287
  const runEffectiveParameters = replay && registration.parameters.restoreRecordedParameters
286
288
  ? runParameters
287
289
  : registration.parameters.project(runTarget.source, runParameters);
288
- if (registration.parameters.requiredInputIssue?.(runEffectiveParameters)) return;
290
+ if (registration.parameters.requiredInputIssue?.(runEffectiveParameters, runTarget.effectiveSelection, nextPrompt)) return;
289
291
  const runHasAlternativeInput = registration.parameters.hasAlternativeInput(runEffectiveParameters);
290
292
  // Raw document inputs retain their original whitespace so annotation
291
293
  // offsets refer to the exact text the user entered. A parameter-owned input
@@ -298,6 +300,55 @@ function TextStudioShell({
298
300
  if (profile.requiresParameterInput && !runHasAlternativeInput) return;
299
301
  if (!(replay && capability.id === 'vision.locate' ? Boolean(savedTextMedia) : hasRequiredImage)) return;
300
302
  if (!runTarget.canDispatch) return;
303
+ submittingRef.current = true;
304
+ const preRefreshSeq = runSeqRef.current;
305
+ try {
306
+ const refresh = await runTarget.waitForTargetRefresh(
307
+ runTarget.effectiveSelection?.resource?.oneofKind === 'local',
308
+ );
309
+ if (runSeqRef.current !== preRefreshSeq || abortControllerRef.current) return;
310
+ if (refresh.waited) {
311
+ if (!refresh.snapshot) return;
312
+ if (refresh.snapshot.revision !== runTarget.snapshot?.revision) {
313
+ setDraftError(t('Studio.run.targetChanged'));
314
+ return;
315
+ }
316
+ if (runTarget.capabilityContract) {
317
+ const refreshedSelection = refresh.snapshot.effectiveSelections.find(
318
+ (item) => item.capabilityContract === runTarget.capabilityContract,
319
+ );
320
+ if (!refreshedSelection || refreshedSelection.state !== 'ready') return;
321
+ const issue = registration.parameters.requiredInputIssue?.(runEffectiveParameters, refreshedSelection, nextPrompt);
322
+ if (issue) { setDraftError(t(issue)); return; }
323
+ const refreshedResource = refreshedSelection.resource;
324
+ const refreshedSource = refreshedResource?.oneofKind === 'local'
325
+ ? 'local'
326
+ : refreshedResource?.oneofKind === 'cloud'
327
+ ? 'cloud'
328
+ : refreshedResource?.oneofKind === 'external'
329
+ ? 'external'
330
+ : 'unknown';
331
+ const refreshedTargetRef = refreshedResource?.oneofKind === 'local'
332
+ ? refreshedResource.local.loadoutRef
333
+ : refreshedResource?.oneofKind === 'cloud'
334
+ ? (typeof refreshedResource.cloud.target.providerModelTarget.providerModelId === 'string'
335
+ ? refreshedResource.cloud.target.providerModelTarget.providerModelId
336
+ : undefined)
337
+ : refreshedResource?.oneofKind === 'external'
338
+ ? `${refreshedResource.external.executor.executorRef}:${refreshedResource.external.target.targetRef}`
339
+ : undefined;
340
+ if (refreshedSelection.localLoadoutRevision !== runTarget.effectiveSelection?.localLoadoutRevision
341
+ || (refreshedSource !== 'unknown' && refreshedSource !== runTarget.source)
342
+ || (runTarget.targetRef && refreshedTargetRef && refreshedTargetRef !== runTarget.targetRef)) {
343
+ setDraftError(t('Studio.run.targetChanged'));
344
+ return;
345
+ }
346
+ }
347
+ }
348
+ } finally {
349
+ submittingRef.current = false;
350
+ }
351
+ if (draftError === t('Studio.run.targetChanged')) setDraftError(null);
301
352
  const runSeq = runSeqRef.current + 1;
302
353
  runSeqRef.current = runSeq;
303
354
  const abortController = new AbortController();
@@ -348,6 +399,9 @@ function TextStudioShell({
348
399
  || (capability.id === 'text.tools' && submittedParameters.delivery === 'stream');
349
400
  if (isStreaming) setStreamingText('');
350
401
  const directive = textStudioDirectiveForTarget(runTarget, profile);
402
+ const emptyMediaPrompt = (capability.id === 'world.generate' || capability.id === 'video.generate')
403
+ && runHasAlternativeInput && !displayPrompt && !nextContext.trim();
404
+ const plainDocument = capability.id === 'text.embed' && !nextContext.trim();
351
405
  if (capability.id === 'text.generate' && runAttachments.length > 0 &&
352
406
  !textStudioMediaInputAvailable(await rendererHost.sdk.aiConfig.getSnapshot(), runAttachments[0]?.mimeType)) {
353
407
  result = {
@@ -361,7 +415,7 @@ function TextStudioShell({
361
415
  recordedRunConfig: runConfig,
362
416
  recordedCreatedAt: pendingRun.createdAt,
363
417
  recordedPrompt: displayPrompt,
364
- prompt: ((capability.id === 'world.generate' || capability.id === 'video.generate') && runHasAlternativeInput && !displayPrompt && !nextContext.trim()) || usesVerbatimStudioPrompt(capability.id) || profile.rawPrompt || recordedInput
418
+ prompt: emptyMediaPrompt || plainDocument || usesVerbatimStudioPrompt(capability.id) || profile.rawPrompt || recordedInput
365
419
  ? displayPrompt
366
420
  : textStudioRuntimePrompt(displayPrompt, nextContext, directive),
367
421
  scenarioId: preset.id,
@@ -378,7 +432,20 @@ function TextStudioShell({
378
432
  onJobUpdate: job => {
379
433
  if (runSeqRef.current !== runSeq) return;
380
434
  const jobStatus = job.status === ScenarioJobStatus.QUEUED || job.status === ScenarioJobStatus.SUBMITTED ? 'queued' : job.status === ScenarioJobStatus.RUNNING ? 'running' : undefined;
381
- if (jobStatus) setExecutingRun(current => current?.id === pendingRun.id ? { ...current, jobStatus } : current);
435
+ const totalSteps = Number.isFinite(job.progressTotalSteps) && job.progressTotalSteps > 0 ? Math.trunc(job.progressTotalSteps) : 0;
436
+ const currentStep = Number.isFinite(job.progressCurrentStep) && job.progressCurrentStep >= 0 ? Math.trunc(job.progressCurrentStep) : 0;
437
+ const percent = Number.isFinite(job.progressPercent) ? Math.max(0, Math.min(100, Math.round(job.progressPercent))) : 0;
438
+ const jobProgress = totalSteps > 0 ? { percent, currentStep, totalSteps } : undefined;
439
+ if (job.jobId || jobStatus || jobProgress) {
440
+ setExecutingRun(current => current?.id === pendingRun.id
441
+ ? {
442
+ ...current,
443
+ ...(job.jobId ? { jobId: job.jobId } : {}),
444
+ ...(jobStatus ? { jobStatus } : {}),
445
+ jobProgress,
446
+ }
447
+ : current);
448
+ }
382
449
  },
383
450
  });
384
451
  } catch (error) {
@@ -551,6 +618,7 @@ function TextStudioShell({
551
618
  capabilityId={capability.id}
552
619
  contract={registration.parameters}
553
620
  source={runTarget.source}
621
+ effectiveSelection={runTarget.effectiveSelection}
554
622
  parameters={capabilityParameters}
555
623
  disabled={running || preparingInput}
556
624
  onChange={(next) => parameterStore.setParameters(capability.id, next)}
@@ -606,7 +674,7 @@ function TextStudioShell({
606
674
  <header className="studio__head">
607
675
  <div className="studio__heading">
608
676
  <div className="studio__title">
609
- <h2>{t(capability.labelKey)}</h2>
677
+ <h1>{t(capability.labelKey)}</h1>
610
678
  {capability.capabilityContract ? <code>{capability.capabilityContract}</code> : null}
611
679
  </div>
612
680
  <div className="studio__status" role="status">
@@ -670,7 +738,7 @@ function TextStudioShell({
670
738
  </div>
671
739
  {draftError ? <InlineAlert className="studio__head-alert" tone="warning">{draftError}</InlineAlert> : null}
672
740
  </header>
673
- <main className="studio__stage">
741
+ <div className="studio__stage">
674
742
  {hasActiveRun && displayedRun ? (
675
743
  <TextStudioResultState
676
744
  registration={registration}
@@ -717,7 +785,7 @@ function TextStudioShell({
717
785
  onSelectHistoryRun={selectHistoryRecord}
718
786
  />
719
787
  ) : null}
720
- </main>
788
+ </div>
721
789
  </div>
722
790
  <CapabilityRunHistory
723
791
  history={history}
@@ -793,6 +861,7 @@ export function SectionAITesting({
793
861
  {renderAIConfigPanel ? <OverlayShell
794
862
  open={configOpen}
795
863
  kind="drawer"
864
+ closeLabel={t('Common.close')}
796
865
  size="M"
797
866
  title={t('StudioModelConfig.drawerTitle')}
798
867
  description={t('StudioModelConfig.drawerDescription', { appTitle })}
@@ -1,11 +1,12 @@
1
1
  import { browserFilesToDataUrlAttachments, type BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
2
2
  import type { NimiLocalAppAssetsClient } from '@nimiplatform/sdk/app';
3
3
  import type { StudioManagedArtifact } from './runtime-types.js';
4
+ import { STUDIO_TEXT_MEDIA_MIMES } from './section-ai-testing-input.js';
4
5
  import { studioDocumentSha256 } from './text-annotation-document.js';
5
6
 
6
7
  /** Restore the saved input, never the current composer's unrelated attachment. */
7
8
  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
+ return readStudioOwnedReplayMedia(assets, source, signal, STUDIO_TEXT_MEDIA_MIMES);
9
10
  }
10
11
 
11
12
  export function readStudioLocateReplayImage(assets: Pick<NimiLocalAppAssetsClient, 'read'>, source: StudioManagedArtifact, signal: AbortSignal): Promise<BrowserDataUrlAttachment> {
@@ -20,7 +20,11 @@ import {
20
20
  type StudioRunHistory,
21
21
  type StudioRunHistoryRecord,
22
22
  } from './history.js';
23
- import { studioHistoryClearOutcomeTone } from './history-policy.js';
23
+ import {
24
+ appendStudioRunHistoryRecord,
25
+ studioHistoryClearOutcomeTone,
26
+ studioHistoryFromRecords,
27
+ } from './history-policy.js';
24
28
  import type { StudioCapabilityRegistration } from './module-registration.js';
25
29
  import { createStudioNonSuccess } from './non-success-presentation.js';
26
30
  import type { StudioParameterState } from './parameters.js';
@@ -158,12 +162,27 @@ export function useAIStudioWorkspaceController({
158
162
  );
159
163
  const currentRepository = useRef(historyRepository);
160
164
  currentRepository.current = historyRepository;
165
+ const projectionRef = useRef<AIStudioHistoryProjection | null>(null);
166
+ projectionRef.current = projection;
167
+ const pendingRemovedIdsRef = useRef(new Set<string>());
168
+ const activeUndoToastsRef = useRef(new Set<string>());
161
169
  const active = useRef(true);
162
170
  useEffect(() => {
163
171
  active.current = true;
164
- return () => { active.current = false; };
172
+ return () => {
173
+ active.current = false;
174
+ for (const id of activeUndoToastsRef.current) nimiToast.dismiss(id);
175
+ activeUndoToastsRef.current.clear();
176
+ pendingRemovedIdsRef.current.clear();
177
+ };
165
178
  }, []);
166
179
 
180
+ useEffect(() => () => {
181
+ for (const id of activeUndoToastsRef.current) nimiToast.dismiss(id);
182
+ activeUndoToastsRef.current.clear();
183
+ pendingRemovedIdsRef.current.clear();
184
+ }, [historyRepository]);
185
+
167
186
  const refreshHistory = useCallback(async () => {
168
187
  try {
169
188
  const next = await historyRepository.load();
@@ -226,9 +245,86 @@ export function useAIStudioWorkspaceController({
226
245
 
227
246
  const historyActions = useMemo(() => ({
228
247
  removeRecord: async (recordId: string, deleteAssets = false) => {
248
+ const currentProjection = projectionRef.current;
249
+ const removedRecord = !deleteAssets && currentProjection
250
+ ? Object.values(currentProjection.runHistory).flat().find((item) => item.id === recordId)
251
+ : undefined;
252
+ const removedMedia = !deleteAssets && currentProjection
253
+ ? currentProjection.mediaHistory.filter((item) => (item.runId || item.id) === recordId)
254
+ : [];
255
+ if (!deleteAssets && removedRecord) {
256
+ let undone = false;
257
+ pendingRemovedIdsRef.current.add(recordId);
258
+ setProjection((current) => current ? removeRecordFromProjection(current, recordId) : current);
259
+ const removePromise = historyRepository.remove(recordId, false);
260
+ let toastId = '';
261
+ const restore = async () => {
262
+ if (undone) return;
263
+ undone = true;
264
+ if (toastId) activeUndoToastsRef.current.delete(toastId);
265
+ pendingRemovedIdsRef.current.delete(recordId);
266
+ if (active.current && currentRepository.current === historyRepository) {
267
+ setProjection((current) => current
268
+ ? restoreRecordInProjection(current, removedRecord, removedMedia)
269
+ : { runHistory: studioHistoryFromRecords([removedRecord]), mediaHistory: removedMedia });
270
+ }
271
+ try {
272
+ await removePromise.catch(() => undefined);
273
+ // Once Undo has been accepted, always complete the restore write against the
274
+ // captured repository even if the workspace unmounts before removal settles.
275
+ const restored = await historyRepository.appendRecord(removedRecord);
276
+ if (!active.current || currentRepository.current !== historyRepository) return;
277
+ if ('refreshError' in restored) {
278
+ setHistoryIssue(current => current?.kind === 'save' ? current : { kind: 'load', saved: true, message: restored.refreshError });
279
+ return;
280
+ }
281
+ setProjection(filterPendingRemovedProjection(restored, pendingRemovedIdsRef.current));
282
+ } catch {
283
+ if (active.current && currentRepository.current === historyRepository) {
284
+ await refreshHistory();
285
+ nimiToast.danger(translate('History.restoreFailed'));
286
+ }
287
+ }
288
+ };
289
+ toastId = nimiToast.success(translate('History.deletedRecordOnly'), {
290
+ durationMs: 6000,
291
+ action: {
292
+ label: translate('Common.undo'),
293
+ onClick: () => { void restore(); },
294
+ },
295
+ });
296
+ activeUndoToastsRef.current.add(toastId);
297
+ try {
298
+ const outcome = await removePromise;
299
+ pendingRemovedIdsRef.current.delete(recordId);
300
+ if (undone || !active.current || currentRepository.current !== historyRepository) return;
301
+ if (outcome.skipped > 0) {
302
+ activeUndoToastsRef.current.delete(toastId);
303
+ nimiToast.dismiss(toastId);
304
+ setProjection(filterPendingRemovedProjection(outcome.projection, pendingRemovedIdsRef.current));
305
+ nimiToast.danger(translate('History.deleteAssetFailed'));
306
+ } else if (outcome.failed > 0) {
307
+ activeUndoToastsRef.current.delete(toastId);
308
+ nimiToast.dismiss(toastId);
309
+ setProjection(filterPendingRemovedProjection(outcome.projection, pendingRemovedIdsRef.current));
310
+ nimiToast.danger(translate('History.deleteFailed'));
311
+ } else {
312
+ setProjection(filterPendingRemovedProjection(outcome.projection, pendingRemovedIdsRef.current));
313
+ }
314
+ } catch {
315
+ pendingRemovedIdsRef.current.delete(recordId);
316
+ activeUndoToastsRef.current.delete(toastId);
317
+ nimiToast.dismiss(toastId);
318
+ if (!undone && active.current && currentRepository.current === historyRepository) {
319
+ await refreshHistory();
320
+ nimiToast.danger(translate('History.deleteFailed'));
321
+ }
322
+ }
323
+ return;
324
+ }
229
325
  try {
230
326
  const outcome = await historyRepository.remove(recordId, deleteAssets);
231
- setProjection(outcome.projection);
327
+ setProjection(filterPendingRemovedProjection(outcome.projection, pendingRemovedIdsRef.current));
232
328
  if (outcome.skipped > 0) nimiToast.danger(translate('History.deleteAssetFailed'));
233
329
  else if (outcome.failed > 0) nimiToast.danger(translate('History.deleteFailed'));
234
330
  else nimiToast.success(translate(deleteAssets ? 'History.deletedRecordAndAsset' : 'History.deletedRecordOnly'));
@@ -469,6 +565,45 @@ export function AIStudioWorkspace({
469
565
  );
470
566
  }
471
567
 
568
+ function removeRecordFromProjection(
569
+ projection: AIStudioHistoryProjection,
570
+ recordId: string,
571
+ ): AIStudioHistoryProjection {
572
+ const remainingRuns = Object.values(projection.runHistory).flat().filter((item) => item.id !== recordId);
573
+ return {
574
+ runHistory: studioHistoryFromRecords(remainingRuns),
575
+ mediaHistory: projection.mediaHistory.filter((item) => (item.runId || item.id) !== recordId),
576
+ };
577
+ }
578
+
579
+ function filterPendingRemovedProjection(
580
+ projection: AIStudioHistoryProjection,
581
+ pendingRemovedIds: ReadonlySet<string>,
582
+ ): AIStudioHistoryProjection {
583
+ if (pendingRemovedIds.size === 0) return projection;
584
+ const remainingRuns = Object.values(projection.runHistory).flat().filter((item) => !pendingRemovedIds.has(item.id));
585
+ return {
586
+ runHistory: studioHistoryFromRecords(remainingRuns),
587
+ mediaHistory: projection.mediaHistory.filter((item) => !pendingRemovedIds.has(item.runId || item.id)),
588
+ };
589
+ }
590
+
591
+ function restoreRecordInProjection(
592
+ projection: AIStudioHistoryProjection,
593
+ record: StudioRunHistoryRecord,
594
+ mediaRows: readonly StudioMediaHistoryRecord[],
595
+ ): AIStudioHistoryProjection {
596
+ const restoredMediaIds = new Set(mediaRows.map((item) => item.id));
597
+ const mergedMedia = [
598
+ ...mediaRows,
599
+ ...projection.mediaHistory.filter((item) => !restoredMediaIds.has(item.id)),
600
+ ].sort((left, right) => right.createdAt.localeCompare(left.createdAt));
601
+ return {
602
+ runHistory: appendStudioRunHistoryRecord(projection.runHistory, record),
603
+ mediaHistory: mergedMedia,
604
+ };
605
+ }
606
+
472
607
  function errorMessage(error: unknown, fallback: string): string {
473
608
  return error instanceof Error ? error.message : String(error || fallback);
474
609
  }
@@ -1,4 +1,4 @@
1
- import { useMemo, type ComponentProps } from 'react';
1
+ import { useEffect, useMemo, useState, type ComponentProps } from 'react';
2
2
  import {
3
3
  AppAgentCenterEntry,
4
4
  createAgentCenterShellHostMechanics,
@@ -8,9 +8,25 @@ import {
8
8
  hasElectronInvoke,
9
9
  } from '@nimiplatform/kit/shell/renderer/bridge';
10
10
 
11
+ function useDocumentLanguage(explicit?: string): string {
12
+ const [docLang, setDocLang] = useState(() => globalThis.document?.documentElement.lang || 'en');
13
+ useEffect(() => {
14
+ if (explicit) return undefined;
15
+ const root = globalThis.document?.documentElement;
16
+ if (!root || typeof MutationObserver === 'undefined') return undefined;
17
+ const sync = () => setDocLang(root.lang || 'en');
18
+ sync();
19
+ const observer = new MutationObserver(sync);
20
+ observer.observe(root, { attributes: true, attributeFilter: ['lang'] });
21
+ return () => observer.disconnect();
22
+ }, [explicit]);
23
+ return explicit || docLang;
24
+ }
25
+
11
26
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-019c
12
27
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-agid-014a
13
- export function AgentCenterCapability(props: { readonly client: ComponentProps<typeof AppAgentCenterEntry>['client'] }) {
28
+ export function AgentCenterCapability(props: { readonly client: ComponentProps<typeof AppAgentCenterEntry>['client']; readonly language?: string }) {
29
+ const language = useDocumentLanguage(props.language);
14
30
  const hostMechanics = useMemo(() => (
15
31
  hasElectronInvoke()
16
32
  ? createAgentCenterShellHostMechanics(createAgentCenterShellBridge())
@@ -20,7 +36,7 @@ export function AgentCenterCapability(props: { readonly client: ComponentProps<t
20
36
  <AppAgentCenterEntry
21
37
  client={props.client}
22
38
  hostMechanics={hostMechanics}
23
- language={globalThis.document?.documentElement.lang || 'en'}
39
+ language={language}
24
40
  />
25
41
  );
26
42
  }