@nimiplatform/app-tools 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +113 -5
  2. package/bin/nimi-app.mjs +4 -0
  3. package/lib/app-doctor-update.mjs +7 -1
  4. package/lib/app-pack.mjs +33 -11
  5. package/lib/app-project-lifecycle.mjs +1 -0
  6. package/lib/app-scaffold-profiles.mjs +29 -14
  7. package/lib/app-scaffold.mjs +53 -7
  8. package/lib/macos-native.mjs +96 -0
  9. package/lib/payload-links.mjs +41 -0
  10. package/package.json +7 -7
  11. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +31 -0
  12. package/templates/app-source/src/ai-studio-core/history-policy.ts +23 -1
  13. package/templates/app-source/src/ai-studio-core/history.ts +7 -1
  14. package/templates/app-source/src/ai-studio-core/messages/en.json +1 -0
  15. package/templates/app-source/src/ai-studio-core/messages/zh.json +1 -0
  16. package/templates/app-source/src/ai-studio-core/module-registration.ts +2 -2
  17. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +6 -2
  18. package/templates/app-source/src/ai-studio-core/run-target.ts +1 -1
  19. package/templates/app-source/src/ai-studio-core/runtime-types.ts +4 -0
  20. package/templates/app-source/src/ai-studio-core/runtime.ts +13 -4
  21. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +3 -3
  22. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +41 -13
  23. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +1 -1
  24. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +1 -0
  25. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +26 -1
  26. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +14 -4
  27. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +3 -1
  28. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +12 -3
  29. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-input.tsx +56 -0
  30. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +22 -0
  31. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +54 -29
  32. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +2 -2
  33. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +1 -0
  34. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +6 -1
  35. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +19 -0
  36. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +19 -0
  37. package/templates/app-source/src/studio-modules/studio-media/registration.ts +10 -1
  38. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +2 -0
  39. package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +18 -0
  40. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +58 -0
  41. package/templates/app-source/src/workbench-core/workbench-core.css +5 -0
  42. package/templates/app-source.manifest.json +16 -0
  43. package/templates/default-starter/README.md +25 -1
