@nimiplatform/app-tools 0.1.3 → 0.2.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 (120) hide show
  1. package/LICENSE +198 -6
  2. package/README.md +83 -27
  3. package/bin/nimi-app.mjs +328 -45
  4. package/lib/app-access-declaration.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +411 -149
  6. package/lib/app-pack.mjs +401 -0
  7. package/lib/app-project-lifecycle.mjs +1141 -0
  8. package/lib/app-scaffold-capabilities.mjs +769 -0
  9. package/lib/app-scaffold-default-source.mjs +21 -0
  10. package/lib/app-scaffold-profiles.mjs +1093 -0
  11. package/lib/app-scaffold.mjs +1266 -813
  12. package/lib/index.mjs +194 -42
  13. package/lib/simulator-conformance-ast.mjs +498 -0
  14. package/lib/simulator-conformance-css.mjs +116 -0
  15. package/lib/simulator-conformance-graph.mjs +757 -0
  16. package/lib/simulator-conformance.d.mts +14 -0
  17. package/lib/simulator-conformance.mjs +203 -0
  18. package/lib/simulator-css-profile.d.mts +27 -0
  19. package/lib/simulator-css-profile.mjs +531 -0
  20. package/lib/simulator-kit-export-resolution.mjs +70 -0
  21. package/lib/simulator-manifest.mjs +334 -0
  22. package/package.json +66 -3
  23. package/scripts/dev-shell.mjs +465 -0
  24. package/scripts/sync-app-source.mjs +300 -0
  25. package/scripts/sync-scaffold-versions.mjs +91 -0
  26. package/templates/app-source/LICENSE +21 -0
  27. package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
  28. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
  29. package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
  30. package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
  31. package/templates/app-source/src/ai-studio-core/history.ts +824 -0
  32. package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
  33. package/templates/app-source/src/ai-studio-core/index.ts +214 -0
  34. package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
  35. package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
  36. package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
  37. package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
  38. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
  39. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
  40. package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
  41. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
  42. package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
  43. package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
  44. package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
  45. package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
  58. package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
  59. package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
  60. package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
  61. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
  62. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
  63. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
  64. package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
  65. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
  66. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
  67. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
  68. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
  69. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
  70. package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
  71. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
  72. package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
  73. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
  74. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
  75. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
  76. package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
  77. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
  78. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
  79. package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
  80. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
  81. package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
  82. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
  83. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
  84. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
  85. package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
  86. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
  87. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
  88. package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
  90. package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
  91. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
  92. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
  95. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
  96. package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
  97. package/templates/app-source/src/workbench-core/index.ts +17 -0
  98. package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
  99. package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
  100. package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
  101. package/templates/app-source.manifest.json +333 -0
  102. package/templates/default-starter/AGENTS.md +33 -0
  103. package/templates/default-starter/LICENSE +21 -0
  104. package/templates/default-starter/README.md +41 -0
  105. package/templates/default-starter/SECURITY.md +5 -0
  106. package/templates/default-starter/index.html +12 -0
  107. package/templates/default-starter/scripts/validate.mjs +26 -0
  108. package/templates/default-starter/src/shell/App.tsx +27 -0
  109. package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
  110. package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
  111. package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
  112. package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
  113. package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
  114. package/templates/default-starter/src/styles.css +26 -0
  115. package/templates/default-starter/src-tauri/Cargo.toml +17 -0
  116. package/templates/default-starter/src-tauri/build.rs +5 -0
  117. package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
  118. package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
  119. package/templates/default-starter/tsconfig.json +18 -0
  120. package/templates/default-starter.manifest.json +99 -0
