@nimiplatform/app-tools 0.6.3 → 0.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +153 -12
  2. package/bin/nimi-app.mjs +16 -14
  3. package/lib/app-access-declaration.mjs +1 -0
  4. package/lib/app-dependency-combinations.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +84 -23
  6. package/lib/app-info.mjs +33 -3
  7. package/lib/app-lifecycle-guidance.mjs +4 -2
  8. package/lib/app-pack.mjs +5 -2
  9. package/lib/app-project-lifecycle.mjs +284 -53
  10. package/lib/app-safety-profile.mjs +204 -0
  11. package/lib/app-scaffold-capabilities.mjs +11 -3
  12. package/lib/app-scaffold-profiles.mjs +136 -27
  13. package/lib/app-scaffold.mjs +55 -7
  14. package/lib/canonical-capability-ids.generated.mjs +25 -0
  15. package/lib/index.mjs +0 -4
  16. package/package.json +27 -31
  17. package/scripts/dev-shell.mjs +80 -18
  18. package/skills/nimi-app-lifecycle/SKILL.md +7 -3
  19. package/skills/nimi-app-lifecycle/references/acceptance.md +7 -1
  20. package/skills/nimi-app-lifecycle/references/adapt.md +46 -1
  21. package/skills/nimi-app-lifecycle/references/audit.md +55 -0
  22. package/skills/nimi-app-lifecycle/references/platform-gaps.md +15 -0
  23. package/skills/nimi-app-lifecycle/references/release.md +2 -2
  24. package/skills/nimi-app-lifecycle/references/safety-declaration.md +37 -0
  25. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +16 -2
  26. package/templates/app-source/src/ai-studio-core/ai-config.ts +17 -3
  27. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +40 -3
  28. package/templates/app-source/src/ai-studio-core/audio-separation-request.ts +24 -0
  29. package/templates/app-source/src/ai-studio-core/contexts.tsx +4 -0
  30. package/templates/app-source/src/ai-studio-core/history-policy.ts +395 -41
  31. package/templates/app-source/src/ai-studio-core/history.ts +262 -10
  32. package/templates/app-source/src/ai-studio-core/host-context.tsx +15 -2
  33. package/templates/app-source/src/ai-studio-core/index.ts +15 -4
  34. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +105 -0
  35. package/templates/app-source/src/ai-studio-core/job-recovery.ts +224 -0
  36. package/templates/app-source/src/ai-studio-core/managed-result-references.ts +79 -0
  37. package/templates/app-source/src/ai-studio-core/messages/en.json +185 -10
  38. package/templates/app-source/src/ai-studio-core/messages/zh.json +185 -10
  39. package/templates/app-source/src/ai-studio-core/module-registration.ts +9 -1
  40. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +81 -2
  41. package/templates/app-source/src/ai-studio-core/parameters.ts +34 -1
  42. package/templates/app-source/src/ai-studio-core/runtime-types.ts +124 -8
  43. package/templates/app-source/src/ai-studio-core/runtime.ts +218 -20
  44. package/templates/app-source/src/ai-studio-core/section-ai-testing-annotation-result.tsx +123 -0
  45. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +3 -0
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-audio-separation-result.tsx +26 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +14 -7
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-decision-result.tsx +76 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +71 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +20 -4
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +29 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +45 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +132 -10
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +122 -38
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +4 -3
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +66 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +100 -22
  58. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +6 -0
  59. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +45 -0
  60. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +106 -0
  61. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +23 -4
  62. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-asset-actions.tsx +40 -0
  63. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-conversion-result.tsx +20 -0
  64. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +219 -35
  65. package/templates/app-source/src/ai-studio-core/text-annotation-document.ts +50 -0
  66. package/templates/app-source/src/ai-studio-core/text-media-replay.ts +51 -0
  67. package/templates/app-source/src/ai-studio-core/voice-assets.ts +17 -0
  68. package/templates/app-source/src/ai-studio-core/workspace.tsx +48 -6
  69. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +1 -1
  70. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +13 -1
  71. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +13 -1
  72. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
  73. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -2
  74. package/templates/app-source/src/studio-modules/studio-create/registration.ts +2 -2
  75. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +121 -3
  76. package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +72 -0
  77. package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +90 -0
  78. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +16 -1
  79. package/templates/app-source/src/studio-modules/studio-media/index.ts +2 -0
  80. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +225 -7
  81. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +225 -7
  82. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +85 -0
  83. package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +85 -0
  84. package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +64 -0
  85. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +9 -26
  86. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +170 -6
  87. package/templates/app-source/src/studio-modules/studio-media/registration.ts +29 -1
  88. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +90 -6
  89. package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +1 -0
  90. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +23 -5
  91. package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +132 -0
  92. package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +120 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/audio-url.ts +25 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +4 -4
  95. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +4 -4
  96. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +36 -10
  97. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +66 -30
  98. package/templates/app-source/src/workbench-core/index.ts +2 -0
  99. package/templates/app-source/src/workbench-core/runtime-gate.tsx +102 -6
  100. package/templates/app-source/src/workbench-core/workbench-core.css +42 -0
  101. package/templates/app-source/src/workbench-core/workbench-core.tsx +69 -18
  102. package/templates/app-source.manifest.json +100 -0
  103. package/templates/default-starter/AGENTS.md +4 -2
  104. package/templates/default-starter/README.md +2 -1
  105. package/templates/default-starter/src/shell/workbench-target-adapter.ts +102 -12
  106. package/templates/default-starter.manifest.json +0 -4
  107. package/lib/simulator-conformance-ast.mjs +0 -498
  108. package/lib/simulator-conformance-css.mjs +0 -116
  109. package/lib/simulator-conformance-graph.mjs +0 -757
  110. package/lib/simulator-conformance.d.mts +0 -14
  111. package/lib/simulator-conformance.mjs +0 -203
  112. package/lib/simulator-css-profile.d.mts +0 -27
  113. package/lib/simulator-css-profile.mjs +0 -531
  114. package/lib/simulator-kit-export-resolution.mjs +0 -70
  115. package/lib/simulator-manifest.mjs +0 -334
