@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,1093 @@
1
+ export const SUPPORTED_APP_SCAFFOLD_PROFILES = ['standalone'];
2
+
3
+ export function buildDefaultStarterFiles(identity) {
4
+ return [
5
+ {
6
+ path: 'src/main.tsx',
7
+ content: renderDefaultMain(identity),
8
+ mutationClass: 'scaffold-managed glue',
9
+ },
10
+ {
11
+ path: 'src/shell/routes/product-area.tsx',
12
+ content: renderDefaultProductArea(identity),
13
+ mutationClass: 'app-owned product code',
14
+ },
15
+ ...buildGeneratedModuleCompositionFiles(identity),
16
+ {
17
+ path: 'src-tauri/src/main.rs',
18
+ content: renderDefaultTauriMain(),
19
+ mutationClass: 'scaffold-managed glue',
20
+ },
21
+ {
22
+ path: 'src-electron/main.ts',
23
+ content: renderDefaultElectronMain(identity),
24
+ mutationClass: 'scaffold-managed glue',
25
+ },
26
+ {
27
+ path: 'src-electron/preload.cts',
28
+ content: DEFAULT_ELECTRON_PRELOAD,
29
+ mutationClass: 'scaffold-managed glue',
30
+ },
31
+ {
32
+ path: 'scripts/bundle-electron-preload.mjs',
33
+ content: DEFAULT_ELECTRON_PRELOAD_BUNDLER,
34
+ mutationClass: 'scaffold-managed glue',
35
+ },
36
+ {
37
+ path: 'tsconfig.electron.json',
38
+ content: DEFAULT_ELECTRON_TSCONFIG,
39
+ mutationClass: 'scaffold-managed glue',
40
+ },
41
+ {
42
+ path: 'vite.config.ts',
43
+ content: DEFAULT_VITE_CONFIG,
44
+ mutationClass: 'scaffold-managed glue',
45
+ },
46
+ ];
47
+ }
48
+
49
+ const DEFAULT_VITE_CONFIG = [
50
+ "import { defineConfig } from 'vite';",
51
+ "import react from '@vitejs/plugin-react';",
52
+ "import tailwindcss from '@tailwindcss/vite';",
53
+ '',
54
+ 'export default defineConfig({',
55
+ " base: './',",
56
+ " cacheDir: '.vite',",
57
+ ' plugins: [react(), tailwindcss()],',
58
+ ' resolve: {',
59
+ " dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],",
60
+ ' },',
61
+ '});',
62
+ '',
63
+ ].join('\n');
64
+
65
+ const DEFAULT_ELECTRON_PRELOAD = [
66
+ "import { contextBridge, ipcRenderer } from 'electron';",
67
+ "import { installNimiElectronRuntimeBridge } from '@nimiplatform/kit/shell/electron/preload-cjs';",
68
+ '',
69
+ 'installNimiElectronRuntimeBridge({ contextBridge, ipcRenderer });',
70
+ '',
71
+ ].join('\n');
72
+
73
+ const DEFAULT_ELECTRON_PRELOAD_BUNDLER = [
74
+ "import { build } from 'esbuild';",
75
+ "import path from 'node:path';",
76
+ "import { fileURLToPath } from 'node:url';",
77
+ '',
78
+ "const appRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');",
79
+ '',
80
+ 'await build({',
81
+ " entryPoints: [path.join(appRoot, 'src-electron/preload.cts')],",
82
+ " outfile: path.join(appRoot, 'dist-electron/preload.cjs'),",
83
+ ' bundle: true,',
84
+ " platform: 'node',",
85
+ " target: 'node22',",
86
+ " format: 'cjs',",
87
+ " external: ['electron'],",
88
+ " logLevel: 'silent',",
89
+ '});',
90
+ '',
91
+ ].join('\n');
92
+
93
+ const DEFAULT_ELECTRON_TSCONFIG = `${JSON.stringify({
94
+ extends: './tsconfig.json',
95
+ compilerOptions: {
96
+ target: 'ES2022',
97
+ module: 'NodeNext',
98
+ moduleResolution: 'NodeNext',
99
+ strict: true,
100
+ skipLibCheck: true,
101
+ noEmit: false,
102
+ outDir: 'dist-electron',
103
+ rootDir: 'src-electron',
104
+ types: ['node', 'electron'],
105
+ },
106
+ include: ['src-electron/**/*.ts', 'src-electron/**/*.cts'],
107
+ }, null, 2)}\n`;
108
+
109
+ function renderDefaultMain(identity) {
110
+ return [
111
+ "import React, { Suspense, lazy } from 'react';",
112
+ "import { createRoot } from 'react-dom/client';",
113
+ "import { NimiThemeProvider, TooltipProvider } from '@nimiplatform/kit/ui';",
114
+ "import { installNimiShellRuntimeBridge } from '@nimiplatform/kit/shell/renderer/bridge';",
115
+ 'import {',
116
+ ' DEFAULT_DEV_RENDERER_ENTRY_IMPORT_RETRY_DELAYS_MS,',
117
+ ' createRendererEntryModuleLoader,',
118
+ "} from '@nimiplatform/kit/shell/renderer/bootstrap';",
119
+ "import './styles.css';",
120
+ '',
121
+ 'installNimiShellRuntimeBridge();',
122
+ '',
123
+ 'const entryModuleLoader = createRendererEntryModuleLoader({',
124
+ ' retryDelaysMs: DEFAULT_DEV_RENDERER_ENTRY_IMPORT_RETRY_DELAYS_MS,',
125
+ '});',
126
+ '',
127
+ 'const App = lazy(async () => {',
128
+ ` const mod = await entryModuleLoader.load('entry:${identity.rendererEntryId}', () => import('./shell/App.js'));`,
129
+ ' return { default: mod.App };',
130
+ '});',
131
+ '',
132
+ "const rendererRoot = document.getElementById('root') as HTMLElement;",
133
+ "rendererRoot.classList.add('nimi-workbench-host');",
134
+ 'createRoot(rendererRoot).render(',
135
+ ' <React.StrictMode>',
136
+ ` <NimiThemeProvider accentPack="${identity.accentPack}">`,
137
+ ' <TooltipProvider>',
138
+ ' <Suspense fallback={null}>',
139
+ ' <App />',
140
+ ' </Suspense>',
141
+ ' </TooltipProvider>',
142
+ ' </NimiThemeProvider>',
143
+ ' </React.StrictMode>,',
144
+ ');',
145
+ '',
146
+ ].join('\n');
147
+ }
148
+
149
+ function renderDefaultProductArea(_identity) {
150
+ return [
151
+ "import { WorkbenchCore, WorkbenchEmptyState } from '../../workbench-core/index.js';",
152
+ "import { appTitle } from '../auth/app-identity.js';",
153
+ "import { GeneratedModuleHost, GeneratedRouteRegistry } from '../../scaffold/generated/route-registry.js';",
154
+ 'import {',
155
+ ' generatedInitialViewId,',
156
+ ' generatedNavigationGroups,',
157
+ ' hasGeneratedViews,',
158
+ ' isGeneratedViewId,',
159
+ "} from '../../scaffold/generated/navigation.js';",
160
+ "import { useCallback, useState } from 'react';",
161
+ '',
162
+ "const VIEW_STORAGE_KEY = 'nimi.app.workbench-view.v1';",
163
+ '',
164
+ 'function readInitialViewId(): string | null {',
165
+ ' try {',
166
+ ' const stored = globalThis.localStorage?.getItem(VIEW_STORAGE_KEY);',
167
+ ' return stored && isGeneratedViewId(stored) ? stored : generatedInitialViewId;',
168
+ ' } catch {',
169
+ ' return generatedInitialViewId;',
170
+ ' }',
171
+ '}',
172
+ '',
173
+ 'export function ProductArea() {',
174
+ ' const [activeViewId, setActiveViewId] = useState<string | null>(readInitialViewId);',
175
+ ' const selectView = useCallback((viewId: string) => {',
176
+ ' if (!isGeneratedViewId(viewId)) return;',
177
+ ' setActiveViewId(viewId);',
178
+ ' try { globalThis.localStorage?.setItem(VIEW_STORAGE_KEY, viewId); } catch { /* UI state remains session-local. */ }',
179
+ ' }, []);',
180
+ ' return (',
181
+ ' <GeneratedModuleHost onSelectView={selectView}>',
182
+ ' <WorkbenchCore<string>',
183
+ ' activeViewId={activeViewId}',
184
+ ' navigationLabel="App modules"',
185
+ ' navigationGroups={generatedNavigationGroups}',
186
+ ' onSelectView={selectView}',
187
+ ' rootTestId="nimi-app-workbench"',
188
+ ' >',
189
+ ' {hasGeneratedViews && activeViewId ? (',
190
+ ' <GeneratedRouteRegistry activeViewId={activeViewId} onSelectView={selectView} />',
191
+ ' ) : (',
192
+ ' <WorkbenchEmptyState',
193
+ ' appTitle={appTitle}',
194
+ ' eyebrow="Nimi App"',
195
+ ' title="Ready for product modules"',
196
+ ' description="This identity-neutral workbench is ready. Add a coarse product module when the App needs one."',
197
+ ' status="Runtime ready"',
198
+ ' />',
199
+ ' )}',
200
+ ' </WorkbenchCore>',
201
+ ' </GeneratedModuleHost>',
202
+ ' );',
203
+ '}',
204
+ '',
205
+ ].join('\n');
206
+ }
207
+
208
+ function buildGeneratedModuleCompositionFiles(identity) {
209
+ const resolution = identity.capabilityResolution;
210
+ const files = [
211
+ generatedFile('capability-registry.ts', renderGeneratedCapabilityRegistry(resolution)),
212
+ generatedFile('runtime-registry.ts', renderGeneratedRuntimeRegistry(resolution)),
213
+ generatedFile('navigation.ts', renderGeneratedNavigation(resolution)),
214
+ generatedFile('route-registry.tsx', renderGeneratedRouteRegistry(resolution)),
215
+ generatedFile('module-styles.css', renderGeneratedModuleStyles(resolution)),
216
+ ];
217
+ if (hasAIStudioResolution(resolution)) {
218
+ files.push(generatedFile('i18n.ts', renderGeneratedAIStudioI18n()));
219
+ files.push(generatedFile('host-adapters.tsx', renderGeneratedAIStudioHostAdapter(resolution)));
220
+ }
221
+ return files;
222
+ }
223
+
224
+ function generatedFile(filename, content) {
225
+ return {
226
+ path: `src/scaffold/generated/${filename}`,
227
+ content,
228
+ mutationClass: 'scaffold-managed glue',
229
+ };
230
+ }
231
+
232
+ function aiStudioFeatureModules(resolution) {
233
+ return resolution.modules.filter((module) => (
234
+ module.kind === 'feature' && module.productEntry.kind === 'ai-studio-module'
235
+ ));
236
+ }
237
+
238
+ function componentFeatureModules(resolution) {
239
+ return resolution.modules.filter((module) => (
240
+ module.kind === 'feature' && module.productEntry.kind === 'component'
241
+ ));
242
+ }
243
+
244
+ function hasAIStudioResolution(resolution) {
245
+ return aiStudioFeatureModules(resolution).length > 0;
246
+ }
247
+
248
+ function generatedModuleImportPath(module) {
249
+ const modulePath = module.productEntry.modulePath;
250
+ const mapping = module.sourceMappings.find((candidate) => (
251
+ modulePath === candidate.sourceRoot || modulePath.startsWith(`${candidate.sourceRoot}/`)
252
+ ));
253
+ if (!mapping) throw new Error(`Generated module entry is outside its source mappings: ${module.id}`);
254
+ const suffix = modulePath.slice(mapping.sourceRoot.length).replace(/^\//u, '');
255
+ const target = `${mapping.targetRoot}${suffix ? `/${suffix}` : ''}`
256
+ .replace(/^src\//u, '')
257
+ .replace(/\.(?:tsx?|jsx?)$/u, '.js');
258
+ return `../../${target}`;
259
+ }
260
+
261
+ function resolvedAIStudioCore(resolution) {
262
+ const core = resolution.modules.find((module) => module.id === 'ai-studio-core');
263
+ if (!core || core.productEntry.kind !== 'ai-studio-core') {
264
+ throw new Error('Generated AI Studio composition requires the internal AI core');
265
+ }
266
+ return core;
267
+ }
268
+
269
+ function renderGeneratedCapabilityRegistry(resolution) {
270
+ const modules = aiStudioFeatureModules(resolution);
271
+ if (modules.length === 0) {
272
+ return [
273
+ 'export const generatedAIStudioModules = Object.freeze([]);',
274
+ 'export const generatedAIStudioRegistrations = Object.freeze([]);',
275
+ 'export const generatedAIStudioMessageBundles = Object.freeze({ en: Object.freeze({}), zh: Object.freeze({}) });',
276
+ '',
277
+ ].join('\n');
278
+ }
279
+ const core = resolvedAIStudioCore(resolution);
280
+ const imports = [
281
+ 'import {',
282
+ ` ${core.productEntry.messageExport},`,
283
+ ' composeAIStudioModules,',
284
+ ' mergeAIStudioMessageBundles,',
285
+ `} from '${generatedModuleImportPath(core)}';`,
286
+ ];
287
+ for (const module of modules) {
288
+ imports.push(
289
+ `import { ${module.productEntry.registrationExport}, ${module.productEntry.messageExport} } from '${generatedModuleImportPath(module)}';`,
290
+ );
291
+ }
292
+ const registrations = modules.map((module) => module.productEntry.registrationExport);
293
+ const messageBundles = modules.map((module) => module.productEntry.messageExport);
294
+ return [
295
+ ...imports,
296
+ '',
297
+ `export const generatedAIStudioModules = Object.freeze([${registrations.join(', ')}]);`,
298
+ 'export const generatedAIStudioComposition = composeAIStudioModules(generatedAIStudioModules);',
299
+ 'export const generatedAIStudioRegistrations = generatedAIStudioComposition.capabilities;',
300
+ 'export const generatedAIStudioMessageBundles = Object.freeze({',
301
+ ` en: mergeAIStudioMessageBundles([${core.productEntry.messageExport}.en, ${messageBundles.map((name) => `${name}.en`).join(', ')}]),`,
302
+ ` zh: mergeAIStudioMessageBundles([${core.productEntry.messageExport}.zh, ${messageBundles.map((name) => `${name}.zh`).join(', ')}]),`,
303
+ '});',
304
+ '',
305
+ ].join('\n');
306
+ }
307
+
308
+ function renderGeneratedRuntimeRegistry(resolution) {
309
+ const modules = aiStudioFeatureModules(resolution);
310
+ if (modules.length === 0) {
311
+ return ['export const generatedStudioRuntimeHandlers = Object.freeze({});', ''].join('\n');
312
+ }
313
+ const imports = [
314
+ `import { composeStudioCapabilityRuntimeHandlers } from '${generatedModuleImportPath(resolvedAIStudioCore(resolution))}';`,
315
+ ];
316
+ for (const module of modules) {
317
+ imports.push(
318
+ `import { ${module.productEntry.runtimeExport} } from '${generatedModuleImportPath(module)}';`,
319
+ );
320
+ }
321
+ return [
322
+ ...imports,
323
+ '',
324
+ 'export const generatedStudioRuntimeHandlers = composeStudioCapabilityRuntimeHandlers([',
325
+ ...modules.map((module) => ` ${module.productEntry.runtimeExport},`),
326
+ ']);',
327
+ '',
328
+ ].join('\n');
329
+ }
330
+
331
+ function renderGeneratedNavigation(resolution) {
332
+ const aiModules = aiStudioFeatureModules(resolution);
333
+ const componentModules = componentFeatureModules(resolution);
334
+ const imports = [
335
+ "import type { WorkbenchNavigationGroup } from '../../workbench-core/index.js';",
336
+ ];
337
+ if (aiModules.length > 0) {
338
+ imports.push(
339
+ "import { generatedAIStudioModules } from './capability-registry.js';",
340
+ "import { translateGeneratedMessage } from './i18n.js';",
341
+ );
342
+ }
343
+ if (componentModules.length > 0) {
344
+ imports.push("import { Boxes } from 'lucide-react';");
345
+ }
346
+ const groups = [];
347
+ if (aiModules.length > 0) {
348
+ groups.push(
349
+ ' ...generatedAIStudioModules.map((module) => ({',
350
+ ' id: module.id,',
351
+ ' items: module.capabilities.map((registration) => ({',
352
+ ' id: registration.descriptor.id,',
353
+ ' label: translateGeneratedMessage(registration.descriptor.labelKey),',
354
+ ' icon: registration.icon,',
355
+ ' })),',
356
+ ' })),',
357
+ );
358
+ }
359
+ for (const module of componentModules) {
360
+ groups.push(
361
+ ` { id: ${JSON.stringify(module.id)}, items: [{ id: ${JSON.stringify(module.views[0])}, label: ${JSON.stringify(module.label)}, icon: Boxes }] },`,
362
+ );
363
+ }
364
+ return [
365
+ ...imports,
366
+ ...(imports.length > 0 ? [''] : []),
367
+ 'export const generatedNavigationGroups: readonly WorkbenchNavigationGroup<string>[] = Object.freeze([',
368
+ ...groups,
369
+ ']);',
370
+ 'export const generatedInitialViewId = generatedNavigationGroups[0]?.items[0]?.id ?? null;',
371
+ 'export const hasGeneratedViews = generatedInitialViewId !== null;',
372
+ 'export function isGeneratedViewId(viewId: string): boolean {',
373
+ ' return generatedNavigationGroups.some((group) => group.items.some((item) => item.id === viewId));',
374
+ '}',
375
+ 'export function generatedViewLabel(viewId: string): string {',
376
+ ' for (const group of generatedNavigationGroups) {',
377
+ ' const item = group.items.find((candidate) => candidate.id === viewId);',
378
+ ' if (item) return item.label;',
379
+ ' }',
380
+ ' return viewId;',
381
+ '}',
382
+ '',
383
+ ].join('\n');
384
+ }
385
+
386
+ function renderGeneratedRouteRegistry(resolution) {
387
+ const aiModules = aiStudioFeatureModules(resolution);
388
+ const componentModules = componentFeatureModules(resolution);
389
+ const imports = [
390
+ "import { useEffect, useRef, type ReactNode } from 'react';",
391
+ "import { generatedViewLabel } from './navigation.js';",
392
+ ];
393
+ if (aiModules.length > 0) {
394
+ imports.push(
395
+ "import { generatedAIStudioRegistrations } from './capability-registry.js';",
396
+ "import { GeneratedAIStudioHost, GeneratedAIStudioRoute } from './host-adapters.js';",
397
+ );
398
+ }
399
+ for (const module of componentModules) {
400
+ imports.push(
401
+ `import { ${module.productEntry.componentExport} } from '${generatedModuleImportPath(module)}';`,
402
+ );
403
+ }
404
+ if (componentModules.some((module) => module.productEntry.identityProp)) {
405
+ imports.push("import { appId } from '../../shell/auth/app-identity.js';");
406
+ }
407
+ if (componentModules.some((module) => module.productEntry.clientProp)) {
408
+ imports.push("import { getNimiLocalAppClient } from '../../shell/auth/local-app-client.js';");
409
+ }
410
+ const branches = [];
411
+ if (aiModules.length > 0) {
412
+ branches.push(
413
+ ' if (generatedAIStudioRegistrations.some((registration) => registration.descriptor.id === activeViewId)) {',
414
+ ' content = <GeneratedAIStudioRoute capabilityId={activeViewId} />;',
415
+ ' }',
416
+ );
417
+ }
418
+ for (const module of componentModules) {
419
+ const identityProp = module.productEntry.identityProp
420
+ ? ` ${module.productEntry.identityProp}={appId}`
421
+ : '';
422
+ const clientProp = module.productEntry.clientProp
423
+ ? ` ${module.productEntry.clientProp}={getNimiLocalAppClient()}`
424
+ : '';
425
+ branches.push(
426
+ ` if (activeViewId === ${JSON.stringify(module.views[0])}) content = <${module.productEntry.componentExport}${identityProp}${clientProp} />;`,
427
+ );
428
+ }
429
+ return [
430
+ ...imports,
431
+ ...(imports.length > 0 ? [''] : []),
432
+ 'export function GeneratedModuleHost({',
433
+ ' onSelectView,',
434
+ ' children,',
435
+ '}: {',
436
+ ' readonly onSelectView: (viewId: string) => void;',
437
+ ' readonly children: ReactNode;',
438
+ '}) {',
439
+ ...(aiModules.length > 0
440
+ ? [' return <GeneratedAIStudioHost onSelectCapability={onSelectView}>{children}</GeneratedAIStudioHost>;']
441
+ : [' return <>{children}</>;']),
442
+ '}',
443
+ '',
444
+ 'export function GeneratedRouteRegistry({',
445
+ ' activeViewId,',
446
+ ' onSelectView,',
447
+ '}: {',
448
+ ' readonly activeViewId: string;',
449
+ ' readonly onSelectView: (viewId: string) => void;',
450
+ '}) {',
451
+ ' const rootRef = useRef<HTMLDivElement>(null);',
452
+ ' useEffect(() => { rootRef.current?.focus(); }, [activeViewId]);',
453
+ ' let content: ReactNode = null;',
454
+ ...branches,
455
+ ' if (!content) return null;',
456
+ ' return (',
457
+ ' <div',
458
+ ' ref={rootRef}',
459
+ ' tabIndex={-1}',
460
+ ' role="region"',
461
+ ' aria-label={generatedViewLabel(activeViewId)}',
462
+ ' data-generated-view-id={activeViewId}',
463
+ ' className="h-full min-h-0 outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--nimi-focus-ring-color)]"',
464
+ ' >',
465
+ ' {content}',
466
+ ' </div>',
467
+ ' );',
468
+ '}',
469
+ '',
470
+ ].join('\n');
471
+ }
472
+
473
+ function renderGeneratedModuleStyles(resolution) {
474
+ const imports = [];
475
+ if (hasAIStudioResolution(resolution)) {
476
+ const core = resolvedAIStudioCore(resolution);
477
+ for (const style of core.styles) {
478
+ const mapping = core.sourceMappings.find((candidate) => (
479
+ style === candidate.sourceRoot || style.startsWith(`${candidate.sourceRoot}/`)
480
+ || style === candidate.targetRoot || style.startsWith(`${candidate.targetRoot}/`)
481
+ ));
482
+ if (!mapping) throw new Error(`Generated AI Studio style is outside the AI core source mappings: ${style}`);
483
+ const sourceBased = style === mapping.sourceRoot || style.startsWith(`${mapping.sourceRoot}/`);
484
+ const suffix = sourceBased
485
+ ? style.slice(mapping.sourceRoot.length).replace(/^\//u, '')
486
+ : style.slice(mapping.targetRoot.length).replace(/^\//u, '');
487
+ const target = `${mapping.targetRoot}${suffix ? `/${suffix}` : ''}`.replace(/^src\//u, '');
488
+ imports.push(`@import "../../${target}";`);
489
+ }
490
+ }
491
+ return `${imports.join('\n')}${imports.length > 0 ? '\n' : ''}`;
492
+ }
493
+
494
+ function renderGeneratedAIStudioI18n() {
495
+ return [
496
+ "import i18next from 'i18next';",
497
+ "import { generatedAIStudioMessageBundles } from './capability-registry.js';",
498
+ '',
499
+ "export const generatedLocale = globalThis.navigator?.language?.toLowerCase().startsWith('zh') ? 'zh' : 'en';",
500
+ 'const generatedI18n = i18next.createInstance();',
501
+ 'void generatedI18n.init({',
502
+ ' lng: generatedLocale,',
503
+ " fallbackLng: 'en',",
504
+ ' initImmediate: false,',
505
+ ' interpolation: { escapeValue: false },',
506
+ ' resources: {',
507
+ ' en: { translation: generatedAIStudioMessageBundles.en },',
508
+ ' zh: { translation: generatedAIStudioMessageBundles.zh },',
509
+ ' },',
510
+ '});',
511
+ '',
512
+ 'export function translateGeneratedMessage(',
513
+ ' key: string,',
514
+ ' values?: Readonly<Record<string, unknown>>,',
515
+ '): string {',
516
+ ' return String(generatedI18n.t(key, values ? { ...values } : undefined));',
517
+ '}',
518
+ '',
519
+ ].join('\n');
520
+ }
521
+
522
+ function renderGeneratedAIStudioHostAdapter(resolution) {
523
+ const core = resolvedAIStudioCore(resolution);
524
+ const coreImportPath = generatedModuleImportPath(core);
525
+ const workspaceExport = core.productEntry.componentExport;
526
+ return [
527
+ "import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';",
528
+ "import type { NimiAIConfigSnapshot } from '@nimiplatform/sdk/ai';",
529
+ "import { createNimiClientId } from '@nimiplatform/sdk/types';",
530
+ "import { ModelConfigAIConfigSurface } from '@nimiplatform/kit/features/model-config';",
531
+ "import { openDesktopIntent } from '@nimiplatform/kit/shell/renderer/bridge';",
532
+ "import { StatusBadge } from '@nimiplatform/kit/ui';",
533
+ 'import {',
534
+ ' AIStudioHostProvider,',
535
+ ` ${workspaceExport},`,
536
+ ' DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES,',
537
+ ' boundStudioRunHistoryWithRecord,',
538
+ ' cleanupStudioHistoryArtifacts,',
539
+ ' clearStudioHistoryWithPolicy,',
540
+ ' createStudioNonSuccess,',
541
+ ' createStudioRunTargetSummary,',
542
+ ' createEmptyStudioPromptDraftStore,',
543
+ ' loadStudioAIConfig,',
544
+ ' parseAIStudioHistoryPanelPreferences,',
545
+ ' parseStudioRunHistory,',
546
+ ' parseStudioPromptDraftStore,',
547
+ ' projectStudioManagedHistory,',
548
+ ' readStudioPromptDraft,',
549
+ ' requireStudioAIConfigOwner,',
550
+ ' removeStudioHistoryWithPolicy,',
551
+ ' runStudioCapability,',
552
+ ' subscribeStudioAIConfigRefresh,',
553
+ ' studioHistoryArtifactPaths,',
554
+ ' updateStudioPromptDraftStore,',
555
+ ' useAIStudioWorkspaceController,',
556
+ ' type AIStudioHistoryMutationOutcome,',
557
+ ' type AIStudioHistoryPanelPreferences,',
558
+ ' type AIStudioHistoryProjection,',
559
+ ' type AIStudioHistoryRepository,',
560
+ ' type AIStudioHostPort,',
561
+ ' type AIStudioWorkspaceController,',
562
+ ' type StudioPromptDraftStore,',
563
+ ' type StudioRunHistory,',
564
+ ' type StudioRunHistoryRecord,',
565
+ ' type StudioRuntimeInspection,',
566
+ `} from '${coreImportPath}';`,
567
+ "import { appId, appTitle } from '../../shell/auth/app-identity.js';",
568
+ "import { getNimiLocalAppClient } from '../../shell/auth/local-app-client.js';",
569
+ "import { getRuntimePlatformProjection } from '../../shell/auth/runtime-platform.js';",
570
+ 'import {',
571
+ ' generatedAIStudioComposition,',
572
+ ' generatedAIStudioRegistrations,',
573
+ "} from './capability-registry.js';",
574
+ "import { generatedStudioRuntimeHandlers } from './runtime-registry.js';",
575
+ "import { generatedLocale, translateGeneratedMessage } from './i18n.js';",
576
+ '',
577
+ "const HISTORY_PATH = 'ai-studio/run-history.v1.json';",
578
+ "const PROMPT_DRAFT_STORAGE_KEY = 'nimi.ai-studio.prompt-drafts.v1';",
579
+ 'const translate: AIStudioHostPort[\'translate\'] = translateGeneratedMessage;',
580
+ '',
581
+ 'async function inspectTargetRuntime(): Promise<StudioRuntimeInspection> {',
582
+ ' const projection = await getRuntimePlatformProjection();',
583
+ " if (projection.status === 'ready') {",
584
+ " return { status: 'connected', mode: projection.mode, detail: 'The protected local-app Runtime session is connected.' };",
585
+ ' }',
586
+ " return { status: 'unavailable', mode: projection.mode, detail: projection.message };",
587
+ '}',
588
+ '',
589
+ 'function reasonCode(error: unknown): string {',
590
+ " if (!error || typeof error !== 'object') return '';",
591
+ ' const value = (error as { readonly reasonCode?: unknown; readonly code?: unknown }).reasonCode',
592
+ ' ?? (error as { readonly code?: unknown }).code;',
593
+ " return typeof value === 'string' ? value.trim().toUpperCase().replaceAll('-', '_') : '';",
594
+ '}',
595
+ '',
596
+ 'function isStorageEntryNotFound(error: unknown): boolean {',
597
+ ' const normalized = reasonCode(error);',
598
+ ' return normalized === \'APP_STORAGE_ENTRY_NOT_FOUND\'',
599
+ " || normalized === 'NOT_FOUND'",
600
+ " || normalized === 'ENTRY_NOT_FOUND'",
601
+ " || normalized.endsWith('_STORAGE_JSON_NOT_FOUND')",
602
+ " || normalized.endsWith('_STORAGE_ENTRY_NOT_FOUND')",
603
+ " || normalized.endsWith('_LOCAL_ASSET_NOT_FOUND');",
604
+ '}',
605
+ '',
606
+ 'async function loadRunHistory(): Promise<StudioRunHistory> {',
607
+ ' try {',
608
+ ' const document = await getNimiLocalAppClient().storage.readJson(HISTORY_PATH);',
609
+ ' return parseStudioRunHistory(document.value);',
610
+ ' } catch (error) {',
611
+ ' if (isStorageEntryNotFound(error)) return {};',
612
+ ' throw error;',
613
+ ' }',
614
+ '}',
615
+ '',
616
+ 'async function writeRunHistory(history: StudioRunHistory): Promise<StudioRunHistory> {',
617
+ ' const normalized = parseStudioRunHistory(JSON.parse(JSON.stringify(history)) as unknown);',
618
+ ' await getNimiLocalAppClient().storage.writeJson(HISTORY_PATH, normalized as never);',
619
+ ' return normalized;',
620
+ '}',
621
+ '',
622
+ 'let historyMutationTail: Promise<unknown> = Promise.resolve();',
623
+ 'function mutateHistory<TValue>(operation: () => Promise<TValue>): Promise<TValue> {',
624
+ ' const next = historyMutationTail.then(operation, operation);',
625
+ ' historyMutationTail = next.then(() => undefined, () => undefined);',
626
+ ' return next;',
627
+ '}',
628
+ '',
629
+ 'const cleanupArtifacts: AIStudioHistoryRepository[\'cleanupArtifacts\'] = (relativePaths) => cleanupStudioHistoryArtifacts({',
630
+ ' relativePaths,',
631
+ ' removeArtifact: (relativePath) => getNimiLocalAppClient().storage.assets.remove(relativePath),',
632
+ ' isNotFound: isStorageEntryNotFound,',
633
+ '});',
634
+ '',
635
+ 'async function verifyHistoryProjection(runHistory: StudioRunHistory): Promise<AIStudioHistoryProjection> {',
636
+ ' return projectStudioManagedHistory({',
637
+ ' runHistory,',
638
+ ' resolveCapabilityLabel: (capabilityId) => generatedAIStudioRegistrations.find((entry) => (',
639
+ ' entry.descriptor.id === capabilityId',
640
+ ' ))?.descriptor.label ?? capabilityId,',
641
+ ' statArtifact: (artifact) => getNimiLocalAppClient().storage.assets.stat(artifact.relativePath),',
642
+ ' });',
643
+ '}',
644
+ '',
645
+ 'async function loadVerifiedHistory(): Promise<AIStudioHistoryProjection> {',
646
+ ' return verifyHistoryProjection(await loadRunHistory());',
647
+ '}',
648
+ '',
649
+ 'async function appendRecord(record: StudioRunHistoryRecord): Promise<AIStudioHistoryProjection> {',
650
+ ' return mutateHistory(async () => {',
651
+ ' const current = await loadRunHistory();',
652
+ ' const next = boundStudioRunHistoryWithRecord(current, record);',
653
+ ' return verifyHistoryProjection(await writeRunHistory(next));',
654
+ ' });',
655
+ '}',
656
+ '',
657
+ 'async function persistHistory({ result, record }: { readonly result: Parameters<AIStudioHistoryRepository[\'persist\']>[0][\'result\']; readonly record: StudioRunHistoryRecord }) {',
658
+ ' try {',
659
+ ' return { ok: true as const, projection: await appendRecord(record) };',
660
+ ' } catch (error) {',
661
+ ' const paths = studioHistoryArtifactPaths(record);',
662
+ ' const cleanup = await cleanupArtifacts(paths);',
663
+ " const message = error instanceof Error ? error.message : String(error || 'History persistence failed.');",
664
+ ' return {',
665
+ ' ok: false as const,',
666
+ ' message,',
667
+ ' retryRecord: paths.length === 0,',
668
+ ' remainingCleanupPaths: cleanup.remainingCleanupPaths,',
669
+ ' ...(paths.length > 0 ? {',
670
+ " displayFailure: { reason: 'runtime-call-failed' as const, message: `Runtime completed, but managed artifact history persistence failed: ${message}` },",
671
+ ' } : {}),',
672
+ ' };',
673
+ ' }',
674
+ '}',
675
+ '',
676
+ 'async function removeHistoryRecord(recordId: string, deleteAssets: boolean): Promise<AIStudioHistoryMutationOutcome> {',
677
+ ' return mutateHistory(async () => {',
678
+ ' const current = await loadRunHistory();',
679
+ ' return removeStudioHistoryWithPolicy({',
680
+ ' history: current,',
681
+ ' recordId,',
682
+ ' deleteAssets,',
683
+ ' removeArtifact: (relativePath) => getNimiLocalAppClient().storage.assets.remove(relativePath),',
684
+ ' isNotFound: isStorageEntryNotFound,',
685
+ ' commit: async (next) => { await writeRunHistory(next); },',
686
+ ' project: verifyHistoryProjection,',
687
+ ' });',
688
+ ' });',
689
+ '}',
690
+ '',
691
+ 'async function clearHistory(capabilityId: string | null, deleteAssets: boolean): Promise<AIStudioHistoryMutationOutcome> {',
692
+ ' return mutateHistory(async () => {',
693
+ ' const current = await loadRunHistory();',
694
+ ' return clearStudioHistoryWithPolicy({',
695
+ ' history: current,',
696
+ ' capabilityId,',
697
+ ' deleteAssets,',
698
+ ' removeArtifact: (relativePath) => getNimiLocalAppClient().storage.assets.remove(relativePath),',
699
+ ' isNotFound: isStorageEntryNotFound,',
700
+ ' commit: async (next) => { await writeRunHistory(next); },',
701
+ ' project: verifyHistoryProjection,',
702
+ ' });',
703
+ ' });',
704
+ '}',
705
+ '',
706
+ "const HISTORY_PANEL_STORAGE_KEY = 'nimi.ai-studio.history-panel.v1';",
707
+ 'function loadPanelPreferences(): AIStudioHistoryPanelPreferences {',
708
+ ' try {',
709
+ ' const raw = globalThis.localStorage?.getItem(HISTORY_PANEL_STORAGE_KEY);',
710
+ ' if (!raw) return DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES;',
711
+ ' return parseAIStudioHistoryPanelPreferences(JSON.parse(raw));',
712
+ ' } catch { return DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES; }',
713
+ '}',
714
+ 'function savePanelPreferences(preferences: AIStudioHistoryPanelPreferences): void {',
715
+ ' try { globalThis.localStorage?.setItem(HISTORY_PANEL_STORAGE_KEY, JSON.stringify(preferences)); } catch { /* UI state remains session-local. */ }',
716
+ '}',
717
+ '',
718
+ 'const historyRepository: AIStudioHistoryRepository = Object.freeze({',
719
+ ' load: loadVerifiedHistory,',
720
+ ' persist: persistHistory,',
721
+ ' appendRecord,',
722
+ ' cleanupArtifacts,',
723
+ ' remove: removeHistoryRecord,',
724
+ ' clear: clearHistory,',
725
+ " nextIdentity: async () => ({ runId: createNimiClientId('run'), createdAt: new Date().toISOString() }),",
726
+ ' loadPanelPreferences,',
727
+ ' savePanelPreferences,',
728
+ '});',
729
+ '',
730
+ 'let promptDraftStore = readPromptDraftStore();',
731
+ '',
732
+ 'function readPromptDraftStore(): StudioPromptDraftStore {',
733
+ ' try {',
734
+ ' const raw = globalThis.localStorage?.getItem(PROMPT_DRAFT_STORAGE_KEY);',
735
+ ' if (!raw) return createEmptyStudioPromptDraftStore();',
736
+ ' return parseStudioPromptDraftStore(JSON.parse(raw));',
737
+ ' } catch {',
738
+ ' return createEmptyStudioPromptDraftStore();',
739
+ ' }',
740
+ '}',
741
+ '',
742
+ 'async function savePromptDraft(key: Parameters<AIStudioHostPort[\'app\'][\'commands\'][\'savePromptDraft\']>[0], prompt: string, enabled: boolean) {',
743
+ ' const next = updateStudioPromptDraftStore(promptDraftStore, key, prompt, enabled);',
744
+ ' if (next === promptDraftStore) return promptDraftStore;',
745
+ ' promptDraftStore = next;',
746
+ ' try { globalThis.localStorage?.setItem(PROMPT_DRAFT_STORAGE_KEY, JSON.stringify(promptDraftStore)); } catch { /* UI state remains session-local. */ }',
747
+ ' return promptDraftStore;',
748
+ '}',
749
+ '',
750
+ 'function downloadBlob(filename: string, blob: Blob): void {',
751
+ ' const url = URL.createObjectURL(blob);',
752
+ " const anchor = document.createElement('a');",
753
+ ' anchor.href = url;',
754
+ ' anchor.download = filename;',
755
+ ' anchor.click();',
756
+ ' queueMicrotask(() => URL.revokeObjectURL(url));',
757
+ '}',
758
+ '',
759
+ 'const RUN_STATUS_LABEL_KEYS: Readonly<Record<string, string>> = Object.freeze({',
760
+ " ready: 'StudioShell.runStatusReady',",
761
+ " unavailable: 'StudioShell.runStatusUnavailable',",
762
+ " failed: 'StudioShell.runStatusFailed',",
763
+ " canceled: 'StudioShell.runStatusCanceled',",
764
+ " 'timed-out': 'StudioShell.runStatusTimedOut',",
765
+ '});',
766
+ 'function runStatusLabel(status: string): string {',
767
+ ' const key = RUN_STATUS_LABEL_KEYS[status];',
768
+ ' return key ? translate(key) : status;',
769
+ '}',
770
+ '',
771
+ 'const hostValue: AIStudioHostPort = {',
772
+ ' appTitle,',
773
+ ' translate,',
774
+ ' locale: generatedLocale,',
775
+ ' clock: { now: () => Date.now() },',
776
+ ' app: {',
777
+ ' projection: {',
778
+ ' promptDraft: (key, enabled) => ({ prompt: readStudioPromptDraft(promptDraftStore, key, enabled) }),',
779
+ ' projectRunTarget: createStudioRunTargetSummary,',
780
+ ' runStatusLabel,',
781
+ ' },',
782
+ ' events: {',
783
+ ' subscribeAIConfigRefresh: (listener) => subscribeStudioAIConfigRefresh(listener, window, document),',
784
+ ' },',
785
+ ' commands: {',
786
+ ' savePromptDraft,',
787
+ ' async copyText(text) {',
788
+ ' try {',
789
+ ' await navigator.clipboard.writeText(text);',
790
+ ' return { ok: true, value: { copied: true } };',
791
+ ' } catch (error) {',
792
+ ' return { ok: false, error };',
793
+ ' }',
794
+ ' },',
795
+ " exportText: async ({ filename, body }) => downloadBlob(filename, new Blob([body], { type: 'text/plain;charset=utf-8' })),",
796
+ ' },',
797
+ ' },',
798
+ ' sdk: {',
799
+ ' runCapability: (input) => runStudioCapability(input, {',
800
+ ' appId,',
801
+ " surfaceId: 'ai-capabilities',",
802
+ " abortReason: 'studio-user-canceled',",
803
+ ' handlers: generatedStudioRuntimeHandlers,',
804
+ ' resolveCapability: (capabilityId) => generatedAIStudioComposition.getCapability(capabilityId).descriptor,',
805
+ ' inspectRuntime: inspectTargetRuntime,',
806
+ ' getClient: getNimiLocalAppClient,',
807
+ " createScenarioId: (capability) => `studio:${capability.id}`,",
808
+ ' nonSuccess: (capability, reason, message, diagnostics) => (',
809
+ ' createStudioNonSuccess(capability, reason, message, translate, diagnostics)',
810
+ ' ),',
811
+ ' }),',
812
+ ' async listLocalAppVoiceAssets() {',
813
+ " const result = await getNimiLocalAppClient().ai.voiceAssets.list({ pageSize: 100, pageToken: '' });",
814
+ ' return result.assets.map((asset) => ({',
815
+ ' voiceAssetId: asset.voiceAssetId,',
816
+ ' creationSource: asset.creationSource,',
817
+ ' status: asset.status,',
818
+ ' }));',
819
+ ' },',
820
+ ' uploadLocalAppArtifact: (input) => getNimiLocalAppClient().ai.artifacts.upload(input),',
821
+ ' aiConfig: {',
822
+ ' get: () => loadStudioAIConfig({',
823
+ ' get: async () => (await getNimiLocalAppClient().aiConfig.get()).config,',
824
+ ' }, appId),',
825
+ ' },',
826
+ ' revealLocalAppAsset: (relativePath) => getNimiLocalAppClient().storage.assets.reveal(relativePath),',
827
+ ' },',
828
+ '};',
829
+ '',
830
+ 'const generatedCapabilityContracts = Object.freeze([',
831
+ ' ...new Set(generatedAIStudioRegistrations.flatMap((registration) => (',
832
+ ' registration.descriptor.capabilityContract ? [registration.descriptor.capabilityContract] : []',
833
+ ' ))),',
834
+ ']);',
835
+ '',
836
+ 'function GeneratedAIConfigPanel({',
837
+ ' runtime,',
838
+ ' capabilityId,',
839
+ '}: {',
840
+ ' readonly runtime: StudioRuntimeInspection | null;',
841
+ ' readonly capabilityId: string;',
842
+ '}) {',
843
+ ' const [snapshot, setSnapshot] = useState<NimiAIConfigSnapshot | null>(null);',
844
+ ' const [loading, setLoading] = useState(true);',
845
+ ' const [loadError, setLoadError] = useState<string | null>(null);',
846
+ ' const refresh = async () => {',
847
+ ' setLoading(true);',
848
+ ' setLoadError(null);',
849
+ ' try {',
850
+ ' const next = await getNimiLocalAppClient().aiConfig.get();',
851
+ ' if (next.config) requireStudioAIConfigOwner(next.config, appId);',
852
+ ' setSnapshot(next);',
853
+ ' } catch (error) {',
854
+ " setLoadError(error instanceof Error ? error.message : String(error || 'AIConfig load failed.'));",
855
+ ' } finally {',
856
+ ' setLoading(false);',
857
+ ' }',
858
+ ' };',
859
+ ' useEffect(() => {',
860
+ ' void refresh();',
861
+ ' return subscribeStudioAIConfigRefresh(() => { void refresh(); }, window, document);',
862
+ ' }, []);',
863
+ ' const runtimeLabel = runtime?.status === \'connected\'',
864
+ " ? translate('StudioShell.statusConfigured')",
865
+ " : translate('StudioShell.statusNotAdmitted');",
866
+ ' return (',
867
+ ' <section className="flex h-full min-h-0 flex-col" aria-label={translate(\'StudioModelConfig.drawerDescription\', { appTitle })}>',
868
+ ' <div className="min-h-0 flex-1 overflow-y-auto p-5">',
869
+ ' <ModelConfigAIConfigSurface',
870
+ " context={{ owner: 'app-ai-config', appId }}",
871
+ ' capabilityContracts={generatedCapabilityContracts}',
872
+ ' initialCapabilityContract={capabilityId}',
873
+ ' capabilities={snapshot?.config ? snapshot.config.capabilities as never : snapshot ? null : undefined}',
874
+ ' revision={snapshot?.revision}',
875
+ ' effectiveSelections={snapshot?.effectiveSelections}',
876
+ ' listOptions={(query) => getNimiLocalAppClient().aiConfig.listOptions(query)}',
877
+ ' loading={loading && !snapshot}',
878
+ ' loadError={loadError}',
879
+ ' onRetry={() => { void refresh(); }}',
880
+ ' onOverwrite={async (input) => {',
881
+ ' const result = await getNimiLocalAppClient().aiConfig.overwrite(input);',
882
+ ' setSnapshot({ config: result.config, revision: result.revision, effectiveSelections: [] });',
883
+ " if (result.outcome === 'committed') void refresh();",
884
+ ' return result;',
885
+ ' }}',
886
+ ' onOpenOwnerConfiguration={() => {',
887
+ ' void openDesktopIntent({',
888
+ " requestId: createNimiClientId('desktop-open'),",
889
+ " intent: { kind: 'open-apps', appId, section: 'ai-models' },",
890
+ ' });',
891
+ ' }}',
892
+ ' copy={{',
893
+ " title: translate('StudioModelConfig.drawerTitle'),",
894
+ " description: translate('StudioModelConfig.drawerDescription', { appTitle }),",
895
+ ' capabilityLabel: (contract, fallback) => (',
896
+ ' generatedAIStudioRegistrations.find((entry) => entry.descriptor.capabilityContract === contract)',
897
+ ' ? translate(generatedAIStudioRegistrations.find((entry) => entry.descriptor.capabilityContract === contract)!.descriptor.labelKey)',
898
+ ' : fallback',
899
+ ' ),',
900
+ ' }}',
901
+ ' headerSlot={<StatusBadge tone={runtime?.status === \'connected\' ? \'neutral\' : \'warning\'} shape="dot">{runtimeLabel}</StatusBadge>}',
902
+ ' />',
903
+ ' </div>',
904
+ ' </section>',
905
+ ' );',
906
+ '}',
907
+ '',
908
+ 'type GeneratedAIStudioState = {',
909
+ ' readonly runtime: StudioRuntimeInspection | null;',
910
+ ' readonly controller: AIStudioWorkspaceController;',
911
+ '};',
912
+ 'const GeneratedAIStudioStateContext = createContext<GeneratedAIStudioState | null>(null);',
913
+ '',
914
+ 'export function GeneratedAIStudioHost({',
915
+ ' onSelectCapability,',
916
+ ' children,',
917
+ '}: {',
918
+ ' readonly onSelectCapability: (capabilityId: string) => void;',
919
+ ' readonly children: ReactNode;',
920
+ '}) {',
921
+ ' const [runtime, setRuntime] = useState<StudioRuntimeInspection | null>(null);',
922
+ ' useEffect(() => {',
923
+ ' let active = true;',
924
+ ' void inspectTargetRuntime().then((next) => { if (active) setRuntime(next); });',
925
+ ' return () => { active = false; };',
926
+ ' }, []);',
927
+ ' const controller = useAIStudioWorkspaceController({',
928
+ ' historyRepository,',
929
+ ' registrations: generatedAIStudioRegistrations,',
930
+ ' onSelectCapability,',
931
+ ' translate,',
932
+ ' });',
933
+ ' const state = useMemo(() => ({ runtime, controller }), [controller, runtime]);',
934
+ ' return (',
935
+ ' <AIStudioHostProvider value={hostValue}>',
936
+ ' <GeneratedAIStudioStateContext.Provider value={state}>',
937
+ ' {children}',
938
+ ' </GeneratedAIStudioStateContext.Provider>',
939
+ ' </AIStudioHostProvider>',
940
+ ' );',
941
+ '}',
942
+ '',
943
+ 'function useGeneratedAIStudioState(): GeneratedAIStudioState {',
944
+ ' const state = useContext(GeneratedAIStudioStateContext);',
945
+ " if (!state) throw new Error('GENERATED_AI_STUDIO_HOST_UNAVAILABLE');",
946
+ ' return state;',
947
+ '}',
948
+ '',
949
+ 'export function GeneratedAIStudioRoute({',
950
+ ' capabilityId,',
951
+ '}: {',
952
+ ' readonly capabilityId: string;',
953
+ '}) {',
954
+ ' const { runtime, controller } = useGeneratedAIStudioState();',
955
+ ' const registration = useMemo(() => (',
956
+ ' generatedAIStudioRegistrations.find((entry) => entry.descriptor.id === capabilityId)',
957
+ ' ?? generatedAIStudioRegistrations[0]',
958
+ ' ), [capabilityId]);',
959
+ ' if (!registration) return null;',
960
+ ' return (',
961
+ ` <${workspaceExport}`,
962
+ ' registration={registration}',
963
+ ' registrations={generatedAIStudioRegistrations}',
964
+ ' runtime={runtime}',
965
+ ' controller={controller}',
966
+ ' renderAIConfigPanel={(input) => <GeneratedAIConfigPanel {...input} />}',
967
+ ' rootTestId="nimi-app-ai-studio"',
968
+ ' />',
969
+ ' );',
970
+ '}',
971
+ '',
972
+ ].join('\n');
973
+ }
974
+
975
+ function renderDefaultTauriMain() {
976
+ return [
977
+ 'fn main() {',
978
+ ' tauri::Builder::default()',
979
+ ' .setup(|app| {',
980
+ ' use tauri::Manager;',
981
+ ' app.manage(',
982
+ ' nimi_shell_tauri::capabilities::runtime::RuntimeBridgeLocalAppHost::platform_default(),',
983
+ ' );',
984
+ ' Ok(())',
985
+ ' })',
986
+ ' .invoke_handler(nimi_shell_tauri::nimi_shell_tauri_local_app_standard_shell_handler![])',
987
+ ' .run(tauri::generate_context!())',
988
+ ' .expect("failed to run Nimi App shell");',
989
+ '}',
990
+ '',
991
+ ].join('\n');
992
+ }
993
+
994
+ function renderDefaultElectronMain(identity) {
995
+ return [
996
+ "import path from 'node:path';",
997
+ "import { fileURLToPath, pathToFileURL } from 'node:url';",
998
+ "import { app, BrowserWindow, ipcMain, Menu, protocol, session, webContents } from 'electron';",
999
+ 'import {',
1000
+ ' isAllowedElectronRendererUrl,',
1001
+ ' registerNimiElectronAppAssetProtocolScheme,',
1002
+ ' registerNimiElectronAppBridge,',
1003
+ "} from '@nimiplatform/kit/shell/electron/main';",
1004
+ '',
1005
+ `const APP_ID = '${identity.appId}';`,
1006
+ `const NATIVE_BUNDLE_IDENTIFIER = ${JSON.stringify(identity.nativeBundleIdentifier)};`,
1007
+ "const currentDir = path.dirname(fileURLToPath(import.meta.url));",
1008
+ "const appRoot = path.resolve(currentDir, '..');",
1009
+ "const preloadPath = path.join(currentDir, 'preload.cjs');",
1010
+ "const productionRendererUrl = pathToFileURL(path.join(appRoot, 'dist', 'index.html')).toString();",
1011
+ 'const developmentRendererUrl = readDevelopmentRendererUrl();',
1012
+ 'const rendererUrl = developmentRendererUrl || productionRendererUrl;',
1013
+ 'const allowedRendererUrls = [rendererUrl];',
1014
+ '',
1015
+ `app.setName(${JSON.stringify(identity.appTitle)});`,
1016
+ 'app.setAppUserModelId(NATIVE_BUNDLE_IDENTIFIER);',
1017
+ 'Menu.setApplicationMenu(null);',
1018
+ 'registerNimiElectronAppAssetProtocolScheme(protocol);',
1019
+ '',
1020
+ 'void app.whenReady().then(async () => {',
1021
+ ' registerNimiElectronAppBridge({',
1022
+ ' appId: APP_ID,',
1023
+ ' allowedRendererUrls,',
1024
+ ' assetMediaPlatform: { protocol, webRequest: session.defaultSession.webRequest, webContents },',
1025
+ ' ipcMain,',
1026
+ ' });',
1027
+ ' await createMainWindow();',
1028
+ ' app.on(\'activate\', () => {',
1029
+ ' if (BrowserWindow.getAllWindows().length === 0) void createMainWindow();',
1030
+ ' });',
1031
+ '});',
1032
+ '',
1033
+ "app.on('window-all-closed', () => {",
1034
+ " if (process.platform !== 'darwin') app.quit();",
1035
+ '});',
1036
+ '',
1037
+ 'async function createMainWindow(): Promise<void> {',
1038
+ ' const window = new BrowserWindow({',
1039
+ ' width: 1180,',
1040
+ ' height: 780,',
1041
+ ' minWidth: 360,',
1042
+ ' minHeight: 560,',
1043
+ ` title: ${JSON.stringify(identity.appTitle)},`,
1044
+ ' autoHideMenuBar: true,',
1045
+ ' webPreferences: {',
1046
+ ' preload: preloadPath,',
1047
+ ' contextIsolation: true,',
1048
+ ' nodeIntegration: false,',
1049
+ ' sandbox: true,',
1050
+ ' },',
1051
+ ' });',
1052
+ ' window.webContents.setWindowOpenHandler(() => ({ action: \'deny\' }));',
1053
+ " window.webContents.on('will-navigate', (event, url) => {",
1054
+ ' if (!isAllowedElectronRendererUrl(url, allowedRendererUrls)) event.preventDefault();',
1055
+ ' });',
1056
+ ' await window.loadURL(rendererUrl);',
1057
+ '}',
1058
+ '',
1059
+ 'function readDevelopmentRendererUrl(): string {',
1060
+ " const prefix = '--nimi-dev-renderer-url=';",
1061
+ ' const values = process.argv.filter((value) => value.startsWith(prefix));',
1062
+ ' if (values.length === 0) return \'\';',
1063
+ " if (values.length !== 1) throw new Error('Nimi development renderer URL must be singular.');",
1064
+ ' const selected = values[0];',
1065
+ " if (!selected) throw new Error('Nimi development renderer URL is missing.');",
1066
+ ' const raw = selected.slice(prefix.length);',
1067
+ ' const parsed = new URL(raw);',
1068
+ ' if (',
1069
+ " parsed.protocol !== 'http:'",
1070
+ " || !['127.0.0.1', 'localhost', '[::1]', '::1'].includes(parsed.hostname.toLowerCase())",
1071
+ ' || !parsed.port',
1072
+ ' || parsed.username',
1073
+ ' || parsed.password',
1074
+ " || (parsed.pathname !== '/' && parsed.pathname !== '')",
1075
+ ' || parsed.search',
1076
+ ' || parsed.hash',
1077
+ ' ) {',
1078
+ " throw new Error('Nimi development renderer URL must be exact loopback.');",
1079
+ ' }',
1080
+ ' return parsed.origin;',
1081
+ '}',
1082
+ '',
1083
+ ].join('\n');
1084
+ }
1085
+
1086
+ function escapeJsxText(input) {
1087
+ return String(input)
1088
+ .replaceAll('&', '&amp;')
1089
+ .replaceAll('<', '&lt;')
1090
+ .replaceAll('>', '&gt;')
1091
+ .replaceAll('{', '&#123;')
1092
+ .replaceAll('}', '&#125;');
1093
+ }