@@ -0,0 +1,306 @@
1
+ import {
2
+ runRuntimeAIConsumeCapability,
3
+ runRuntimeImageGenerate,
4
+ runRuntimeMusicGenerate,
5
+ runRuntimeSpeechSynthesize,
6
+ runRuntimeSpeechTranscribe,
7
+ runRuntimeVideoGenerate,
8
+ runRuntimeVoiceCatalog,
9
+ runtimeScenarioJobNonSuccessReasonFromError,
10
+ } from '@nimiplatform/kit/features/generation/runtime';
11
+ import {
12
+ createNimiLocalAppRuntimeScenarioJobClient,
13
+ type NimiLocalAppClient,
14
+ } from '@nimiplatform/sdk/app';
15
+ import type {
16
+ StudioCapabilityRunInput,
17
+ StudioCapabilityRunResult,
18
+ StudioManagedArtifact,
19
+ StudioNonSuccess,
20
+ StudioNonSuccessDiagnostics,
21
+ StudioNonSuccessReason,
22
+ StudioRuntimeCapabilityDescriptor,
23
+ StudioRuntimeInspection,
24
+ } from './runtime-types.js';
25
+ import {
26
+ dispatchStudioCapabilityRuntime,
27
+ type StudioCapabilityRuntimeHandlers,
28
+ } from './runtime-dispatcher.js';
29
+
30
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-019c
31
+
32
+ export type StudioRuntimeRunnerSet = {
33
+ readonly aiConsume: typeof runRuntimeAIConsumeCapability;
34
+ readonly imageGenerate: typeof runRuntimeImageGenerate;
35
+ readonly musicGenerate: typeof runRuntimeMusicGenerate;
36
+ readonly videoGenerate: typeof runRuntimeVideoGenerate;
37
+ readonly speechSynthesize: typeof runRuntimeSpeechSynthesize;
38
+ readonly speechTranscribe: typeof runRuntimeSpeechTranscribe;
39
+ readonly voiceCatalog: typeof runRuntimeVoiceCatalog;
40
+ };
41
+
42
+ export type StudioCapabilityNonSuccessFactory = (
43
+ capability: StudioRuntimeCapabilityDescriptor,
44
+ reason: StudioNonSuccessReason,
45
+ message: string,
46
+ diagnostics?: StudioNonSuccessDiagnostics,
47
+ ) => StudioNonSuccess;
48
+
49
+ export type StudioRuntimeHost = {
50
+ readonly appId: string;
51
+ readonly surfaceId: string;
52
+ readonly abortReason: string;
53
+ readonly client: NimiLocalAppClient;
54
+ readonly createScenarioJobClient: typeof createNimiLocalAppRuntimeScenarioJobClient;
55
+ readonly runners: StudioRuntimeRunnerSet;
56
+ readonly nonSuccess: StudioCapabilityNonSuccessFactory;
57
+ };
58
+
59
+ export type StudioCapabilityRuntimeContext = {
60
+ readonly capability: StudioRuntimeCapabilityDescriptor;
61
+ readonly input: StudioCapabilityRunInput;
62
+ readonly prompt: string;
63
+ readonly scenarioId: string;
64
+ readonly host: StudioRuntimeHost;
65
+ };
66
+
67
+ export type StudioCapabilityRuntimeOrchestrator = {
68
+ readonly appId: string;
69
+ readonly surfaceId: string;
70
+ readonly abortReason: string;
71
+ readonly handlers: StudioCapabilityRuntimeHandlers;
72
+ readonly resolveCapability: (capabilityId: string) => StudioRuntimeCapabilityDescriptor;
73
+ readonly inspectRuntime: () => Promise<StudioRuntimeInspection>;
74
+ readonly getClient: () => NimiLocalAppClient;
75
+ readonly createScenarioId: (capability: StudioRuntimeCapabilityDescriptor) => string;
76
+ readonly createScenarioJobClient?: typeof createNimiLocalAppRuntimeScenarioJobClient;
77
+ readonly runners?: Partial<StudioRuntimeRunnerSet>;
78
+ readonly nonSuccess: StudioCapabilityNonSuccessFactory;
79
+ readonly onMissingHandler?: (
80
+ context: StudioCapabilityRuntimeContext,
81
+ ) => StudioCapabilityRunResult | null | Promise<StudioCapabilityRunResult | null>;
82
+ };
83
+
84
+ export const DEFAULT_STUDIO_RUNTIME_RUNNERS: StudioRuntimeRunnerSet = Object.freeze({
85
+ aiConsume: runRuntimeAIConsumeCapability,
86
+ imageGenerate: runRuntimeImageGenerate,
87
+ musicGenerate: runRuntimeMusicGenerate,
88
+ videoGenerate: runRuntimeVideoGenerate,
89
+ speechSynthesize: runRuntimeSpeechSynthesize,
90
+ speechTranscribe: runRuntimeSpeechTranscribe,
91
+ voiceCatalog: runRuntimeVoiceCatalog,
92
+ });
93
+
94
+ export function createStudioRuntimeRunnerSet(
95
+ overrides: Partial<StudioRuntimeRunnerSet> = {},
96
+ ): StudioRuntimeRunnerSet {
97
+ return { ...DEFAULT_STUDIO_RUNTIME_RUNNERS, ...overrides };
98
+ }
99
+
100
+ export async function runStudioCapability(
101
+ input: StudioCapabilityRunInput,
102
+ orchestrator: StudioCapabilityRuntimeOrchestrator,
103
+ ): Promise<StudioCapabilityRunResult> {
104
+ const capability = orchestrator.resolveCapability(input.capabilityId);
105
+ const runtime = await orchestrator.inspectRuntime();
106
+ if (runtime.status !== 'connected') {
107
+ return orchestrator.nonSuccess(capability, 'runtime-unavailable', runtime.detail);
108
+ }
109
+
110
+ const context: StudioCapabilityRuntimeContext = {
111
+ capability,
112
+ input,
113
+ prompt: input.prompt.trim(),
114
+ scenarioId: input.scenarioId?.trim() || orchestrator.createScenarioId(capability),
115
+ host: {
116
+ appId: orchestrator.appId,
117
+ surfaceId: orchestrator.surfaceId,
118
+ abortReason: orchestrator.abortReason,
119
+ client: orchestrator.getClient(),
120
+ createScenarioJobClient: orchestrator.createScenarioJobClient
121
+ ?? createNimiLocalAppRuntimeScenarioJobClient,
122
+ runners: createStudioRuntimeRunnerSet(orchestrator.runners),
123
+ nonSuccess: orchestrator.nonSuccess,
124
+ },
125
+ };
126
+
127
+ try {
128
+ const dispatched = dispatchStudioCapabilityRuntime(orchestrator.handlers, context);
129
+ if (dispatched) return await dispatched;
130
+ if (!context.prompt) {
131
+ return orchestrator.nonSuccess(
132
+ capability,
133
+ 'input-invalid',
134
+ `${capability.label} requires non-empty input.`,
135
+ );
136
+ }
137
+ const hostProjection = orchestrator.onMissingHandler
138
+ ? await orchestrator.onMissingHandler(context)
139
+ : null;
140
+ if (hostProjection) return hostProjection;
141
+ return orchestrator.nonSuccess(
142
+ capability,
143
+ 'sdk-method-unavailable',
144
+ `No Runtime handler is registered for ${capability.id}.`,
145
+ );
146
+ } catch (error) {
147
+ return projectStudioRuntimeError(context, error);
148
+ }
149
+ }
150
+
151
+ export function createStudioScenarioJobClient(context: StudioCapabilityRuntimeContext) {
152
+ return context.host.createScenarioJobClient(context.host.client.ai);
153
+ }
154
+
155
+ type ArtifactRunnerResult = Awaited<ReturnType<
156
+ | typeof runRuntimeImageGenerate
157
+ | typeof runRuntimeMusicGenerate
158
+ | typeof runRuntimeVideoGenerate
159
+ | typeof runRuntimeSpeechSynthesize
160
+ >>;
161
+
162
+ export async function projectStudioArtifactRunnerResult(
163
+ context: StudioCapabilityRuntimeContext,
164
+ result: ArtifactRunnerResult,
165
+ ): Promise<StudioCapabilityRunResult> {
166
+ if (result.ok === false) return projectStudioRunnerNonSuccess(context, result);
167
+ const artifacts: StudioManagedArtifact[] = [];
168
+ const adoptedPaths: string[] = [];
169
+ try {
170
+ for (const [index, sourceArtifact] of result.output.artifacts.entries()) {
171
+ if (!sourceArtifact.artifactId) {
172
+ throw new Error('Runtime artifact metadata omitted the custody artifact identifier required for adoption.');
173
+ }
174
+ const relativePath = await managedStudioAssetPath(
175
+ context.capability.id,
176
+ result.output.jobId,
177
+ index,
178
+ );
179
+ const adopted = await context.host.client.storage.assets.adoptArtifact({
180
+ artifactId: sourceArtifact.artifactId,
181
+ relativePath,
182
+ overwrite: false,
183
+ });
184
+ adoptedPaths.push(adopted.relativePath);
185
+ artifacts.push({
186
+ relativePath: adopted.relativePath,
187
+ ...(adopted.mediaType ? { mediaType: adopted.mediaType } : {}),
188
+ sizeBytes: adopted.sizeBytes,
189
+ sha256: adopted.sha256,
190
+ displayName: index === 0
191
+ ? context.capability.label
192
+ : `${context.capability.label} ${index + 1}`,
193
+ previewSource: 'managed-asset',
194
+ });
195
+ }
196
+ } catch (error) {
197
+ const cleanupFailures: string[] = [];
198
+ for (const relativePath of [...adoptedPaths].reverse()) {
199
+ try {
200
+ await context.host.client.storage.assets.remove(relativePath);
201
+ } catch (cleanupError) {
202
+ cleanupFailures.push(`${relativePath}: ${studioRuntimeErrorMessage(cleanupError)}`);
203
+ }
204
+ }
205
+ if (cleanupFailures.length > 0) {
206
+ throw new Error(`${studioRuntimeErrorMessage(error)} Managed artifact cleanup also failed: ${cleanupFailures.join('; ')}`);
207
+ }
208
+ throw error;
209
+ }
210
+ return {
211
+ ok: true,
212
+ capabilityId: context.capability.id,
213
+ capabilityLabel: context.capability.label,
214
+ message: result.message,
215
+ output: {
216
+ kind: 'artifacts',
217
+ jobId: result.output.jobId,
218
+ jobState: result.output.jobStatus,
219
+ artifactCount: result.output.artifactCount,
220
+ artifacts,
221
+ ...(artifacts[0] ? { firstArtifact: artifacts[0] } : {}),
222
+ },
223
+ ...(result.trace?.traceId ? { trace: { traceId: result.trace.traceId } } : {}),
224
+ };
225
+ }
226
+
227
+ export function projectStudioRunnerNonSuccess(
228
+ context: StudioCapabilityRuntimeContext,
229
+ result: { readonly ok: false; readonly reason: string; readonly message: string; readonly error?: unknown },
230
+ ): StudioNonSuccess {
231
+ return context.host.nonSuccess(
232
+ context.capability,
233
+ studioNonSuccessReason(result.reason),
234
+ result.message,
235
+ studioNonSuccessDiagnostics(result.error),
236
+ );
237
+ }
238
+
239
+ export function projectStudioRuntimeError(
240
+ context: StudioCapabilityRuntimeContext,
241
+ error: unknown,
242
+ ): StudioNonSuccess {
243
+ return context.host.nonSuccess(
244
+ context.capability,
245
+ studioNonSuccessReason(runtimeScenarioJobNonSuccessReasonFromError(error)),
246
+ studioRuntimeErrorMessage(error),
247
+ studioNonSuccessDiagnostics(error),
248
+ );
249
+ }
250
+
251
+ export function studioNonSuccessReason(reason: string): StudioNonSuccessReason {
252
+ if (reason === 'input-invalid' || reason === 'sdk-method-unavailable'
253
+ || reason === 'principal-unauthorized' || reason === 'operation-aborted'
254
+ || reason === 'runtime-canceled' || reason === 'runtime-timeout'
255
+ || reason === 'stream-interrupted') {
256
+ return reason;
257
+ }
258
+ return 'runtime-call-failed';
259
+ }
260
+
261
+ export function studioNonSuccessDiagnostics(error: unknown): StudioNonSuccessDiagnostics | undefined {
262
+ if (!error || typeof error !== 'object' || Array.isArray(error)) return undefined;
263
+ const record = error as Record<string, unknown>;
264
+ const reasonCode = typeof record.reasonCode === 'string' ? record.reasonCode.trim() : '';
265
+ if (!/^[A-Z][A-Z0-9_]{0,127}$/u.test(reasonCode)) return undefined;
266
+ const rawActionHint = typeof record.actionHint === 'string' ? record.actionHint.trim() : '';
267
+ const actionHint = /^[A-Za-z0-9_.-]{1,256}$/u.test(rawActionHint) ? rawActionHint : '';
268
+ const rawTraceId = typeof record.traceId === 'string' ? record.traceId.trim() : '';
269
+ const traceId = /^[A-Za-z0-9_.:-]{1,512}$/u.test(rawTraceId) ? rawTraceId : '';
270
+ const source = record.source === 'runtime' || record.source === 'sdk' || record.source === 'realm'
271
+ ? record.source
272
+ : '';
273
+ return {
274
+ reasonCode,
275
+ ...(actionHint ? { actionHint } : {}),
276
+ ...(traceId ? { traceId } : {}),
277
+ ...(typeof record.retryable === 'boolean' ? { retryable: record.retryable } : {}),
278
+ ...(source ? { source } : {}),
279
+ };
280
+ }
281
+
282
+ export function studioRuntimeErrorMessage(error: unknown): string {
283
+ const record = error && typeof error === 'object' ? error as Record<string, unknown> : null;
284
+ const message = error instanceof Error ? error.message.trim() : '';
285
+ const reasonCode = typeof record?.reasonCode === 'string' ? record.reasonCode.trim() : '';
286
+ if (message && reasonCode) return `${message} (${reasonCode})`;
287
+ return message || reasonCode || String(error || 'The Runtime capability call failed.');
288
+ }
289
+
290
+ export function studioAbortError(): Error {
291
+ const error = new Error('Aborted');
292
+ error.name = 'AbortError';
293
+ return error;
294
+ }
295
+
296
+ async function managedStudioAssetPath(
297
+ capabilityId: string,
298
+ jobId: string,
299
+ artifactIndex: number,
300
+ ): Promise<string> {
301
+ const identity = artifactIndex === 0 ? jobId : `${jobId}:${artifactIndex}`;
302
+ const bytes = new TextEncoder().encode(identity);
303
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
304
+ const token = Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('');
305
+ return `media/${capabilityId.replaceAll('.', '-')}/${token}.asset`;
306
+ }
@@ -0,0 +1,38 @@
1
+ import type { StudioCapabilityRegistration } from './module-registration.js';
2
+ import type { StudioCapabilityRunResult } from './runtime-types.js';
3
+ import type { StudioRunTargetSummary } from './history.js';
4
+ import type { StudioTranslate } from './non-success-presentation.js';
5
+
6
+ export type CapabilityStatus = {
7
+ label: 'configured' | 'blocked' | 'not admitted' | 'SDK gap' | 'tauri-only' | 'checking';
8
+ tone: 'success' | 'warning' | 'info' | 'neutral';
9
+ detail: string;
10
+ };
11
+
12
+ export function statusForCapability(
13
+ registration: StudioCapabilityRegistration,
14
+ target: StudioRunTargetSummary,
15
+ lastResult: StudioCapabilityRunResult | null,
16
+ translate: StudioTranslate,
17
+ ): CapabilityStatus {
18
+ const capability = registration.descriptor;
19
+ if (capability.execution === 'standalone-tauri') {
20
+ return { label: 'tauri-only', tone: 'info', detail: target.detail };
21
+ }
22
+ if (capability.execution === 'typed-unavailable') {
23
+ return { label: 'SDK gap', tone: 'warning', detail: capability.missingSurface || translate('Studio.admission.sdkGapDetail') };
24
+ }
25
+ if (
26
+ lastResult?.capabilityId === capability.id
27
+ && !lastResult.ok
28
+ && 'reason' in lastResult
29
+ && lastResult.reason === 'sdk-method-unavailable'
30
+ ) {
31
+ return { label: 'SDK gap', tone: 'warning', detail: lastResult.message };
32
+ }
33
+ if (target.status === 'configured') return { label: 'configured', tone: 'info', detail: target.detail };
34
+ if (target.status === 'checking') return { label: 'checking', tone: 'neutral', detail: target.detail };
35
+ if (target.status === 'not-admitted') return { label: 'not admitted', tone: 'info', detail: target.detail };
36
+ if (target.status === 'sdk-gap') return { label: 'SDK gap', tone: 'warning', detail: target.detail };
37
+ return { label: 'blocked', tone: 'warning', detail: target.detail };
38
+ }
@@ -0,0 +1,30 @@
1
+ import { Component, type ReactNode } from 'react';
2
+ import { Button } from '@nimiplatform/kit/ui';
3
+
4
+ import type { StudioTranslate } from './non-success-presentation.js';
5
+
6
+ export class DrawerErrorBoundary extends Component<{
7
+ readonly onClose: () => void;
8
+ readonly translate: StudioTranslate;
9
+ readonly children: ReactNode;
10
+ }, { error: Error | null }> {
11
+ state = { error: null as Error | null };
12
+
13
+ static getDerivedStateFromError(error: Error) {
14
+ return { error };
15
+ }
16
+
17
+ render() {
18
+ if (this.state.error) {
19
+ const { translate } = this.props;
20
+ return (
21
+ <div className="section-ai-testing__drawer-error" role="alert">
22
+ <strong>{translate('Studio.drawerError.title')}</strong>
23
+ <p>{this.state.error.message || translate('Studio.drawerError.fallback')}</p>
24
+ <Button type="button" tone="secondary" size="sm" onClick={this.props.onClose}>{translate('Common.close')}</Button>
25
+ </div>
26
+ );
27
+ }
28
+ return this.props.children;
29
+ }
30
+ }
@@ -0,0 +1,40 @@
1
+ export type StudioArtifactPreviewSource = {
2
+ relativePath?: string;
3
+ mediaType?: string;
4
+ sha256?: string;
5
+ displayName?: string;
6
+ previewSource?: 'managed-asset';
7
+ sizeBytes?: number;
8
+ };
9
+
10
+ export type StudioArtifactRenderBranch =
11
+ | 'image'
12
+ | 'audio'
13
+ | 'video'
14
+ | 'metadata-only'
15
+ | 'unsupported'
16
+ | 'none';
17
+
18
+ export const STUDIO_ARTIFACT_IMAGE_LOADING = 'eager' as const;
19
+
20
+ // Single pure projection shared by current and persisted result renderers.
21
+ // Playback exists only for managed assets; source artifact URLs and bodies are
22
+ // never treated as persistent media truth.
23
+ export function studioArtifactRenderBranch(
24
+ artifact?: StudioArtifactPreviewSource,
25
+ ): StudioArtifactRenderBranch {
26
+ if (!artifact) return 'none';
27
+ if (artifact.previewSource !== 'managed-asset' || !artifact.relativePath?.trim()) return 'metadata-only';
28
+ const mimeType = artifact.mediaType?.trim().toLowerCase() ?? '';
29
+ if (mimeType.startsWith('image/')) return 'image';
30
+ if (mimeType.startsWith('audio/')) return 'audio';
31
+ if (mimeType.startsWith('video/')) return 'video';
32
+ return 'unsupported';
33
+ }
34
+
35
+ export function hasStudioArtifactMedia(
36
+ artifact?: StudioArtifactPreviewSource,
37
+ ): boolean {
38
+ const branch = studioArtifactRenderBranch(artifact);
39
+ return branch === 'image' || branch === 'audio' || branch === 'video';
40
+ }
@@ -0,0 +1,257 @@
1
+ import { useState, type ChangeEvent, type ReactNode } from 'react';
2
+ import { Button, IconButton, NimiText, TextareaField, Tooltip } from '@nimiplatform/kit/ui';
3
+ import { ArrowUp, Paperclip, Play, Plus, RefreshCw, SlidersHorizontal, X } from 'lucide-react';
4
+ import type { BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
5
+ import { useAIStudioHost } from './host-context.js';
6
+ import type { StudioCapabilityRegistration } from './module-registration.js';
7
+ import { hasStudioCapabilityRunInput } from './section-ai-testing-input.js';
8
+
9
+ function IntentSummaryChip({
10
+ label,
11
+ onOpen,
12
+ configurable,
13
+ }: {
14
+ label: string;
15
+ onOpen?: () => void;
16
+ configurable: boolean;
17
+ }) {
18
+ const { translate: t } = useAIStudioHost();
19
+ if (!configurable || !onOpen) {
20
+ return (
21
+ <span
22
+ className="studio-intent-chip studio-intent-chip--static"
23
+ aria-label={t('Studio.composer.runtimeOwnedIntent')}
24
+ >
25
+ <SlidersHorizontal size={15} aria-hidden="true" />
26
+ <span>{label}</span>
27
+ </span>
28
+ );
29
+ }
30
+ return (
31
+ <Button
32
+ type="button"
33
+ className="studio-intent-chip"
34
+ tone="ghost"
35
+ size="sm"
36
+ leadingIcon={<SlidersHorizontal size={15} aria-hidden="true" />}
37
+ onClick={onOpen}
38
+ aria-label={t('Studio.composer.openIntentConfig')}
39
+ >
40
+ {label}
41
+ </Button>
42
+ );
43
+ }
44
+
45
+ export function TextStudioComposer({
46
+ registration,
47
+ prompt,
48
+ context,
49
+ intentLabel,
50
+ running,
51
+ attachments,
52
+ onOpenAttachmentPicker,
53
+ onRemoveAttachment,
54
+ canDispatch,
55
+ canConfigureIntent,
56
+ intentConfigurable = true,
57
+ compact = false,
58
+ parameterPanel,
59
+ parametersActive = false,
60
+ hasAlternativeInput = false,
61
+ onPromptChange,
62
+ onContextChange,
63
+ onOpenIntentConfig,
64
+ onSubmit,
65
+ }: {
66
+ registration: StudioCapabilityRegistration;
67
+ prompt: string;
68
+ context: string;
69
+ intentLabel: string;
70
+ running: boolean;
71
+ attachments: readonly BrowserDataUrlAttachment[];
72
+ onOpenAttachmentPicker: () => void;
73
+ onRemoveAttachment: (index: number) => void;
74
+ canDispatch: boolean;
75
+ canConfigureIntent: boolean;
76
+ intentConfigurable?: boolean;
77
+ compact?: boolean;
78
+ parameterPanel?: ReactNode;
79
+ parametersActive?: boolean;
80
+ hasAlternativeInput?: boolean;
81
+ onPromptChange: (value: string) => void;
82
+ onContextChange: (value: string) => void;
83
+ onOpenIntentConfig?: () => void;
84
+ onSubmit: () => void;
85
+ }) {
86
+ const { translate: t } = useAIStudioHost();
87
+ const capability = registration.descriptor;
88
+ const profile = registration.profile;
89
+ const isReadOnlyComposer = profile.inputKind === 'none';
90
+ const requiresPrompt = !isReadOnlyComposer;
91
+ const contextAttached = Boolean(context.trim());
92
+ const supportsContext = requiresPrompt && capability.id !== 'audio.transcribe';
93
+ const [contextOpen, setContextOpen] = useState(false);
94
+ const [parametersOpen, setParametersOpen] = useState(false);
95
+ const promptReady = hasStudioCapabilityRunInput({ requiresPrompt, prompt, hasAlternativeInput });
96
+ const intentConfigAction = Boolean(onOpenIntentConfig) && !canDispatch && canConfigureIntent;
97
+ const generateDisabled = running || !promptReady || (!canDispatch && !intentConfigAction);
98
+ const generateLabel = running
99
+ ? t(profile.primaryRunningLabelKey)
100
+ : intentConfigAction
101
+ ? t('Studio.composer.configureIntent')
102
+ : t(profile.primaryLabelKey);
103
+ const composerBar = (
104
+ <div className="studio-composer__bar">
105
+ <div className="studio-composer__controls">
106
+ {supportsContext ? (
107
+ <Button
108
+ type="button"
109
+ tone="ghost"
110
+ size="sm"
111
+ className={contextAttached ? 'studio-context-chip studio-context-chip--attached' : 'studio-context-chip'}
112
+ leadingIcon={<Plus size={18} aria-hidden="true" />}
113
+ onClick={() => setContextOpen((current) => !current)}
114
+ aria-expanded={contextOpen}
115
+ >
116
+ {contextAttached ? t('Studio.composer.contextAttached') : t('Studio.composer.context')}
117
+ </Button>
118
+ ) : null}
119
+ {parameterPanel ? (
120
+ <Button
121
+ type="button"
122
+ tone="ghost"
123
+ size="sm"
124
+ className={parametersActive ? 'studio-context-chip studio-context-chip--attached' : 'studio-context-chip'}
125
+ leadingIcon={<SlidersHorizontal size={16} aria-hidden="true" />}
126
+ onClick={() => setParametersOpen((current) => !current)}
127
+ aria-expanded={parametersOpen}
128
+ >
129
+ {t('Studio.parameters.title')}
130
+ </Button>
131
+ ) : null}
132
+ </div>
133
+ <div className="studio-composer__actions">
134
+ <IntentSummaryChip
135
+ label={intentLabel}
136
+ onOpen={onOpenIntentConfig}
137
+ configurable={intentConfigurable && Boolean(onOpenIntentConfig)}
138
+ />
139
+ {profile.supportsAttachments ? (
140
+ <div className="studio-attachment-strip studio-attachment-strip--icon">
141
+ <Tooltip content={t('Studio.composer.attachContext')} placement="top">
142
+ <Button
143
+ type="button"
144
+ className="h-8 w-8 rounded-full px-0"
145
+ size="sm"
146
+ tone="ghost"
147
+ onClick={onOpenAttachmentPicker}
148
+ disabled={running}
149
+ aria-label={t('Studio.composer.attachContext')}
150
+ >
151
+ <Paperclip size={15} aria-hidden="true" />
152
+ </Button>
153
+ </Tooltip>
154
+ {attachments.map((item, index) => (
155
+ <span key={item.id} className="studio-attachment-chip">
156
+ {item.kind === 'image' ? (
157
+ <img src={item.dataUrl} alt={item.name} />
158
+ ) : (
159
+ <span className="studio-attachment-chip__video" aria-hidden="true">
160
+ <Play size={13} />
161
+ </span>
162
+ )}
163
+ <span className="studio-attachment-chip__name">{item.name}</span>
164
+ <IconButton
165
+ aria-label={t('Studio.composer.removeAttachment', { name: item.name })}
166
+ onClick={() => onRemoveAttachment(index)}
167
+ icon={<X size={13} aria-hidden="true" />}
168
+ size="sm"
169
+ tone="ghost"
170
+ className="h-6 w-6"
171
+ />
172
+ </span>
173
+ ))}
174
+ </div>
175
+ ) : null}
176
+ <Tooltip content={generateLabel} placement="top">
177
+ <IconButton
178
+ type="button"
179
+ className={intentConfigAction ? 'studio-generate-action studio-generate-action--configure' : 'studio-generate-action'}
180
+ tone="primary"
181
+ size="sm"
182
+ aria-label={generateLabel}
183
+ disabled={generateDisabled}
184
+ onClick={intentConfigAction ? onOpenIntentConfig : onSubmit}
185
+ icon={running ? <RefreshCw size={15} aria-hidden="true" className="studio-spin" /> : <ArrowUp size={16} aria-hidden="true" />}
186
+ />
187
+ </Tooltip>
188
+ </div>
189
+ </div>
190
+ );
191
+ return (
192
+ <div className={compact ? 'studio-composer studio-composer--compact' : 'studio-composer'}>
193
+ <div className={isReadOnlyComposer ? 'studio-input studio-input--readonly' : 'studio-input'}>
194
+ {isReadOnlyComposer ? (
195
+ <NimiText role="body" className="studio-input__note">
196
+ {profile.inputNoteKey ? t(profile.inputNoteKey) : ''}
197
+ </NimiText>
198
+ ) : (
199
+ <TextareaField
200
+ tone="quiet"
201
+ className="rounded-none focus-within:border-transparent focus-within:ring-0"
202
+ textareaClassName="min-h-[calc(2*1.55em)] resize-none px-0 py-0 text-[15px] leading-[1.55]"
203
+ rows={2}
204
+ wrap="soft"
205
+ maxLength={2000}
206
+ aria-label={t('Studio.composer.requestAriaLabel', { capability: t(capability.labelKey) })}
207
+ placeholder={capability.id === 'text.generate' ? t('Studio.composer.textGeneratePlaceholder') : t(profile.inputPlaceholderKey)}
208
+ value={prompt}
209
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onPromptChange(event.currentTarget.value)}
210
+ />
211
+ )}
212
+ {supportsContext ? (
213
+ <div className={contextOpen ? 'studio-context studio-context--open' : 'studio-context'}>
214
+ <TextareaField
215
+ tone="quiet"
216
+ className="rounded-none focus-within:border-transparent focus-within:ring-0"
217
+ textareaClassName="min-h-[56px] resize-none px-0 py-0 text-[15px] leading-[1.55]"
218
+ rows={compact ? 2 : 3}
219
+ wrap="soft"
220
+ maxLength={1600}
221
+ aria-label={t('Studio.composer.context')}
222
+ placeholder={t('Studio.composer.contextPlaceholder')}
223
+ value={context}
224
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onContextChange(event.currentTarget.value)}
225
+ />
226
+ </div>
227
+ ) : null}
228
+ {parameterPanel ? (
229
+ <div className={parametersOpen ? 'studio-parameters-drawer studio-parameters-drawer--open' : 'studio-parameters-drawer'}>
230
+ {parameterPanel}
231
+ </div>
232
+ ) : null}
233
+ {composerBar}
234
+ </div>
235
+ </div>
236
+ );
237
+ }
238
+
239
+ export function TextStudioStartState({
240
+ registration,
241
+ composer,
242
+ }: {
243
+ registration: StudioCapabilityRegistration;
244
+ composer: ReactNode;
245
+ }) {
246
+ const { translate: t } = useAIStudioHost();
247
+ const capability = registration.descriptor;
248
+ const profile = registration.profile;
249
+ return (
250
+ <section className="studio-start" aria-label={t('Studio.composer.startAriaLabel', { capability: t(capability.labelKey) })}>
251
+ <div className="studio-start__center">
252
+ <h2>{t(profile.inputTitleKey)}</h2>
253
+ <div className="studio-start__composer">{composer}</div>
254
+ </div>
255
+ </section>
256
+ );
257
+ }