@@ -0,0 +1,96 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-024a
2
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-024b
3
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-034a
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { spawnSync } from 'node:child_process';
7
+
8
+ function command(binary, args) {
9
+ const result = spawnSync(binary, args, { encoding: 'utf8', timeout: 60000, maxBuffer: 4 * 1024 * 1024 });
10
+ if (result.error) throw result.error;
11
+ return { status: result.status, text: `${result.stdout || ''}\n${result.stderr || ''}`, stdout: result.stdout || '' };
12
+ }
13
+
14
+ function requireCommand(binary, args) {
15
+ const result = command(binary, args);
16
+ if (result.status !== 0) throw new Error(`${path.basename(binary)} native verification failed: ${result.text.trim()}`);
17
+ return result;
18
+ }
19
+
20
+ export function inspectMacOSMachO(bytes) {
21
+ if (bytes.length < 32 || bytes.readUInt32LE(0) !== 0xfeedfacf || bytes.readUInt32LE(4) !== 0x0100000c || bytes.readUInt32LE(12) !== 2) {
22
+ throw new Error('macOS Runtime entry must be a native arm64 Mach-O executable');
23
+ }
24
+ const count = bytes.readUInt32LE(16);
25
+ const end = 32 + bytes.readUInt32LE(20);
26
+ if (end > bytes.length) throw new Error('Invalid Mach-O load-command extent');
27
+ let cursor = 32;
28
+ let signaturePresent = false;
29
+ for (let index = 0; index < count; index += 1) {
30
+ if (cursor + 8 > end) throw new Error('Invalid Mach-O load command');
31
+ const size = bytes.readUInt32LE(cursor + 4);
32
+ if (size < 8 || cursor + size > end) throw new Error('Invalid Mach-O load-command size');
33
+ if (bytes.readUInt32LE(cursor) === 0x1d) {
34
+ if (signaturePresent || size !== 16) throw new Error('Invalid Mach-O signature command');
35
+ const offset = bytes.readUInt32LE(cursor + 8);
36
+ const signatureSize = bytes.readUInt32LE(cursor + 12);
37
+ if (!signatureSize || offset < end || offset + signatureSize > bytes.length) throw new Error('Invalid Mach-O signature extent');
38
+ signaturePresent = true;
39
+ }
40
+ cursor += size;
41
+ }
42
+ if (cursor !== end) throw new Error('Invalid Mach-O load-command count');
43
+ return { signaturePresent };
44
+ }
45
+
46
+ export function macOSBundleForRuntimeEntry(runtimePath) {
47
+ const executableRoot = path.dirname(runtimePath);
48
+ const contentsRoot = path.dirname(executableRoot);
49
+ const bundleRoot = path.dirname(contentsRoot);
50
+ if (path.basename(executableRoot) !== 'MacOS' || path.basename(contentsRoot) !== 'Contents' || !bundleRoot.endsWith('.app')) {
51
+ throw new Error('macOS Runtime entry must be a direct bundle Contents/MacOS executable');
52
+ }
53
+ return bundleRoot;
54
+ }
55
+
56
+ export function classifyMacOSNativeTrustObservation(observation) {
57
+ if (observation.signature === 'absent' || observation.signature === 'ad-hoc') {
58
+ if (observation.certificateSubject !== null || observation.notarization !== 'absent') throw new Error('macOS absent publisher identity has contradictory native metadata');
59
+ return { posture: 'production-unsigned', macos_developer_id: 'absent', macos_notarization: 'absent', certificate_subject: null };
60
+ }
61
+ if (observation.signature === 'developer-id-valid' && typeof observation.certificateSubject === 'string' && observation.certificateSubject.trim() === observation.certificateSubject && observation.certificateSubject && ['absent', 'notarized'].includes(observation.notarization)) {
62
+ return { posture: 'observed-valid-native-signature', macos_developer_id: 'valid', macos_notarization: observation.notarization, certificate_subject: observation.certificateSubject };
63
+ }
64
+ throw new Error('macOS native signature or notarization is invalid or unresolved');
65
+ }
66
+
67
+ export function observeMacOSExecutableFacts(runtimePath) {
68
+ if (process.platform !== 'darwin' || process.arch !== 'arm64') throw new Error('Production macOS pack must run on macos-aarch64');
69
+ const bundleRoot = macOSBundleForRuntimeEntry(runtimePath);
70
+ const bytes = readFileSync(runtimePath);
71
+ const { signaturePresent } = inspectMacOSMachO(bytes);
72
+ const info = JSON.parse(requireCommand('/usr/bin/plutil', ['-convert', 'json', '-o', '-', path.join(bundleRoot, 'Contents', 'Info.plist')]).stdout);
73
+ if (info.CFBundleExecutable !== path.basename(runtimePath) || Object.hasOwn(info, 'SMPrivilegedExecutables') || existsSync(path.join(bundleRoot, 'Contents', 'Library', 'LaunchDaemons'))) {
74
+ throw new Error('macOS bundle does not satisfy the ordinary current-user execution profile');
75
+ }
76
+ const detail = command('/usr/bin/codesign', ['--display', '--verbose=4', bundleRoot]);
77
+ let observation;
78
+ if (!signaturePresent) {
79
+ if (detail.status === 0 || !/code object is not signed at all/u.test(detail.text)) throw new Error('macOS unsigned observation is unresolved');
80
+ observation = { signature: 'absent', certificateSubject: null, notarization: 'absent' };
81
+ } else {
82
+ if (detail.status !== 0) throw new Error(`macOS code signature is unreadable: ${detail.text.trim()}`);
83
+ requireCommand('/usr/bin/codesign', ['--verify', '--deep', '--strict', bundleRoot]);
84
+ if (/^Signature=adhoc$/mu.test(detail.text)) {
85
+ observation = { signature: 'ad-hoc', certificateSubject: null, notarization: 'absent' };
86
+ } else {
87
+ requireCommand('/usr/bin/codesign', ['--verify', '--strict', '-R=anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.13] exists', bundleRoot]);
88
+ const subject = detail.text.match(/^Authority=(Developer ID Application: .+)$/mu)?.[1];
89
+ if (!subject) throw new Error('macOS publisher signature is not a verified Developer ID identity');
90
+ const ticket = command('/usr/bin/xcrun', ['stapler', 'validate', bundleRoot]);
91
+ if (ticket.status !== 0 && !/does not have a ticket stapled to it/u.test(ticket.text)) throw new Error(`macOS notarization is unresolved: ${ticket.text.trim()}`);
92
+ observation = { signature: 'developer-id-valid', certificateSubject: subject, notarization: ticket.status === 0 ? 'notarized' : 'absent' };
93
+ }
94
+ }
95
+ return { nativeTrust: classifyMacOSNativeTrustObservation(observation), executionProfile: { launch_mode: 'current-user' } };
96
+ }
@@ -0,0 +1,41 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-014a
2
+ import path from 'node:path';
3
+
4
+ export const SYMBOLIC_LINK_MODE = 0o120777;
5
+
6
+ // Electron frameworks contain relative links such as Versions/Current -> A.
7
+ // Resolve against the archive tree, never against the publisher's filesystem.
8
+ export function validatePayloadLinks(entries, os) {
9
+ const directories = new Set();
10
+ for (const name of entries.keys()) {
11
+ for (let parent = path.posix.dirname(name); parent !== '.'; parent = path.posix.dirname(parent)) {
12
+ directories.add(parent);
13
+ }
14
+ }
15
+ for (const name of directories) {
16
+ if (entries.has(name)) throw new Error(`nimiapp file/directory collision: ${name}`);
17
+ }
18
+ const resolve = (name, visited = new Set()) => {
19
+ const parts = name.split('/');
20
+ for (let length = 1; length <= parts.length; length += 1) {
21
+ const prefix = parts.slice(0, length).join('/');
22
+ const entry = entries.get(prefix);
23
+ if (entry?.mode !== SYMBOLIC_LINK_MODE) continue;
24
+ if (visited.has(prefix)) throw new Error(`Cyclic payload symbolic link: ${prefix}`);
25
+ const target = entry.bytes.toString('utf8');
26
+ if (!target || target.includes('\\') || target.includes('\0') || path.posix.isAbsolute(target)) {
27
+ throw new Error(`Invalid payload symbolic link: ${prefix}`);
28
+ }
29
+ const destination = path.posix.normalize(path.posix.join(path.posix.dirname(prefix), target, ...parts.slice(length)));
30
+ if (!destination.startsWith('payload/')) throw new Error(`Payload symbolic link escapes its root: ${prefix}`);
31
+ return resolve(destination, new Set([...visited, prefix]));
32
+ }
33
+ if (!entries.has(name) && !directories.has(name)) throw new Error(`Missing payload symbolic link destination: ${name}`);
34
+ return name;
35
+ };
36
+ for (const [name, entry] of entries) {
37
+ if (entry.mode !== SYMBOLIC_LINK_MODE) continue;
38
+ if (os !== 'macos' || !name.startsWith('payload/')) throw new Error(`Symbolic link is not admitted for this target: ${name}`);
39
+ resolve(name);
40
+ }
41
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nimiplatform/app-tools",
3
- "version": "0.2.8",
3
+ "version": "0.3.0",
4
4
  "description": "Public app-authoring CLI for Nimi App projects.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -18,11 +18,11 @@
18
18
  "provenance": true
19
19
  },
