@nimiplatform/app-tools 0.14.0 → 0.16.0-rc.9

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 (96) hide show
  1. package/README.md +48 -5
  2. package/bin/nimi-app.mjs +26 -10
  3. package/lib/app-access-declaration.mjs +3 -0
  4. package/lib/app-dependency-combinations.mjs +70 -24
  5. package/lib/app-doctor-update.mjs +92 -36
  6. package/lib/app-host-support.mjs +6 -0
  7. package/lib/app-identifiers.mjs +27 -0
  8. package/lib/app-lifecycle-guidance.mjs +1 -1
  9. package/lib/app-pack.mjs +14 -36
  10. package/lib/app-project-lifecycle.mjs +141 -243
  11. package/lib/app-scaffold-capabilities.mjs +13 -109
  12. package/lib/app-scaffold-profiles.mjs +81 -115
  13. package/lib/app-scaffold.mjs +68 -164
  14. package/lib/app-toolchain-updates.mjs +45 -0
  15. package/lib/canonical-capability-ids.generated.mjs +2 -0
  16. package/lib/development-environment.d.mts +10 -0
  17. package/lib/development-environment.mjs +39 -0
  18. package/lib/hosted-web-release.mjs +98 -0
  19. package/lib/index.mjs +40 -1
  20. package/lib/mobile-development.mjs +19 -0
  21. package/lib/realm-environments.generated.mjs +5 -0
  22. package/lib/web-coordination.mjs +59 -0
  23. package/lib/web-development.d.mts +23 -0
  24. package/lib/web-development.mjs +118 -0
  25. package/lib/web-scaffold.mjs +125 -0
  26. package/package.json +32 -21
  27. package/scripts/dev-shell.mjs +4 -1
  28. package/scripts/sync-scaffold-versions.mjs +0 -2
  29. package/skills/nimi-app-lifecycle/SKILL.md +3 -1
  30. package/skills/nimi-app-lifecycle/references/acceptance.md +6 -2
  31. package/skills/nimi-app-lifecycle/references/adapt.md +5 -3
  32. package/skills/nimi-app-lifecycle/references/audit.md +3 -2
  33. package/skills/nimi-app-lifecycle/references/create.md +6 -2
  34. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +12 -7
  35. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +87 -52
  36. package/templates/app-source/src/ai-studio-core/history-policy.ts +45 -11
  37. package/templates/app-source/src/ai-studio-core/history.ts +22 -11
  38. package/templates/app-source/src/ai-studio-core/host-context.tsx +9 -4
  39. package/templates/app-source/src/ai-studio-core/index.ts +2 -0
  40. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +15 -5
  41. package/templates/app-source/src/ai-studio-core/job-recovery.ts +2 -2
  42. package/templates/app-source/src/ai-studio-core/messages/en.json +73 -19
  43. package/templates/app-source/src/ai-studio-core/messages/zh.json +73 -19
  44. package/templates/app-source/src/ai-studio-core/module-registration.ts +1 -0
  45. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +30 -5
  46. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +12 -6
  47. package/templates/app-source/src/ai-studio-core/parameters.ts +4 -0
  48. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +42 -0
  49. package/templates/app-source/src/ai-studio-core/runtime-types.ts +9 -2
  50. package/templates/app-source/src/ai-studio-core/runtime.ts +8 -4
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +98 -90
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +1 -1
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +205 -48
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +1 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +36 -14
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +96 -75
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +59 -16
  58. package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +2 -0
  59. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +12 -21
  60. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +2 -2
  61. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +3 -3
  62. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +158 -76
  63. package/templates/app-source/src/ai-studio-core/workspace.tsx +49 -22
  64. package/templates/app-source/src/product-modules/agent-center/index.tsx +2 -3
  65. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +2 -3
  66. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +12 -3
  67. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +12 -3
  68. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
  69. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -1
  70. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +47 -5
  71. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +59 -8
  72. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +59 -8
  73. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +2 -1
  74. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +271 -83
  75. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +120 -2
  76. package/templates/app-source/src/studio-modules/studio-media/registration.ts +1 -0
  77. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +24 -14
  78. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +1 -1
  79. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +3 -2
  80. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +3 -2
  81. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +46 -23
  82. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +2 -1
  83. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +2 -2
  84. package/templates/app-source/src/workbench-core/workbench-core.tsx +27 -3
  85. package/templates/default-starter/AGENTS.md +3 -3
  86. package/templates/default-starter/README.md +1 -1
  87. package/templates/default-starter/src/shell/App.tsx +6 -18
  88. package/templates/default-starter/src/shell/auth/local-app-client.ts +6 -15
  89. package/templates/default-starter/src/shell/auth/runtime-platform.ts +7 -107
  90. package/templates/default-starter/src/shell/workbench-target-adapter.ts +9 -126
  91. package/templates/default-starter.manifest.json +0 -16
  92. package/templates/hosted-web-release.yml +88 -0
  93. package/templates/default-starter/src-tauri/Cargo.toml +0 -17
  94. package/templates/default-starter/src-tauri/build.rs +0 -32
  95. package/templates/default-starter/src-tauri/capabilities/default.json +0 -7
  96. package/templates/default-starter/src-tauri/tauri.conf.json +0 -26
