@mica-js/editor 0.13.0 → 0.15.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.
@@ -1,9 +1,10 @@
1
- import { a as isImageBitmap, c as toWireFailure, d as transferPackageBytes, f as transferPresentationBytes, m as transferResourceBytes, n as FusedBridgeError, o as mapWireFailure, p as transferProgramArtifact, s as messageOf, u as transferOverlayFrame } from "./wire-BDHL5Aj9.js";
1
+ import { a as isImageBitmap, c as toWireFailure, d as transferOverlayFrame, f as transferPackageBytes, h as transferResourceBytes, m as transferProgramArtifact, n as FusedBridgeError, o as mapWireFailure, p as transferPresentationBytes, s as messageOf, u as transferDeviceState } from "./wire-Di4FVpnu.js";
2
2
  import { Emitter, toDisposable } from "@mica-js/core/lifecycle";
3
3
  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);
167
- const simulation = simulationRpc.getProxy(fusedSimulationService);
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) });
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;
@@ -552,6 +655,122 @@ function createHostModelRouter(proxy) {
552
655
  };
553
656
  }
554
657
  //#endregion
658
+ //#region src/fused/runtime/host/device-state.ts
659
+ var equal = (a, b) => a !== void 0 && a.length === b.length && a.every((value, index) => value === b[index]);
660
+ function createDeviceState(provider, document, report) {
661
+ const lifetime = new AbortController();
662
+ let active;
663
+ function failure(kind, instanceId, cause) {
664
+ const error = new FusedBridgeError(`device-state/${kind}-failed`, `Device state ${kind} for "${instanceId}": ${cause instanceof Error ? cause.message : String(cause)}`, { instanceId });
665
+ report({
666
+ code: error.code,
667
+ message: error.message,
668
+ instanceId
669
+ });
670
+ return error;
671
+ }
672
+ function startWrite(slot) {
673
+ if (slot.writing !== void 0) return slot.writing;
674
+ slot.writing = Promise.resolve().then(async () => {
675
+ while (slot.latest !== void 0 && !equal(slot.saved, slot.latest)) {
676
+ const snapshot = slot.latest;
677
+ try {
678
+ await provider.write(slot.key, snapshot.slice(), lifetime.signal);
679
+ } catch (cause) {
680
+ throw failure("write", slot.key.instanceId, cause);
681
+ }
682
+ slot.saved = snapshot;
683
+ }
684
+ }).finally(() => {
685
+ slot.writing = void 0;
686
+ });
687
+ return slot.writing;
688
+ }
689
+ function observe(slot, image, checkpoint = false) {
690
+ if (checkpoint && image instanceof Uint8Array && image.length === 0) return;
691
+ if (!(image instanceof Uint8Array) || image.length !== slot.request.byteLength) {
692
+ const error = failure("invalid", slot.key.instanceId, "Invalid image length or type");
693
+ if (checkpoint) throw error;
694
+ return;
695
+ }
696
+ if (equal(slot.latest ?? slot.saved, image)) return;
697
+ slot.latest = image.slice();
698
+ if (!checkpoint) startWrite(slot).catch(() => void 0);
699
+ }
700
+ return {
701
+ async read() {
702
+ const slots = /* @__PURE__ */ new Map();
703
+ for (const instance of document.instances) {
704
+ const version = document.dependencies[instance.device]?.version;
705
+ const binding = provider.bindings.find((entry) => entry.device === instance.device && entry.version === version);
706
+ if (binding === void 0) continue;
707
+ const { device, slot, formatVersion, byteLength, property, method, event } = binding;
708
+ const key = {
709
+ instanceId: instance.id,
710
+ device,
711
+ slot,
712
+ formatVersion
713
+ };
714
+ const bytes = await Promise.resolve().then(() => provider.read(key, lifetime.signal)).catch((cause) => {
715
+ throw failure("read", instance.id, cause);
716
+ });
717
+ if (bytes !== void 0 && (!(bytes instanceof Uint8Array) || bytes.length !== byteLength)) throw failure("invalid", instance.id, "Invalid image length or type");
718
+ const request = {
719
+ instanceId: instance.id,
720
+ property,
721
+ method,
722
+ event,
723
+ byteLength,
724
+ ...bytes === void 0 ? {} : { image: bytes.slice() }
725
+ };
726
+ slots.set(instance.id, {
727
+ key,
728
+ request,
729
+ saved: void 0,
730
+ latest: void 0,
731
+ writing: void 0
732
+ });
733
+ }
734
+ return {
735
+ slots,
736
+ requests: Array.from(slots.values(), (slot) => slot.request)
737
+ };
738
+ },
739
+ activate(generation, slots, baselines) {
740
+ for (const { instanceId, image } of baselines) {
741
+ const slot = slots.get(instanceId);
742
+ if (slot !== void 0) slot.saved = image.slice();
743
+ }
744
+ const previous = active;
745
+ active = {
746
+ generation,
747
+ slots
748
+ };
749
+ return () => {
750
+ active = previous;
751
+ };
752
+ },
753
+ event(event) {
754
+ if (active === void 0 || event.stateGeneration !== active.generation) return;
755
+ const slot = active.slots.get(event.instanceId);
756
+ if (slot?.request.event === event.event) observe(slot, event.payload.value);
757
+ },
758
+ async checkpoint(call) {
759
+ if (active === void 0) return;
760
+ const slots = [...active.slots.values()];
761
+ if (call !== void 0) for (const slot of slots) observe(slot, await call(slot.key.instanceId, slot.request.method), true);
762
+ const results = await Promise.allSettled(slots.map(startWrite));
763
+ for (const result of results) if (result.status === "rejected") throw result.reason;
764
+ },
765
+ clear() {
766
+ active = void 0;
767
+ },
768
+ dispose() {
769
+ lifetime.abort();
770
+ }
771
+ };
772
+ }
773
+ //#endregion
555
774
  //#region src/fused/runtime/host/runtime.ts
