@mica-js/editor 0.14.0 → 0.15.1

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.
@@ -4,6 +4,7 @@ import { timePs, toTimePs } from "@mica-js/core";
4
4
  import { parseFusedDocument, parseGeometry2D, parseStrictJson } from "@mica-js/document/fused";
5
5
  import { FusedPreparationError, PreparationError, createHeadlessRuntime, createProgramFiles, openDevicePackage, readonlyBytes, resolveInstanceProperties } from "@mica-js/sdk/fused";
6
6
  import { createRpc, defineRpcService } from "@mica-js/core/rpc";
7
+ import { loggerService } from "@mica-js/core/logging";
7
8
  import { WidgetAudioEngine } from "@mica-js/widget/audio-host";
8
9
  import { createWidgetAudioRuntime } from "@mica-js/widget/audio-guest";
9
10
  //#region src/fused/runtime/protocol.ts
@@ -137,6 +138,94 @@ function connectFusedAudio(rpc, display, options, report) {
137
138
  };
138
139
  }
139
140
  //#endregion
141
+ //#region src/fused/runtime/observability.ts
142
+ var fusedHostPerformanceService = defineRpcService("fused-host-performance");
143
+ var levels = [
144
+ "debug",
145
+ "info",
146
+ "warn",
147
+ "error"
148
+ ];
149
+ /** Runtime errors already written before a workbench command receives their rejection. */
150
+ var loggedStartupFailures = /* @__PURE__ */ new WeakSet();
151
+ function writeFusedLog(options, source, record) {
152
+ if (options === void 0 || levels.indexOf(record.level) < levels.indexOf(options.logLevel ?? "info")) return;
153
+ try {
154
+ options.onLog?.({
155
+ ...record,
156
+ source,
157
+ receivedAt: Date.now()
158
+ });
159
+ } catch (cause) {
160
+ console.error("[mica] Workbench log sink failed", cause);
161
+ }
162
+ }
163
+ function writeWorkbenchConsole(record) {
164
+ const { receivedAt, level, source, scope, code, message, runId, sessionId, instanceId, fields, data } = record;
165
+ const prefix = `${new Date(receivedAt).toISOString().slice(11, 23)} ${level.toUpperCase()} [${source}/${scope}]`;
166
+ const details = {
167
+ ...runId === void 0 ? {} : { runId },
168
+ ...sessionId === void 0 ? {} : { sessionId },
169
+ ...instanceId === void 0 ? {} : { instanceId },
170
+ ...fields
171
+ };
172
+ console[level]("%s", `${prefix} ${code === void 0 ? "" : `${code} `}${message}`, ...Object.keys(details).length === 0 ? [] : [details], ...data);
173
+ }
174
+ var nextMark = 0;
175
+ function startStartupSpan(phase, trace, startedAt = performance.now()) {
176
+ if (!trace) return () => performance.now() - startedAt;
177
+ const start = `mica:${phase}:start:${++nextMark}`;
178
+ const measure = `mica:${phase}`;
179
+ performance.mark(start, { startTime: startedAt });
180
+ return () => {
181
+ try {
182
+ return performance.measure(measure, start).duration;
183
+ } finally {
184
+ performance.clearMarks(start);
185
+ performance.clearMeasures(measure);
186
+ }
187
+ };
188
+ }
189
+ function summarizeStartup(samples) {
190
+ const groups = /* @__PURE__ */ new Map();
191
+ for (const { phase, kind, warmup, packageId, version, outcome, durationMs } of samples) {
192
+ const key = {
193
+ phase,
194
+ ...kind === void 0 ? {} : { kind },
195
+ ...warmup === void 0 ? {} : { warmup },
196
+ ...packageId === void 0 ? {} : { packageId },
197
+ ...version === void 0 ? {} : { version }
198
+ };
199
+ const id = JSON.stringify(key);
200
+ let group = groups.get(id);
201
+ if (group === void 0) {
202
+ group = {
203
+ key,
204
+ durations: [],
205
+ failed: 0,
206
+ cancelled: 0
207
+ };
208
+ groups.set(id, group);
209
+ }
210
+ if (outcome === "success") group.durations.push(durationMs);
211
+ else if (outcome === "failure") group.failed++;
212
+ else group.cancelled++;
213
+ }
214
+ return Array.from(groups.values(), ({ key, durations, failed, cancelled }) => {
215
+ durations.sort((a, b) => a - b);
216
+ const count = durations.length;
217
+ return {
218
+ ...key,
219
+ count,
220
+ failed,
221
+ cancelled,
222
+ p50Ms: durations[Math.ceil(count * .5) - 1] ?? null,
223
+ p95Ms: durations[Math.ceil(count * .95) - 1] ?? null,
224
+ maxMs: durations[count - 1] ?? null
225
+ };
226
+ });
227
+ }
228
+ //#endregion
140
229
  //#region src/fused/runtime/host/connection.ts