@@ -0,0 +1,204 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-043a
2
+
3
+ // Publisher safety declaration: `nimi.app.yaml.safety_profile` is the only
4
+ // author input. This module owns the closed vocabulary, the structural
5
+ // constraints, and the canonical serialization (key order, list order,
6
+ // deduplication) that every generated copy uses. It never fills, infers, or
7
+ // certifies a value; an absent declaration is "undeclared", not an empty
8
+ // risk list.
9
+
10
+ export const SAFETY_PROFILE_FIELD = 'safety_profile';
11
+ export const SAFETY_PROFILE_MAX_BYTES = 16 * 1024;
12
+
13
+ export const SAFETY_PROFILE_VOCABULARY = Object.freeze({
14
+ intended_audience: Object.freeze(['children', 'general', 'teen', 'adult']),
15
+ content_descriptors: Object.freeze([
16
+ 'sexual-content', 'violence', 'self-harm', 'drugs-alcohol', 'gambling',
17
+ 'hate-harassment', 'frightening-content', 'strong-language', 'unmoderated-shared-content',
18
+ ]),
19
+ risk_features: Object.freeze(['realistic-face-manipulation', 'realistic-voice-replication', 'emotion-recognition', 'biometric-categorization']),
20
+ modality: Object.freeze(['text', 'image', 'audio', 'video', 'virtual-scene']),
21
+ exposure: Object.freeze(['in-app-only', 'exportable', 'publishable']),
22
+ publication_control: Object.freeze(['not-applicable', 'user-confirmed', 'automatic']),
23
+ notice: Object.freeze(['present', 'absent', 'not-applicable']),
24
+ marking: Object.freeze(['present', 'absent']),
25
+ export_visible_marking: Object.freeze(['present', 'absent', 'not-applicable']),
26
+ telemetry: Object.freeze(['crash-diagnostics', 'usage-analytics']),
27
+ third_party_account: Object.freeze(['none', 'optional', 'required']),
28
+ user_content_sharing: Object.freeze(['none', 'private', 'public']),
29
+ commercial_features: Object.freeze(['purchase', 'subscription', 'advertising']),
30
+ sensitive_data_categories: Object.freeze(['precise-location', 'contacts', 'health', 'financial', 'biometric', 'government-identifier']),
31
+ high_impact_decision_uses: Object.freeze([
32
+ 'medical-diagnosis-treatment', 'legal-decision-support', 'employment-decision', 'education-admission-decision',
33
+ 'credit-insurance-decision', 'biometric-identification', 'public-safety-decision',
34
+ ]),
35
+ });
36
+
37
+ const SUBJECT_NOTICE_TRIGGERS = new Set(['emotion-recognition', 'biometric-categorization']);
38
+
39
+ class SafetyProfileError extends Error {
40
+ constructor(field, detail) {
41
+ super(`${field} ${detail}`);
42
+ this.name = 'SafetyProfileError';
43
+ this.field = field;
44
+ }
45
+ }
46
+
47
+ function fail(field, detail) {
48
+ throw new SafetyProfileError(field, detail);
49
+ }
50
+
51
+ function object(value, field, required) {
52
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail(field, 'must be an object');
53
+ const allowed = new Set(required);
54
+ for (const key of Object.keys(value)) if (!allowed.has(key)) fail(`${field}.${key}`, 'is not a supported safety_profile field');
55
+ for (const key of required) if (!Object.hasOwn(value, key)) fail(`${field}.${key}`, 'is required');
56
+ return value;
57
+ }
58
+
59
+ function enumeration(value, field, vocabulary) {
60
+ if (typeof value !== 'string' || !vocabulary.includes(value)) {
61
+ fail(field, `must be one of ${vocabulary.join(', ')}`);
62
+ }
63
+ return value;
64
+ }
65
+
66
+ function boolean(value, field) {
67
+ if (typeof value !== 'boolean') fail(field, 'must be true or false');
68
+ return value;
69
+ }
70
+
71
+ function closedList(value, field, vocabulary) {
72
+ if (!Array.isArray(value)) fail(field, 'must be an explicit list (empty is allowed)');
73
+ const seen = new Set();
74
+ for (const item of value) {
75
+ enumeration(item, field, vocabulary);
76
+ if (seen.has(item)) fail(field, `must not repeat ${item}`);
77
+ seen.add(item);
78
+ }
79
+ // Tool-owned order: the closed vocabulary order, never author order.
80
+ return vocabulary.filter((item) => seen.has(item));
81
+ }
82
+
83
+ function output(value, index) {
84
+ const field = `${SAFETY_PROFILE_FIELD}.ai.outputs[${index}]`;
85
+ object(value, field, ['modality', 'exposure', 'publication_control', 'in_product_notice', 'export_visible_marking', 'machine_readable_marking']);
86
+ const modality = enumeration(value.modality, `${field}.modality`, SAFETY_PROFILE_VOCABULARY.modality);
87
+ const exposure = enumeration(value.exposure, `${field}.exposure`, SAFETY_PROFILE_VOCABULARY.exposure);
88
+ const publicationControl = enumeration(value.publication_control, `${field}.publication_control`, SAFETY_PROFILE_VOCABULARY.publication_control);
89
+ if (exposure === 'publishable' ? publicationControl === 'not-applicable' : publicationControl !== 'not-applicable') {
90
+ fail(`${field}.publication_control`, exposure === 'publishable' ? 'must be user-confirmed or automatic for publishable output' : 'must be not-applicable unless exposure is publishable');
91
+ }
92
+ const exportVisibleMarking = enumeration(value.export_visible_marking, `${field}.export_visible_marking`, SAFETY_PROFILE_VOCABULARY.export_visible_marking);
93
+ if (exposure === 'in-app-only' ? exportVisibleMarking !== 'not-applicable' : exportVisibleMarking === 'not-applicable') {
94
+ fail(`${field}.export_visible_marking`, exposure === 'in-app-only' ? 'must be not-applicable for in-app-only output' : 'must be present or absent for exportable or publishable output');
95
+ }
96
+ return {
97
+ modality,
98
+ exposure,
99
+ publication_control: publicationControl,
100
+ in_product_notice: enumeration(value.in_product_notice, `${field}.in_product_notice`, SAFETY_PROFILE_VOCABULARY.marking),
101
+ export_visible_marking: exportVisibleMarking,
102
+ machine_readable_marking: enumeration(value.machine_readable_marking, `${field}.machine_readable_marking`, SAFETY_PROFILE_VOCABULARY.marking),
103
+ };
104
+ }
105
+
106
+ function ai(value) {
107
+ const field = `${SAFETY_PROFILE_FIELD}.ai`;
108
+ object(value, field, ['direct_interaction', 'interaction_notice', 'risk_features', 'subject_notice', 'outputs']);
109
+ const directInteraction = boolean(value.direct_interaction, `${field}.direct_interaction`);
110
+ const interactionNotice = enumeration(value.interaction_notice, `${field}.interaction_notice`, SAFETY_PROFILE_VOCABULARY.notice);
111
+ if (directInteraction ? interactionNotice === 'not-applicable' : interactionNotice !== 'not-applicable') {
112
+ fail(`${field}.interaction_notice`, directInteraction ? 'must be present or absent when direct_interaction is true' : 'must be not-applicable when direct_interaction is false');
113
+ }
114
+ const riskFeatures = closedList(value.risk_features, `${field}.risk_features`, SAFETY_PROFILE_VOCABULARY.risk_features);
115
+ const subjectNotice = enumeration(value.subject_notice, `${field}.subject_notice`, SAFETY_PROFILE_VOCABULARY.notice);
116
+ const subjectNoticeApplies = riskFeatures.some((item) => SUBJECT_NOTICE_TRIGGERS.has(item));
117
+ if (subjectNoticeApplies ? subjectNotice === 'not-applicable' : subjectNotice !== 'not-applicable') {
118
+ fail(`${field}.subject_notice`, subjectNoticeApplies ? 'must be present or absent when emotion-recognition or biometric-categorization is declared' : 'must be not-applicable without emotion-recognition or biometric-categorization');
119
+ }
120
+ if (!Array.isArray(value.outputs)) fail(`${field}.outputs`, 'must be an explicit list (empty is allowed)');
121
+ const outputs = value.outputs.map(output);
122
+ const modalities = new Set();
123
+ for (const entry of outputs) {
124
+ if (modalities.has(entry.modality)) fail(`${field}.outputs`, `must declare at most one entry for ${entry.modality}`);
125
+ modalities.add(entry.modality);
126
+ }
127
+ outputs.sort((left, right) => SAFETY_PROFILE_VOCABULARY.modality.indexOf(left.modality) - SAFETY_PROFILE_VOCABULARY.modality.indexOf(right.modality));
128
+ return { direct_interaction: directInteraction, interaction_notice: interactionNotice, risk_features: riskFeatures, subject_notice: subjectNotice, outputs };
129
+ }
130
+
131
+ function dataPractices(value) {
132
+ const field = `${SAFETY_PROFILE_FIELD}.data_practices`;
133
+ object(value, field, ['publisher_direct_external_network', 'telemetry', 'third_party_account', 'user_content_sharing', 'commercial_features', 'sensitive_data_categories']);
134
+ return {
135
+ publisher_direct_external_network: boolean(value.publisher_direct_external_network, `${field}.publisher_direct_external_network`),
136
+ telemetry: closedList(value.telemetry, `${field}.telemetry`, SAFETY_PROFILE_VOCABULARY.telemetry),
137
+ third_party_account: enumeration(value.third_party_account, `${field}.third_party_account`, SAFETY_PROFILE_VOCABULARY.third_party_account),
138
+ user_content_sharing: enumeration(value.user_content_sharing, `${field}.user_content_sharing`, SAFETY_PROFILE_VOCABULARY.user_content_sharing),
139
+ commercial_features: closedList(value.commercial_features, `${field}.commercial_features`, SAFETY_PROFILE_VOCABULARY.commercial_features),
140
+ sensitive_data_categories: closedList(value.sensitive_data_categories, `${field}.sensitive_data_categories`, SAFETY_PROFILE_VOCABULARY.sensitive_data_categories),
141
+ };
142
+ }
143
+
144
+ // Canonical form uses sorted object keys (matching the canonical JSON sidecar
145
+ // that Registry and Runtime consume) and closed-vocabulary list order.
146
+ function sortedKeys(value) {
147
+ if (Array.isArray(value)) return value.map(sortedKeys);
148
+ if (!value || typeof value !== 'object') return value;
149
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortedKeys(value[key])]));
150
+ }
151
+
152
+ // Returns the canonical declaration or throws naming the offending field.
153
+ // `undefined` input is not accepted here: callers decide what "absent" means.
154
+ export function normalizeSafetyProfile(value) {
155
+ const field = SAFETY_PROFILE_FIELD;
156
+ object(value, field, ['intended_audience', 'content_descriptors', 'ai', 'data_practices', 'high_impact_decision_uses']);
157
+ const normalized = {
158
+ intended_audience: enumeration(value.intended_audience, `${field}.intended_audience`, SAFETY_PROFILE_VOCABULARY.intended_audience),
159
+ content_descriptors: closedList(value.content_descriptors, `${field}.content_descriptors`, SAFETY_PROFILE_VOCABULARY.content_descriptors),
160
+ ai: ai(value.ai),
161
+ data_practices: dataPractices(value.data_practices),
162
+ high_impact_decision_uses: closedList(value.high_impact_decision_uses, `${field}.high_impact_decision_uses`, SAFETY_PROFILE_VOCABULARY.high_impact_decision_uses),
163
+ };
164
+ if (Buffer.byteLength(JSON.stringify(normalized)) > SAFETY_PROFILE_MAX_BYTES) fail(field, `exceeds ${SAFETY_PROFILE_MAX_BYTES} bytes`);
165
+ return sortedKeys(normalized);
166
+ }
167
+
168
+ export function isCanonicalSafetyProfile(value) {
169
+ try {
170
+ return JSON.stringify(normalizeSafetyProfile(value)) === JSON.stringify(value);
171
+ } catch {
172
+ return false;
173
+ }
174
+ }
175
+
176
+ // Field-level difference between two canonical declarations for review and
177
+ // display. Returns [] when both are absent or equal; an absent side is
178
+ // reported as `undeclared`.
179
+ export function diffSafetyProfiles(before, after) {
180
+ const changes = [];
181
+ const flatten = (value, prefix, into) => {
182
+ if (Array.isArray(value)) {
183
+ if (prefix.endsWith('.outputs')) {
184
+ for (const entry of value) flatten(entry, `${prefix}[${entry.modality}]`, into);
185
+ } else into.set(prefix, value.join(', ') || '[]');
186
+ return;
187
+ }
188
+ if (value && typeof value === 'object') {
189
+ for (const [key, child] of Object.entries(value)) flatten(child, prefix ? `${prefix}.${key}` : key, into);
190
+ return;
191
+ }
192
+ into.set(prefix, String(value));
193
+ };
194
+ const left = new Map();
195
+ const right = new Map();
196
+ if (before !== undefined && before !== null) flatten(before, '', left);
197
+ if (after !== undefined && after !== null) flatten(after, '', right);
198
+ for (const key of new Set([...left.keys(), ...right.keys()])) {
199
+ const previous = left.has(key) ? left.get(key) : 'undeclared';
200
+ const next = right.has(key) ? right.get(key) : 'undeclared';
201
+ if (previous !== next) changes.push({ field: key, before: previous, after: next });
202
+ }
203
+ return changes.sort((a, b) => (a.field < b.field ? -1 : a.field > b.field ? 1 : 0));
204
+ }
@@ -1,6 +1,9 @@
1
1
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-019c
2
2
 