556
775
  /**
557
776
  * Fused editor runtime bridge of one workbench (RFC 0025).
@@ -566,13 +785,30 @@ var IDLE$1 = Object.freeze({
566
785
  status: "idle",
567
786
  simTime: timePs(0)
568
787
  });
788
+ var nextRun = 0;
789
+ var nextSession = 0;
569
790
  /** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */
570
791
  async function createFusedRuntime(options) {
571
- const workers = options.workers ?? (await import("./workers-Og_Z_xzw.js")).fusedWorkerFactories;
792
+ const workers = options.workers ?? (await import("./workers-BpHcfNEu.js")).fusedWorkerFactories;
572
793
  const diagnostics = new Emitter();
573
794
  const overlays = new Emitter();
574
795
  const states = new Emitter();
575
- 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
+ });
576
812
  diagnostics.fire(entry);
577
813
  options.onDiagnostic?.(entry);
578
814
  };
@@ -583,12 +819,29 @@ async function createFusedRuntime(options) {
583
819
  ...options.container === void 0 ? {} : { container: options.container },
584
820
  ...options.resolveResource === void 0 ? {} : { resolveResource: options.resolveResource },
585
821
  ...options.programs === void 0 ? {} : { programs: options.programs },
586
- 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
+ }
587
839
  });
840
+ armedForDisconnect = true;
588
841
  const models = createHostModelRouter(connection.simulation);