141
230
  /**
142
231
  * Worker wiring of one fused workbench (RFC 0025).
@@ -155,6 +244,15 @@ async function connectFusedWorkbench(options) {
155
244
  let displayRpc;
156
245
  try {
157
246
  await Promise.all([simulationWorker.ready, displayWorker.ready]);
247
+ for (const [worker, source] of [[simulationWorker, "simulation"], [displayWorker, "display"]]) {
248
+ const unsubscribe = worker.onError?.(({ message }) => {
249
+ options.onDiagnostic?.({
250
+ code: "runtime/guest-error",
251
+ message
252
+ }, source);
253
+ });
254
+ if (unsubscribe !== void 0) subscriptions.push(unsubscribe);
255
+ }
158
256
  const simulationChannel = new MessageChannel();
159
257
  const displayChannel = new MessageChannel();
160
258
  const modelChannel = new MessageChannel();
@@ -164,10 +262,15 @@ async function connectFusedWorkbench(options) {
164
262
  displayRpc = createRpc(displayChannel.port1);
165
263
  registerHostServices(simulationRpc, options);
166
264
  registerHostServices(displayRpc, options);
265
+ for (const [rpc, source] of [[simulationRpc, "simulation"], [displayRpc, "display"]]) {
266
+ rpc.register(loggerService, { write: (record) => writeFusedLog(options.observability, source, record) });
267
+ rpc.onDidClose(() => options.onDisconnect?.(source));
268
+ }
269
+ simulationRpc.register(fusedHostPerformanceService, { record: (sample) => options.observability?.onSample?.(sample) });
167
270
  const simulation = simulationRpc.getProxy(fusedSimulationService, { transfer: transferDeviceState });
168
271
  const display = displayRpc.getProxy(fusedDisplayService, { transfer: (member, args) => member === "attachAudio" ? [args[0]] : [] });
169
- const audio = connectFusedAudio(displayRpc, display, options.audio, (diagnostic) => options.onDiagnostic?.(diagnostic));
170
- subscriptions.push(simulation.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)), display.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)));
272
+ const audio = connectFusedAudio(displayRpc, display, options.audio, (diagnostic) => options.onDiagnostic?.(diagnostic, "audio"));
273
+ subscriptions.push(simulation.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry, "simulation")), display.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry, "display")));
171
274
  const ownedSimulationRpc = simulationRpc;
172
275
  const ownedDisplayRpc = displayRpc;
173
276
  let disposal;
@@ -682,13 +785,30 @@ var IDLE$1 = Object.freeze({
682
785
  status: "idle",
683
786
  simTime: timePs(0)
684
787
  });
788
+ var nextRun = 0;
789
+ var nextSession = 0;
685
790
  /** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */
