@nimiplatform/app-tools 0.2.8 → 0.3.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 (43) hide show
  1. package/README.md +113 -5
  2. package/bin/nimi-app.mjs +4 -0
  3. package/lib/app-doctor-update.mjs +7 -1
  4. package/lib/app-pack.mjs +33 -11
  5. package/lib/app-project-lifecycle.mjs +1 -0
  6. package/lib/app-scaffold-profiles.mjs +29 -14
  7. package/lib/app-scaffold.mjs +53 -7
  8. package/lib/macos-native.mjs +96 -0
  9. package/lib/payload-links.mjs +41 -0
  10. package/package.json +7 -7
  11. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +31 -0
  12. package/templates/app-source/src/ai-studio-core/history-policy.ts +23 -1
  13. package/templates/app-source/src/ai-studio-core/history.ts +7 -1
  14. package/templates/app-source/src/ai-studio-core/messages/en.json +1 -0
  15. package/templates/app-source/src/ai-studio-core/messages/zh.json +1 -0
  16. package/templates/app-source/src/ai-studio-core/module-registration.ts +2 -2
  17. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +6 -2
  18. package/templates/app-source/src/ai-studio-core/run-target.ts +1 -1
  19. package/templates/app-source/src/ai-studio-core/runtime-types.ts +4 -0
  20. package/templates/app-source/src/ai-studio-core/runtime.ts +13 -4
  21. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +3 -3
  22. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +41 -13
  23. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +1 -1
  24. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +1 -0
  25. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +26 -1
  26. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +14 -4
  27. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +3 -1
  28. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +12 -3
  29. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-input.tsx +56 -0
  30. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +22 -0
  31. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +54 -29
  32. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +2 -2
  33. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +1 -0
  34. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +6 -1
  35. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +19 -0
  36. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +19 -0
  37. package/templates/app-source/src/studio-modules/studio-media/registration.ts +10 -1
  38. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +2 -0
  39. package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +18 -0
  40. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +58 -0
  41. package/templates/app-source/src/workbench-core/workbench-core.css +5 -0
  42. package/templates/app-source.manifest.json +16 -0
  43. package/templates/default-starter/README.md +25 -1