20
20
  "nimiScaffoldVersions": {
21
- "sdkVersion": "^0.9.1",
22
- "appToolsVersion": "^0.2.8",
23
- "nimicodingVersion": "0.6.1",
21
+ "sdkVersion": "^0.10.0",
22
+ "appToolsVersion": "^0.3.0",
23
+ "nimicodingVersion": "0.6.2",
24
24
  "aiSdkVersion": "^6.0.85",
25
- "kitVersion": "^0.5.1",
25
+ "kitVersion": "^0.6.0",
26
26
  "reactVersion": "^19.2.8",
27
27
  "reactDomVersion": "^19.2.8",
28
28
  "i18nextVersion": "^25.10.10",
@@ -57,8 +57,8 @@
57
57
  "sync:app-source": "node scripts/sync-app-source.mjs --apply",
58
58
  "prepack": "pnpm run build",
59
59
  "prepublishOnly": "pnpm run build",
60
- "test": "node scripts/sync-scaffold-versions.mjs --check && node ../scripts/with-workspace-surfaces.mjs -- node --test test/simulator-conformance.test.mjs test/dev-shell.test.mjs && node ../scripts/with-workspace-surfaces.mjs -- node --test test/app-project-lifecycle.test.mjs test/app-pack.test.mjs test/app-scaffold.test.mjs",
61
- "test:full": "node ../scripts/with-workspace-surfaces.mjs -- node --test --test-name-pattern=\"^(sync regenerates|sync rejects|unsupported previous app scaffold lock|check fails closed on a missing scaffold lock|check fails closed on provider/model hardcoding|check fails closed on app-owned Realm permission grant shortcuts|check fails closed on installed-app custody bypasses|check requires official Desktop-supervised development scripts|sync fails closed on unsupported locks and classification conflicts|app source resolves only scaffoldable slices)\" test/app-scaffold.test.mjs"
60
+ "test": "node ../scripts/with-workspace-surfaces.mjs -- pnpm run test:prepared",
61
+ "test:prepared": "node scripts/sync-scaffold-versions.mjs --check && node --test test/simulator-conformance.test.mjs test/dev-shell.test.mjs && node --test test/app-project-lifecycle.test.mjs test/app-pack.test.mjs test/app-scaffold.test.mjs"
62
62
  },
63
63
  "files": [
64
64
  "bin",
@@ -37,6 +37,37 @@
37
37
  .studio-parameters-drawer{ display: none;}
38
38
  .studio-parameters-drawer--open{ display: block; max-height: min(420px, 52cqh); overflow: auto; border-top: 1px solid var(--nimi-border-subtle); padding: 12px 6px 2px 0;}
39
39
  .studio-parameters{ display: grid; gap: 12px;}
40
+ .studio-start--vision{ overflow-y: auto; align-items: start; padding-bottom: 32px;}
41
+ .studio-start--vision .studio-start__center{ gap: 24px;}
42
+ .studio-composer--vision{ gap: 16px;}
43
+ .studio-locate-input{ min-width: 0; overflow: hidden; border-radius: var(--nimi-radius-lg); background: var(--nimi-surface-card);}
44
+ .studio-locate-input__empty{ display: grid; justify-items: center; align-content: center; gap: 12px; min-height: 156px; padding: 24px;}
45
+ .studio-locate-input__empty p{ margin: 0; color: var(--nimi-text-secondary); font-size: 13px; line-height: 1.5; text-align: center;}
46
+ .studio-locate-input__preview{ display: block; width: 100%; height: 220px; object-fit: contain; image-orientation: from-image;}
47
+ .studio-locate-input__file{ display: flex; align-items: center; gap: 8px; padding: 8px 12px;}
48
+ .studio-locate-input__file > span{ flex: 1; min-width: 0; overflow: hidden; color: var(--nimi-text-secondary); font-size: 13px; text-overflow: ellipsis; white-space: nowrap;}
49
+ .studio-locate-input__label{ color: var(--nimi-text-primary); font-size: 13px; font-weight: var(--nimi-type-label-weight);}
50
+ .studio-locate-parameters{ padding: 12px 0;}
51
+ .studio-locate-parameters p{ margin: 0; color: var(--nimi-text-secondary); font-size: 12px; line-height: 1.5;}
52
+ .studio-composer--vision .studio-composer__bar{ flex-wrap: wrap; justify-content: flex-end;}
53
+ .studio-composer--vision .studio-composer__controls{ display: none;}
54
+ .studio-composer--vision .studio-composer__actions{ justify-content: flex-end;}
55
+ .studio-composer--vision.studio-composer--compact{ gap: 10px;}
56
+ .studio-composer--vision.studio-composer--compact .studio-locate-input{ display: grid; grid-template-columns: 100px minmax(0, 1fr); align-items: center;}
57
+ .studio-composer--vision.studio-composer--compact .studio-locate-input__preview{ height: 64px;}
58
+ .studio-composer--vision.studio-composer--compact .studio-locate-input__empty{ grid-column: 1 / -1; min-height: 80px; padding: 12px;}
59
+ .studio-composer--vision.studio-composer--compact .studio-locate-parameters{ padding: 8px 0;}
60
+ .studio-composer--vision.studio-composer--compact .studio-locate-parameters p{ display: none;}
61
+ .studio-composer--vision.studio-composer--compact .studio-input{ padding-bottom: 16px;}
62
+ .studio-locate-result{margin:0;display:grid;gap:12px;min-width:0;}
63
+ .studio-locate-result__image{position:relative;width:100%;overflow:hidden;background:var(--nimi-surface-card);border-radius:var(--nimi-radius-md);}
64
+ .studio-locate-result__image img{display:block;width:100%;height:100%;object-fit:contain;image-orientation:from-image;}
65
+ .studio-locate-result__image svg{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;}
66
+ .studio-locate-result__image rect{fill:transparent;stroke:var(--nimi-accent);stroke-width:3;filter:drop-shadow(0 1px 1px white);}
67
+ .studio-locate-result__image circle{fill:var(--nimi-accent);stroke:white;stroke-width:2;}
68
+ .studio-locate-result details{font-size:13px;}
69
+ .studio-locate-result summary{cursor:pointer;color:var(--nimi-text-secondary);}
70
+ .studio-locate-result pre{max-height:320px;overflow:auto;font-size:12px;}
40
71
  .studio-parameters__head{ display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--nimi-text-muted); font-size: 12px;}