686
791
  async function createFusedRuntime(options) {
687
- const workers = options.workers ?? (await import("./workers-c759BKce.js")).fusedWorkerFactories;
792
+ const workers = options.workers ?? (await import("./workers-BpHcfNEu.js")).fusedWorkerFactories;
688
793
  const diagnostics = new Emitter();
689
794
  const overlays = new Emitter();
690
795
  const states = new Emitter();
691
- const report = (entry) => {
796
+ const observer = options.observability;
797
+ let startup;
798
+ let sessionId;
799
+ let runId;
800
+ let armedForDisconnect = false;
801
+ let closed = false;
802
+ const report = (entry, source = "workbench") => {
803
+ const level = entry.code !== "runtime/guest-error" && (source === "audio" || source === "display" || entry.code === "runtime/presentation-failed") ? "warn" : "error";
804
+ if (level === "error" && startup !== void 0) startup.reportedError = true;
805
+ writeFusedLog(observer, source, {
806
+ ...ids(),
807
+ ...entry,
808
+ level,
809
+ scope: "diagnostic",
810
+ data: []
811
+ });
692
812
  diagnostics.fire(entry);
693
813
  options.onDiagnostic?.(entry);
694
814
  };
@@ -699,12 +819,29 @@ async function createFusedRuntime(options) {
699
819
  ...options.container === void 0 ? {} : { container: options.container },
700
820
  ...options.resolveResource === void 0 ? {} : { resolveResource: options.resolveResource },
701
821
  ...options.programs === void 0 ? {} : { programs: options.programs },
702
- onDiagnostic: report
822
+ onDiagnostic: report,
823
+ ...observer === void 0 ? {} : { observability: {
824
+ ...observer,
825
+ onSample: recordSample
826
+ } },
827
+ onDisconnect: (source) => {
828
+ if (!armedForDisconnect || closed) return;
829
+ writeFusedLog(observer, source, {
830
+ ...ids(),
831
+ level: "error",
832
+ scope: "connection",
833
+ code: "runtime/guest-disconnected",
834
+ message: "Guest connection closed unexpectedly",
835
+ data: []
836
+ });
837
+ finishStartup("failure");
838
+ }
703
839
  });
840
+ armedForDisconnect = true;
704
841
  const models = createHostModelRouter(connection.simulation);
705
842
  const displayHost = createFusedDisplay({
706
843
  proxy: connection.display,
707
- onDiagnostic: report,
844
+ onDiagnostic: (entry) => report(entry, "display"),
708
845
  onOverlay: (frame) => {
709
846
  overlays.fire(frame);
710
847
  options.onOverlay?.(frame);
@@ -715,7 +852,6 @@ async function createFusedRuntime(options) {
715
852
  let prepared = [];
716
853
  let mode;
717
854
  let preparation = 0;
718
- let closed = false;
719
855
  let disposal;
720
856
  const clients = /* @__PURE__ */ new Map();
721
857
  const deviceState = options.deviceStateProvider === void 0 ? void 0 : createDeviceState(options.deviceStateProvider, options.document, report);
@@ -727,7 +863,7 @@ async function createFusedRuntime(options) {
727
863
  controls = next.catch(() => void 0);
728
864
  return next;
729
865
  }
730
- const stopState = connection.simulation.onDidChangeState((next) => setState(next));
866
+ const stopState = connection.simulation.onDidChangeState(setState);
731
867
  /**
732
868
  * 宿主能主动报告产物变化时按通知作废缓存;没有这条通道时退回「每次进入运行前重新解析」,
733
869
  * 否则代码工程重新编译并发布的固件进不了下一次运行。
@@ -752,19 +888,112 @@ async function createFusedRuntime(options) {
752
888
  dispose
753
889
  };
754
890
  try {
755
- await prepareDisplay({ mode: options.mode ?? "edit" });
891
+ await prepareDisplay({
892
+ mode: options.mode ?? "edit",
893
+ ...options.requestedAt === void 0 ? {} : { requestedAt: options.requestedAt }
894
+ });
756
895
  } catch (cause) {
757
896
  await dispose().catch(() => void 0);
758
897
  throw cause;
759
898
  }
760
899
  return runtime;
761
- function setState(next) {
900
+ function setState(next, boot) {
901
+ if (boot !== void 0 && startup?.context.runId === boot.runId) finishStartup(boot.outcome, void 0, boot.warmup);
762
902
  if (next.status === "running") connection.audio.resume();
763
903
  else connection.audio.suspend();
764
904
  if (next.status === state.status && next.simTime === state.simTime) return;
765
905
  state = next;
766
906
  states.fire(next);
767
907
  }
908
+ function ids() {
909
+ return {
910
+ ...sessionId === void 0 ? {} : { sessionId },
911
+ ...runId === void 0 ? {} : { runId }
912
+ };
913
+ }
914
+ function observation() {
915
+ if (observer === void 0) return void 0;
916
+ return startup?.context ?? {
917
+ debug: observer.logLevel === "debug",
918
+ performance: observer.performance === true
919
+ };
920
+ }
921
+ function recordSample(sample) {
922
+ if (observer?.performance !== true) return;
923
+ try {
924
+ observer.onSample?.(sample);
925
+ } catch (cause) {
926
+ console.error("[mica] Workbench performance sink failed", cause);
927
+ }
928
+ }
929
+ function beginStartup(kind, requestedAt) {
930
+ if (observer === void 0) return void 0;
931
+ finishStartup("cancelled");
932
+ if (kind !== "resume" || sessionId === void 0) sessionId = `s${++nextSession}`;
933
+ runId = `r${++nextRun}`;
934
+ const context = {
935
+ debug: observer.logLevel === "debug",
936
+ performance: observer.performance === true,
937
+ runId,
938
+ sessionId,
939
+ kind
940
+ };
941
+ startup = {
942
+ context,
943
+ end: startStartupSpan("workbench-startup", context.performance, requestedAt),
944
+ awaitingFirstStep: false,
945
+ reportedError: false
946
+ };
947
+ writeFusedLog(observer, "workbench", {
948
+ ...ids(),
949
+ level: "info",
950
+ scope: "startup",
951
+ code: "runtime/start-requested",
952
+ message: "Simulation start requested",
953
+ fields: { kind },
954
+ data: []
955
+ });
956
+ return startup;
957
+ }
958
+ function finishStartup(outcome, cause, warmup) {
959
+ if (startup === void 0) return;
960
+ const { context, end, reportedError } = startup;
961
+ const fields = ids();
962
+ startup = void 0;
963
+ const durationMs = end();
964
+ recordSample({
965
+ ...fields,
966
+ phase: "workbench-startup",
967
+ outcome,
968
+ durationMs,
969
+ ...context.kind === void 0 ? {} : { kind: context.kind },
970
+ ...warmup === void 0 ? {} : { warmup }
971
+ });
972
+ if (outcome === "cancelled") writeFusedLog(observer, "workbench", {
973
+ ...fields,
974
+ level: "info",
975
+ scope: "startup",
976
+ code: "runtime/start-cancelled",
977
+ message: "Simulation start cancelled",
978
+ fields: { durationMs },
979
+ data: []
980
+ });
981
+ if (outcome === "failure" && cause !== void 0) {
982
+ if (!reportedError) writeFusedLog(observer, "workbench", {
983
+ ...fields,
984
+ level: "error",
985
+ scope: "startup",
986
+ code: cause instanceof FusedBridgeError ? cause.code : "runtime/start-failed",
987
+ message: messageOf(cause),
988
+ data: []
989
+ });
990
+ if (observer?.onLog !== void 0 && typeof cause === "object" && cause !== null) loggedStartupFailures.add(cause);
991
+ }
992
+ }
993
+ async function startAdvancing(attempt) {
994
+ if (attempt !== void 0 && startup === attempt) attempt.awaitingFirstStep = true;
995
+ await mapWireFailure(() => connection.simulation.resume(attempt?.context));
996
+ }
768
997
  function assertOpen() {
769
998
  if (closed) throw new FusedBridgeError("runtime/unavailable-state", "The fused runtime is disposed.");
770
999
  }
@@ -785,6 +1014,16 @@ async function createFusedRuntime(options) {
785
1014
  }
786
1015
  async function prepareDisplay(input) {
787
1016
  assertOpen();
1017
+ if (input.mode === "edit") finishStartup("cancelled");
1018
+ const startupAttempt = input.mode === "run" ? beginStartup("start", input.requestedAt) : void 0;
1019
+ try {
1020
+ return await prepareMode(input, startupAttempt);
1021
+ } catch (cause) {
1022
+ if (startup === startupAttempt) finishStartup("failure", cause);
1023
+ throw cause;
1024
+ }
1025
+ }
1026
+ async function prepareMode(input, startupAttempt) {
788
1027
  const attempt = ++preparation;
789
1028
  connection.audio.suspend();
790
1029
  connection.audio.clear();
@@ -794,9 +1033,11 @@ async function createFusedRuntime(options) {
794
1033
  if (input.mode === "run" && stopProgramChanges === void 0) await mapWireFailure(() => connection.simulation.invalidatePrograms());
795
1034
  const boot = input.mode === "run" ? await deviceState?.read() : void 0;
796
1035
  if (!current()) return prepared;
1036
+ const context = observation();
797
1037
  const described = await mapWireFailure(() => connection.simulation.prepare({
798
1038
  document: options.document,
799
1039
  mode: input.mode,
1040
+ ...context === void 0 ? {} : { observation: context },
800
1041
  ...boot === void 0 ? {} : { deviceState: boot.requests.map(copyImage) }
801
1042
  }));
802
1043
  if (!current()) return prepared;
@@ -804,6 +1045,8 @@ async function createFusedRuntime(options) {
804
1045
  await mapWireFailure(() => connection.simulation.dispose());
805
1046
  if (!current()) return prepared;
806
1047
  deviceState?.clear();
1048
+ sessionId = void 0;
1049
+ runId = void 0;
807
1050
  }
808
1051
  await displayHost.prepare({ mode: input.mode }, described.instances);
809
1052
  if (!current()) return prepared;
@@ -813,6 +1056,7 @@ async function createFusedRuntime(options) {
813
1056
  const loaded = await mapWireFailure(() => connection.simulation.load({
814
1057
  document: options.document,
815
1058
  step: options.step,
1059
+ ...context === void 0 ? {} : { observation: context },
816
1060
  ...boot === void 0 ? {} : {
817
1061
  deviceState: boot.requests.map(copyImage),
818
1062
  stateGeneration: attempt
@@ -837,7 +1081,7 @@ async function createFusedRuntime(options) {
837
1081
  await displayHost.activate();
838
1082
  if (!current()) return prepared;
839
1083
  displayHost.display.invalidate();
840
- if (input.mode === "run") await mapWireFailure(() => connection.simulation.resume());
1084
+ if (input.mode === "run") await startAdvancing(startupAttempt);
841
1085
  return prepared;
842
1086
  }
843
1087
  /**
@@ -849,19 +1093,29 @@ async function createFusedRuntime(options) {
849
1093
  async function warmup() {
850
1094
  assertOpen();
851
1095
  if (mode !== "edit") return;
1096
+ const context = observation();
852
1097
  await mapWireFailure(() => connection.simulation.warmup({
853
1098
  document: options.document,
854
1099
  step: options.step,
1100
+ ...context === void 0 ? {} : { observation: context },
855
1101
  ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
856
1102
  }));
857
1103
  }
858
1104
  async function resume() {
859
1105
  assertRun("resume");
860
- await mapWireFailure(() => connection.simulation.resume());
1106
+ if (state.status === "starting" || state.status === "running" || startup?.awaitingFirstStep) return;
1107
+ const attempt = beginStartup("resume");
1108
+ try {
1109
+ await startAdvancing(attempt);
1110
+ } catch (cause) {
1111
+ if (startup === attempt) finishStartup("failure", cause);
1112
+ throw cause;
1113
+ }
861
1114
  }
862
1115
  async function pause() {
863
1116
  if (closed || mode !== "run") return;
864
1117
  await mapWireFailure(() => connection.simulation.pause());
1118
+ if (startup?.awaitingFirstStep) finishStartup("cancelled");
865
1119
  await deviceState?.checkpoint(state.status === "faulted" ? void 0 : (id, method) => mapWireFailure(() => connection.simulation.call(id, method, null)));
866
1120
  }
867
1121
  async function step() {
@@ -874,6 +1128,15 @@ async function createFusedRuntime(options) {
874
1128
  await prepareDisplay({ mode: "run" });
875
1129
  return;
876
1130
  }
1131
+ const startupAttempt = beginStartup("restart");
1132
+ try {
1133
+ await resetModels(startupAttempt);
1134
+ } catch (cause) {
1135
+ if (startup === startupAttempt) finishStartup("failure", cause);
1136
+ throw cause;
1137
+ }
1138
+ }
1139
+ async function resetModels(startupAttempt) {
877
1140
  connection.audio.suspend();
878
1141
  connection.audio.clear();
879
1142
  const attempt = ++preparation;
@@ -887,13 +1150,14 @@ async function createFusedRuntime(options) {
887
1150
  await displayHost.activate();
888
1151
  if (!current()) return;
889
1152
  displayHost.display.invalidate();
890
- await mapWireFailure(() => connection.simulation.resume());
1153
+ await startAdvancing(startupAttempt);
891
1154
  }
892
1155
  function dispose() {
893
1156
  if (disposal !== void 0) return disposal;
894
1157
  disposal = control(async () => {
895
1158
  if (deviceState !== void 0) await pause();
896
1159
  closed = true;
1160
+ finishStartup("cancelled");
897
1161
  connection.audio.dispose();
898
1162
  stopDeviceState?.();
899
1163
  deviceState?.dispose();
@@ -1174,6 +1438,21 @@ function startFusedSimulationGuest(port, options = {}) {
1174
1438
  const endpoint = (options.createEndpoint ?? createRpc)(port);
1175
1439
  const importModule = options.importModule ?? importCode;
1176
1440
  const packages = createHostPackageGateway(endpoint);
1441
+ const logger = endpoint.getProxy(loggerService);
1442
+ const performanceSink = endpoint.getProxy(fusedHostPerformanceService);
1443
+ function log(context, record) {
1444
+ logger.write({
1445
+ ...observationIds(context),
1446
+ ...record,
1447
+ data: []
1448
+ }).catch(() => void 0);
1449
+ }
1450
+ function sample(context, value) {
1451
+ if (context.performance) performanceSink.record({
1452
+ ...observationIds(context),
1453
+ ...value
1454
+ }).catch(() => void 0);
1455
+ }
1177
1456
  /** 已校验的器件包与已求值的模块都按发布身份缓存:同一 realm 里的下一次 load 直接复用。 */
1178
1457
  const openedPackages = /* @__PURE__ */ new Map();
1179
1458
  const openedModules = /* @__PURE__ */ new Map();
@@ -1183,19 +1462,68 @@ function startFusedSimulationGuest(port, options = {}) {
1183
1462
  * 校验结论只取决于宿主交来的字节,而宿主按发布身份缓存字节,所以同一 lock 在
1184
1463
  * 一个 realm 里只需要校验一次。
1185
1464
  */
1186
- function openVerifiedPackage(lock) {
1465
+ function openVerifiedPackage(lock, context) {
1187
1466
  const key = packageLockKey(lock);
1188
1467
  const cached = openedPackages.get(key);
1189
- if (cached !== void 0) return cached;
1468
+ const fields = {
1469
+ packageId: lock.id,
1470
+ version: lock.version
1471
+ };
1472
+ if (cached !== void 0) {
1473
+ if (context?.debug) log(context, {
1474
+ level: "debug",
1475
+ scope: "package",
1476
+ code: "device/package-cache",
1477
+ message: "Reusing device package",
1478
+ fields: {
1479
+ ...fields,
1480
+ cache: cached.verified ? "hit" : "in-flight"
1481
+ }
1482
+ });
1483
+ return cached.pending;
1484
+ }
1485
+ const end = context?.debug || context?.performance ? startStartupSpan("device-package", context.performance) : void 0;
1190
1486
  const pending = openDevicePackage(packages, lock);
1191
- openedPackages.set(key, pending);
1192
- pending.catch(() => {
1193
- if (openedPackages.get(key) === pending) openedPackages.delete(key);
1487
+ const entry = {
1488
+ pending,
1489
+ verified: false
1490
+ };
1491
+ openedPackages.set(key, entry);
1492
+ pending.then(() => {
1493
+ entry.verified = true;
1494
+ if (context === void 0 || end === void 0) return;
1495
+ const durationMs = end();
1496
+ if (context.debug) log(context, {
1497
+ level: "debug",
1498
+ scope: "package",
1499
+ code: "device/package-loaded",
1500
+ message: "Device package opened and verified",
1501
+ fields: {
1502
+ ...fields,
1503
+ durationMs
1504
+ }
1505
+ });
1506
+ sample(context, {
1507
+ phase: "device-package",
1508
+ outcome: "success",
1509
+ durationMs,
1510
+ ...fields
1511
+ });
1512
+ }, () => {
1513
+ if (openedPackages.get(key) === entry) openedPackages.delete(key);
1514
+ if (context !== void 0 && end !== void 0) sample(context, {
1515
+ phase: "device-package",
1516
+ outcome: "failure",
1517
+ durationMs: end(),
1518
+ ...fields
1519
+ });
1194
1520
  });
1195
1521
  return pending;
1196
1522
  }
1197
1523
  /** 校验接口原样交给运行时,避免它把同一份发布再校验一遍。 */
1198
- const verifiedRegistry = { open: (lock) => openVerifiedPackage(lock).then((entry) => entry.source) };
1524
+ function verifiedRegistry(context) {
1525
+ return { open: (lock) => openVerifiedPackage(lock, context).then((entry) => entry.source) };
1526
+ }
1199
1527
  const resources = createResourceGateway(endpoint);
1200
1528
  const diagnostics = new Emitter();
1201
1529
  const states = new Emitter();
@@ -1211,15 +1539,16 @@ function startFusedSimulationGuest(port, options = {}) {
1211
1539
  /** 递增即取消正在进行的预热;真实的准备与装载都会取消它。 */
1212
1540
  let warmupGeneration = 0;
1213
1541
  let warmupPending;
1542
+ let warmupProgress = "not-started";
1214
1543
  let closing = false;
1215
1544
  let disposal;
1216
1545
  endpoint.register(fusedSimulationService, {
1217
1546
  prepare,
1218
- load,
1547
+ load: observedLoad,
1219
1548
  warmup,
1220
1549
  step,
1221
1550
  resume,
1222
- pause,
1551
+ pause: () => pause(),
1223
1552
  reset,
1224
1553
  dispose: releaseModels,
1225
1554
  invalidatePrograms: async (projectId, fingerprint) => {
@@ -1228,7 +1557,7 @@ function startFusedSimulationGuest(port, options = {}) {
1228
1557
  call: (instanceId, method, params) => callModel(instanceId, method, params),
1229
1558
  getState: () => state,
1230
1559
  onDidChangeState(listener) {
1231
- const subscription = states.event((value) => listener(value));
1560
+ const subscription = states.event(({ state, boot }) => listener(state, boot));
1232
1561
  return () => subscription.dispose();
1233
1562
  },
1234
1563
  onDidReportDiagnostic(listener) {
@@ -1247,10 +1576,13 @@ function startFusedSimulationGuest(port, options = {}) {
1247
1576
  function report(entry) {
1248
1577
  diagnostics.fire(entry);
1249
1578
  }
1250
- function setState(next) {
1251
- if (next.status === state.status && next.simTime === state.simTime) return;
1579
+ function setState(next, boot) {
1580
+ if (boot === void 0 && next.status === state.status && next.simTime === state.simTime) return;
1252
1581
  state = next;
1253
- states.fire(next);
1582
+ states.fire({
1583
+ state: next,
1584
+ boot
1585
+ });
1254
1586
  }
1255
1587
  function assertOpen() {
1256
1588
  if (closing) throw toWireFailure(new FusedBridgeError("runtime/unavailable-state", "The fused simulation guest is disposed."));
@@ -1269,7 +1601,7 @@ function startFusedSimulationGuest(port, options = {}) {
1269
1601
  const stateImages = new Map(request.deviceState?.map((image) => [image.instanceId, image]));
1270
1602
  const deviceState = [];
1271
1603
  for (const [index, instance] of document.instances.entries()) try {
1272
- const described = await describeInstance(index, document, instance, stateImages.get(instance.id), deviceState);
1604
+ const described = await describeInstance(index, document, instance, stateImages.get(instance.id), deviceState, request.observation);
1273
1605
  if (described !== void 0) instances.push(described);
1274
1606
  } catch (cause) {
1275
1607
  if (cause instanceof FusedBridgeError && cause.code === "runtime/presentation-failed") {
@@ -1293,7 +1625,7 @@ function startFusedSimulationGuest(port, options = {}) {
1293
1625
  ...request.deviceState === void 0 ? {} : { deviceState }
1294
1626
  };
1295
1627
  }
1296
- async function describeInstance(index, document, instance, stateImage, deviceState) {
1628
+ async function describeInstance(index, document, instance, stateImage, deviceState, observation) {
1297
1629
  const dependency = document.dependencies[instance.device];
1298
1630
  if (dependency === void 0) throw new FusedBridgeError("document/unlocked-device", `Instance "${instance.id}" uses the unlocked device "${instance.device}".`, { instanceId: instance.id });
1299
1631
  const lock = {
@@ -1301,7 +1633,7 @@ function startFusedSimulationGuest(port, options = {}) {
1301
1633
  version: dependency.version,
1302
1634
  integrity: dependency.integrity
1303
1635
  };
1304
- const verified = await openVerifiedPackage(lock);
1636
+ const verified = await openVerifiedPackage(lock, observation);
1305
1637
  const descriptors = verified.manifest.properties ?? {};
1306
1638
  let props;
1307
1639
  if (stateImage !== void 0) {
@@ -1386,7 +1718,15 @@ function startFusedSimulationGuest(port, options = {}) {
1386
1718
  if (!Number.isSafeInteger(step) || step <= 0) throw toWireFailure(new FusedBridgeError("runtime/invalid-time", `\`step\` must be a positive integer number of picoseconds, received ${String(step)}.`));
1387
1719
  const generation = ++warmupGeneration;
1388
1720
  const current = () => !closing && generation === warmupGeneration;
1389
- const task = runWarmup(request, step, current).finally(() => {
1721
+ const task = runWarmup(request, step, current).then((outcome) => {
1722
+ if (request.observation?.debug) log(request.observation, {
1723
+ level: "debug",
1724
+ scope: "startup",
1725
+ code: `runtime/warmup-${outcome}`,
1726
+ message: "Background warmup finished",
1727
+ fields: { outcome }
1728
+ });
1729
+ }).finally(() => {
1390
1730
  if (warmupPending === task) warmupPending = void 0;
1391
1731
  });
1392
1732
  warmupPending = task;
@@ -1397,7 +1737,7 @@ function startFusedSimulationGuest(port, options = {}) {
1397
1737
  try {
1398
1738
  created = await createHeadlessRuntime({
1399
1739
  document: parseFusedDocument(request.document),
1400
- registry: verifiedRegistry,
1740
+ registry: verifiedRegistry(request.observation),
1401
1741
  loadModule,
1402
1742
  step,
1403
1743
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
@@ -1405,15 +1745,20 @@ function startFusedSimulationGuest(port, options = {}) {
1405
1745
  programs: resources.programs,
1406
1746
  onModelEvent: () => {}
1407
1747
  });
1408
- if (!current()) return;
1748
+ if (!current()) return "cancelled";
1409
1749
  const slice = Math.floor(step / WARMUP_SLICES);
1410
1750
  for (let index = 1; index <= WARMUP_SLICES; index++) {
1411
- if (!current()) return;
1751
+ if (!current()) return "cancelled";
1412
1752
  const amount = index === WARMUP_SLICES ? step - slice * 7 : slice;
1413
1753
  await created.step(timePs(amount));
1754
+ if (!current()) return "cancelled";
1755
+ warmupProgress = index === WARMUP_SLICES ? "completed" : "partial";
1414
1756
  if (index < WARMUP_SLICES) await yieldToHost();
1415
1757
  }
1416
- } catch {} finally {
1758
+ return "completed";
1759
+ } catch {
1760
+ return current() ? "failed" : "cancelled";
1761
+ } finally {
1417
1762
  if (created !== void 0) await created.dispose().catch(() => void 0);
1418
1763
  }
1419
1764
  }
@@ -1422,7 +1767,42 @@ function startFusedSimulationGuest(port, options = {}) {
1422
1767
  warmupGeneration += 1;
1423
1768
  warmupPending = void 0;
1424
1769
  }
1425
- async function load(request) {
1770
+ async function observedLoad(request) {
1771
+ const context = request.observation;
1772
+ if (context === void 0) return load(request);
1773
+ const end = startStartupSpan("simulation-load", context.performance);
1774
+ const finish = (outcome) => {
1775
+ const durationMs = end();
1776
+ sample(context, {
1777
+ phase: "simulation-load",
1778
+ outcome,
1779
+ durationMs
1780
+ });
1781
+ return durationMs;
1782
+ };
1783
+ let loaded = false;
1784
+ try {
1785
+ const state = await load(request, (instanceCount) => {
1786
+ loaded = true;
1787
+ log(context, {
1788
+ level: "info",
1789
+ scope: "startup",
1790
+ code: "runtime/load-completed",
1791
+ message: "Models loaded",
1792
+ fields: {
1793
+ instanceCount,
1794
+ durationMs: finish("success")
1795
+ }
1796
+ });
1797
+ });
1798
+ if (!loaded) finish("cancelled");
1799
+ return state;
1800
+ } catch (cause) {
1801
+ finish("failure");
1802
+ throw cause;
1803
+ }
1804
+ }
1805
+ async function load(request, onLoaded) {
1426
1806
  assertOpen();
1427
1807
  cancelWarmup();
1428
1808
  const step = request.step;
@@ -1441,7 +1821,7 @@ function startFusedSimulationGuest(port, options = {}) {
1441
1821
  for (const entry of request.deviceState ?? []) if (entry.image !== void 0) binaryOverrides.set(entry.instanceId, /* @__PURE__ */ new Map([[entry.property, entry.image]]));
1442
1822
  created = await createHeadlessRuntime({
1443
1823
  document,
1444
- registry: verifiedRegistry,
1824
+ registry: verifiedRegistry(request.observation),
1445
1825
  loadModule,
1446
1826
  step,
1447
1827
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
@@ -1473,12 +1853,12 @@ function startFusedSimulationGuest(port, options = {}) {
1473
1853
  runtime: created,
1474
1854
  step,
1475
1855
  pacing: pacing ?? "unlimited",
1856
+ warmup: warmupProgress,
1476
1857
  run: void 0,
1477
1858
  subscriptions: [created.onDidChangeState((next) => {
1478
1859
  if (sessionToken !== token) return;
1479
1860
  if (next.status === "paused" && adopted.run !== void 0) return;
1480
- stopRun(adopted);
1481
- setState(next);
1861
+ setState(next, stopRun(adopted, next.status === "faulted" ? "failure" : "cancelled"));
1482
1862
  }), created.onDidReportDiagnostic((entry) => {
1483
1863
  if (sessionToken === token) report(entry);
1484
1864
  })]
@@ -1490,6 +1870,7 @@ function startFusedSimulationGuest(port, options = {}) {
1490
1870
  status: initial.status,
1491
1871
  simTime: initial.simTime
1492
1872
  });
1873
+ onLoaded?.(document.instances.length);
1493
1874
  return state;
1494
1875
  }
1495
1876
  async function step() {
@@ -1498,17 +1879,49 @@ function startFusedSimulationGuest(port, options = {}) {
1498
1879
  await mapGuestCall(() => target.runtime.step());
1499
1880
  return state;
1500
1881
  }
1501
- async function resume() {
1882
+ async function resume(context) {
1502
1883
  const target = requireSession("resume");
1503
1884
  if (target.run !== void 0) return;
1504
1885
  const current = target.runtime.getState();
1505
1886
  if (current.status === "faulted") throw toWireFailure(new FusedBridgeError("runtime/model-failed", "resume is not allowed while the runtime is faulted; call reset first."));
1887
+ const startedAt = performance.now();
1506
1888
  const run = {
1507
- wallStartMs: performance.now(),
1889
+ wallStartMs: startedAt,
1508
1890
  simStartPs: current.simTime,
1509
1891
  timer: void 0,
1510
- waiting: void 0
1892
+ waiting: void 0,
1893
+ finishBoot: void 0
1511
1894
  };
1895
+ if (context !== void 0) {
1896
+ const end = startStartupSpan("first-step", context.performance, startedAt);
1897
+ const warmup = context.kind === "start" ? target.warmup : void 0;
1898
+ run.finishBoot = (outcome) => {
1899
+ run.finishBoot = void 0;
1900
+ const durationMs = end();
1901
+ const attributes = warmup === void 0 ? {} : { warmup };
1902
+ sample(context, {
1903
+ phase: "first-step",
1904
+ outcome,
1905
+ durationMs,
1906
+ ...attributes
1907
+ });
1908
+ if (outcome === "success") log(context, {
1909
+ level: "info",
1910
+ scope: "startup",
1911
+ code: "runtime/first-step-completed",
1912
+ message: "First fixed step completed",
1913
+ fields: {
1914
+ durationMs,
1915
+ ...attributes
1916
+ }
1917
+ });
1918
+ return context.runId === void 0 ? void 0 : {
1919
+ runId: context.runId,
1920
+ outcome,
1921
+ ...attributes
1922
+ };
1923
+ };
1924
+ }
1512
1925
  target.run = run;
1513
1926
  setState({
1514
1927
  status: "starting",
@@ -1528,8 +1941,14 @@ function startFusedSimulationGuest(port, options = {}) {
1528
1941
  const amount = index === slices ? target.step - slice * (slices - 1) : slice;
1529
1942
  try {
1530
1943
  await target.runtime.step(timePs(amount));
1531
- } catch {
1532
- if (target.run === run) pause();
1944
+ } catch (cause) {
1945
+ if (target.run === run) {
1946
+ report({
1947
+ code: "runtime/first-step-failed",
1948
+ message: messageOf(cause)
1949
+ });
1950
+ pause("failure");
1951
+ }
1533
1952
  return;
1534
1953
  }
1535
1954
  if (target.run !== run) return;
@@ -1538,10 +1957,11 @@ function startFusedSimulationGuest(port, options = {}) {
1538
1957
  if (target.run !== run) return;
1539
1958
  run.wallStartMs = performance.now();
1540
1959
  run.simStartPs = target.runtime.getState().simTime;
1960
+ const boot = run.finishBoot?.("success");
1541
1961
  setState({
1542
1962
  status: "running",
1543
1963
  simTime: run.simStartPs
1544
- });
1964
+ }, boot);
1545
1965
  scheduleSlice(target, run, run.wallStartMs);
1546
1966
  }
1547
1967
  /** Returns to the event loop; `stopRun` resolves the same promise so a stop is immediate. */
@@ -1601,20 +2021,29 @@ function startFusedSimulationGuest(port, options = {}) {
1601
2021
  });
1602
2022
  scheduleSlice(target, run, startedAt);
1603
2023
  }
1604
- function stopRun(target) {
2024
+ function stopRun(target, outcome = "cancelled") {
1605
2025
  const run = target.run;
1606
2026
  target.run = void 0;
1607
2027
  if (run === void 0) return;
2028
+ const boot = run.finishBoot?.(outcome);
1608
2029
  clearTimeout(run.timer);
1609
2030
  run.timer = void 0;
1610
2031
  const waiting = run.waiting;
1611
2032
  run.waiting = void 0;
1612
2033
  waiting?.();
2034
+ return boot;
2035
+ }
2036
+ function observationIds(context) {
2037
+ return {
2038
+ ...context.runId === void 0 ? {} : { runId: context.runId },
2039
+ ...context.sessionId === void 0 ? {} : { sessionId: context.sessionId },
2040
+ ...context.kind === void 0 ? {} : { kind: context.kind }
2041
+ };
1613
2042
  }
1614
- function pause() {
2043
+ function pause(outcome = "cancelled") {
1615
2044
  if (session === void 0) return;
1616
- stopRun(session);
1617
- setState(session.runtime.getState());
2045
+ const boot = stopRun(session, outcome);
2046
+ setState(session.runtime.getState(), boot);
1618
2047
  }
1619
2048
  async function reset() {
1620
2049
  const target = requireSession("reset");
@@ -2199,10 +2628,10 @@ function closeBitmap(bitmap) {
2199
2628
  * same factories to several runtimes.
2200
2629
  */
2201
2630
  async function loadFusedWorkerFactories() {
2202
- const { fusedWorkerFactories } = await import("./workers-c759BKce.js");
2631
+ const { fusedWorkerFactories } = await import("./workers-BpHcfNEu.js");
2203
2632
  return fusedWorkerFactories;
2204
2633
  }
2205
2634
  //#endregion
2206
- export { fusedModelSinkService as _, createFusedRuntime as a, createModelEventRouter as c, createHostPackageGateway as d, packageLockKey as f, fusedModelChannelService as g, fusedHostResourceService as h, startFusedSimulationGuest as i, createFusedDisplay as l, fusedHostPackageService as m, startFusedDisplayGuest as n, createHostModelRouter as o, fusedDisplayService as p, createViewSession as r, channelKey as s, loadFusedWorkerFactories as t, connectFusedWorkbench as u, fusedSimulationService as v };
2635
+ export { fusedSimulationService as S, fusedDisplayService as _, createFusedRuntime as a, fusedModelChannelService as b, createModelEventRouter as c, loggedStartupFailures as d, summarizeStartup as f, packageLockKey as g, createHostPackageGateway as h, startFusedSimulationGuest as i, createFusedDisplay as l, writeWorkbenchConsole as m, startFusedDisplayGuest as n, createHostModelRouter as o, writeFusedLog as p, createViewSession as r, channelKey as s, loadFusedWorkerFactories as t, connectFusedWorkbench as u, fusedHostPackageService as v, fusedModelSinkService as x, fusedHostResourceService as y };
2207
2636
 
2208
- //# sourceMappingURL=runtime-_9IqvWDa.js.map
2637
+ //# sourceMappingURL=runtime-DuxZ_yVl.js.map