@@ -1,3 +1,4 @@
1
+ import { buildWebStarterFiles } from './web-scaffold.mjs';
1
2
  import path from 'node:path';
2
3
  import { readFileSync } from 'node:fs';
3
4
 
@@ -42,6 +43,7 @@ export function resolveWindowsResourceVersion(appVersion) {
42
43
  }
43
44
 
44
45
  export function buildDefaultStarterFiles(identity) {
46
+ if (identity.platform === 'web') return [...buildWebStarterFiles(identity, { productArea: renderDefaultProductArea(identity), navigation: renderDefaultAppNavigation() }), ...buildGeneratedModuleCompositionFiles(identity)];
45
47
  return [
46
48
  {
47
49
  path: 'src/main.tsx',
@@ -59,11 +61,6 @@ export function buildDefaultStarterFiles(identity) {
59
61
  mutationClass: 'app-owned product code',
60
62
  },
61
63
  ...buildGeneratedModuleCompositionFiles(identity),
62
- {
63
- path: 'src-tauri/src/main.rs',
64
- content: renderDefaultTauriMain(),
65
- mutationClass: 'scaffold-managed glue',
66
- },
67
64
  {
68
65
  path: 'src-electron/main.ts',
69
66
  content: renderDefaultElectronMain(identity),
@@ -115,10 +112,11 @@ const DEFAULT_VITE_CONFIG = [
115
112
  'export default defineConfig({',
116
113
  " base: './',",
117
114
  " cacheDir: '.vite',",
115
+ " optimizeDeps: { entries: ['index.html'] },",
118
116
  ' // The bootstrap creates the root once; only components participate in Fast Refresh.',
119
117
  " plugins: [react({ exclude: [/\\/node_modules\\//, /\\/src\\/main\\.tsx$/] }), tailwindcss()],",
120
118
  ' server: {',
121
- " watch: { ignored: ['**/.nimi/local/**', '**/dist/**', '**/dist-electron/**', '**/dist-electron-package/**'] },",
119
+ " watch: { ignored: ['**/.nimi/local/**', '**/dist/**', '**/dist-electron/**', '**/dist-electron-package/**', '**/dist-web/**', '**/dist-mobile/**', '**/android/**/build/**', '**/android/app/src/main/assets/public/**'] },",
122
120
  ' },',
123
121
  ' resolve: {',
124
122
  " dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],",
@@ -314,6 +312,8 @@ function renderDefaultElectronProductionPackager(identity) {
314
312
  " await writeFile(packagedManifestPath, `${JSON.stringify(packagedManifest, null, 2)}\\n`);",
315
313
  ' }],',
316
314
  ' win32metadata: {',
315
+ ' // Match the starter license holder when the App omits its optional author.',
316
+ ' ...(appPackage.author ? {} : { CompanyName: APP_PRODUCT_NAME }),',
317
317
  ' ProductName: APP_PRODUCT_NAME,',
318
318
  ' FileDescription: APP_PRODUCT_NAME,',
319
319
  ' InternalName: APP_EXECUTABLE_NAME,',
@@ -403,9 +403,11 @@ function renderDefaultMain(identity) {
403
403
  ' DEFAULT_DEV_RENDERER_ENTRY_IMPORT_RETRY_DELAYS_MS,',
404
404
  ' createRendererEntryModuleLoader,',
405
405
  "} from '@nimiplatform/kit/shell/renderer/bootstrap';",
406
+ "import { getTargetAppSession, endTargetAppSession } from './shell/workbench-target-adapter.js';",
406
407
  "import './styles.css';",
407
408
  '',
408
409
  'installNimiShellRuntimeBridge();',
410
+ 'const session = getTargetAppSession();',
409
411
  '',
410
412
  'const entryModuleLoader = createRendererEntryModuleLoader({',
411
413
  ' retryDelaysMs: DEFAULT_DEV_RENDERER_ENTRY_IMPORT_RETRY_DELAYS_MS,',
@@ -420,7 +422,8 @@ function renderDefaultMain(identity) {
420
422
  '/* Admitted workbench styles use this module scope, including body-portaled controls. */',
421
423
  "document.body.classList.add('nimi-ui-module--lab');",
422
424
  "rendererRoot.classList.add('nimi-workbench-host', 'nimi-ui-module--lab');",
423
- 'createRoot(rendererRoot).render(',
425
+ 'const reactRoot = createRoot(rendererRoot);',
426
+ 'reactRoot.render(',
424
427
  ' <React.StrictMode>',
425
428
  ` <NimiThemeProvider accentPack="${identity.accentPack}">`,
426
429
  ' <TooltipProvider>',
@@ -431,6 +434,8 @@ function renderDefaultMain(identity) {
431
434
  ' </NimiThemeProvider>',
432
435
  ' </React.StrictMode>,',
433
436
  ');',
437
+ 'void session.start();',
438
+ 'if (import.meta.hot) import.meta.hot.dispose(() => { endTargetAppSession(session); reactRoot.unmount(); });',
434
439
  '',
435
440
  ].join('\n');
436
441
  }
@@ -549,7 +554,7 @@ function buildGeneratedModuleCompositionFiles(identity) {
549
554
  ];
550
555
  if (hasAIStudioResolution(resolution)) {
551
556
  files.push(generatedFile('i18n.ts', renderGeneratedAIStudioI18n()));
552
- files.push(generatedFile('host-adapters.tsx', renderGeneratedAIStudioHostAdapter(resolution)));
557
+ files.push(generatedFile('host-adapters.tsx', renderGeneratedAIStudioHostAdapter(resolution, identity.platform)));
553
558
  }
554
559
  return files;
555
560
  }
@@ -855,7 +860,7 @@ function renderGeneratedAIStudioI18n() {
855
860
  ].join('\n');
856
861
  }
857
862
 
858
- function renderGeneratedAIStudioHostAdapter(resolution) {
863
+ function renderGeneratedAIStudioHostAdapter(resolution, platform = 'desktop') {
859
864
  const core = resolvedAIStudioCore(resolution);
860
865
  const coreImportPath = generatedModuleImportPath(core);
861
866
  const workspaceExport = core.productEntry.componentExport;
@@ -865,30 +870,26 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
865
870
  "import type { NimiAIConfigSnapshot } from '@nimiplatform/sdk/ai';",
866
871
  "import { createNimiClientId } from '@nimiplatform/sdk/types';",
867
872
  "import { ModelConfigAIConfigSurface } from '@nimiplatform/kit/features/model-config';",
868
- "import { openDesktopIntent } from '@nimiplatform/kit/shell/renderer/bridge';",
873
+ platform === 'web' ? "import { requestDownload, downloadAsset, openAssetMediaUrl } from '../../shell/web-download.js';" : "import { openDesktopIntent, openNimiLocalAppAssetMediaUrl } from '@nimiplatform/kit/shell/renderer/bridge';",
869
874
  "import { StatusBadge } from '@nimiplatform/kit/ui';",
870
875
  'import {',
871
876
  ' AIStudioHostProvider,',
872
877
  ` ${workspaceExport},`,
873
878
  ' DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES,',
874
- ' appendStudioRunHistoryRecord,',
875
879
  ' cleanupStudioHistoryArtifacts,',
876
880
  ' clearStudioHistoryWithPolicy,',
877
881
  ' createStudioNonSuccess,',
878
882
  ' createStudioRunTargetSummary,',
879
- ' createEmptyStudioPromptDraftStore,',
883
+ ' createStudioPromptDraftRepository,',
880
884
  ' loadStudioAIConfig,',
881
885
  ' parseAIStudioHistoryPanelPreferences,',
882
- ' parseStudioRunHistory,',
883
- ' parseStudioPromptDraftStore,',
886
+ ' parseStudioRunHistoryRecord,',
887
+ ' studioHistoryFromRecords,',
884
888
  ' projectStudioManagedHistory,',
885
- ' readStudioPromptDraft,',
886
889
  ' requireStudioAIConfigOwner,',
887
890
  ' removeStudioHistoryWithPolicy,',
888
891
  ' runStudioCapability,',
889
892
  ' subscribeStudioAIConfigRefresh,',
890
- ' studioHistoryArtifactPaths,',
891
- ' updateStudioPromptDraftStore,',
892
893
  ' useAIStudioWorkspaceController,',
893
894
  ' type AIStudioHistoryMutationOutcome,',
894
895
  ' type AIStudioHistoryPanelPreferences,',
@@ -896,11 +897,11 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
896
897
  ' type AIStudioHistoryRepository,',
897
898
  ' type AIStudioHostPort,',
898
899
  ' type AIStudioWorkspaceController,',
899
- ' type StudioPromptDraftStore,',
900
900
  ' type StudioRunHistory,',
901
901
  ' type StudioRunHistoryRecord,',
902
902
  ' type StudioRuntimeInspection,',
903
903
  `} from '${coreImportPath}';`,
904
+ "import { createNimiAppRecordStore } from '@nimiplatform/kit/core/app-record-storage';",
904
905
  "import { appId, appTitle } from '../../shell/auth/app-identity.js';",
905
906
  "import { getNimiLocalAppClient } from '../../shell/auth/local-app-client.js';",
906
907
  "import { getRuntimePlatformProjection } from '../../shell/auth/runtime-platform.js';",
@@ -911,10 +912,12 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
911
912
  "import { generatedStudioRuntimeHandlers } from './runtime-registry.js';",
912
913
  "import { generatedLocale, translateGeneratedMessage } from './i18n.js';",
913
914
  '',
914
- "const HISTORY_PATH = 'ai-studio/run-history.v1.json';",
915
- "const PROMPT_DRAFT_STORAGE_KEY = 'nimi.ai-studio.prompt-drafts.v1';",
916
915
  'const translate: AIStudioHostPort[\'translate\'] = translateGeneratedMessage;',
917
916
  '',
917
+ 'function createGeneratedServices(client: ReturnType<typeof getNimiLocalAppClient>) {',
918
+ platform === 'web'
919
+ ? 'const storageScope = appId; // Only non-sensitive panel preferences use browser storage.'
920
+ : "const storageScope = '';",
918
921
  'async function inspectTargetRuntime(): Promise<StudioRuntimeInspection> {',
919
922
  ' const projection = await getRuntimePlatformProjection();',
920
923
  " if (projection.status === 'ready') {",
@@ -940,20 +943,9 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
940
943
  " || normalized.endsWith('_LOCAL_ASSET_NOT_FOUND');",
941
944
  '}',
942
945
  '',
946
+ "const historyRecords = createNimiAppRecordStore(client.storage.assets, 'ai-studio/history', parseStudioRunHistoryRecord);",
943
947
  'async function loadRunHistory(): Promise<StudioRunHistory> {',
944
- ' try {',
945
- ' const document = await getNimiLocalAppClient().storage.readJson(HISTORY_PATH);',
946
- ' return parseStudioRunHistory(document.value);',
947
- ' } catch (error) {',
948
- ' if (isStorageEntryNotFound(error)) return {};',
949
- ' throw error;',
950
- ' }',
951
- '}',
952
- '',
953
- 'async function writeRunHistory(history: StudioRunHistory): Promise<StudioRunHistory> {',
954
- ' const normalized = parseStudioRunHistory(JSON.parse(JSON.stringify(history)) as unknown);',
955
- ' await getNimiLocalAppClient().storage.writeJson(HISTORY_PATH, normalized as never);',
956
- ' return normalized;',
948
+ ' return studioHistoryFromRecords((await historyRecords.list()).sort((a, b) => b.createdAt.localeCompare(a.createdAt)));',
957
949
  '}',
958
950
  '',
959
951
  'let historyMutationTail: Promise<unknown> = Promise.resolve();',
@@ -965,7 +957,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
965
957
  '',
966
958
  'const cleanupArtifacts: AIStudioHistoryRepository[\'cleanupArtifacts\'] = (relativePaths) => cleanupStudioHistoryArtifacts({',
967
959
  ' relativePaths,',
968
- ' removeArtifact: (relativePath) => getNimiLocalAppClient().storage.assets.remove(relativePath),',
960
+ ' removeArtifact: (relativePath) => client.storage.assets.remove(relativePath),',
969
961
  ' isNotFound: isStorageEntryNotFound,',
970
962
  '});',
971
963
  '',
@@ -975,7 +967,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
975
967
  ' resolveCapabilityLabel: (capabilityId) => generatedAIStudioRegistrations.find((entry) => (',
976
968
  ' entry.descriptor.id === capabilityId',
977
969
  ' ))?.descriptor.label ?? capabilityId,',
978
- ' statArtifact: (artifact) => getNimiLocalAppClient().storage.assets.stat(artifact.relativePath),',
970
+ ' statArtifact: (artifact) => client.storage.assets.stat(artifact.relativePath),',
979
971
  ' });',
980
972
  '}',
981
973
  '',
@@ -983,34 +975,23 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
983
975
  ' return verifyHistoryProjection(await loadRunHistory());',
984
976
  '}',
985
977
  '',
986
- 'async function appendRecord(record: StudioRunHistoryRecord): Promise<AIStudioHistoryProjection> {',
978
+ 'async function appendRecord(record: StudioRunHistoryRecord) {',
987
979
  ' return mutateHistory(async () => {',
988
- ' const current = await loadRunHistory();',
989
- ' const next = appendStudioRunHistoryRecord(current, record);',
990
- ' return verifyHistoryProjection(await writeRunHistory(next));',
980
+ ' const saved = await historyRecords.read(record.id);',
981
+ ' if (!saved) await historyRecords.write(record, null);',
982
+ ' try { return await verifyHistoryProjection(await loadRunHistory()); }',
983
+ " catch (error) { return { record: saved ?? record, refreshError: error instanceof Error ? error.message : String(error || 'History refresh failed.') }; }",
991
984
  ' });',
992
985
  '}',
993
986
  '',
994
987
  'async function persistHistory({ result, record }: { readonly result: Parameters<AIStudioHistoryRepository[\'persist\']>[0][\'result\']; readonly record: StudioRunHistoryRecord }) {',
995
988
  ' try {',
996
- ' return { ok: true as const, projection: await appendRecord(record) };',
989
+ ' const saved = await appendRecord(record);',
990
+ " return 'refreshError' in saved ? { ok: true as const, ...saved } : { ok: true as const, projection: saved, record };",
997
991
  ' } catch (error) {',
998
- ' const paths = studioHistoryArtifactPaths(record);',
999
- ' if (result.ok && result.output.kind === \'artifacts\' && (result.output.musicGeneration || result.output.musicTranscription || result.output.voiceConversion)) {',
1000
- ' // Music recovery already owns these assets; history is an additional index.',
1001
- ' return { ok: false as const, message: error instanceof Error ? error.message : String(error), retryRecord: true, remainingCleanupPaths: [] };',
1002
- ' }',
1003
- ' const cleanup = await cleanupArtifacts(paths);',
1004
992
  " const message = error instanceof Error ? error.message : String(error || 'History persistence failed.');",
1005
- ' return {',
1006
- ' ok: false as const,',
1007
- ' message,',
1008
- ' retryRecord: paths.length === 0,',
1009
- ' remainingCleanupPaths: cleanup.remainingCleanupPaths,',
1010
- ' ...(paths.length > 0 ? {',
1011
- " displayFailure: { reason: 'runtime-call-failed' as const, message: `Runtime completed, but managed artifact history persistence failed: ${message}` },",
1012
- ' } : {}),',
1013
- ' };',
993
+ ' // A lost publish response must not delete assets of a committed record.',
994
+ ' return { ok: false as const, message, retryRecord: true, remainingCleanupPaths: [] };',
1014
995
  ' }',
1015
996
  '}',
1016
997
  '',
@@ -1021,9 +1002,12 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1021
1002
  ' history: current,',
1022
1003
  ' recordId,',
1023
1004
  ' deleteAssets,',
1024
- ' removeArtifact: (relativePath) => getNimiLocalAppClient().storage.assets.remove(relativePath),',
1005
+ ' removeArtifact: (relativePath) => client.storage.assets.remove(relativePath),',
1025
1006
  ' isNotFound: isStorageEntryNotFound,',
1026
- ' commit: async (next) => { await writeRunHistory(next); },',
1007
+ ' commit: async (next) => {',
1008
+ ' const retained = new Set(Object.values(next).flat().map(record => record.id));',
1009
+ ' for (const record of Object.values(current).flat()) if (!retained.has(record.id)) await historyRecords.remove(record.id);',
1010
+ ' },',
1027
1011
  ' project: verifyHistoryProjection,',
1028
1012
  ' });',
1029
1013
  ' });',
@@ -1036,9 +1020,12 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1036
1020
  ' history: current,',
1037
1021
  ' capabilityId,',
1038
1022
  ' deleteAssets,',
1039
- ' removeArtifact: (relativePath) => getNimiLocalAppClient().storage.assets.remove(relativePath),',
1023
+ ' removeArtifact: (relativePath) => client.storage.assets.remove(relativePath),',
1040
1024
  ' isNotFound: isStorageEntryNotFound,',
1041
- ' commit: async (next) => { await writeRunHistory(next); },',
1025
+ ' commit: async (next) => {',
1026
+ ' const retained = new Set(Object.values(next).flat().map(record => record.id));',
1027
+ ' for (const record of Object.values(current).flat()) if (!retained.has(record.id)) await historyRecords.remove(record.id);',
1028
+ ' },',
1042
1029
  ' project: verifyHistoryProjection,',
1043
1030
  ' });',
1044
1031
  ' });',
@@ -1047,13 +1034,13 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1047
1034
  "const HISTORY_PANEL_STORAGE_KEY = 'nimi.ai-studio.history-panel.v1';",
1048
1035
  'function loadPanelPreferences(): AIStudioHistoryPanelPreferences {',
1049
1036
  ' try {',
1050
- ' const raw = globalThis.localStorage?.getItem(HISTORY_PANEL_STORAGE_KEY);',
1037
+ ' const raw = globalThis.localStorage?.getItem(HISTORY_PANEL_STORAGE_KEY + storageScope);',
1051
1038
  ' if (!raw) return DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES;',
1052
1039
  ' return parseAIStudioHistoryPanelPreferences(JSON.parse(raw));',
1053
1040
  ' } catch { return DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES; }',
1054
1041
  '}',
1055
1042
  'function savePanelPreferences(preferences: AIStudioHistoryPanelPreferences): void {',
1056
- ' try { globalThis.localStorage?.setItem(HISTORY_PANEL_STORAGE_KEY, JSON.stringify(preferences)); } catch { /* UI state remains session-local. */ }',
1043
+ ' try { globalThis.localStorage?.setItem(HISTORY_PANEL_STORAGE_KEY + storageScope, JSON.stringify(preferences)); } catch { /* UI state remains session-local. */ }',
1057
1044
  '}',
1058
1045
  '',
1059
1046
  'const historyRepository: AIStudioHistoryRepository = Object.freeze({',
@@ -1068,37 +1055,25 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1068
1055
  ' savePanelPreferences,',
1069
1056
  '});',
1070
1057
  '',
1071
- 'let promptDraftStore = readPromptDraftStore();',
1072
- '',
1073
- 'function readPromptDraftStore(): StudioPromptDraftStore {',
1074
- ' try {',
1075
- ' const raw = globalThis.localStorage?.getItem(PROMPT_DRAFT_STORAGE_KEY);',
1076
- ' if (!raw) return createEmptyStudioPromptDraftStore();',
1077
- ' return parseStudioPromptDraftStore(JSON.parse(raw));',
1078
- ' } catch {',
1079
- ' return createEmptyStudioPromptDraftStore();',
1080
- ' }',
1081
- '}',
1082
- '',
1083
- 'async function savePromptDraft(key: Parameters<AIStudioHostPort[\'app\'][\'commands\'][\'savePromptDraft\']>[0], prompt: string, enabled: boolean) {',
1084
- ' const next = updateStudioPromptDraftStore(promptDraftStore, key, prompt, enabled);',
1085
- ' if (next === promptDraftStore) return promptDraftStore;',
1086
- ' promptDraftStore = next;',
1087
- ' try { globalThis.localStorage?.setItem(PROMPT_DRAFT_STORAGE_KEY, JSON.stringify(promptDraftStore)); } catch { /* UI state remains session-local. */ }',
1088
- ' return promptDraftStore;',
1089
- '}',
1058
+ 'const promptDrafts = createStudioPromptDraftRepository(client.storage);',
1090
1059
  '',
1060
+ ...(platform === 'web' ? [
1061
+ "const exportText: AIStudioHostPort['app']['commands']['exportText'] = async ({ filename, body }) => {",
1062
+ " try { return { ok: true, value: requestDownload(filename, new Blob([body], { type: 'text/plain' })) }; } catch (error) { return { ok: false, error }; }",
1063
+ '};', '',
1064
+ ] : [
1091
1065
  "const exportText: AIStudioHostPort['app']['commands']['exportText'] = async ({ filename, body }) => {",
1092
1066
  ' try {',
1093
- ' const assets = getNimiLocalAppClient().storage.assets;',
1067
+ ' const assets = client.storage.assets;',
1094
1068
  " const saved = await assets.write({ relativePath: `exports/${crypto.randomUUID()}/${filename}`,",
1095
1069
  " body: new Blob([body], { type: 'text/plain' }), mediaType: 'text/plain', overwrite: false });",
1096
1070
  ' let revealed = false;',
1097
1071
  ' try { await assets.reveal(saved.relativePath); revealed = true; } catch { /* The file remains saved. */ }',
1098
- ' return { ok: true, value: { filename, artifactPath: saved.relativePath, byteSize: saved.sizeBytes, revealed } };',
1072
+ " return { ok: true, value: { destination: 'runtime-asset', filename, artifactPath: saved.relativePath, byteSize: saved.sizeBytes, revealed } };",
1099
1073
  ' } catch (error) { return { ok: false, error }; }',
1100
1074
  '};',
1101
1075
  '',
1076
+ ]),
1102
1077
  'const RUN_STATUS_LABEL_KEYS: Readonly<Record<string, string>> = Object.freeze({',
1103
1078
  " ready: 'StudioShell.runStatusReady',",
1104
1079
  " unavailable: 'StudioShell.runStatusUnavailable',",
@@ -1118,7 +1093,8 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1118
1093
  ' clock: { now: () => Date.now() },',
1119
1094
  ' app: {',
1120
1095
  ' projection: {',
1121
- ' promptDraft: (key, enabled) => ({ prompt: readStudioPromptDraft(promptDraftStore, key, enabled) }),',
1096
+ ' promptDraft: promptDrafts.load,',
1097
+ ` assetExportAction: () => '${platform === 'web' ? 'download' : 'reveal'}',`,
1122
1098
  ' projectRunTarget: createStudioRunTargetSummary,',
1123
1099
  ' runStatusLabel,',
1124
1100
  ' },',
@@ -1126,7 +1102,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1126
1102
  ' subscribeAIConfigRefresh: (listener) => subscribeStudioAIConfigRefresh(listener, window, document),',
1127
1103
  ' },',
1128
1104
  ' commands: {',
1129
- ' savePromptDraft,',
1105
+ ' savePromptDraft: promptDrafts.save,',
1130
1106
  ' async copyText(text) {',
1131
1107
  ' try {',
1132
1108
  ' await navigator.clipboard.writeText(text);',
@@ -1136,6 +1112,8 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1136
1112
  ' }',
1137
1113
  ' },',
1138
1114
  ' exportText,',
1115
+ platform === 'web' ? ' exportAsset: async relativePath => { await downloadAsset(relativePath); },' : ' exportAsset: async (relativePath) => { await client.storage.assets.reveal(relativePath); },',
1116
+ platform === 'web' ? ' openAssetMediaUrl,' : ' openAssetMediaUrl: openNimiLocalAppAssetMediaUrl,',
1139
1117
  ' },',
1140
1118
  ' },',
1141
1119
  ' sdk: {',
@@ -1147,34 +1125,36 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1147
1125
  ' handlers: generatedStudioRuntimeHandlers,',
1148
1126
  ' resolveCapability: (capabilityId) => generatedAIStudioComposition.getCapability(capabilityId).descriptor,',
1149
1127
  ' inspectRuntime: inspectTargetRuntime,',
1150
- ' getClient: getNimiLocalAppClient,',
1128
+ ' getClient: () => client,',
1151
1129
  " createScenarioId: (capability) => `studio:${capability.id}`,",
1152
1130
  ' nonSuccess: (capability, reason, message, diagnostics) => (',
1153
1131
  ' createStudioNonSuccess(capability, reason, message, translate, diagnostics)',
1154
1132
  ' ),',
1155
1133
  ' }),',
1156
- ' deleteLocalAppVoiceAsset: (voiceAssetId) => getNimiLocalAppClient().ai.voiceAssets.delete(voiceAssetId),',
1134
+ ' deleteLocalAppVoiceAsset: (voiceAssetId) => client.ai.voiceAssets.delete(voiceAssetId),',
1157
1135
  ' async listLocalAppVoiceAssets() {',
1158
- " const result = await getNimiLocalAppClient().ai.voiceAssets.list({ pageSize: 100, pageToken: '' });",
1136
+ " const result = await client.ai.voiceAssets.list({ pageSize: 100, pageToken: '' });",
1159
1137
  ' return result.assets.map((asset) => ({',
1160
1138
  ' voiceAssetId: asset.voiceAssetId,',
1161
1139
  ' creationSource: asset.creationSource,',
1162
1140
  ' status: asset.status,',
1163
1141
  ' }));',
1164
1142
  ' },',
1165
- ' uploadLocalAppArtifact: (input) => getNimiLocalAppClient().ai.artifacts.upload(input),',
1166
- ' assets: getNimiLocalAppClient().storage.assets,',
1167
- ' storage: getNimiLocalAppClient().storage,',
1143
+ ' uploadLocalAppArtifact: (input) => client.ai.artifacts.upload(input),',
1144
+ ' assets: client.storage.assets,',
1145
+ ' storage: client.storage,',
1168
1146
  ' aiConfig: {',
1169
- ' getSnapshot: () => getNimiLocalAppClient().aiConfig.get(),',
1147
+ ' getSnapshot: () => client.aiConfig.get(),',
1170
1148
  ' get: () => loadStudioAIConfig({',
1171
- ' get: async () => (await getNimiLocalAppClient().aiConfig.get()).config,',
1149
+ ' get: async () => (await client.aiConfig.get()).config,',
1172
1150
  ' }, appId),',
1173
1151
  ' },',
1174
- ' revealLocalAppAsset: (relativePath) => getNimiLocalAppClient().storage.assets.reveal(relativePath),',
1175
1152
  ' },',
1176
1153
  '};',
1177
1154
  '',
1155
+ 'return { hostValue, historyRepository, inspectTargetRuntime };',
1156
+ '}',
1157
+ '',
1178
1158
  'const generatedCapabilityContracts = Object.freeze([',
1179
1159
  ' ...new Set(generatedAIStudioRegistrations.flatMap((registration) => (',
1180
1160
  ' registration.descriptor.capabilityContract ? [registration.descriptor.capabilityContract] : []',
@@ -1191,6 +1171,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1191
1171
  ' // Absent when the App-owned ai-studio-core predates commit reporting.',
1192
1172
  ' readonly onCommitted?: () => void;',
1193
1173
  '}) {',
1174
+ ' const [client] = useState(getNimiLocalAppClient);',
1194
1175
  ' const [snapshot, setSnapshot] = useState<NimiAIConfigSnapshot | null>(null);',
1195
1176
  ' const [loading, setLoading] = useState(true);',
1196
1177
  ' const [loadError, setLoadError] = useState<string | null>(null);',
@@ -1198,7 +1179,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1198
1179
  ' setLoading(true);',
1199
1180
  ' setLoadError(null);',
1200
1181
  ' try {',
1201
- ' const next = await getNimiLocalAppClient().aiConfig.get();',
1182
+ ' const next = await client.aiConfig.get();',
1202
1183
  ' if (next.config) requireStudioAIConfigOwner(next.config, appId);',
1203
1184
  ' setSnapshot(next);',
1204
1185
  ' } catch (error) {',
@@ -1224,12 +1205,12 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1224
1205
  ' capabilities={snapshot?.config ? snapshot.config.capabilities as never : snapshot ? null : undefined}',
1225
1206
  ' revision={snapshot?.revision}',
1226
1207
  ' effectiveSelections={snapshot?.effectiveSelections}',
1227
- ' listOptions={(query) => getNimiLocalAppClient().aiConfig.listOptions(query)}',
1208
+ ' listOptions={(query) => client.aiConfig.listOptions(query)}',
1228
1209
  ' loading={loading && !snapshot}',
1229
1210
  ' loadError={loadError}',
1230
1211
  ' onRetry={() => { void refresh(); }}',
1231
1212
  ' onOverwrite={async (input) => {',
1232
- ' const result = await getNimiLocalAppClient().aiConfig.overwrite(input);',
1213
+ ' const result = await client.aiConfig.overwrite(input);',
1233
1214
  ' setSnapshot({ config: result.config, revision: result.revision, effectiveSelections: [] });',
1234
1215
  ' // A commit re-reads every mounted consumer, this panel included,',
1235
1216
  ' // even when the drawer closed before the write finished.',
@@ -1239,12 +1220,14 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1239
1220
  ' }',
1240
1221
  ' return result;',
1241
1222
  ' }}',
1223
+ ...(platform === 'web' ? [] : [
1242
1224
  ' onOpenOwnerConfiguration={() => {',
1243
1225
  ' void openDesktopIntent({',
1244
1226
  " requestId: createNimiClientId('desktop-open'),",
1245
1227
  " intent: { kind: 'open-apps', appId, section: 'ai-models' },",
1246
1228
  ' });',
1247
1229
  ' }}',
1230
+ ]),
1248
1231
  ' copy={{',
1249
1232
  " title: translate('StudioModelConfig.drawerTitle'),",
1250
1233
  " description: translate('StudioModelConfig.drawerDescription', { appTitle }),",
@@ -1274,6 +1257,7 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1274
1257
  ' readonly onSelectCapability: (capabilityId: string, runId?: string) => void;',
1275
1258
  ' readonly children: ReactNode;',
1276
1259
  '}) {',
1260
+ ' const [{ hostValue, historyRepository, inspectTargetRuntime }] = useState(() => createGeneratedServices(getNimiLocalAppClient()));',
1277
1261
  ' const snapshot = useNimiNavigationSnapshot<{ id: string; runId?: string }>();',
1278
1262
  ' const [runtime, setRuntime] = useState<StudioRuntimeInspection | null>(null);',
1279
1263
  ' useEffect(() => {',
@@ -1330,25 +1314,6 @@ function renderGeneratedAIStudioHostAdapter(resolution) {
1330
1314
  ].join('\n');
1331
1315
  }
1332
1316
 
1333
- function renderDefaultTauriMain() {
1334
- return [
1335
- 'fn main() {',
1336
- ' tauri::Builder::default()',
1337
- ' .setup(|app| {',
1338
- ' use tauri::Manager;',
1339
- ' app.manage(',
1340
- ' nimi_shell_tauri::capabilities::runtime::RuntimeBridgeLocalAppHost::platform_default(),',
1341
- ' );',
1342
- ' Ok(())',
1343
- ' })',
1344
- ' .invoke_handler(nimi_shell_tauri::nimi_shell_tauri_local_app_standard_shell_handler![])',
1345
- ' .run(tauri::generate_context!())',
1346
- ' .expect("failed to run Nimi App shell");',
1347
- '}',
1348
- '',
1349
- ].join('\n');
1350
- }
1351
-
1352
1317
  function renderDefaultElectronMain(identity) {
1353
1318
  return [
1354
1319
  "import path from 'node:path';",
@@ -1403,6 +1368,7 @@ function renderDefaultElectronMain(identity) {
1403
1368
  'const chromeHost = createNimiElectronAppChromeHost({',
1404
1369
  ` metadata: { name: ${JSON.stringify(identity.appTitle)}, version: ${JSON.stringify(identity.version)} },`,
1405
1370
  ' allowedRendererUrls, app,',
1371
+ " appCommands: [{ id: 'app.nimi-account', menu: 'file', labels: { en: 'Nimi account', zh: 'Nimi 账号' } }],",
1406
1372
  ' menu: { buildFromTemplate: template => Menu.buildFromTemplate(template as Electron.MenuItemConstructorOptions[]), setApplicationMenu: menu => Menu.setApplicationMenu(menu as Electron.Menu | null) },',
1407
1373
  '});',
1408
1374
  'registerNimiElectronAppAssetProtocolScheme(protocol);',