3
3
  import semver from 'semver';
4
+ import { CANONICAL_CAPABILITY_IDS } from './canonical-capability-ids.generated.mjs';
5
+
6
+ const canonicalCapabilityIds = new Set(CANONICAL_CAPABILITY_IDS);
4
7
 
5
8
  function frozenSourceMapping(sourceRoot, targetRoot = sourceRoot) {
6
9
  return Object.freeze({ sourceRoot, targetRoot });
@@ -94,13 +97,13 @@ export const APP_SCAFFOLD_MODULE_REGISTRY = Object.freeze({
94
97
  requires: ['ai-studio-core'],
95
98
  sourceMappings: [frozenSourceMapping('src/studio-modules/studio-media', 'src/capabilities/studio-media')],
96
99
  appAccessItems: ['runtime.consume'],
97
- capabilityContractRefs: ['image.generate', 'video.generate', 'music.generate'],
100
+ capabilityContractRefs: ['image.generate', 'video.generate', 'music.generate', 'music.transcribe', 'audio.voice.convert', 'audio.separate'],
98
101
  requiredStandardizedFeatureRefs: [],
99
102
  npmDependencies: {},
100
103
  cargoDependencies: {},
101
104
  hostAdapterContract: 'ai-studio-host-v1',
102
- views: ['image.generate', 'video.generate', 'music.generate'],
103
- navigation: ['image.generate', 'video.generate', 'music.generate'],
105
+ views: ['image.generate', 'video.generate', 'music.generate', 'music.transcribe', 'audio.voice.convert', 'audio.separate'],
106
+ navigation: ['image.generate', 'video.generate', 'music.generate', 'music.transcribe', 'audio.voice.convert', 'audio.separate'],
104
107
  styles: [],
105
108
  assets: [],
106
109
  productEntry: Object.freeze({
@@ -440,6 +443,11 @@ function assertModuleEntry(id, entry, registry) {
440
443
  assertUniqueStrings(entry.requires, `${id} requires`);
441
444
  assertUniqueStrings(entry.appAccessItems, `${id} appAccessItems`);
442
445
  assertUniqueStrings(entry.capabilityContractRefs || [], `${id} capabilityContractRefs`);
446
+ for (const capability of entry.capabilityContractRefs || []) {
447
+ if (!canonicalCapabilityIds.has(capability)) {
448
+ throw new Error(`App scaffold module references unknown canonical capability: ${id}: ${capability}`);
449
+ }
450
+ }
443
451
  assertUniqueStrings(entry.requiredStandardizedFeatureRefs || [], `${id} requiredStandardizedFeatureRefs`);
444
452
  assertUniqueStrings(entry.views, `${id} views`);
445
453
  assertUniqueStrings(entry.navigation, `${id} navigation`);
@@ -1,5 +1,33 @@
1
+ import path from 'node:path';
2
+
1
3
  export const SUPPORTED_APP_SCAFFOLD_PROFILES = ['standalone'];
2
4
 
5
+ export function rebaseLocalPackagePaths(value, sourceDir, targetDir) {
6
+ // Parsed pnpm documents retain complete locators in overrides, specifiers
7
+ // and resolutions. Reuse those exact strings in package/peer keys instead
8
+ // of guessing whether a parenthesis belongs to a path or a peer suffix.
9
+ const replacements = new Map();
10
+ const collect = (item) => {
11
+ if (typeof item === 'string' && /^file:[^\r\n]+\.(?:tgz|tar\.gz)$/u.test(item)) {
12
+ replacements.set(item, 'file:' + path.relative(targetDir, path.resolve(sourceDir, item.slice(5))).split(path.sep).join('/'));
13
+ } else if (Array.isArray(item)) item.forEach(collect);
14
+ else if (item && typeof item === 'object') Object.values(item).forEach(collect);
15
+ };
16
+ collect(value);
17
+ if (replacements.size === 0) return value;
18
+ const pattern = new RegExp([...replacements.keys()].sort((a, b) => b.length - a.length)
19
+ .map((locator) => locator.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')).join('|'), 'gu');
20
+ const rebase = (text) => text.replace(pattern, (locator) => replacements.get(locator));
21
+ const rewrite = (item) => {
22
+ if (typeof item === 'string') return rebase(item);
23
+ if (Array.isArray(item)) return item.map(rewrite);
24
+ if (item && typeof item === 'object') return Object.fromEntries(Object.entries(item)
25
+ .map(([key, child]) => [rebase(key), rewrite(child)]));
26
+ return item;
27
+ };
28
+ return rewrite(value);
29
+ }
30
+
3
31
  export function resolveWindowsResourceVersion(appVersion) {
4
32
  const semverPattern = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/u;
5
33
  if (typeof appVersion !== 'string' || !semverPattern.test(appVersion)) {
@@ -76,7 +104,11 @@ const DEFAULT_VITE_CONFIG = [
76
104
  'export default defineConfig({',
77
105
  " base: './',",
78
106
  " cacheDir: '.vite',",
79
- ' plugins: [react(), tailwindcss()],',
107
+ ' // The bootstrap creates the root once; only components participate in Fast Refresh.',
108
+ " plugins: [react({ exclude: [/\\/node_modules\\//, /\\/src\\/main\\.tsx$/] }), tailwindcss()],",
109
+ ' server: {',
110
+ " watch: { ignored: ['**/.nimi/local/**', '**/dist/**', '**/dist-electron/**', '**/dist-electron-package/**'] },",
111
+ ' },',
80
112
  ' resolve: {',
81
113
  " dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],",
82
114
  ' },',
@@ -127,15 +159,16 @@ function renderDefaultElectronProductionPackager(identity) {
127
159
  "import { spawn } from 'node:child_process';",
128
160
  "import { copyFile, cp, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';",
129
161
  "import { createRequire } from 'node:module';",
130
- "import { tmpdir } from 'node:os';",
131
162
  "import path from 'node:path';",
132
163
  "import { fileURLToPath } from 'node:url';",
133
164
  "import { packager } from '@electron/packager';",
134
165
  "import { build } from 'esbuild';",
166
+ "import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';",
135
167
  '',
136
168
  `const APP_EXECUTABLE_NAME = ${JSON.stringify(identity.cargoPackageName)};`,
137
169
  `const APP_PRODUCT_NAME = ${JSON.stringify(identity.appTitle)};`,
138
170
  resolveWindowsResourceVersion.toString(),
171
+ rebaseLocalPackagePaths.toString(),
139
172
  "const MACOS_BUILD = process.platform === 'darwin' && process.arch === 'arm64';",
140
173
  "const NATIVE_PLATFORM = MACOS_BUILD ? 'darwin' : 'win32';",
141
174
  "const NATIVE_ARCH = MACOS_BUILD ? 'arm64' : 'x64';",
@@ -168,7 +201,11 @@ function renderDefaultElectronProductionPackager(identity) {
168
201
  'const nativePackageRoot = await findPackageRoot(nativeEntry, NATIVE_BINDING_PACKAGE);',
169
202
  '',
170
203
  'await rm(outputRoot, { recursive: true, force: true });',
171
- "const stagingRoot = await mkdtemp(path.join(tmpdir(), 'nimi-electron-packager-'));",
204
+ '// Use the physical staging root: pnpm canonicalizes cwd before resolving relative tarballs.',
205
+ '// Staging is this project\'s ignored work area, not OS temp; finally removes it.',
206
+ "const stagingParent = path.join(appRoot, '.nimi', 'local', 'build');",
207
+ 'await mkdir(stagingParent, { recursive: true });',
208
+ "const stagingRoot = await realpath(await mkdtemp(path.join(stagingParent, 'electron-')));",
172
209
  "const productionSourceRoot = path.join(stagingRoot, 'app');",
173
210
  "const packagerTempRoot = path.join(stagingRoot, 'packager');",
174
211
  'let packageCompleted = false;',
@@ -192,7 +229,16 @@ function renderDefaultElectronProductionPackager(identity) {
192
229
  '',
193
230
  ' await mkdir(path.join(productionSourceRoot, \'dist-electron\'), { recursive: true });',
194
231
  " await copyFile(path.join(appRoot, 'package.json'), path.join(productionSourceRoot, 'package.json'));",
195
- " await copyFile(path.join(appRoot, 'pnpm-lock.yaml'), path.join(productionSourceRoot, 'pnpm-lock.yaml'));",
232
+ " const dependencyLock = parseYaml(await readFile(path.join(appRoot, 'pnpm-lock.yaml'), 'utf8'));",
233
+ " await writeFile(path.join(productionSourceRoot, 'pnpm-lock.yaml'), stringifyYaml(rebaseLocalPackagePaths(dependencyLock, appRoot, productionSourceRoot)));",
234
+ ' try {',
235
+ " const workspace = parseYaml(await readFile(path.join(appRoot, 'pnpm-workspace.yaml'), 'utf8'));",
236
+ " await writeFile(path.join(productionSourceRoot, 'pnpm-workspace.yaml'), stringifyYaml({ ...rebaseLocalPackagePaths(workspace, appRoot, productionSourceRoot), packages: ['.'] }));",
237
+ " } catch (cause) {",
238
+ " if (cause.code !== 'ENOENT') throw cause;",
239
+ ' // Staging sits inside the project: keep pnpm from adopting an enclosing workspace.',
240
+ " await writeFile(path.join(productionSourceRoot, 'pnpm-workspace.yaml'), stringifyYaml({ packages: ['.'] }));",
241
+ ' }',
196
242
  " await cp(path.join(appRoot, 'dist'), path.join(productionSourceRoot, 'dist'), { recursive: true, force: false });",
197
243
  " await copyFile(path.join(appRoot, 'dist-electron', 'main.js'), path.join(productionSourceRoot, 'dist-electron', 'main.js'));",
198
244
  " await copyFile(path.join(appRoot, 'dist-electron', 'preload.cjs'), path.join(productionSourceRoot, 'dist-electron', 'preload.cjs'));",
@@ -203,6 +249,7 @@ function renderDefaultElectronProductionPackager(identity) {
203
249
  ' delete productionManifest.devDependencies;',
204
250
  " await writeFile(productionManifestPath, `${JSON.stringify(productionManifest, null, 2)}\\n`);",
205
251
  " await rm(path.join(productionSourceRoot, 'pnpm-lock.yaml'));",
252
+ " await rm(path.join(productionSourceRoot, 'pnpm-workspace.yaml'), { force: true });",
206
253
  '',
207
254
  " const installedNativePackage = path.join(productionSourceRoot, 'node_modules', ...NATIVE_BINDING_PACKAGE.split('/'));",
208
255
  ' const nativeDestination = MACOS_BUILD',
@@ -227,7 +274,9 @@ function renderDefaultElectronProductionPackager(identity) {
227
274
  ' tmpdir: packagerTempRoot,',
228
275
  ' overwrite: false,',
229
276
  ' // Native add-ons and their shared libraries must remain accessible to the OS loader.',
230
- " asar: { unpack: '**/*.{node,dylib,dll}' },",
277
+ ' // asar matches absolute paths with matchBase; a slash-free pattern matches file names,',
278
+ " // because '**' does not cross the dot directories of this staging or the App's path.",
279
+ " asar: { unpack: '*.{node,dylib,dll}' },",
231
280
  " ...(MACOS_BUILD ? { extraResource: [path.join(stagingRoot, 'nimi-native')] } : {}),",
232
281
  ' prune: false,',
233
282
  ' quiet: true,',
@@ -236,7 +285,7 @@ function renderDefaultElectronProductionPackager(identity) {
236
285
  ' // Runtime preserves these bytes; Nimi never signs installed third-party code.',
237
286
  ' ...(MACOS_BUILD ? { osxSign: {',
238
287
  " identity: '-', identityValidation: false, preAutoEntitlements: false,",
239
- ' preEmbedProvisioningProfile: false, strictVerify: true,',
288
+ ' preEmbedProvisioningProfile: false, strictVerify: true, continueOnError: false,',
240
289
  " optionsForFile: () => ({ entitlements: [], hardenedRuntime: false, timestamp: 'none' }),",
241
290
  ' } } : {}),',
242
291
  ' beforeAsar: [async ({ buildPath }) => {',
@@ -349,7 +398,9 @@ function renderDefaultMain(identity) {
349
398
  '});',
350
399
  '',
351
400
  "const rendererRoot = document.getElementById('root') as HTMLElement;",
352
- "rendererRoot.classList.add('nimi-workbench-host');",
401
+ '/* Admitted workbench styles use this module scope, including body-portaled controls. */',
402
+ "document.body.classList.add('nimi-ui-module--lab');",
403
+ "rendererRoot.classList.add('nimi-workbench-host', 'nimi-ui-module--lab');",
353
404
  'createRoot(rendererRoot).render(',
354
405
  ' <React.StrictMode>',
355
406
  ` <NimiThemeProvider accentPack="${identity.accentPack}">`,
@@ -720,7 +771,7 @@ function renderGeneratedAIStudioI18n() {
720
771
  'void generatedI18n.init({',
721
772
  ' lng: generatedLocale,',
722
773
  " fallbackLng: 'en',",
723
- ' initImmediate: false,',
774
+ ' initAsync: false,',
724
775
  ' interpolation: { escapeValue: false },',
725
776
  ' resources: {',
726
777
  ' en: { translation: generatedAIStudioMessageBundles.en },',
@@ -753,7 +804,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
753
804
  ' AIStudioHostProvider,',
754
805
  ` ${workspaceExport},`,
755
806
  ' DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES,',
756
- ' boundStudioRunHistoryWithRecord,',
807
+ ' appendStudioRunHistoryRecord,',
757
808
  ' cleanupStudioHistoryArtifacts,',
758
809
  ' clearStudioHistoryWithPolicy,',
759
810
  ' createStudioNonSuccess,',
@@ -868,7 +919,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
868
919
  'async function appendRecord(record: StudioRunHistoryRecord): Promise<AIStudioHistoryProjection> {',
869
920
  ' return mutateHistory(async () => {',
870
921
  ' const current = await loadRunHistory();',
871
- ' const next = boundStudioRunHistoryWithRecord(current, record);',
922
+ ' const next = appendStudioRunHistoryRecord(current, record);',
872
923
  ' return verifyHistoryProjection(await writeRunHistory(next));',
873
924
  ' });',
874
925
  '}',
@@ -878,6 +929,10 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
878
929
  ' return { ok: true as const, projection: await appendRecord(record) };',
879
930
  ' } catch (error) {',
880
931
  ' const paths = studioHistoryArtifactPaths(record);',
932
+ ' if (result.ok && result.output.kind === \'artifacts\' && (result.output.musicGeneration || result.output.musicTranscription || result.output.voiceConversion)) {',
933
+ ' // Music recovery already owns these assets; history is an additional index.',
934
+ ' return { ok: false as const, message: error instanceof Error ? error.message : String(error), retryRecord: true, remainingCleanupPaths: [] };',
935
+ ' }',
881
936
  ' const cleanup = await cleanupArtifacts(paths);',
882
937
  " const message = error instanceof Error ? error.message : String(error || 'History persistence failed.');",
883
938
  ' return {',
@@ -966,14 +1021,16 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
966
1021
  ' return promptDraftStore;',
967
1022
  '}',
968
1023
  '',
969
- 'function downloadBlob(filename: string, blob: Blob): void {',
970
- ' const url = URL.createObjectURL(blob);',
971
- " const anchor = document.createElement('a');",
972
- ' anchor.href = url;',
973
- ' anchor.download = filename;',
974
- ' anchor.click();',
975
- ' queueMicrotask(() => URL.revokeObjectURL(url));',
976
- '}',
1024
+ "const exportText: AIStudioHostPort['app']['commands']['exportText'] = async ({ filename, body }) => {",
1025
+ ' try {',
1026
+ ' const assets = getNimiLocalAppClient().storage.assets;',
1027
+ " const saved = await assets.write({ relativePath: `exports/${crypto.randomUUID()}/${filename}`,",
1028
+ " body: new Blob([body], { type: 'text/plain' }), mediaType: 'text/plain', overwrite: false });",
1029
+ ' let revealed = false;',
1030
+ ' try { await assets.reveal(saved.relativePath); revealed = true; } catch { /* The file remains saved. */ }',
1031
+ ' return { ok: true, value: { filename, artifactPath: saved.relativePath, byteSize: saved.sizeBytes, revealed } };',
1032
+ ' } catch (error) { return { ok: false, error }; }',
1033
+ '};',
977
1034
  '',
978
1035
  'const RUN_STATUS_LABEL_KEYS: Readonly<Record<string, string>> = Object.freeze({',
979
1036
  " ready: 'StudioShell.runStatusReady',",
@@ -1011,7 +1068,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1011
1068
  ' return { ok: false, error };',
1012
1069
  ' }',
1013
1070
  ' },',
1014
- " exportText: async ({ filename, body }) => downloadBlob(filename, new Blob([body], { type: 'text/plain;charset=utf-8' })),",
1071
+ ' exportText,',
1015
1072
  ' },',
1016
1073
  ' },',
1017
1074
  ' sdk: {',
@@ -1029,6 +1086,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1029
1086
  ' createStudioNonSuccess(capability, reason, message, translate, diagnostics)',
1030
1087
  ' ),',
1031
1088
  ' }),',
1089
+ ' deleteLocalAppVoiceAsset: (voiceAssetId) => getNimiLocalAppClient().ai.voiceAssets.delete(voiceAssetId),',
1032
1090
  ' async listLocalAppVoiceAssets() {',
1033
1091
  " const result = await getNimiLocalAppClient().ai.voiceAssets.list({ pageSize: 100, pageToken: '' });",
1034
1092
  ' return result.assets.map((asset) => ({',
@@ -1038,7 +1096,10 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1038
1096
  ' }));',
1039
1097
  ' },',
1040
1098
  ' uploadLocalAppArtifact: (input) => getNimiLocalAppClient().ai.artifacts.upload(input),',
1099
+ ' assets: getNimiLocalAppClient().storage.assets,',
1100
+ ' storage: getNimiLocalAppClient().storage,',
1041
1101
  ' aiConfig: {',
1102
+ ' getSnapshot: () => getNimiLocalAppClient().aiConfig.get(),',
1042
1103
  ' get: () => loadStudioAIConfig({',
1043
1104
  ' get: async () => (await getNimiLocalAppClient().aiConfig.get()).config,',
1044
1105
  ' }, appId),',
@@ -1056,9 +1117,12 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1056
1117
  'function GeneratedAIConfigPanel({',
1057
1118
  ' runtime,',
1058
1119
  ' capabilityId,',
1120
+ ' onCommitted,',
1059
1121
  '}: {',
1060
1122
  ' readonly runtime: StudioRuntimeInspection | null;',
1061
1123
  ' readonly capabilityId: string;',
1124
+ ' // Absent when the App-owned ai-studio-core predates commit reporting.',
1125
+ ' readonly onCommitted?: () => void;',
1062
1126
  '}) {',
1063
1127
  ' const [snapshot, setSnapshot] = useState<NimiAIConfigSnapshot | null>(null);',
1064
1128
  ' const [loading, setLoading] = useState(true);',
@@ -1100,7 +1164,12 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1100
1164
  ' onOverwrite={async (input) => {',
1101
1165
  ' const result = await getNimiLocalAppClient().aiConfig.overwrite(input);',
1102
1166
  ' setSnapshot({ config: result.config, revision: result.revision, effectiveSelections: [] });',
1103
- " if (result.outcome === 'committed') void refresh();",
1167
+ ' // A commit re-reads every mounted consumer, this panel included,',
1168
+ ' // even when the drawer closed before the write finished.',
1169
+ " if (result.outcome === 'committed') {",
1170
+ ' if (onCommitted) onCommitted();',
1171
+ ' else void refresh();',
1172
+ ' }',
1104
1173
  ' return result;',
1105
1174
  ' }}',
1106
1175
  ' onOpenOwnerConfiguration={() => {',
@@ -1216,13 +1285,28 @@ function renderDefaultElectronMain(identity) {
1216
1285
  "import path from 'node:path';",
1217
1286
  "import { fileURLToPath, pathToFileURL } from 'node:url';",
1218
1287
  "import { app, BrowserWindow, ipcMain, Menu, protocol, session, webContents } from 'electron';",
1219
- 'import {',
1288
+ "import { configureNimiElectronAppHostProfile } from '@nimiplatform/kit/shell/electron/host-profile';",
1289
+ '',
1290
+ 'declare const __NIMI_ELECTRON_PRODUCTION__: boolean;',
1291
+ '',
1292
+ '// Bind user data, session data and temp to the Host profile Nimi Desktop',
1293
+ '// prepared under the selected data root, before any session or window and',
1294
+ '// before the rest of Kit loads: a module that failed to load first would',
1295
+ "// leave Electron on its default paths in the OS user's profile.",
1296
+ 'try {',
1297
+ ' configureNimiElectronAppHostProfile(app);',
1298
+ '} catch (error) {',
1299
+ ' process.stderr.write(`[nimi-app-host-profile] ${error instanceof Error ? error.message : String(error)}\\n`);',
1300
+ ' app.exit(78);',
1301
+ ' throw error;',
1302
+ '}',
1303
+ '',
1304
+ 'const {',
1305
+ ' createNimiElectronStandardApplicationMenuTemplate,',
1220
1306
  ' isAllowedElectronRendererUrl,',
1221
1307
  ' registerNimiElectronAppAssetProtocolScheme,',
1222
1308
  ' registerNimiElectronAppBridge,',
1223
- "} from '@nimiplatform/kit/shell/electron/main';",
1224
- '',
1225
- 'declare const __NIMI_ELECTRON_PRODUCTION__: boolean;',
1309
+ "} = await import('@nimiplatform/kit/shell/electron/main');",
1226
1310
  '',
1227
1311
  `const APP_ID = '${identity.appId}';`,
1228
1312
  `const NATIVE_BUNDLE_IDENTIFIER = ${JSON.stringify(identity.nativeBundleIdentifier)};`,
@@ -1235,10 +1319,15 @@ function renderDefaultElectronMain(identity) {
1235
1319
  'const developmentRendererUrl = readDevelopmentRendererUrl();',
1236
1320
  'const rendererUrl = developmentRendererUrl || productionRendererUrl;',
1237
1321
  'const allowedRendererUrls = [rendererUrl];',
1322
+ 'let resettingRenderer = false;',
1323
+ 'let quitting = false;',
1238
1324
  '',
1239
1325
  `app.setName(${JSON.stringify(identity.appTitle)});`,
1240
1326
  'app.setAppUserModelId(NATIVE_BUNDLE_IDENTIFIER);',
1241
- 'Menu.setApplicationMenu(null);',
1327
+ '// macOS routes Cmd+C/V/X/A/Z and Cmd+Q through application menu roles.',
1328
+ 'Menu.setApplicationMenu(Menu.buildFromTemplate(',
1329
+ ` createNimiElectronStandardApplicationMenuTemplate({ appName: ${JSON.stringify(identity.appTitle)} }),`,
1330
+ '));',
1242
1331
  'registerNimiElectronAppAssetProtocolScheme(protocol);',
1243
1332
  '',
1244
1333
  'void app.whenReady().then(async () => {',
@@ -1247,6 +1336,7 @@ function renderDefaultElectronMain(identity) {
1247
1336
  ' allowedRendererUrls,',
1248
1337
  ' assetMediaPlatform: { protocol, webRequest: session.defaultSession.webRequest, webContents },',
1249
1338
  ' ipcMain,',
1339
+ ' onSessionInvalidated: resetAccountScopedRenderer,',
1250
1340
  ' });',
1251
1341
  ' await createMainWindow();',
1252
1342
  ' app.on(\'activate\', () => {',
@@ -1255,8 +1345,23 @@ function renderDefaultElectronMain(identity) {
1255
1345
  '});',
1256
1346
  '',
1257
1347
  "app.on('window-all-closed', () => {",
1258
- " if (process.platform !== 'darwin') app.quit();",
1348
+ " if (process.platform !== 'darwin' && !resettingRenderer && BrowserWindow.getAllWindows().length === 0) app.quit();",
1259
1349
  '});',
1350
+ "app.on('before-quit', () => { quitting = true; });",
1351
+ '',
1352
+ '// A revoked/account-changed scope must not leave renderer timers or queued',
1353
+ '// promises alive to use the rebound Host. This does not run on normal renewal.',
1354
+ 'function resetAccountScopedRenderer(): void {',
1355
+ ' const windows = BrowserWindow.getAllWindows();',
1356
+ ' if (quitting || windows.length === 0) return;',
1357
+ ' resettingRenderer = true;',
1358
+ ' try {',
1359
+ ' for (const window of windows) window.destroy();',
1360
+ ' void createMainWindow().catch((error: unknown) => {',
1361
+ ' process.stderr.write(`[nimi-app-session-reset] ${error instanceof Error ? error.message : String(error)}\\n`);',
1362
+ ' });',
1363
+ ' } finally { resettingRenderer = false; }',
1364
+ '}',
1260
1365
  '',
1261
1366
  'async function createMainWindow(): Promise<void> {',
1262
1367
  ' const window = new BrowserWindow({',
@@ -1277,7 +1382,11 @@ function renderDefaultElectronMain(identity) {
1277
1382
  " window.webContents.on('will-navigate', (event, url) => {",
1278
1383
  ' if (!isAllowedElectronRendererUrl(url, allowedRendererUrls)) event.preventDefault();',
1279
1384
  ' });',
1280
- ' await window.loadURL(rendererUrl);',
1385
+ ' try {',
1386
+ ' await window.loadURL(rendererUrl);',
1387
+ ' } catch (error) {',
1388
+ ' if (!window.isDestroyed()) throw error;',
1389
+ ' }',
1281
1390
  '}',
1282
1391
  '',
1283
1392
  'function readDevelopmentRendererUrl(): string {',