@@ -17,6 +17,7 @@ export function formatTypedOutput(
17
17
  translate: StudioTranslate,
18
18
  ): string {
19
19
  const output = result.output;
20
+ if (output.kind === 'vision-locate') return JSON.stringify({ jobId: output.jobId, ...output.result }, null, 2);
20
21
  if (output.kind === 'text') {
21
22
  return output.text || translate('StudioShell.emptyBody');
22
23
  }
@@ -153,6 +154,7 @@ export function ArtifactMediaPreview({
153
154
  const branch = studioArtifactRenderBranch(artifact);
154
155
  const { translate: t } = useAIStudioHost();
155
156
  const [imagePreviewOpen, setImagePreviewOpen] = useState(false);
157
+ const [imagePreviewUrl, setImagePreviewUrl] = useState<string | null>(null);
156
158
  const [url, setUrl] = useState<string | null>(null);
157
159
  useEffect(() => {
158
160
  setImagePreviewOpen(false);
@@ -175,6 +177,27 @@ export function ArtifactMediaPreview({
175
177
  if (revoke) void revoke();
176
178
  };
177
179
  }, [artifact, mimeType, relativePath]);
180
+ useEffect(() => {
181
+ setImagePreviewUrl(null);
182
+ if (!imagePreviewOpen || !relativePath) return undefined;
183
+ let active = true;
184
+ let revoke: (() => Promise<void>) | undefined;
185
+ void openNimiLocalAppAssetMediaUrl(relativePath)
186
+ .then((handle) => {
187
+ revoke = handle.revoke;
188
+ if (active) setImagePreviewUrl(handle.url);
189
+ else void handle.revoke();
190
+ })
191
+ .catch(() => {
192
+ if (!active) return;
193
+ setImagePreviewOpen(false);
194
+ nimiToast.danger(t('StudioShell.imagePreviewFailed'));
195
+ });
196
+ return () => {
197
+ active = false;
198
+ if (revoke) void revoke();
199
+ };
200
+ }, [imagePreviewOpen, relativePath, t]);
178
201
  if (!hasPreviewableArtifact(artifact) || !url) return null;
179
202
  const label = artifact?.displayName || relativePath || fallbackLabel;
180
203
  const isImage = branch === 'image';
@@ -222,7 +245,9 @@ export function ArtifactMediaPreview({
222
245
  onClick={() => setImagePreviewOpen(false)}
223
246
  icon={<X size={20} aria-hidden="true" />}
224
247
  />
225
- <img src={url} alt={label} className="ai-result-preview-modal__image" />
248
+ {imagePreviewUrl
249
+ ? <img src={imagePreviewUrl} alt={label} className="ai-result-preview-modal__image" />
250
+ : <p role="status">{t('Common.loading')}</p>}
226
251
  </DialogContent>
227
252
  </Dialog>
228
253
  ) : null}
@@ -2,6 +2,7 @@ import { useState, type ReactNode } from 'react';
2
2
  import { IconButton, nimiToast, StatusBadge, Tooltip } from '@nimiplatform/kit/ui';
3
3
  import { AlertTriangle, ChevronRight, Copy as CopyIcon, Download as DownloadIcon, FileText, FolderOpen, MessageSquare, RefreshCw, SlidersHorizontal, SquarePen } from 'lucide-react';
4
4
  import { useAIStudioHost } from './host-context.js';
5
+ import { VisionLocateResultView } from './section-ai-testing-vision-result.js';
5
6
  import type { StudioCapabilityRegistration } from './module-registration.js';
6
7
  import { formatStudioRunTimestamp, getStudioRunConfigParamRows, getStudioRunIntentLabel, getStudioRunPromptControlFacts, getStudioRunResultTags, getStudioRunStatusTone, type StudioRunConfigParamRow, type StudioRunHistoryRecord, type StudioRunHistoryResultSnapshot, type StudioRunPromptControlFact } from './history.js';
7
8
  import { studioNonSuccessReasonTitle, studioNonSuccessReasonUserAction, studioNonSuccessReasonUserMessage } from './non-success-presentation.js';
@@ -131,10 +132,12 @@ function historyResultToneClass(record: StudioRunHistoryRecord): string {
131
132
 
132
133
  function TextStudioHistoryRecordResult({
133
134
  record,
135
+ canRegenerate,
134
136
  onRegenerate,
135
137
  onUseAsDraft,
136
138
  }: {
137
139
  record: StudioRunHistoryRecord;
140
+ canRegenerate: boolean;
138
141
  onRegenerate: () => void;
139
142
  onUseAsDraft: (record: StudioRunHistoryRecord) => void;
140
143
  }) {
@@ -194,8 +197,8 @@ function TextStudioHistoryRecordResult({
194
197
  <AlertTriangle size={15} aria-hidden="true" />
195
198
  <span>{studioNonSuccessReasonTitle(snapshot.reason, t)}</span>
196
199
  </div>
197
- <p>{studioNonSuccessReasonUserMessage(snapshot.reason, t)}</p>
198
- <p className="studio-result__hint">{studioNonSuccessReasonUserAction(snapshot.reason, t)}</p>
200
+ <p>{studioNonSuccessReasonUserMessage(snapshot.reason, t, record.capabilityId, snapshot.diagnostics)}</p>
201
+ <p className="studio-result__hint">{studioNonSuccessReasonUserAction(snapshot.reason, t, record.capabilityId, snapshot.diagnostics)}</p>
199
202
  <details className="studio-diag">
200
203
  <summary>{t('StudioShell.runtimeDetails')}</summary>
201
204
  <RuntimeDiagnosticsActions text={diagnosticsText} filenameBase={record.capabilityId} />
@@ -232,7 +235,7 @@ function TextStudioHistoryRecordResult({
232
235
  <IconButton type="button" className="studio-result__action" onClick={() => onUseAsDraft(record)} aria-label={t('StudioShell.useAsDraft')} icon={<SquarePen size={16} aria-hidden="true" />} />
233
236
  </Tooltip>
234
237
  <Tooltip content={t('StudioShell.regenerate')} placement="top">
235
- <IconButton type="button" className="studio-result__action" onClick={onRegenerate} aria-label={t('StudioShell.regenerate')} icon={<RefreshCw size={16} aria-hidden="true" />} />
238
+ <IconButton type="button" className="studio-result__action" onClick={onRegenerate} disabled={!canRegenerate} aria-label={t('StudioShell.regenerate')} icon={<RefreshCw size={16} aria-hidden="true" />} />
236
239
  </Tooltip>
237
240
  </div>
238
241
  </div>
@@ -269,6 +272,9 @@ function TextStudioHistoryRecordResult({
269
272
 
270
273
  function TextStudioHistorySnapshotBody({ snapshot }: { snapshot: Extract<StudioRunHistoryResultSnapshot, { ok: true }> }) {
271
274
  const { translate: t } = useAIStudioHost();
275
+ if (snapshot.kind === 'vision-locate') return snapshot.result
276
+ ? <VisionLocateResultView output={{kind:'vision-locate', jobId:snapshot.jobId, result:snapshot.result}} />
277
+ : <><p>{snapshot.summary}</p><p className="studio-result__hint">{t('VisionLocate.historySummaryOnly')}</p><pre>{JSON.stringify({ jobId: snapshot.jobId }, null, 2)}</pre></>;
272
278
  if (snapshot.kind === 'text' || snapshot.kind === 'transcript') {
273
279
  return <TextStudioOutputBody text={snapshot.body} />;
274
280
  }
@@ -338,6 +344,7 @@ export function TextStudioResultState({
338
344
  admission,
339
345
  intentLabel,
340
346
  running,
347
+ canRegenerate,
341
348
  cancelRequested,
342
349
  streamingText,
343
350
  verboseConsole,
@@ -353,6 +360,7 @@ export function TextStudioResultState({
353
360
  admission: ReturnType<typeof statusForCapability>;
354
361
  intentLabel: string;
355
362
  running: boolean;
363
+ canRegenerate: boolean;
356
364
  cancelRequested: boolean;
357
365
  streamingText: string | null;
358
366
  verboseConsole: boolean;
@@ -388,6 +396,7 @@ export function TextStudioResultState({
388
396
  <StudioResult
389
397
  result={activeRun.result}
390
398
  running={running}
399
+ canRegenerate={canRegenerate}
391
400
  cancelRequested={cancelRequested}
392
401
  registration={registration}
393
402
  admission={admission}
@@ -395,6 +404,7 @@ export function TextStudioResultState({
395
404
  intentLabel={intentLabel}
396
405
  requestSettings={activeRun.record && hasTextStudioRequestSettings(activeRun.record) ? <TextStudioRequestSettings record={activeRun.record} /> : null}
397
406
  streamingText={streamingText}
407
+ jobStatus={activeRun.jobStatus}
398
408
  verboseConsole={verboseConsole}
399
409
  onCopy={onCopy}
400
410
  onDownload={onDownload}
@@ -403,7 +413,7 @@ export function TextStudioResultState({
403
413
  />
404
414
  </>
405
415
  ) : activeRun.record ? (
406
- <TextStudioHistoryRecordResult record={activeRun.record} onRegenerate={onRegenerate} onUseAsDraft={onUseAsDraft} />
416
+ <TextStudioHistoryRecordResult record={activeRun.record} canRegenerate={canRegenerate} onRegenerate={onRegenerate} onUseAsDraft={onUseAsDraft} />
407
417
  ) : null}
408
418
  </article>
409
419
  </div>
@@ -20,6 +20,7 @@ import {
20
20
  import type { StudioTranslate } from './non-success-presentation.js';
21
21
 
22
22
  export type TextStudioActiveRun = {
23
+ jobStatus?: 'queued' | 'running';
23
24
  id: string;
24
25
  prompt: string;
25
26
  context: string;
@@ -62,6 +63,7 @@ export function canConfigureRunTarget(runTarget: StudioRunTargetSummary): boolea
62
63
  export function useStudioRunTargetSummary(
63
64
  registration: StudioCapabilityRegistration,
64
65
  runtime: StudioRuntimeInspection | null,
66
+ configOpen = false,
65
67
  ): StudioRunTargetSummary {
66
68
  const host = useAIStudioHost();
67
69
  const [configProjection, setConfigProjection] = useState<{
@@ -99,7 +101,7 @@ export function useStudioRunTargetSummary(
99
101
  requestGeneration += 1;
100
102
  unsubscribe();
101
103
  };
102
- }, [host]);
104
+ }, [host, configOpen]);
103
105
 
104
106
  return useMemo(() => host.app.projection.projectRunTarget({
105
107
  capability: registration.descriptor,
@@ -2,6 +2,7 @@ import { useEffect, useState, type ReactNode } from 'react';
2
2
  import { EmptyState, IconButton, StatusBadge, Surface, Tooltip } from '@nimiplatform/kit/ui';
3
3
  import { AlertTriangle, ChevronRight, Clock, Copy as CopyIcon, Download as DownloadIcon, FileText, FolderOpen, Loader2, RefreshCw, Sparkles, Square } from 'lucide-react';
4
4
  import { useAIStudioHost } from './host-context.js';
5
+ import { VisionLocateResultView } from './section-ai-testing-vision-result.js';
5
6
  import type { StudioCapabilityRunResult } from './runtime-types.js';
6
7
  import type { StudioCapabilityDescriptor, StudioCapabilityRegistration } from './module-registration.js';
7
8
  import { formatStudioRunTimestamp } from './history.js';
@@ -16,6 +17,7 @@ import { ArtifactMediaResult, RuntimeDiagnosticsActions, formatTypedOutput, form
16
17
  function ReadyBody({ result }: { result: StudioCapabilityRunResult & { ok: true } }) {
17
18
  const { translate: t } = useAIStudioHost();
18
19
  const output = result.output;
20
+ if (output.kind === 'vision-locate') return <VisionLocateResultView output={output} />;
19
21
  if (output.kind === 'text' || output.kind === 'transcript') {
20
22
  return <TextStudioOutputBody text={output.text} />;
21
23
  }
@@ -172,6 +174,7 @@ function studioResultIntentLabel(result: StudioCapabilityRunResult | null, capab
172
174
  export function StudioResult({
173
175
  result,
174
176
  running,
177
+ canRegenerate,
175
178
  cancelRequested,
176
179
  registration,
177
180
  admission,
@@ -179,6 +182,7 @@ export function StudioResult({
179
182
  intentLabel,
180
183
  requestSettings,
181
184
  streamingText,
185
+ jobStatus,
182
186
  verboseConsole,
183
187
  onCopy,
184
188
  onDownload,
@@ -187,6 +191,7 @@ export function StudioResult({
187
191
  }: {
188
192
  result: StudioCapabilityRunResult | null;
189
193
  running: boolean;
194
+ canRegenerate: boolean;
190
195
  cancelRequested: boolean;
191
196
  registration: StudioCapabilityRegistration;
192
197
  admission: CapabilityStatus;
@@ -194,6 +199,7 @@ export function StudioResult({
194
199
  intentLabel?: string;
195
200
  requestSettings?: ReactNode;
196
201
  streamingText?: string | null;
202
+ jobStatus?: 'queued' | 'running';
197
203
  verboseConsole: boolean;
198
204
  onCopy: () => void;
199
205
  onDownload: () => void;
@@ -276,6 +282,7 @@ export function StudioResult({
276
282
  { label: t('Studio.result.statResult'), value: t(output.creationSource === 'text-description' ? 'Studio.result.createdFromDescription' : 'Studio.result.createdFromAudio') },
277
283
  ];
278
284
  }
285
+ if (output.kind === 'vision-locate') return [{ label: t('VisionLocate.matches'), value: String(output.result.locations.length) }];
279
286
  return [
280
287
  { label: t('Studio.result.statVoices'), value: String(output.voiceCount) },
281
288
  { label: t('Studio.result.statResult'), value: fallbackMetric },
@@ -289,6 +296,7 @@ export function StudioResult({
289
296
  else if (output.kind === 'artifacts') metric = t('Studio.result.metricArtifacts', { count: output.artifactCount });
290
297
  else if (output.kind === 'embedding') metric = t('Studio.result.metricCreated');
291
298
  else if (output.kind === 'voice-asset') metric = output.creationSource;
299
+ else if (output.kind === 'vision-locate') metric = String(output.result.locations.length);
292
300
  else metric = t('Studio.result.metricVoices', { count: output.voiceCount });
293
301
  }
294
302
  const stats = studioResultStats(metric);
@@ -302,6 +310,7 @@ export function StudioResult({
302
310
  <Loader2 size={15} aria-hidden="true" className="studio-spin" />
303
311
  <span>{cancelRequested
304
312
  ? t('Studio.result.pendingCancel')
313
+ : capability.id === 'vision.locate' && jobStatus ? t(`VisionLocate.${jobStatus}`)
305
314
  : profile.pendingLabelKey
306
315
  ? t(profile.pendingLabelKey)
307
316
  : hasStream ? t('Studio.result.pendingStreaming') : t('Studio.result.pendingRuntime')}</span>
@@ -349,8 +358,8 @@ export function StudioResult({
349
358
  <AlertTriangle size={15} aria-hidden="true" />
350
359
  <span>{t('StudioShell.generationFailed')}</span>
351
360
  </div>
352
- <p>{studioNonSuccessReasonUserMessage(blocked.reason, t)}</p>
353
- <p className="studio-result__hint">{studioNonSuccessReasonUserAction(blocked.reason, t)}</p>
361
+ <p>{studioNonSuccessReasonUserMessage(blocked.reason, t, blocked.capabilityId, blocked.diagnostics)}</p>
362
+ <p className="studio-result__hint">{studioNonSuccessReasonUserAction(blocked.reason, t, blocked.capabilityId, blocked.diagnostics)}</p>
354
363
  </div>
355
364
  );
356
365
  } else if (ready) {
@@ -403,7 +412,7 @@ export function StudioResult({
403
412
  </>
404
413
  ) : null}
405
414
  <Tooltip content={t('StudioShell.regenerate')} placement="top">
406
- <IconButton type="button" className="studio-result__action" onClick={onRegenerate} disabled={running} aria-label={t('StudioShell.regenerate')} icon={<RefreshCw size={15} aria-hidden="true" />} />
415
+ <IconButton type="button" className="studio-result__action" onClick={onRegenerate} disabled={running || !canRegenerate} aria-label={t('StudioShell.regenerate')} icon={<RefreshCw size={15} aria-hidden="true" />} />
407
416
  </Tooltip>
408
417
  </div>
409
418
  </div>
@@ -0,0 +1,56 @@
1
+ import { Button, IconButton } from '@nimiplatform/kit/ui';
2
+ import type { BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
3
+ import { ImagePlus, X } from 'lucide-react';
4
+ import { useAIStudioHost } from './host-context.js';
5
+
6
+ // @nimi-authority: rule.nimi.runtime.ai-provider.r126
7
+ export function VisionLocateImageInput({
8
+ image,
9
+ disabled,
10
+ onChoose,
11
+ onRemove,
12
+ }: {
13
+ image?: BrowserDataUrlAttachment;
14
+ disabled: boolean;
15
+ onChoose: () => void;
16
+ onRemove: () => void;
17
+ }) {
18
+ const { translate: t } = useAIStudioHost();
19
+ return (
20
+ <div className="studio-locate-input">
21
+ {image ? (
22
+ <>
23
+ <img className="studio-locate-input__preview" src={image.dataUrl} alt={t('VisionLocate.draftImage')} />
24
+ <div className="studio-locate-input__file">
25
+ <span title={image.name}>{image.name}</span>
26
+ <Button type="button" tone="ghost" size="sm" disabled={disabled} onClick={onChoose}>
27
+ {t('VisionLocate.replaceImage')}
28
+ </Button>
29
+ <IconButton
30
+ type="button"
31
+ tone="ghost"
32
+ size="sm"
33
+ disabled={disabled}
34
+ aria-label={t('Studio.composer.removeAttachment', { name: image.name })}
35
+ icon={<X size={16} aria-hidden="true" />}
36
+ onClick={onRemove}
37
+ />
38
+ </div>
39
+ </>
40
+ ) : (
41
+ <div className="studio-locate-input__empty">
42
+ <Button
43
+ type="button"
44
+ tone="secondary"
45
+ disabled={disabled}
46
+ leadingIcon={<ImagePlus size={18} aria-hidden="true" />}
47
+ onClick={onChoose}
48
+ >
49
+ {t('VisionLocate.chooseImage')}
50
+ </Button>
51
+ <p>{t('VisionLocate.imageHint')}</p>
52
+ </div>
53
+ )}
54
+ </div>
55
+ );
56
+ }
@@ -0,0 +1,22 @@
1
+ import { useState } from 'react';
2
+ import type { StudioTypedOutput } from './runtime-types.js';
3
+ import { useAIStudioHost } from './host-context.js';
4
+
5
+ export function VisionLocateResultView({ output }: { output: Extract<StudioTypedOutput, {kind:'vision-locate'}> }) {
6
+ const { translate: t } = useAIStudioHost();
7
+ const [imageFailed, setImageFailed] = useState(false);
8
+ const { width, height, locations, imageArtifactId } = output.result;
9
+ return <figure className="studio-locate-result">
10
+ {output.imagePreviewUrl && !imageFailed ? <div className="studio-locate-result__image" style={{ aspectRatio: `${width} / ${height}` }}>
11
+ <img src={output.imagePreviewUrl} alt={t('VisionLocate.sourceImage')} onError={() => setImageFailed(true)} />
12
+ <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label={t('VisionLocate.overlay')}>
13
+ {locations.map((location, index) => <g key={index}>
14
+ <title>{location.label || t('VisionLocate.target', { index: index+1 })}</title>
15
+ {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" />}
16
+ </g>)}
17
+ </svg>
18
+ </div> : <p>{t('VisionLocate.previewUnavailable')}</p>}
19
+ <figcaption>{t(locations.length ? 'VisionLocate.found' : 'VisionLocate.noMatch', { count: locations.length })}</figcaption>
20
+ <details><summary>{t('VisionLocate.coordinates')}</summary><pre>{JSON.stringify({ imageArtifactId, width, height, locations }, null, 2)}</pre></details>
21
+ </figure>;
22
+ }
@@ -1,5 +1,5 @@
1
1
  import { Suspense, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
2
- import { IconButton, LoadingSkeleton, nimiToast, OverlayShell, StatusBadge, Tooltip } from '@nimiplatform/kit/ui';
2
+ import { Button, IconButton, LoadingSkeleton, nimiToast, OverlayShell, StatusBadge, Tooltip } from '@nimiplatform/kit/ui';
3
3
  import { PanelRight, SquarePen } from 'lucide-react';
4
4
  import { createBrowserDataUrlAttachmentAdapter, useChatComposer, type BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
5
5
  import { useAIStudioHost } from './host-context.js';
@@ -8,6 +8,7 @@ import type { StudioCapabilityRunResult, StudioRuntimeInspection } from './runti
8
8
  import { getStudioRunIntentLabel, restoreStudioCapabilityRunResult, type StudioRunConfigSnapshot, type StudioRunHistory, type StudioRunHistoryRecord } from './history.js';
9
9
  import { CapabilityRunHistory, DrawerErrorBoundary, downloadTextFile, resultPlainText, statusForCapability, type CapabilityStatus, type SectionAITestingProps } from './section-ai-testing-surface.js';
10
10
  import { TextStudioComposer, TextStudioStartState } from './section-ai-testing-composer.js';
11
+ import { ScenarioJobStatus } from '@nimiplatform/sdk/runtime/generated';
11
12
  import {
12
13
  canCancelStudioCapabilityRun,
13
14
  hasStudioCapabilityRunInput,
@@ -35,6 +36,7 @@ function TextStudioShell({
35
36
  verboseConsole,
36
37
  draftPersistence,
37
38
  onOpenConfig,
39
+ configOpen,
38
40
  history,
39
41
  historySelectionRequest,
40
42
  onSelectHistoryRun,
@@ -48,6 +50,7 @@ function TextStudioShell({
48
50
  verboseConsole: boolean;
49
51
  draftPersistence: boolean;
50
52
  onOpenConfig?: () => void;
53
+ configOpen: boolean;
51
54
  history: StudioRunHistory | null;
52
55
  historySelectionRequest: { requestId: number; record: StudioRunHistoryRecord } | null;
53
56
  onSelectHistoryRun: (record: StudioRunHistoryRecord) => void;
@@ -69,7 +72,7 @@ function TextStudioShell({
69
72
  }, draftPersistence).prompt ?? preset.prompt
70
73
  ));
71
74
  const [context, setContext] = useState('');
72
- const [running, setRunning] = useState(false);
75
+ const [executingRun, setExecutingRun] = useState<TextStudioActiveRun | null>(null);
73
76
  const [cancelRequested, setCancelRequested] = useState(false);
74
77
  const [streamingText, setStreamingText] = useState<string | null>(null);
75
78
  const [activeRun, setActiveRun] = useState<TextStudioActiveRun | null>(null);
@@ -77,11 +80,14 @@ function TextStudioShell({
77
80
  const historyPanel = useContext(StudioHistoryPanelContext);
78
81
  const historyCollapsed = historyPanel?.collapsed ?? true;
79
82
  const runSeqRef = useRef(0);
80
- const abortControllerRef = useRef<AbortController | null>(null);
83
+ const abortControllerRef = useRef<{ runId: string; controller: AbortController } | null>(null);
84
+ const running = executingRun !== null;
85
+ const displayingExecution = executingRun !== null && activeRun?.id === executingRun.id;
86
+ const displayedRun = displayingExecution ? executingRun : activeRun;
81
87
  const expandedHistoryErrorRef = useRef<string | null>(null);
82
88
  const attachmentAdapter = useMemo(
83
- () => createBrowserDataUrlAttachmentAdapter({ idPrefix: 'studio-attachment' }),
84
- [],
89
+ () => createBrowserDataUrlAttachmentAdapter({ idPrefix: 'studio-attachment', ...(capability.id === 'vision.locate' ? { maxAttachments: 1, accept: ['image/png','image/jpeg','image/webp','image/gif'] } : {}) }),
90
+ [capability.id],
85
91
  );
86
92
  const composerState = useChatComposer<BrowserDataUrlAttachment>({
87
93
  adapter: { submit: async () => {} },
@@ -90,16 +96,18 @@ function TextStudioShell({
90
96
  onTextChange: updatePrompt,
91
97
  disabled: running,
92
98
  });
93
- const hasActiveRun = Boolean(activeRun);
94
- const currentResult = activeRun
95
- ? activeRun.result ?? (activeRun.record
96
- ? restoreStudioCapabilityRunResult(activeRun.record, (id) => (
99
+ const hasRequiredImage = capability.id !== 'vision.locate'
100
+ || (composerState.attachments.length === 1 && composerState.attachments[0]?.kind === 'image');
101
+ const hasActiveRun = Boolean(displayedRun);
102
+ const currentResult = displayedRun
103
+ ? displayedRun.result ?? (displayedRun.record
104
+ ? restoreStudioCapabilityRunResult(displayedRun.record, (id) => (
97
105
  registrations.find((item) => item.descriptor.id === id)?.descriptor.label ?? null
98
106
  ))
99
107
  : null)
100
108
  : lastResult?.capabilityId === capability.id ? lastResult : null;
101
109
  const headerResult = hasActiveRun ? currentResult : null;
102
- const runTarget = useStudioRunTargetSummary(registration, runtime);
110
+ const runTarget = useStudioRunTargetSummary(registration, runtime, configOpen);
103
111
  const admission = statusForCapability(registration, runTarget, headerResult, t);
104
112
  const requiresPrompt = profile.inputKind !== 'none';
105
113
  const supportsMedia = profile.supportsAttachments;
@@ -132,7 +140,7 @@ function TextStudioShell({
132
140
  }
133
141
 
134
142
  useEffect(() => {
135
- abortControllerRef.current?.abort('studio-capability-changed');
143
+ abortControllerRef.current?.controller.abort('studio-capability-changed');
136
144
  abortControllerRef.current = null;
137
145
  const draft = rendererHost.app.projection.promptDraft({
138
146
  surfaceId: 'ai-capabilities',
@@ -144,19 +152,20 @@ function TextStudioShell({
144
152
  setContext('');
145
153
  setActiveRun(null);
146
154
  setSessionRuns({});
147
- setRunning(false);
155
+ setExecutingRun(null);
148
156
  setCancelRequested(false);
149
157
  setStreamingText(null);
150
158
  }, [capability.id, draftPersistence, preset, rendererHost]);
151
159
 
152
160
  async function run(nextPrompt = prompt, nextContext = context) {
161
+ if (abortControllerRef.current) return;
153
162
  const displayPrompt = nextPrompt.trim();
154
163
  if (!hasStudioCapabilityRunInput({ requiresPrompt, prompt: displayPrompt, hasAlternativeInput })) return;
164
+ if (!hasRequiredImage) return;
155
165
  if (!runTarget.canDispatch) return;
156
166
  const runSeq = runSeqRef.current + 1;
157
167
  runSeqRef.current = runSeq;
158
168
  const abortController = new AbortController();
159
- abortControllerRef.current = abortController;
160
169
  const startedAt = rendererHost.clock.now();
161
170
  const pendingRun: TextStudioActiveRun = {
162
171
  id: `pending-${startedAt}`,
@@ -167,8 +176,9 @@ function TextStudioShell({
167
176
  record: null,
168
177
  error: null,
169
178
  };
179
+ abortControllerRef.current = { runId: pendingRun.id, controller: abortController };
170
180
  setActiveRun(pendingRun);
171
- setRunning(true);
181
+ setExecutingRun(pendingRun);
172
182
  setCancelRequested(false);
173
183
  try {
174
184
  let result: StudioCapabilityRunResult;
@@ -178,14 +188,21 @@ function TextStudioShell({
178
188
  const directive = textStudioDirectiveForTarget(runTarget, profile);
179
189
  result = await rendererHost.sdk.runCapability({
180
190
  capabilityId: capability.id,
181
- prompt: capability.id === 'audio.transcribe'
191
+ prompt: capability.id === 'audio.transcribe' || capability.id === 'vision.locate'
182
192
  ? displayPrompt
183
193
  : textStudioRuntimePrompt(displayPrompt, nextContext, directive),
184
194
  scenarioId: preset.id,
185
- onPartial: isStreaming ? setStreamingText : undefined,
195
+ onPartial: isStreaming ? (text) => {
196
+ if (runSeqRef.current === runSeq) setStreamingText(text);
197
+ } : undefined,
186
198
  attachments: supportsMedia ? [...composerState.attachments] : undefined,
187
199
  parameters: effectiveCapabilityParameters,
188
200
  signal: abortController.signal,
201
+ onJobUpdate: job => {
202
+ if (runSeqRef.current !== runSeq) return;
203
+ const jobStatus = job.status === ScenarioJobStatus.QUEUED || job.status === ScenarioJobStatus.SUBMITTED ? 'queued' : job.status === ScenarioJobStatus.RUNNING ? 'running' : undefined;
204
+ if (jobStatus) setExecutingRun(current => current?.id === pendingRun.id ? { ...current, jobStatus } : current);
205
+ },
189
206
  });
190
207
  } catch (error) {
191
208
  const message = error instanceof Error ? error.message : String(error || t('NonSuccess.title.runtimeCallFailed'));
@@ -227,8 +244,8 @@ function TextStudioShell({
227
244
  setActiveRun({ ...pendingRun, error: message });
228
245
  } finally {
229
246
  if (runSeq === runSeqRef.current) {
230
- if (abortControllerRef.current === abortController) abortControllerRef.current = null;
231
- setRunning(false);
247
+ if (abortControllerRef.current?.controller === abortController) abortControllerRef.current = null;
248
+ setExecutingRun(null);
232
249
  setCancelRequested(false);
233
250
  setStreamingText(null);
234
251
  }
@@ -341,9 +358,10 @@ function TextStudioShell({
341
358
  }
342
359
 
343
360
  function handleCancel() {
344
- if (cancelRequested) return;
361
+ const execution = abortControllerRef.current;
362
+ if (!execution || cancelRequested || !displayingExecution || execution.runId !== displayedRun?.id) return;
345
363
  setCancelRequested(true);
346
- abortControllerRef.current?.abort('studio-user-canceled');
364
+ execution.controller.abort('studio-user-canceled');
347
365
  }
348
366
 
349
367
  return (
@@ -360,6 +378,11 @@ function TextStudioShell({
360
378
  </div>
361
379
  <div className="studio__head-actions">
362
380
  {headerActions}
381
+ {executingRun && !displayingExecution ? (
382
+ <Button size="sm" tone="secondary" onClick={() => setActiveRun(executingRun)}>
383
+ {t('StudioShell.returnToRunning')}
384
+ </Button>
385
+ ) : null}
363
386
  {hasActiveRun ? (
364
387
  <Tooltip content={t('StudioShell.newRun')} placement="bottom">
365
388
  <IconButton
@@ -388,21 +411,22 @@ function TextStudioShell({
388
411
  </div>
389
412
  </header>
390
413
  <main className="studio__stage">
391
- {hasActiveRun && activeRun ? (
414
+ {hasActiveRun && displayedRun ? (
392
415
  <TextStudioResultState
393
416
  registration={registration}
394
- activeRun={activeRun}
417
+ activeRun={displayedRun}
395
418
  admission={admission}
396
- intentLabel={activeRun.record ? getStudioRunIntentLabel(activeRun.record) : runTarget.intentLabel}
397
- running={running}
398
- cancelRequested={cancelRequested}
399
- streamingText={streamingText}
419
+ intentLabel={displayedRun.record ? getStudioRunIntentLabel(displayedRun.record) : runTarget.intentLabel}
420
+ running={displayingExecution}
421
+ canRegenerate={!running && hasRequiredImage}
422
+ cancelRequested={displayingExecution && cancelRequested}
423
+ streamingText={displayingExecution ? streamingText : null}
400
424
  verboseConsole={verboseConsole}
401
425
  composer={composer}
402
426
  onCopy={handleCopy}
403
427
  onDownload={handleDownload}
404
- onRegenerate={() => void run(activeRun.prompt, activeRun.context)}
405
- onCancel={canCancelStudioCapabilityRun({
428
+ onRegenerate={() => void run(displayedRun.prompt, displayedRun.context)}
429
+ onCancel={displayingExecution && canCancelStudioCapabilityRun({
406
430
  capabilityId: capability.id,
407
431
  resultKind: profile.resultKind,
408
432
  })
@@ -420,7 +444,7 @@ function TextStudioShell({
420
444
  </div>
421
445
  <CapabilityRunHistory
422
446
  history={history}
423
- activeRunId={activeRun?.id ?? null}
447
+ activeRunId={displayedRun?.id ?? null}
424
448
  onSelectRun={onSelectHistoryRun}
425
449
  collapsed={historyCollapsed}
426
450
  currentCapabilityId={capability.id}
@@ -466,6 +490,7 @@ export function SectionAITesting({
466
490
  verboseConsole={verboseConsole}
467
491
  draftPersistence={draftPersistence}
468
492
  onOpenConfig={renderAIConfigPanel ? () => setConfigOpen(true) : undefined}
493
+ configOpen={configOpen}
469
494
  history={history}
470
495
  historySelectionRequest={historySelectionRequest}
471
496
  onSelectHistoryRun={onSelectHistoryRun}
@@ -7,10 +7,10 @@ import {
7
7
 
8
8
  const INPUT_AUDIO = Object.freeze({
9
9
  codec: 'pcm-s16le' as const,
10
- sampleRateHz: 24_000,
10
+ sampleRateHz: 16_000,
11
11
  channelCount: 1 as const,
12
12
  frameDurationMs: 20,
13
- maximumFrameBytes: 960,
13
+ maximumFrameBytes: 640,
14
14
  });
15
15
 
16
16
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-017
@@ -242,6 +242,7 @@ async function* streamLocalAppTextEvents(
242
242
  };
243
243
  return;
244
244
  }
245
+ if (signal?.aborted) throw studioAbortError();
245
246
  } finally {
246
247
  signal?.removeEventListener('abort', cancel);
247
248
  cancel();
@@ -1,4 +1,4 @@
1
- export type StudioMediaCapabilityId = 'image.generate' | 'video.generate' | 'music.generate';
1
+ export type StudioMediaCapabilityId = 'image.generate' | 'video.generate' | 'music.generate' | 'vision.locate';
2
2
 
3
3
  export const studioMediaDescriptors = Object.freeze([
4
4
  {
@@ -19,4 +19,9 @@ export const studioMediaDescriptors = Object.freeze([
19
19
  summary: 'Prompt + lyrics → protected music.generate Scenario Job → adopted WAV.', summaryKey: 'Capabilities.musicGenerate.summary',
20
20
  surface: 'kit.runRuntimeMusicGenerate → sdk.localApp.ai.scenarioJobs + artifact adoption', execution: 'runtime-sdk', capabilityContract: 'music.generate',
21
21
  },
22
+ {
23
+ id: 'vision.locate', label: 'Visual localization', labelKey: 'Capabilities.visionLocate.label', group: 'media', section: 'image',
24
+ summary: 'Locate objects or controls in one image using boxes or points.', summaryKey: 'Capabilities.visionLocate.summary',
25
+ surface: 'sdk.localApp.ai.scenarioJobs + artifact upload', execution: 'runtime-sdk', capabilityContract: 'vision.locate',
26
+ },
22
27
  ] as const);
@@ -1,5 +1,23 @@
1
1
  {
2
+ "VisionLocate": {
3
+ "chooseImage": "Choose image",
4
+ "replaceImage": "Replace image",
5
+ "draftImage": "Image to locate in",
6
+ "imageHint": "One static image · PNG, JPEG, WebP or GIF · Up to 32 MiB",
7
+ "queryLabel": "Describe the target",
8
+ "modelSelectionRequired": "No model configuration is selected for visual localization.",
9
+ "selectModelAction": "In Nimi Desktop, open Runtime → Model configuration and select a visual localization configuration, then locate again.",
10
+ "invalidInput": "The image or target description does not meet the localization requirements.",
11
+ "correctInput": "Use one readable, static JPEG, PNG, WebP or GIF (multi-frame images are unsupported), up to 32 MiB and about 67 million pixels. Enter a nonempty target description of at most 8 KiB in UTF-8, then locate again.",
12
+ "historySummaryOnly": "This large result's history keeps its summary and Job ID. Export full coordinates during the original run.",
13
+ "stoppedBeforeSubmit": "Stopped before submitting a Locate job.",
14
+ "geometry": "Result shape", "box": "Bounding boxes", "point": "Points", "localOnly": "Runs locally. Choose a model using the configuration control below.",
15
+ "inputRequired": "Attach one static image and describe the target to locate.", "imageTooLarge": "Choose a static image of at most 32 MiB.", "resultMissing": "Runtime returned no typed Locate result.",
16
+ "found": "Found {{count}} matching targets", "noMatch": "No matching targets found", "sourceImage": "Image used for this task", "overlay": "Locations on the task image", "target": "Target {{index}}",
17
+ "previewUnavailable": "The input image preview is no longer available. The coordinates below still refer to the recorded image.", "coordinates": "Image identity and coordinates", "matches": "Matches", "queued": "Queued for localization…", "running": "Loading the model or locating targets…"
18
+ },
2
19
  "Capabilities": {
20
+ "visionLocate": { "label": "Visual localization", "summary": "Describe an object or control in one image to get boxes or points." },
3
21
  "imageGenerate": {
4
22
  "label": "Image Generate",
5
23
  "summary": "Prompt → image.generate Scenario Job → typed artifact preview result."
@@ -15,6 +33,7 @@
15
33
  },
16
34
  "Studio": {
17
35
  "profiles": {
36
+ "visionLocate": { "inputTitle": "Test visual localization", "inputPlaceholder": "For example: the search button at the top right, or the red cup on the desk…", "primaryLabel": "Locate targets", "primaryRunningLabel": "Locating…", "emptyTitle": "Locate objects or controls", "emptyHint": "Choose one static image, describe the target, then choose boxes or points.", "footnote": "Coordinates refer to the complete image after applying its orientation." },
18
37
  "imageGenerate": {
19
38
  "inputTitle": "Test image generation",
20
39
  "inputPlaceholder": "Describe the image you want the runtime to render…",