41
72
  .studio-parameters__grid{ display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px;}
42
73
  .studio-parameters__stack{ display: grid; gap: 9px;}
@@ -85,6 +85,20 @@ function validateHistoryResult(value: unknown, path: string): void {
85
85
  return;
86
86
  }
87
87
  optionalString(value.traceId, `${path}.traceId`);
88
+ if (kind === 'vision-locate') {
89
+ requiredString(value.jobId, `${path}.jobId`);
90
+ const result = value.result;
91
+ if (result === undefined) return;
92
+ if (!isJsonObject(result) || typeof result.imageArtifactId !== 'string' || !result.imageArtifactId || !Number.isInteger(result.width) || (result.width as number) <= 0 || !Number.isInteger(result.height) || (result.height as number) <= 0 || !Array.isArray(result.locations)) historyError(path, 'requires a typed Locate result');
93
+ for (const location of result.locations) {
94
+ if (!isJsonObject(location)) historyError(path, 'requires a typed location');
95
+ const axes = location.type === 'box' ? ['x1','y1','x2','y2'] : location.type === 'point' ? ['x','y'] : [];
96
+ if (!axes.length || axes.some(axis => typeof location[axis] !== 'number' || !Number.isFinite(location[axis]) || (location[axis] as number) < 0 || (location[axis] as number) > 1)) historyError(path, 'has invalid Locate coordinates');
97
+ if (location.type === 'box' && !((location.x1 as number) < (location.x2 as number) && (location.y1 as number) < (location.y2 as number))) historyError(path, 'has invalid Locate box ordering');
98
+ optionalString(location.label, `${path}.result.locations.label`);
99
+ }
100
+ return;
101
+ }
88
102
  if (kind === 'text') {
89
103
  requiredString(value.body, `${path}.body`);
90
104
  nonNegativeNumber(value.charCount, `${path}.charCount`);
@@ -213,8 +227,16 @@ export function studioHistoryFromRecords(records: readonly StudioRunHistoryRecor
213
227
  }
214
228
 
215
229
  export function boundStudioRunHistoryWithRecord(history: StudioRunHistory, record: StudioRunHistoryRecord): StudioRunHistory {
230
+ // History has a smaller JSON budget than a complete Runtime Locate result.
231
+ // Preserve the summary/Job reference without mutating the current full result.
232
+ let storedRecord = record;
233
+ if (record.result?.ok && record.result.kind === 'vision-locate' && record.result.result
234
+ && new TextEncoder().encode(JSON.stringify(studioHistoryFromRecords([record]))).byteLength > STUDIO_HISTORY_LIMIT_BYTES) {
235
+ const { result: _locations, ...reference } = record.result;
236
+ storedRecord = { ...record, result: reference };
237
+ }
216
238
  const counts = new Map<string, number>();
217
- const retained = [record, ...flattenStudioHistoryRecords(history).filter((existing) => existing.id !== record.id)]
239
+ const retained = [storedRecord, ...flattenStudioHistoryRecords(history).filter((existing) => existing.id !== record.id)]
218
240
  .sort((left, right) => right.createdAt.localeCompare(left.createdAt))
219
241
  .filter((candidate) => {
220
242
  const count = counts.get(candidate.capabilityId) ?? 0;
@@ -1,4 +1,5 @@
1
1
  import { isJsonObject } from '@nimiplatform/sdk/types';
2
+ import type { NimiLocalAppVisionLocateResult } from '@nimiplatform/sdk/app';
2
3
  import type {
3
4
  StudioCapabilityRunResult,
4
5
  StudioManagedArtifact,
@@ -29,7 +30,7 @@ export type StudioRunTargetStatus =
29
30
  | 'checking'
30
31
  | 'configured'
31
32
  | 'blocked'
32
- | 'tauri-only'
33
+ | 'viewer-only'
33
34
  | 'sdk-gap'
34
35
  | 'not-admitted';
35
36
 
@@ -50,6 +51,7 @@ export type StudioRunConfigSnapshot = {
50
51
  };
51
52
 
52
53
  export type StudioRunHistoryResultSnapshot =
54
+ | { ok: true; kind: 'vision-locate'; summary: string; jobId: string; result?: NimiLocalAppVisionLocateResult; traceId?: string }
53
55
  | {
54
56
  ok: true;
55
57
  kind: 'text';
@@ -456,6 +458,7 @@ export function createStudioRunHistoryResultSnapshot(result: StudioCapabilityRun
456
458
 
457
459
  const trace = traceFields(result);
458
460
  const output = result.output;
461
+ if (output.kind === 'vision-locate') return { ok: true, kind: 'vision-locate', summary: result.message, jobId: output.jobId, result: output.result, ...trace };
459
462
  if (output.kind === 'text') {
460
463
  return {
461
464
  ok: true,
@@ -569,6 +572,7 @@ export function restoreStudioCapabilityRunResult(
569
572
  message: record.message,
570
573
  ...(trace ? { trace } : {}),
571
574
  };
575
+ if (snapshot.kind === 'vision-locate') return snapshot.result ? { ...common, output: { kind: 'vision-locate', jobId: snapshot.jobId, result: snapshot.result } } : null;
572
576
  if (snapshot.kind === 'text') {
573
577
  return {
574
578
  ...common,
@@ -802,6 +806,7 @@ export function getStudioRunMetricSummary(record: StudioRunHistoryRecord): strin
802
806
  if (result.kind === 'artifacts') return `${result.jobState || 'unknown'} / ${result.artifactCount} artifact${result.artifactCount === 1 ? '' : 's'}`;
803
807
  if (result.kind === 'transcript') return `${result.jobState || 'unknown'} / ${result.charCount} chars / ${result.artifactCount} artifact${result.artifactCount === 1 ? '' : 's'}`;
804
808
  if (result.kind === 'voice-asset') return `${result.jobState || 'unknown'} / ${result.creationSource} / ${result.assetStatus}`;
809
+ if (result.kind === 'vision-locate') return result.summary;
805
810
  return `${result.voiceCount} voice${result.voiceCount === 1 ? '' : 's'}`;
806
811
  }
807
812
 
@@ -820,5 +825,6 @@ export function getStudioRunResultTags(record: StudioRunHistoryRecord): string[]
820
825
  if (result.kind === 'artifacts') return ['Ready'];
821
826
  if (result.kind === 'transcript') return ['Ready'];
822
827
  if (result.kind === 'voice-asset') return ['VoiceAsset ready', result.creationSource];
828
+ if (result.kind === 'vision-locate') return result.result ? ['Locate', String(result.result.locations.length)] : ['Locate'];
823
829
  return [`${result.voiceCount} voices`];
824
830
  }
@@ -165,6 +165,7 @@
165
165
  "expandImage": "Expand image",
166
166
  "expandGeneratedImage": "Expand generated image",
167
167
  "imagePreview": "Image preview",
168
+ "imagePreviewFailed": "The image preview could not be opened. Please try again.",
168
169
  "closeImagePreview": "Close image preview",
169
170
  "emptyBody": "(empty body)",
170
171
  "emptyTranscript": "(empty transcript)",
@@ -165,6 +165,7 @@
165
165
  "expandImage": "展开图片",
166
166
  "expandGeneratedImage": "展开生成的图片",
167
167
  "imagePreview": "图片预览",
168
+ "imagePreviewFailed": "无法打开图片预览,请重试。",
168
169
  "closeImagePreview": "关闭图片预览",
169
170
  "emptyBody": "(空内容)",
170
171
  "emptyTranscript": "(空转写)",
@@ -7,7 +7,7 @@ import type { StudioParameterPanelProps } from './parameter-fields.js';
7
7
 
8
8
  export type StudioControlId = 'tone' | 'length';
9
9
  export type StudioInputKind = 'prompt' | 'url' | 'none';
10
- export type StudioResultKind = 'text' | 'transcript' | 'embedding' | 'artifacts' | 'voice-asset' | 'voice-catalog';
10
+ export type StudioResultKind = 'text' | 'transcript' | 'embedding' | 'artifacts' | 'voice-asset' | 'voice-catalog' | 'vision-locate';
11
11
 
12
12
  export type CapabilityStudioProfile = {
13
13
  readonly studioTag: string;
@@ -43,7 +43,7 @@ export type StudioCapabilityDescriptor<TCapabilityId extends string = string> =
43
43
  readonly summary: string;
44
44
  readonly summaryKey: string;
45
45
  readonly surface: string;
46
- readonly execution: 'runtime-sdk' | 'standalone-tauri' | 'typed-unavailable';
46
+ readonly execution: 'runtime-sdk' | 'standalone-electron' | 'typed-unavailable';
47
47
  readonly capabilityContract?: string;
48
48
  readonly missingSurface?: string;
49
49
  };
@@ -29,12 +29,16 @@ export function studioNonSuccessReasonTitle(reason: StudioNonSuccessReason, tran
29
29
  return translate(`NonSuccess.title.${reasonKeySegment(reason)}`);
30
30
  }
31
31
 
32
- export function studioNonSuccessReasonUserMessage(reason: string, translate: StudioTranslate): string {
32
+ export function studioNonSuccessReasonUserMessage(reason: string, translate: StudioTranslate, capabilityId?: string, diagnostics?: StudioNonSuccessDiagnostics): string {
33
+ if (capabilityId === 'vision.locate' && diagnostics?.reasonCode === 'AI_LOCAL_SELECTION_NOT_FOUND') return translate('VisionLocate.modelSelectionRequired');
34
+ if (reason === 'input-invalid' && capabilityId === 'vision.locate') return translate('VisionLocate.invalidInput');
33
35
  const segment = reasonKeySegment(reason);
34
36
  return translate(segment ? `NonSuccess.message.${segment}` : 'NonSuccess.message.fallback');
35
37
  }
36
38
 
37
- export function studioNonSuccessReasonUserAction(reason: string, translate: StudioTranslate): string {
39
+ export function studioNonSuccessReasonUserAction(reason: string, translate: StudioTranslate, capabilityId?: string, diagnostics?: StudioNonSuccessDiagnostics): string {
40
+ if (capabilityId === 'vision.locate' && diagnostics?.reasonCode === 'AI_LOCAL_SELECTION_NOT_FOUND') return translate('VisionLocate.selectModelAction');
41
+ if (reason === 'input-invalid' && capabilityId === 'vision.locate') return translate('VisionLocate.correctInput');
38
42
  const segment = reasonKeySegment(reason);
39
43
  return translate(segment ? `NonSuccess.action.${segment}` : 'NonSuccess.action.fallback');
40
44
  }
@@ -26,7 +26,7 @@ export function createStudioRunTargetSummary(input: {
26
26
  profileOrigin: null,
27
27
  } as const;
28
28
 
29
- if (capability.execution === 'standalone-tauri') {
29
+ if (capability.execution === 'standalone-electron') {
30
30
  throw new Error('Standalone capability run targets must be projected by an app-specific host adapter.');
31
31
  }
32
32
  if (capability.execution === 'typed-unavailable' || !capabilityContract) {
@@ -1,5 +1,7 @@
1
1
  import type { BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
2
2
  import type { StudioParameterValue } from './parameters.js';
3
+ import type { NimiLocalAppVisionLocateResult } from '@nimiplatform/sdk/app';
4
+ import type { NimiRuntimeScenarioJob } from '@nimiplatform/sdk/runtime';
3
5
 
4
6
  export type StudioRuntimeCapabilityDescriptor = {
5
7
  readonly id: string;
@@ -21,6 +23,7 @@ export type StudioManagedArtifact = {
21
23
  };
22
24
 
23
25
  export type StudioTypedOutput =
26
+ | { readonly kind: 'vision-locate'; readonly jobId: string; readonly result: NimiLocalAppVisionLocateResult; readonly imagePreviewUrl?: string }
24
27
  | { readonly kind: 'text'; readonly text: string; readonly finishReason: string; readonly inputTokens?: number; readonly outputTokens?: number; readonly totalTokens?: number; readonly streamed: boolean }
25
28
  | { readonly kind: 'embedding'; readonly vectorCount: number; readonly dimensions: number; readonly sample: number[]; readonly totalTokens?: number }
26
29
  | { readonly kind: 'artifacts'; readonly jobId: string; readonly jobState: string; readonly artifactCount: number; readonly artifacts: StudioManagedArtifact[]; readonly firstArtifact?: StudioManagedArtifact }
@@ -80,6 +83,7 @@ export type StudioCapabilityRunInput = {
80
83
  readonly scenarioId?: string;
81
84
  readonly signal?: AbortSignal;
82
85
  readonly onPartial?: (accumulatedText: string) => void;
86
+ readonly onJobUpdate?: (job: NimiRuntimeScenarioJob) => void;
83
87
  readonly attachments?: BrowserDataUrlAttachment[];
84
88
  readonly directive?: string;
85
89
  readonly parameters?: StudioParameterValue;
@@ -50,6 +50,7 @@ export type StudioRuntimeHost = {
50
50
  readonly appId: string;
51
51
  readonly surfaceId: string;
52
52
  readonly abortReason: string;
53
+ readonly translate: (key: string, values?: Readonly<Record<string, unknown>>) => string;
53
54
  readonly client: NimiLocalAppClient;
54
55
  readonly createScenarioJobClient: typeof createNimiLocalAppRuntimeScenarioJobClient;
55
56
  readonly runners: StudioRuntimeRunnerSet;
@@ -68,6 +69,7 @@ export type StudioCapabilityRuntimeOrchestrator = {
68
69
  readonly appId: string;
69
70
  readonly surfaceId: string;
70
71
  readonly abortReason: string;
72
+ readonly translate: StudioRuntimeHost['translate'];
71
73
  readonly handlers: StudioCapabilityRuntimeHandlers;
72
74
  readonly resolveCapability: (capabilityId: string) => StudioRuntimeCapabilityDescriptor;
73
75
  readonly inspectRuntime: () => Promise<StudioRuntimeInspection>;
@@ -116,6 +118,7 @@ export async function runStudioCapability(
116
118
  appId: orchestrator.appId,
117
119
  surfaceId: orchestrator.surfaceId,
118
120
  abortReason: orchestrator.abortReason,
121
+ translate: orchestrator.translate,
119
122
  client: orchestrator.getClient(),
120
123
  createScenarioJobClient: orchestrator.createScenarioJobClient
121
124
  ?? createNimiLocalAppRuntimeScenarioJobClient,
@@ -240,11 +243,16 @@ export function projectStudioRuntimeError(
240
243
  context: StudioCapabilityRuntimeContext,
241
244
  error: unknown,
242
245
  ): StudioNonSuccess {
246
+ const diagnostics = studioNonSuccessDiagnostics(error);
247
+ // @nimi-authority: rule.nimi.runtime.ai-provider.r126
248
+ const reason = diagnostics?.reasonCode.replaceAll('-', '_').toUpperCase() === 'AI_INPUT_INVALID'
249
+ ? 'input-invalid'
250
+ : studioNonSuccessReason(runtimeScenarioJobNonSuccessReasonFromError(error));
243
251
  return context.host.nonSuccess(
244
252
  context.capability,
245
- studioNonSuccessReason(runtimeScenarioJobNonSuccessReasonFromError(error)),
253
+ reason,
246
254
  studioRuntimeErrorMessage(error),
247
- studioNonSuccessDiagnostics(error),
255
+ diagnostics,
248
256
  );
249
257
  }
250
258
 
@@ -261,8 +269,9 @@ export function studioNonSuccessReason(reason: string): StudioNonSuccessReason {
261
269
  export function studioNonSuccessDiagnostics(error: unknown): StudioNonSuccessDiagnostics | undefined {
262
270
  if (!error || typeof error !== 'object' || Array.isArray(error)) return undefined;
263
271
  const record = error as Record<string, unknown>;
264
- const reasonCode = typeof record.reasonCode === 'string' ? record.reasonCode.trim() : '';
265
- if (!/^[A-Z][A-Z0-9_]{0,127}$/u.test(reasonCode)) return undefined;
272
+ const rawReasonCode = typeof record.reasonCode === 'string' ? record.reasonCode.trim() : '';
273
+ if (!/^(?:[A-Z][A-Z0-9_]{0,127}|[a-z][a-z0-9-]{0,127})$/u.test(rawReasonCode)) return undefined;
274
+ const reasonCode = rawReasonCode.replaceAll('-', '_').toUpperCase();
266
275
  const rawActionHint = typeof record.actionHint === 'string' ? record.actionHint.trim() : '';
267
276
  const actionHint = /^[A-Za-z0-9_.-]{1,256}$/u.test(rawActionHint) ? rawActionHint : '';
268
277
  const rawTraceId = typeof record.traceId === 'string' ? record.traceId.trim() : '';
@@ -4,7 +4,7 @@ import type { StudioRunTargetSummary } from './history.js';
4
4
  import type { StudioTranslate } from './non-success-presentation.js';
5
5
 
6
6
  export type CapabilityStatus = {
7
- label: 'configured' | 'blocked' | 'not admitted' | 'SDK gap' | 'tauri-only' | 'checking';
7
+ label: 'configured' | 'blocked' | 'not admitted' | 'SDK gap' | 'viewer-only' | 'checking';
8
8
  tone: 'success' | 'warning' | 'info' | 'neutral';
9
9
  detail: string;
10
10
  };
@@ -16,8 +16,8 @@ export function statusForCapability(
16
16
  translate: StudioTranslate,
17
17
  ): CapabilityStatus {
18
18
  const capability = registration.descriptor;
19
- if (capability.execution === 'standalone-tauri') {
20
- return { label: 'tauri-only', tone: 'info', detail: target.detail };
19
+ if (capability.execution === 'standalone-electron') {
20
+ return { label: 'viewer-only', tone: 'info', detail: target.detail };
21
21
  }
22
22
  if (capability.execution === 'typed-unavailable') {
23
23
  return { label: 'SDK gap', tone: 'warning', detail: capability.missingSurface || translate('Studio.admission.sdkGapDetail') };
@@ -1,10 +1,11 @@
1
- import { useState, type ChangeEvent, type ReactNode } from 'react';
1
+ import { useId, useState, type ChangeEvent, type ReactNode } from 'react';
2
2
  import { Button, IconButton, NimiText, TextareaField, Tooltip } from '@nimiplatform/kit/ui';
3
- import { ArrowUp, Paperclip, Play, Plus, RefreshCw, SlidersHorizontal, X } from 'lucide-react';
3
+ import { ArrowUp, Paperclip, Play, Plus, RefreshCw, ScanSearch, SlidersHorizontal, X } from 'lucide-react';
4
4
  import type { BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
5
5
  import { useAIStudioHost } from './host-context.js';
6
6
  import type { StudioCapabilityRegistration } from './module-registration.js';
7
7
  import { hasStudioCapabilityRunInput } from './section-ai-testing-input.js';
8
+ import { VisionLocateImageInput } from './section-ai-testing-vision-input.js';
8
9
 
9
10
  function IntentSummaryChip({
10
11
  label,
@@ -86,15 +87,20 @@ export function TextStudioComposer({
86
87
  const { translate: t } = useAIStudioHost();
87
88
  const capability = registration.descriptor;
88
89
  const profile = registration.profile;
90
+ const isVisionLocate = capability.id === 'vision.locate';
91
+ const queryInputId = useId();
89
92
  const isReadOnlyComposer = profile.inputKind === 'none';
90
93
  const requiresPrompt = !isReadOnlyComposer;
91
94
  const contextAttached = Boolean(context.trim());
92
- const supportsContext = requiresPrompt && capability.id !== 'audio.transcribe';
95
+ const supportsContext = requiresPrompt && capability.id !== 'audio.transcribe' && !isVisionLocate;
93
96
  const [contextOpen, setContextOpen] = useState(false);
94
97
  const [parametersOpen, setParametersOpen] = useState(false);
95
- const promptReady = hasStudioCapabilityRunInput({ requiresPrompt, prompt, hasAlternativeInput });
98
+ const promptReady = hasStudioCapabilityRunInput({ requiresPrompt, prompt, hasAlternativeInput })
99
+ && (!isVisionLocate || (attachments.length === 1 && attachments[0]?.kind === 'image'));
96
100
  const intentConfigAction = Boolean(onOpenIntentConfig) && !canDispatch && canConfigureIntent;
97
- const generateDisabled = running || !promptReady || (!canDispatch && !intentConfigAction);
101
+ const generateDisabled = isVisionLocate
102
+ ? running || (!intentConfigAction && (!promptReady || !canDispatch))
103
+ : running || !promptReady || (!canDispatch && !intentConfigAction);
98
104
  const generateLabel = running
99
105
  ? t(profile.primaryRunningLabelKey)
100
106
  : intentConfigAction
@@ -116,7 +122,7 @@ export function TextStudioComposer({
116
122
  {contextAttached ? t('Studio.composer.contextAttached') : t('Studio.composer.context')}
117
123
  </Button>
118
124
  ) : null}
119
- {parameterPanel ? (
125
+ {parameterPanel && !isVisionLocate ? (
120
126
  <Button
121
127
  type="button"
122
128
  tone="ghost"
@@ -136,7 +142,7 @@ export function TextStudioComposer({
136
142
  onOpen={onOpenIntentConfig}
137
143
  configurable={intentConfigurable && Boolean(onOpenIntentConfig)}
138
144
  />
139
- {profile.supportsAttachments ? (
145
+ {profile.supportsAttachments && !isVisionLocate ? (
140
146
  <div className="studio-attachment-strip studio-attachment-strip--icon">
141
147
  <Tooltip content={t('Studio.composer.attachContext')} placement="top">
142
148
  <Button
@@ -173,7 +179,19 @@ export function TextStudioComposer({
173
179
  ))}
174
180
  </div>
175
181
  ) : null}
176
- <Tooltip content={generateLabel} placement="top">
182
+ {isVisionLocate ? (
183
+ <Button
184
+ type="button"
185
+ tone="primary"
186
+ disabled={generateDisabled}
187
+ onClick={intentConfigAction ? onOpenIntentConfig : onSubmit}
188
+ leadingIcon={running
189
+ ? <RefreshCw size={16} aria-hidden="true" className="studio-spin" />
190
+ : <ScanSearch size={16} aria-hidden="true" />}
191
+ >
192
+ {generateLabel}
193
+ </Button>
194
+ ) : <Tooltip content={generateLabel} placement="top">
177
195
  <IconButton
178
196
  type="button"
179
197
  className={intentConfigAction ? 'studio-generate-action studio-generate-action--configure' : 'studio-generate-action'}
@@ -184,26 +202,34 @@ export function TextStudioComposer({
184
202
  onClick={intentConfigAction ? onOpenIntentConfig : onSubmit}
185
203
  icon={running ? <RefreshCw size={15} aria-hidden="true" className="studio-spin" /> : <ArrowUp size={16} aria-hidden="true" />}
186
204
  />
187
- </Tooltip>
205
+ </Tooltip>}
188
206
  </div>
189
207
  </div>
190
208
  );
191
209
  return (
192
- <div className={compact ? 'studio-composer studio-composer--compact' : 'studio-composer'}>
210
+ <div className={`studio-composer${compact ? ' studio-composer--compact' : ''}${isVisionLocate ? ' studio-composer--vision' : ''}`}>
211
+ {isVisionLocate ? <VisionLocateImageInput
212
+ image={attachments[0]?.kind === 'image' ? attachments[0] : undefined}
213
+ disabled={running}
214
+ onChoose={onOpenAttachmentPicker}
215
+ onRemove={() => onRemoveAttachment(0)}
216
+ /> : null}
193
217
  <div className={isReadOnlyComposer ? 'studio-input studio-input--readonly' : 'studio-input'}>
218
+ {isVisionLocate ? <label className="studio-locate-input__label" htmlFor={queryInputId}>{t('VisionLocate.queryLabel')}</label> : null}
194
219
  {isReadOnlyComposer ? (
195
220
  <NimiText role="body" className="studio-input__note">
196
221
  {profile.inputNoteKey ? t(profile.inputNoteKey) : ''}
197
222
  </NimiText>
198
223
  ) : (
199
224
  <TextareaField
225
+ id={queryInputId}
200
226
  tone="quiet"
201
227
  className="rounded-none focus-within:border-transparent focus-within:ring-0"
202
228
  textareaClassName="min-h-[calc(2*1.55em)] resize-none px-0 py-0 text-[15px] leading-[1.55]"
203
229
  rows={2}
204
230
  wrap="soft"
205
231
  maxLength={2000}
206
- aria-label={t('Studio.composer.requestAriaLabel', { capability: t(capability.labelKey) })}
232
+ aria-label={isVisionLocate ? t('VisionLocate.queryLabel') : t('Studio.composer.requestAriaLabel', { capability: t(capability.labelKey) })}
207
233
  placeholder={capability.id === 'text.generate' ? t('Studio.composer.textGeneratePlaceholder') : t(profile.inputPlaceholderKey)}
208
234
  value={prompt}
209
235
  onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onPromptChange(event.currentTarget.value)}
@@ -225,7 +251,9 @@ export function TextStudioComposer({
225
251
  />
226
252
  </div>
227
253
  ) : null}
228
- {parameterPanel ? (
254
+ {parameterPanel && isVisionLocate ? (
255
+ <div className="studio-locate-parameters">{parameterPanel}</div>
256
+ ) : parameterPanel ? (
229
257
  <div className={parametersOpen ? 'studio-parameters-drawer studio-parameters-drawer--open' : 'studio-parameters-drawer'}>
230
258
  {parameterPanel}
231
259
  </div>
@@ -247,7 +275,7 @@ export function TextStudioStartState({
247
275
  const capability = registration.descriptor;
248
276
  const profile = registration.profile;
249
277
  return (
250
- <section className="studio-start" aria-label={t('Studio.composer.startAriaLabel', { capability: t(capability.labelKey) })}>
278
+ <section className={capability.id === 'vision.locate' ? 'studio-start studio-start--vision' : 'studio-start'} aria-label={t('Studio.composer.startAriaLabel', { capability: t(capability.labelKey) })}>
251
279
  <div className="studio-start__center">
252
280
  <h2>{t(profile.inputTitleKey)}</h2>
253
281
  <div className="studio-start__composer">{composer}</div>
@@ -194,7 +194,7 @@ export function CapabilityRunHistory({
194
194
  const historyPanel = useContext(StudioHistoryPanelContext);
195
195
  const locale = rendererHost.locale.startsWith('zh') ? 'zh-CN' : 'en-US';
196
196
  const runtimeHistoryCapabilities = useMemo(() => registrations.filter((item) => (
197
- item.descriptor.execution === 'runtime-sdk' || item.descriptor.execution === 'standalone-tauri'
197
+ item.descriptor.execution === 'runtime-sdk' || item.descriptor.execution === 'standalone-electron'
198
198
  )), [registrations]);
199
199
  const resolveCapabilityLabel = (id: string) => (
200
200
  registrations.find((item) => item.descriptor.id === id)?.descriptor.label ?? null
@@ -15,5 +15,6 @@ export function canCancelStudioCapabilityRun(input: {
15
15
  return input.capabilityId === 'chat.stream'
16
16
  || input.resultKind === 'artifacts'
17
17
  || input.resultKind === 'transcript'
18
+ || input.resultKind === 'vision-locate'
18
19
  || input.resultKind === 'voice-asset';
19
20
  }