589
842
  const displayHost = createFusedDisplay({
590
843
  proxy: connection.display,
591
- onDiagnostic: report,
844
+ onDiagnostic: (entry) => report(entry, "display"),
592
845
  onOverlay: (frame) => {
593
846
  overlays.fire(frame);
594
847
  options.onOverlay?.(frame);
@@ -599,10 +852,18 @@ async function createFusedRuntime(options) {
599
852
  let prepared = [];
600
853
  let mode;
601
854
  let preparation = 0;
602
- let closed = false;
603
855
  let disposal;
604
856
  const clients = /* @__PURE__ */ new Map();
605
- const stopState = connection.simulation.onDidChangeState((next) => setState(next));
857
+ const deviceState = options.deviceStateProvider === void 0 ? void 0 : createDeviceState(options.deviceStateProvider, options.document, report);
858
+ const stopDeviceState = deviceState === void 0 ? void 0 : connection.simulation.onDidModelEvent(deviceState.event);
859
+ let controls = Promise.resolve();
860
+ function control(action) {
861
+ if (deviceState === void 0) return action();
862
+ const next = controls.then(action);
863
+ controls = next.catch(() => void 0);
864
+ return next;
865
+ }
866
+ const stopState = connection.simulation.onDidChangeState(setState);
606
867
  /**
607
868
  * 宿主能主动报告产物变化时按通知作废缓存;没有这条通道时退回「每次进入运行前重新解析」,
608
869
  * 否则代码工程重新编译并发布的固件进不了下一次运行。
@@ -618,28 +879,121 @@ async function createFusedRuntime(options) {
618
879
  onDidRenderOverlay: overlays.event,
619
880
  getModel,
620
881
  display: displayHost.display,
621
- prepareDisplay,
882
+ prepareDisplay: (input) => control(() => prepareDisplay(input)),
622
883
  warmup,
623
- resume,
624
- pause,
625
- step,
626
- reset,
884
+ resume: () => control(resume),
885
+ pause: () => control(pause),
886
+ step: () => control(step),
887
+ reset: () => control(reset),
627
888
  dispose
628
889
  };
629
890
  try {
630
- await prepareDisplay({ mode: options.mode ?? "edit" });
891
+ await prepareDisplay({
892
+ mode: options.mode ?? "edit",
893
+ ...options.requestedAt === void 0 ? {} : { requestedAt: options.requestedAt }
894
+ });
631
895
  } catch (cause) {
632
896
  await dispose().catch(() => void 0);
633
897
  throw cause;
634
898
  }
635
899
  return runtime;
636
- 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);
637
902
  if (next.status === "running") connection.audio.resume();
638
903
  else connection.audio.suspend();
639
904
  if (next.status === state.status && next.simTime === state.simTime) return;
640
905
  state = next;
641
906
  states.fire(next);
642
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
+ }
643
997
  function assertOpen() {
644
998
  if (closed) throw new FusedBridgeError("runtime/unavailable-state", "The fused runtime is disposed.");
645
999
  }
@@ -660,34 +1014,66 @@ async function createFusedRuntime(options) {
660
1014
  }
661
1015
  async function prepareDisplay(input) {
662
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) {
663
1027
  const attempt = ++preparation;
664
1028
  connection.audio.suspend();
665
1029
  connection.audio.clear();
666
1030
  const current = () => !closed && attempt === preparation;
1031
+ if (mode === "run" && deviceState !== void 0) await pause();
1032
+ if (!current()) return prepared;
667
1033
  if (input.mode === "run" && stopProgramChanges === void 0) await mapWireFailure(() => connection.simulation.invalidatePrograms());
1034
+ const boot = input.mode === "run" ? await deviceState?.read() : void 0;
1035
+ if (!current()) return prepared;
1036
+ const context = observation();
668
1037
  const described = await mapWireFailure(() => connection.simulation.prepare({
669
1038
  document: options.document,
670
- mode: input.mode
1039
+ mode: input.mode,
1040
+ ...context === void 0 ? {} : { observation: context },
1041
+ ...boot === void 0 ? {} : { deviceState: boot.requests.map(copyImage) }
671
1042
  }));
672
1043
  if (!current()) return prepared;
673
1044
  if (input.mode === "edit") {
674
1045
  await mapWireFailure(() => connection.simulation.dispose());
675
1046
  if (!current()) return prepared;
1047
+ deviceState?.clear();
1048
+ sessionId = void 0;
1049
+ runId = void 0;
676
1050
  }
677
1051
  await displayHost.prepare({ mode: input.mode }, described.instances);
678
1052
  if (!current()) return prepared;
679
- if (input.mode === "run") try {
680
- const loaded = await mapWireFailure(() => connection.simulation.load({
681
- document: options.document,
682
- step: options.step,
683
- ...options.simulationPacing === void 0 ? {} : { simulationPacing: options.simulationPacing },
684
- ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
685
- }));
686
- if (!current()) return prepared;
687
- setState(loaded);
688
- } catch (cause) {
689
- await displayHost.prepare({ mode: input.mode }, []).catch(() => void 0);
690
- throw cause;
1053
+ if (input.mode === "run") {
1054
+ const rollback = boot === void 0 ? void 0 : deviceState?.activate(attempt, boot.slots, described.deviceState ?? []);
1055
+ try {
1056
+ const loaded = await mapWireFailure(() => connection.simulation.load({
1057
+ document: options.document,
1058
+ step: options.step,
1059
+ ...context === void 0 ? {} : { observation: context },
1060
+ ...boot === void 0 ? {} : {
1061
+ deviceState: boot.requests.map(copyImage),
1062
+ stateGeneration: attempt
1063
+ },
1064
+ ...options.simulationPacing === void 0 ? {} : { simulationPacing: options.simulationPacing },
1065
+ ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
1066
+ }));
1067
+ if (!current()) return prepared;
1068
+ setState(loaded);
1069
+ } catch (cause) {
1070
+ if (current()) rollback?.();
1071
+ if (current()) {
1072
+ await displayHost.prepare({ mode: mode ?? input.mode }, prepared).catch(() => void 0);
1073
+ if (mode === "run") await displayHost.activate().catch(() => void 0);
1074
+ }
1075
+ throw cause;
1076
+ }
691
1077
  }
692
1078
  prepared = described.instances;
693
1079
  mode = input.mode;
@@ -695,7 +1081,7 @@ async function createFusedRuntime(options) {
695
1081
  await displayHost.activate();
696
1082
  if (!current()) return prepared;
697
1083
  displayHost.display.invalidate();
698
- if (input.mode === "run") await mapWireFailure(() => connection.simulation.resume());
1084
+ if (input.mode === "run") await startAdvancing(startupAttempt);
699
1085
  return prepared;
700
1086
  }
701
1087
  /**
@@ -707,19 +1093,30 @@ async function createFusedRuntime(options) {
707
1093
  async function warmup() {
708
1094
  assertOpen();
709
1095
  if (mode !== "edit") return;
1096
+ const context = observation();
710
1097
  await mapWireFailure(() => connection.simulation.warmup({
711
1098
  document: options.document,
712
1099
  step: options.step,
1100
+ ...context === void 0 ? {} : { observation: context },
713
1101
  ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
714
1102
  }));
715
1103
  }
716
1104
  async function resume() {
717
1105
  assertRun("resume");
718
- 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
+ }
719
1114
  }
720
1115
  async function pause() {
721
1116
  if (closed || mode !== "run") return;
722
1117
  await mapWireFailure(() => connection.simulation.pause());
1118
+ if (startup?.awaitingFirstStep) finishStartup("cancelled");
1119
+ await deviceState?.checkpoint(state.status === "faulted" ? void 0 : (id, method) => mapWireFailure(() => connection.simulation.call(id, method, null)));
723
1120
  }
724
1121
  async function step() {
725
1122
  assertRun("step");
@@ -727,6 +1124,19 @@ async function createFusedRuntime(options) {
727
1124
  }
728
1125
  async function reset() {
729
1126
  assertRun("reset");
1127
+ if (deviceState !== void 0) {
1128
+ await prepareDisplay({ mode: "run" });
1129
+ return;
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) {
730
1140
  connection.audio.suspend();
731
1141
  connection.audio.clear();
732
1142
  const attempt = ++preparation;
@@ -740,13 +1150,17 @@ async function createFusedRuntime(options) {
740
1150
  await displayHost.activate();
741
1151
  if (!current()) return;
742
1152
  displayHost.display.invalidate();
743
- await mapWireFailure(() => connection.simulation.resume());
1153
+ await startAdvancing(startupAttempt);
744
1154
  }
745
1155
  function dispose() {
746
1156
  if (disposal !== void 0) return disposal;
747
- closed = true;
748
- connection.audio.dispose();
749
- disposal = (async () => {
1157
+ disposal = control(async () => {
1158
+ if (deviceState !== void 0) await pause();
1159
+ closed = true;
1160
+ finishStartup("cancelled");
1161
+ connection.audio.dispose();
1162
+ stopDeviceState?.();
1163
+ deviceState?.dispose();
750
1164
  const problems = [];
751
1165
  try {
752
1166
  await displayHost.dispose();
@@ -778,10 +1192,19 @@ async function createFusedRuntime(options) {
778
1192
  diagnostics.dispose();
779
1193
  overlays.dispose();
780
1194
  if (problems.length > 0) throw new AggregateError(problems, "The fused runtime failed to release every resource.");
781
- })();
1195
+ }).catch((cause) => {
1196
+ if (!closed) disposal = void 0;
1197
+ throw cause;
1198
+ });
782
1199
  return disposal;
783
1200
  }
784
1201
  }
1202
+ function copyImage(entry) {
1203
+ return entry.image === void 0 ? entry : {
1204
+ ...entry,
1205
+ image: entry.image.slice()
1206
+ };
1207
+ }
785
1208
  //#endregion
786
1209
  //#region src/fused/runtime/values.ts
787
1210
  /**
@@ -1015,6 +1438,21 @@ function startFusedSimulationGuest(port, options = {}) {
1015
1438
  const endpoint = (options.createEndpoint ?? createRpc)(port);
1016
1439
  const importModule = options.importModule ?? importCode;
1017
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
+ }
1018
1456
  /** 已校验的器件包与已求值的模块都按发布身份缓存:同一 realm 里的下一次 load 直接复用。 */
1019
1457
  const openedPackages = /* @__PURE__ */ new Map();
1020
1458
  const openedModules = /* @__PURE__ */ new Map();
@@ -1024,19 +1462,68 @@ function startFusedSimulationGuest(port, options = {}) {
1024
1462
  * 校验结论只取决于宿主交来的字节,而宿主按发布身份缓存字节,所以同一 lock 在
1025
1463
  * 一个 realm 里只需要校验一次。
1026
1464
  */
1027
- function openVerifiedPackage(lock) {
1465
+ function openVerifiedPackage(lock, context) {
1028
1466
  const key = packageLockKey(lock);
1029
1467
  const cached = openedPackages.get(key);
1030
- 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;
1031
1486
  const pending = openDevicePackage(packages, lock);
1032
- openedPackages.set(key, pending);
1033
- pending.catch(() => {
1034
- 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
+ });
1035
1520
  });
1036
1521
  return pending;
1037
1522
  }
1038
1523
  /** 校验接口原样交给运行时,避免它把同一份发布再校验一遍。 */
1039
- 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
+ }
1040
1527
  const resources = createResourceGateway(endpoint);
1041
1528
  const diagnostics = new Emitter();
1042
1529
  const states = new Emitter();
@@ -1052,15 +1539,16 @@ function startFusedSimulationGuest(port, options = {}) {
1052
1539
  /** 递增即取消正在进行的预热;真实的准备与装载都会取消它。 */
1053
1540
  let warmupGeneration = 0;
1054
1541
  let warmupPending;
1542
+ let warmupProgress = "not-started";
1055
1543
  let closing = false;
1056
1544
  let disposal;
1057
1545
  endpoint.register(fusedSimulationService, {
1058
1546
  prepare,
1059
- load,
1547
+ load: observedLoad,
1060
1548
  warmup,
1061
1549
  step,
1062
1550
  resume,
1063
- pause,
1551
+ pause: () => pause(),
1064
1552
  reset,
1065
1553
  dispose: releaseModels,
1066
1554
  invalidatePrograms: async (projectId, fingerprint) => {
@@ -1069,7 +1557,7 @@ function startFusedSimulationGuest(port, options = {}) {
1069
1557
  call: (instanceId, method, params) => callModel(instanceId, method, params),
1070
1558
  getState: () => state,
1071
1559
  onDidChangeState(listener) {
1072
- const subscription = states.event((value) => listener(value));
1560
+ const subscription = states.event(({ state, boot }) => listener(state, boot));
1073
1561
  return () => subscription.dispose();
1074
1562
  },
1075
1563
  onDidReportDiagnostic(listener) {
@@ -1088,10 +1576,13 @@ function startFusedSimulationGuest(port, options = {}) {
1088
1576
  function report(entry) {
1089
1577
  diagnostics.fire(entry);
1090
1578
  }
1091
- function setState(next) {
1092
- 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;
1093
1581
  state = next;
1094
- states.fire(next);
1582
+ states.fire({
1583
+ state: next,
1584
+ boot
1585
+ });
1095
1586
  }
1096
1587
  function assertOpen() {
1097
1588
  if (closing) throw toWireFailure(new FusedBridgeError("runtime/unavailable-state", "The fused simulation guest is disposed."));
@@ -1107,8 +1598,10 @@ function startFusedSimulationGuest(port, options = {}) {
1107
1598
  const document = parseFusedDocument(request.document);
1108
1599
  const problems = [];
1109
1600
  const instances = [];
1601
+ const stateImages = new Map(request.deviceState?.map((image) => [image.instanceId, image]));
1602
+ const deviceState = [];
1110
1603
  for (const [index, instance] of document.instances.entries()) try {
1111
- const described = await describeInstance(index, document, instance);
1604
+ const described = await describeInstance(index, document, instance, stateImages.get(instance.id), deviceState, request.observation);
1112
1605
  if (described !== void 0) instances.push(described);
1113
1606
  } catch (cause) {
1114
1607
  if (cause instanceof FusedBridgeError && cause.code === "runtime/presentation-failed") {
@@ -1127,9 +1620,12 @@ function startFusedSimulationGuest(port, options = {}) {
1127
1620
  }
1128
1621
  for (const problem of problems) report(problem);
1129
1622
  if (problems.length > 0) throw toWireFailure(new FusedBridgeError("runtime/prepare-failed", `${problems.length} instance(s) cannot join the 2D scene.`));
1130
- return { instances };
1623
+ return {
1624
+ instances,
1625
+ ...request.deviceState === void 0 ? {} : { deviceState }
1626
+ };
1131
1627
  }
1132
- async function describeInstance(index, document, instance) {
1628
+ async function describeInstance(index, document, instance, stateImage, deviceState, observation) {
1133
1629
  const dependency = document.dependencies[instance.device];
1134
1630
  if (dependency === void 0) throw new FusedBridgeError("document/unlocked-device", `Instance "${instance.id}" uses the unlocked device "${instance.device}".`, { instanceId: instance.id });
1135
1631
  const lock = {
@@ -1137,7 +1633,27 @@ function startFusedSimulationGuest(port, options = {}) {
1137
1633
  version: dependency.version,
1138
1634
  integrity: dependency.integrity
1139
1635
  };
1140
- const verified = await openVerifiedPackage(lock);
1636
+ const verified = await openVerifiedPackage(lock, observation);
1637
+ const descriptors = verified.manifest.properties ?? {};
1638
+ let props;
1639
+ if (stateImage !== void 0) {
1640
+ const method = verified.manifest.model?.methods?.[stateImage.method];
1641
+ const event = verified.manifest.model?.events?.[stateImage.event];
1642
+ if (descriptors[stateImage.property]?.type !== "binary" || method === void 0 || !("type" in method.params) || method.params.type !== "null" || !("type" in method.returns) || method.returns.type !== "binary" || event === void 0 || !("type" in event) || event.type !== "binary") throw new Error(`Invalid device state binding for "${instance.id}".`);
1643
+ const override = stateImage.image;
1644
+ try {
1645
+ props = await resolvePresentationProps(verified, descriptors, instance, index, override === void 0 ? void 0 : /* @__PURE__ */ new Map([[stateImage.property, override]]));
1646
+ } catch (cause) {
1647
+ throw new Error(`Could not resolve the state seed for "${instance.id}": ${messageOf(cause)}`, { cause });
1648
+ }
1649
+ const value = props[stateImage.property];
1650
+ const image = value === null ? new Uint8Array(stateImage.byteLength) : value.slice();
1651
+ if (image.length !== stateImage.byteLength) throw new Error(`Invalid device state image length for "${instance.id}".`);
1652
+ deviceState.push({
1653
+ instanceId: instance.id,
1654
+ image
1655
+ });
1656
+ }
1141
1657
  const view = verified.manifest.view2d;
1142
1658
  if (view === void 0) {
1143
1659
  report({
@@ -1149,14 +1665,13 @@ function startFusedSimulationGuest(port, options = {}) {
1149
1665
  }
1150
1666
  const pins = Object.keys(verified.manifest.pins ?? {});
1151
1667
  const geometryValue = typeof view.geometry === "string" ? parseStrictJson(decodeSource(await verified.read(view.geometry))) : view.geometry;
1152
- const descriptors = verified.manifest.properties ?? {};
1153
1668
  return {
1154
1669
  instanceId: instance.id,
1155
1670
  device: instance.device,
1156
1671
  lock,
1157
1672
  geometry: parseGeometry2D(geometryValue, pins),
1158
1673
  view: view.entry,
1159
- props: presentationProps(await resolvePresentationProps(verified, descriptors, instance, index), descriptors),
1674
+ props: presentationProps(props ?? await resolvePresentationProps(verified, descriptors, instance, index), descriptors),
1160
1675
  methods: Object.keys(verified.manifest.model?.methods ?? {}),
1161
1676
  events: Object.keys(verified.manifest.model?.events ?? {})
1162
1677
  };
@@ -1168,13 +1683,14 @@ function startFusedSimulationGuest(port, options = {}) {
1168
1683
  *
1169
1684
  * @throws {FusedBridgeError} `runtime/presentation-failed` naming every property that failed.
1170
1685
  */
1171
- async function resolvePresentationProps(verified, descriptors, instance, index) {
1686
+ async function resolvePresentationProps(verified, descriptors, instance, index, binaryOverrides) {
1172
1687
  try {
1173
1688
  return (await resolveInstanceProperties({
1174
1689
  instanceId: instance.id,
1175
1690
  package: verified,
1176
1691
  descriptors,
1177
1692
  overrides: instance.properties ?? {},
1693
+ ...binaryOverrides === void 0 ? {} : { binaryOverrides },
1178
1694
  irProperties: /* @__PURE__ */ new Map(),
1179
1695
  pointer: [
1180
1696
  "instances",
@@ -1202,7 +1718,15 @@ function startFusedSimulationGuest(port, options = {}) {
1202
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)}.`));
1203
1719
  const generation = ++warmupGeneration;
1204
1720
  const current = () => !closing && generation === warmupGeneration;
1205
- 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(() => {
1206
1730
  if (warmupPending === task) warmupPending = void 0;
1207
1731
  });
1208
1732
  warmupPending = task;
@@ -1213,7 +1737,7 @@ function startFusedSimulationGuest(port, options = {}) {
1213
1737
  try {
1214
1738
  created = await createHeadlessRuntime({
1215
1739
  document: parseFusedDocument(request.document),
1216
- registry: verifiedRegistry,
1740
+ registry: verifiedRegistry(request.observation),
1217
1741
  loadModule,
1218
1742
  step,
1219
1743
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
@@ -1221,15 +1745,20 @@ function startFusedSimulationGuest(port, options = {}) {
1221
1745
  programs: resources.programs,
1222
1746
  onModelEvent: () => {}
1223
1747
  });
1224
- if (!current()) return;
1748
+ if (!current()) return "cancelled";
1225
1749
  const slice = Math.floor(step / WARMUP_SLICES);
1226
1750
  for (let index = 1; index <= WARMUP_SLICES; index++) {
1227
- if (!current()) return;
1751
+ if (!current()) return "cancelled";
1228
1752
  const amount = index === WARMUP_SLICES ? step - slice * 7 : slice;
1229
1753
  await created.step(timePs(amount));
1754
+ if (!current()) return "cancelled";
1755
+ warmupProgress = index === WARMUP_SLICES ? "completed" : "partial";
1230
1756
  if (index < WARMUP_SLICES) await yieldToHost();
1231
1757
  }
1232
- } catch {} finally {
1758
+ return "completed";
1759
+ } catch {
1760
+ return current() ? "failed" : "cancelled";
1761
+ } finally {
1233
1762
  if (created !== void 0) await created.dispose().catch(() => void 0);
1234
1763
  }
1235
1764
  }
@@ -1238,7 +1767,42 @@ function startFusedSimulationGuest(port, options = {}) {
1238
1767
  warmupGeneration += 1;
1239
1768
  warmupPending = void 0;
1240
1769
  }
1241
- 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) {
1242
1806
  assertOpen();
1243
1807
  cancelWarmup();
1244
1808
  const step = request.step;
@@ -1253,16 +1817,19 @@ function startFusedSimulationGuest(port, options = {}) {
1253
1817
  const pending = [];
1254
1818
  let created;
1255
1819
  try {
1820
+ const binaryOverrides = /* @__PURE__ */ new Map();
1821
+ for (const entry of request.deviceState ?? []) if (entry.image !== void 0) binaryOverrides.set(entry.instanceId, /* @__PURE__ */ new Map([[entry.property, entry.image]]));
1256
1822
  created = await createHeadlessRuntime({
1257
1823
  document,
1258
- registry: verifiedRegistry,
1824
+ registry: verifiedRegistry(request.observation),
1259
1825
  loadModule,
1260
1826
  step,
1261
1827
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
1262
1828
  resolveResource: resources.resolveResource,
1829
+ ...binaryOverrides.size === 0 ? {} : { binaryOverrides },
1263
1830
  programs: resources.programs,
1264
1831
  onModelEvent: (event) => {
1265
- if (sessionToken === token) publishModelEvent(event);
1832
+ if (sessionToken === token) publishModelEvent(event, request.stateGeneration);
1266
1833
  else if (!superseded()) pending.push(event);
1267
1834
  },
1268
1835
  onDiagnostic: (entry) => {
@@ -1286,23 +1853,24 @@ function startFusedSimulationGuest(port, options = {}) {
1286
1853
  runtime: created,
1287
1854
  step,
1288
1855
  pacing: pacing ?? "unlimited",
1856
+ warmup: warmupProgress,
1289
1857
  run: void 0,
1290
1858
  subscriptions: [created.onDidChangeState((next) => {
1291
1859
  if (sessionToken !== token) return;
1292
1860
  if (next.status === "paused" && adopted.run !== void 0) return;
1293
- stopRun(adopted);
1294
- setState(next);
1861
+ setState(next, stopRun(adopted, next.status === "faulted" ? "failure" : "cancelled"));
1295
1862
  }), created.onDidReportDiagnostic((entry) => {
1296
1863
  if (sessionToken === token) report(entry);
1297
1864
  })]
1298
1865
  };
1299
1866
  session = adopted;
1300
- for (const event of pending.splice(0)) publishModelEvent(event);
1867
+ for (const event of pending.splice(0)) publishModelEvent(event, request.stateGeneration);
1301
1868
  const initial = created.getState();
1302
1869
  setState({
1303
1870
  status: initial.status,
1304
1871
  simTime: initial.simTime
1305
1872
  });
1873
+ onLoaded?.(document.instances.length);
1306
1874
  return state;
1307
1875
  }
1308
1876
  async function step() {
@@ -1311,17 +1879,49 @@ function startFusedSimulationGuest(port, options = {}) {
1311
1879
  await mapGuestCall(() => target.runtime.step());
1312
1880
  return state;
1313
1881
  }
1314
- async function resume() {
1882
+ async function resume(context) {
1315
1883
  const target = requireSession("resume");
1316
1884
  if (target.run !== void 0) return;
1317
1885
  const current = target.runtime.getState();
1318
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();
1319
1888
  const run = {
1320
- wallStartMs: performance.now(),
1889
+ wallStartMs: startedAt,
1321
1890
  simStartPs: current.simTime,
1322
1891
  timer: void 0,
1323
- waiting: void 0
1892
+ waiting: void 0,
1893
+ finishBoot: void 0
1324
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
+ }
1325
1925
  target.run = run;
1326
1926
  setState({
1327
1927
  status: "starting",
@@ -1341,8 +1941,14 @@ function startFusedSimulationGuest(port, options = {}) {
1341
1941
  const amount = index === slices ? target.step - slice * (slices - 1) : slice;
1342
1942
  try {
1343
1943
  await target.runtime.step(timePs(amount));
1344
- } catch {
1345
- 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
+ }
1346
1952
  return;
1347
1953
  }
1348
1954
  if (target.run !== run) return;
@@ -1351,10 +1957,11 @@ function startFusedSimulationGuest(port, options = {}) {
1351
1957
  if (target.run !== run) return;
1352
1958
  run.wallStartMs = performance.now();
1353
1959
  run.simStartPs = target.runtime.getState().simTime;
1960
+ const boot = run.finishBoot?.("success");
1354
1961
  setState({
1355
1962
  status: "running",
1356
1963
  simTime: run.simStartPs
1357
- });
1964
+ }, boot);
1358
1965
  scheduleSlice(target, run, run.wallStartMs);
1359
1966
  }
1360
1967
  /** Returns to the event loop; `stopRun` resolves the same promise so a stop is immediate. */
@@ -1414,20 +2021,29 @@ function startFusedSimulationGuest(port, options = {}) {
1414
2021
  });
1415
2022
  scheduleSlice(target, run, startedAt);
1416
2023
  }
1417
- function stopRun(target) {
2024
+ function stopRun(target, outcome = "cancelled") {
1418
2025
  const run = target.run;
1419
2026
  target.run = void 0;
1420
2027
  if (run === void 0) return;
2028
+ const boot = run.finishBoot?.(outcome);
1421
2029
  clearTimeout(run.timer);
1422
2030
  run.timer = void 0;
1423
2031
  const waiting = run.waiting;
1424
2032
  run.waiting = void 0;
1425
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
+ };
1426
2042
  }
1427
- function pause() {
2043
+ function pause(outcome = "cancelled") {
1428
2044
  if (session === void 0) return;
1429
- stopRun(session);
1430
- setState(session.runtime.getState());
2045
+ const boot = stopRun(session, outcome);
2046
+ setState(session.runtime.getState(), boot);
1431
2047
  }
1432
2048
  async function reset() {
1433
2049
  const target = requireSession("reset");
@@ -1471,11 +2087,12 @@ function startFusedSimulationGuest(port, options = {}) {
1471
2087
  if (strict) throw toWireFailure(cause);
1472
2088
  }
1473
2089
  }
1474
- function publishModelEvent(event) {
2090
+ function publishModelEvent(event, stateGeneration) {
1475
2091
  const wire = {
1476
2092
  instanceId: event.instanceId,
1477
2093
  event: event.event,
1478
- payload: event.payload
2094
+ payload: event.payload,
2095
+ ...stateGeneration === void 0 ? {} : { stateGeneration }
1479
2096
  };
1480
2097
  modelChannel?.deliver(wire);
1481
2098
  events.fire(wire);
@@ -2011,10 +2628,10 @@ function closeBitmap(bitmap) {
2011
2628
  * same factories to several runtimes.
2012
2629
  */
2013
2630
  async function loadFusedWorkerFactories() {
2014
- const { fusedWorkerFactories } = await import("./workers-Og_Z_xzw.js");
2631
+ const { fusedWorkerFactories } = await import("./workers-BpHcfNEu.js");
2015
2632
  return fusedWorkerFactories;
2016
2633
  }
2017
2634
  //#endregion
2018
- 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 };
2019
2636
 
2020
- //# sourceMappingURL=runtime-hyeAcSP7.js.map
2637
+ //# sourceMappingURL=runtime-DuxZ_yVl.js.map