@wildshard/engine 0.1.21 → 0.1.22

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 (57) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +3 -0
  3. package/lint/shardfile-boundaries.mjs +4 -2
  4. package/lint/wildshard-plugin.js +1 -1
  5. package/package.json +2 -1
  6. package/scripts/audio-download-proof.mjs +1 -1
  7. package/scripts/check-spelled-paths.mjs +6 -3
  8. package/scripts/committed-fast-checks.mjs +2 -2
  9. package/scripts/failmode-cases.mjs +1 -1
  10. package/scripts/failmode-proof.mjs +35 -11
  11. package/scripts/grid-crossing-walk-proof.mjs +3 -3
  12. package/scripts/hover-speed-probe.mjs +2 -2
  13. package/scripts/mmo-bots.mjs +7 -3
  14. package/scripts/net-lag-proof.mjs +1 -1
  15. package/scripts/online-rig.mjs +7 -7
  16. package/scripts/parity/boot-smoke.mjs +1 -1
  17. package/scripts/release-cook.mjs +6 -2
  18. package/scripts/test-products.json +0 -21
  19. package/scripts/vps/cook-follow.d.mts +6 -0
  20. package/scripts/vps/cook-follow.mjs +45 -0
  21. package/scripts/vps/harden-apply.sh +10 -1
  22. package/scripts/vps/rebuild.sh +104 -36
  23. package/scripts/vps/wildshard-config +0 -2
  24. package/src/client/app/entry.ts +2 -3
  25. package/src/client/engine/boot/contentRead.ts +24 -4
  26. package/src/client/engine/boot/downloadGiveUp.ts +34 -0
  27. package/src/client/engine/combat/EquipmentService.ts +2 -0
  28. package/src/client/engine/core/Game.ts +6 -2
  29. package/src/client/engine/ui/downloadFailed.ts +54 -0
  30. package/src/client/game/boot/spawnDownload.ts +12 -1
  31. package/src/client/game/grid/copyPrompts.ts +3 -4
  32. package/src/client/game/grid/dataCellKit.ts +91 -0
  33. package/src/client/game/grid/enteredEquipment.ts +11 -2
  34. package/src/client/game/grid/live.ts +9 -299
  35. package/src/client/game/grid/liveSession.ts +31 -8
  36. package/src/client/game/grid/neighbourLife.ts +50 -32
  37. package/src/client/game/grid/reveal.ts +7 -2
  38. package/src/client/game/grid/session.ts +4 -70
  39. package/src/client/game/plugin/weaponFamily.ts +6 -0
  40. package/src/client/game/shardfile/clientWorker.ts +13 -3
  41. package/src/client/host/online/shell.ts +37 -13
  42. package/src/server/game/grid/room.ts +2 -38
  43. package/src/server/game/shardfile/declaredKitItems.ts +8 -2
  44. package/src/server/host/dedicated/cellHost.ts +2 -2
  45. package/src/server/host/dedicated/cellProtocol.ts +1 -1
  46. package/src/server/host/dedicated/cellWorker.ts +1 -1
  47. package/src/server/host/dedicated/dedicatedRoom.ts +8 -3
  48. package/src/server/host/dedicated/gridCells.ts +5 -3
  49. package/src/server/host/dedicated/main.ts +6 -4
  50. package/src/server/host/dedicated/workerTable.ts +0 -10
  51. package/src/server/host/dedicated/world.ts +39 -5
  52. package/src/server/host/standalone/cellWorld.ts +1 -1
  53. package/src/shared/engine/saves/shape.ts +17 -2
  54. package/src/shared/engine/strings.ts +10 -0
  55. package/src/shared/game/grid/placementRows.ts +4 -3
  56. package/src/client/game/grid/cellLoading.ts +0 -110
  57. package/src/client/game/grid/cellScreens.ts +0 -48
@@ -49,7 +49,6 @@ import type { NeighbourRegion } from './neighbourLife';
49
49
  import type { ResidencyAllocator } from '../../../shared/game/grid/allocator';
50
50
  import type { HomeResidencyClaim } from './pageResidency';
51
51
  import { LiveGridHost, type LiveGridAdmission, type LiveGridFrame, type LiveGridRegion, type LiveGridState } from './live';
52
- import { prepareApproachProductInputs } from './approachProductInputs';
53
52
  import { installGridCrossing, type GridCheckpointResult, type GridCrossingSession, type GridCrossingState } from '../../../shared/game/grid/crossing';
54
53
  import { GridWallet, stowGridMount } from '../../../shared/game/grid/wallet';
55
54
  import type { LedgerCatalogueItem } from '../../../shared/game/ledger';
@@ -78,6 +77,7 @@ import { copyPrompts, enteredCopy } from './copyPrompts';
78
77
  import { yieldGridAdmission, yieldGridConstruction } from './admissionYield';
79
78
  import { HybridRuntimeSession, type HybridResident } from '../shardfile/hybrid';
80
79
 
80
+ import { enterDataCellKit, holdsItems } from './dataCellKit';
81
81
  import { enterPlotAudio, pagePlotAudioPorts, plotAudioScene, type PlotAudioPorts, type PlotAudioScene } from './plotAudio';
82
82
  import { shardProductFromAdmission } from '../shardfile/runtimeProduct';
83
83
  import { createRegionalRuntimeFactory, regionalRuntimeAccountedBytes, type PreparedRegionalRuntime, type RegionalRuntimePage, type RegionalRuntimeTextures } from './regionalRuntime';
@@ -235,9 +235,13 @@ export class LiveGridSession {
235
235
  private readonly applied = new Vector3();
236
236
  private readonly roadWallet: GridWallet;
237
237
  /** each admitted region's authored spawn (its level's player start) and its ground / water queries, local */
238
- private readonly regions = new Map<string, { readonly spawn: LiveGridSpawn; readonly items: Shardfile['items']['rows']; readonly queries: PlayerFrameQueries; readonly colliders: PanelRegion['colliders']; readonly prompts: ReturnType<typeof copyPrompts>; readonly audio: PlotAudioScene | null }>();
238
+ private readonly regions = new Map<string, { readonly spawn: LiveGridSpawn; readonly items: Shardfile['items']['rows']; readonly queries: PlayerFrameQueries; readonly colliders: PanelRegion['colliders']; readonly prompts: ReturnType<typeof copyPrompts>; readonly audio: PlotAudioScene | null;
239
+ /** TC-E1b: the copy's admitted source and assets, its declared kit built from them on entry */
240
+ readonly kit: { readonly source: Shardfile; readonly assets: ReadonlyMap<string, Uint8Array> } | null }>();
239
241
  /** AU20: the entered data cell's own audio scene (an Open Plot's score, bed and loops), live while the feet are in it. */
240
242
  private plotAudio: { readonly instance: string; readonly scope: Scope } | null = null;
243
+ /** TC-E1b: the entered data cell's held kit, disposed when the feet leave it */
244
+ private dataKit: { readonly instance: string; readonly scope: Scope } | null = null;
241
245
  private readonly plotBanks = new Map<string, ReturnType<PlotAudioPorts['bank']>>();
242
246
  private readonly runtimeScope: Scope;
243
247
  private readonly runtimeRegions = new Map<string, PreparedRegionalRuntime>();
@@ -273,9 +277,9 @@ export class LiveGridSession {
273
277
  this.runtimeScope = scope.child('grid.runtime.residents');
274
278
  this.hybrid = new HybridRuntimeSession(this.runtimeResidents, scope, { pause: yieldGridConstruction });
275
279
  scope.onDispose(gridCells.onLeave(() => { this.hybrid.leave(); this.prepareDeferredEntries(); }));
276
- scope.onDispose(gridCells.onLeave(() => { this.leavePlotAudio(); }));
280
+ scope.onDispose(gridCells.onLeave(() => { this.leavePlotAudio(); this.leaveDataKit(); }));
277
281
  scope.onDispose(gridCells.onEnter(cell => {
278
- if (!this.runtimeResidents.has(cell.instance)) { this.enterPlotAudio(cell.instance); ports.lightingSettled?.(); return; }
282
+ if (!this.runtimeResidents.has(cell.instance)) { this.enterPlotAudio(cell.instance); this.enterDataKit(cell.instance); ports.lightingSettled?.(); return; }
279
283
  this.startedRuntimes.add(cell.instance);
280
284
  const activation = this.hybrid.enter(cell);
281
285
  this.activation = activation;
@@ -309,8 +313,6 @@ export class LiveGridSession {
309
313
  return { physics: ports.physics, walls: ports.walls, dispose: () => { highwayScope.dispose(); } };
310
314
  } },
311
315
  admit: (cell, required) => this.admit(cell, required),
312
- buildAhead: true, // GC5 / GC36: the road builds the world ahead of its line
313
- prepareTransport: (cell, signal) => prepareApproachProductInputs(cell.slug, { allocator: ports.allocator, scope }, signal, assembly.local(traveller.position, cell)),
314
316
  ...(ports.prepareNeighbourTiles === undefined ? {} : { prepareNeighbour: ports.prepareNeighbourTiles }),
315
317
  prioritize: (cell) => prioritizeGridProduct(cell.slug, { allocator: ports.allocator, scope }),
316
318
  pause: () => yieldGridAdmission(scope),
@@ -711,10 +713,12 @@ export class LiveGridSession {
711
713
  transfer.sync(); this.transferWalls.set(cell.instance, transfer);
712
714
  this.regions.set(cell.instance, { spawn: { x: start.at.x, y: undefined, z: start.at.z, yaw: start.yaw },
713
715
  // the admitted terrain inside the cell (one source of truth); its strips are road level (the terrain tile ends at the cell edge)
714
- queries: { heightAt: (x, z) => (Math.max(Math.abs(x), Math.abs(z)) <= CHUNK_HALF ? heightAt(x, z) : 0), waterSurfaceAt: (x, z) => water.restAt(x, z), platforms: [] }, colliders, items: copySource.items.rows, prompts: copyPrompts(copySource),
716
+ queries: { heightAt: (x, z) => (Math.max(Math.abs(x), Math.abs(z)) <= CHUNK_HALF ? heightAt(x, z) : 0), waterSurfaceAt: (x, z) => water.restAt(x, z), platforms: [] }, colliders, items: copySource.items.rows, prompts: copyPrompts(copySource), kit: holdsItems(copySource) ? { source: copySource, assets } : null,
715
717
  // AU20: the cell's declared audio scene, bound only while the feet stand in it (no entered hooks run here)
716
718
  audio: source.runtime === null && source.audio.scene !== undefined ? plotAudioScene(source, ((plot) => plot.has('client/plan') ? plot.section('client/plan') : undefined)(shardProductFromAdmission(retained.admitted, shell.scope))) : null });
717
719
  this.respawnCells.set(cell.instance, { instance: cell.instance, origin: cell.origin, entryways: source.entryways });
720
+ // TC-E1b: feet that entered before this admission finished get the cell's kit now
721
+ if (gridCells.cell?.instance === cell.instance && this.dataKit === null) this.enterDataKit(cell.instance);
718
722
  // G321: its own sky inside its cell (its data look's dome and light), laid while it is resident
719
723
  {
720
724
  const request = { instance: cell.instance, slug: cell.slug, look: copySource.look, assets, page: this.page.runtimePage?.() ?? null, allocator: this.ports.allocator, scope: shell.scope };
@@ -722,7 +726,7 @@ export class LiveGridSession {
722
726
  try { await hangCellDataSky(request); } catch (error) { console.warn(`[region sky] ${cell.instance}`, error); }
723
727
  })();
724
728
  }
725
- const unlist = (): void => { if (this.plotAudio?.instance === cell.instance) this.leavePlotAudio(); this.plotBanks.delete(cell.instance); this.regions.delete(cell.instance); this.transferWalls.delete(cell.instance); };
729
+ const unlist = (): void => { if (this.plotAudio?.instance === cell.instance) this.leavePlotAudio(); if (this.dataKit?.instance === cell.instance) this.leaveDataKit(); this.plotBanks.delete(cell.instance); this.regions.delete(cell.instance); this.transferWalls.delete(cell.instance); };
726
730
  return { host: shell, shell, dispose: () => {
727
731
  unlist();
728
732
  try { shell.dispose(); } finally { retained.release(); }
@@ -856,6 +860,25 @@ export class LiveGridSession {
856
860
  try { enterPlotAudio(scene, owner, ports); }
857
861
  catch (error) { this.leavePlotAudio(); ports.fault(error); }
858
862
  }
863
+ /** TC-E1b: the feet entered a data cell; its declared items are the page's held kit until they leave. */
864
+ private enterDataKit(instance: string): void {
865
+ this.leaveDataKit();
866
+ const kit = this.regions.get(instance)?.kit ?? null, page = this.page.runtimePage?.() ?? null;
867
+ if (kit === null || page === null) return;
868
+ const entry = this.ports.scope.child(`grid.data-kit.${instance}`);
869
+ this.dataKit = { instance, scope: entry };
870
+ const enter = async (): Promise<void> => {
871
+ try { await enterDataCellKit(kit.source, kit.assets, page, entry, () => this.wire === null || this.wire.site() === instance); } catch (error: unknown) {
872
+ if (this.dataKit?.scope === entry) this.leaveDataKit();
873
+ console.error(`[grid] ${instance}'s declared kit refused`, error);
874
+ }
875
+ };
876
+ void enter();
877
+ }
878
+ private leaveDataKit(): void {
879
+ const entered = this.dataKit; this.dataKit = null;
880
+ entered?.scope.dispose();
881
+ }
859
882
  private leavePlotAudio(): void {
860
883
  const entered = this.plotAudio; this.plotAudio = null;
861
884
  entered?.scope.dispose();
@@ -1,8 +1,11 @@
1
1
  /**
2
- * A cell's client life (SHARD-PLATFORM SF25 render side): each shardfile cell that declares `clientScripts` gets its
3
- * creatures drawn in its cell root (the SF9c skins, following its regional host's authoritative entities) and its own
2
+ * A cell's client life (SHARD-PLATFORM SF25 render side): a shardfile cell gets its creatures drawn in its cell root (the
3
+ * SF9c skins, following its regional host's authoritative entities): the ones its `clientScripts` bind, and in a data cell
4
+ * (no runtime, no declared client page: the templates) every spawn with a skin look, bound or not (TEMPLATE-E2E TC-E1a:
5
+ * Brasscap binds only particles, so its bandits were never drawn). A cell that declares `clientScripts` also gets its own
4
6
  * isolated client lane (`createShardfileClientScripts`, sp-x5) stepped on the page's fixed tick; `ClientScriptViews`
5
- * composes its frames on top of the views and draws its particles. Nothing here writes a simulation.
7
+ * composes its frames on top of the views and draws its particles. A lane that fails to build leaves the creatures drawn.
8
+ * Nothing here writes a simulation.
6
9
  *
7
10
  * Only while the traveller is inside the cell (G663, tile streaming T7: a neighbour is scene-graph level of detail, with
8
11
  * no logic or runtime; it replaced G66's "frozen, but alive-looking" neighbours): a frozen cell's lane never steps and its
@@ -15,6 +18,7 @@ import type { ClientScriptTarget } from '@wildshard/format/clientScripts';
15
18
  import { loadClientSkins, SkinDriver, type ClientSkin, type SkinDriveState } from '../shardfile/clientSkins';
16
19
  import { ClientScriptViews, type ClientScriptViewTarget, type ClientScriptViewState } from "../plugin/ui";
17
20
  import type { Shardfile } from '@wildshard/format/shardSchema';
21
+ import { hasDeclaredClientPage } from '@wildshard/format/runtimeBinds';
18
22
  import type { GridCell } from '../../../shared/game/grid/assembly';
19
23
 
20
24
  /** One creature as a view draws it (E6): a page reads the region's sim entity, a client reads its row. */
@@ -37,7 +41,8 @@ export interface NeighbourLifeCell { readonly instance: string; readonly creatur
37
41
  interface CreatureView { readonly id: string; readonly mesh: SkinnedMesh; readonly driver: SkinDriver; readonly spawn: { at: readonly [number, number, number]; yaw: number; scale: number }; readonly bodyY: number; t: number; phase: number }
38
42
  interface CellLife {
39
43
  readonly cell: GridCell; readonly root: Group; readonly creatures: ReadonlyMap<string, CreatureView>;
40
- readonly scripts: ReturnType<typeof createShardfileClientScripts>; readonly views: ClientScriptViews; failed: string | null;
44
+ /** null: the cell binds no script (or its lane failed to build, `failed` says why); its creatures still draw */
45
+ lane: { readonly scripts: ReturnType<typeof createShardfileClientScripts>; readonly views: ClientScriptViews } | null; failed: string | null;
41
46
  }
42
47
 
43
48
  /** A static view of one skin: the factory's bone layout (positions relative to the parent), bound once. */
@@ -68,17 +73,19 @@ export class NeighbourLife {
68
73
 
69
74
  /** Admit one neighbour's life once its product and materials are ready (the session's shared per-slug load). */
70
75
  async admit(cell: GridCell, root: Group, source: Shardfile, assets: ReadonlyMap<string, Uint8Array>, compile: Parameters<typeof loadClientSkins>[2], skinsBySlug: Map<string, Promise<ReadonlyMap<string, ClientSkin>>>): Promise<void> {
71
- const declared = source.clientScripts;
72
- if (declared.bindings.length === 0 || this.cells.has(cell.instance)) return;
76
+ const declared = source.clientScripts, data = source.runtime === null && !hasDeclaredClientPage(source);
77
+ // the creatures this page draws: the script-bound ones, and in a data cell every spawn (its runtime draws a native cell's)
78
+ const drawn = [...new Set([...declared.bindings.flatMap((binding) => binding.target.kind === 'creature' ? [binding.target.id] : []),
79
+ ...(data ? source.creatures.spawns.map((row) => row.id) : [])])];
80
+ if ((declared.bindings.length === 0 && drawn.length === 0) || this.cells.has(cell.instance)) return;
73
81
  const scope = this.ports.scope;
74
82
  let loading = skinsBySlug.get(cell.slug);
75
83
  if (loading === undefined) { loading = loadClientSkins(source, assets, compile, scope); skinsBySlug.set(cell.slug, loading); }
76
84
  const skins = await loading;
77
85
  if (scope.disposed) return;
78
86
  const creatures = new Map<string, CreatureView>();
79
- for (const binding of declared.bindings) {
80
- if (binding.target.kind !== 'creature' || creatures.has(binding.target.id)) continue;
81
- const id = binding.target.id, spawn = source.creatures.spawns.find((row) => row.id === id);
87
+ for (const id of drawn) {
88
+ const spawn = source.creatures.spawns.find((row) => row.id === id);
82
89
  const species = spawn === undefined ? undefined : source.rows.species.find((row) => row.id === spawn.species);
83
90
  const look = species === undefined ? undefined : source.rows.looks.find((row) => row.species === species.id);
84
91
  const skin = look === undefined ? undefined : skins.get(look.id);
@@ -89,6 +96,20 @@ export class NeighbourLife {
89
96
  root.add(mesh); creatures.set(id, view);
90
97
  }
91
98
  const instance = cell.instance;
99
+ const life: CellLife = { cell, root, creatures, lane: null, failed: null };
100
+ if (declared.bindings.length > 0) {
101
+ try { life.lane = this.lane(instance, source, assets, root, creatures); } catch (error) { life.failed = error instanceof Error ? error.message : String(error); }
102
+ }
103
+ this.cells.set(instance, life);
104
+ scope.onDispose(() => {
105
+ life.lane?.scripts.dispose();
106
+ for (const view of creatures.values()) { view.mesh.removeFromParent(); view.mesh.skeleton.dispose(); const m = view.mesh.material; if (!Array.isArray(m)) m.dispose(); }
107
+ });
108
+ }
109
+
110
+ /** The cell's own client lane and the views its frames compose on (throws when its scripts are refused). */
111
+ private lane(instance: string, source: Shardfile, assets: ReadonlyMap<string, Uint8Array>, root: Group, creatures: ReadonlyMap<string, CreatureView>): NonNullable<CellLife['lane']> {
112
+ const declared = source.clientScripts;
92
113
  const observe = (target: ClientScriptTarget): { position: readonly [number, number, number]; frozen: boolean } => {
93
114
  const frozen = !this.ports.active(instance);
94
115
  if (target.kind === 'particles') return { position: target.at, frozen };
@@ -97,39 +118,36 @@ export class NeighbourLife {
97
118
  const p = view.mesh.position; return { position: [p.x, p.y, p.z], frozen };
98
119
  };
99
120
  const scripts = createShardfileClientScripts(source, assets, { actorId: 'actor.neighbour', observe });
100
- const targets = scripts.targets.map(({ entity, target }): ClientScriptViewTarget => {
101
- const view = target.kind === 'creature' ? creatures.get(target.id) : undefined;
102
- const emitters = declared.bindings.find((b) => b.entity === entity)?.emitters.map((e) => ({ id: e.id, live: e.live, colour: e.colour, size: e.size, velocity: e.velocity, gravity: e.gravity })) ?? [];
103
- const anchor = (out: Vector3): Vector3 => {
104
- if (target.kind === 'particles') return out.fromArray(target.at);
105
- if (view === undefined) return out.set(0, 0, 0);
106
- return out.copy(view.mesh.position).setY(view.mesh.position.y + view.bodyY * 1.6);
107
- };
108
- const object: Object3D | null = view?.mesh ?? null;
109
- return { entity, object, anchor, emitters };
110
- });
111
- const views = new ClientScriptViews(scripts.lane, targets, { root, scope });
112
- const life: CellLife = { cell, root, creatures, scripts, views, failed: null };
113
- this.cells.set(instance, life);
114
- scope.onDispose(() => {
115
- scripts.dispose();
116
- for (const view of creatures.values()) { view.mesh.removeFromParent(); view.mesh.skeleton.dispose(); const m = view.mesh.material; if (!Array.isArray(m)) m.dispose(); }
117
- });
121
+ try {
122
+ const targets = scripts.targets.map(({ entity, target }): ClientScriptViewTarget => {
123
+ const view = target.kind === 'creature' ? creatures.get(target.id) : undefined;
124
+ const emitters = declared.bindings.find((b) => b.entity === entity)?.emitters.map((e) => ({ id: e.id, live: e.live, colour: e.colour, size: e.size, velocity: e.velocity, gravity: e.gravity })) ?? [];
125
+ const anchor = (out: Vector3): Vector3 => {
126
+ if (target.kind === 'particles') return out.fromArray(target.at);
127
+ if (view === undefined) return out.set(0, 0, 0);
128
+ return out.copy(view.mesh.position).setY(view.mesh.position.y + view.bodyY * 1.6);
129
+ };
130
+ const object: Object3D | null = view?.mesh ?? null;
131
+ return { entity, object, anchor, emitters };
132
+ });
133
+ return { scripts, views: new ClientScriptViews(scripts.lane, targets, { root, scope: this.ports.scope }) };
134
+ } catch (error) { scripts.dispose(); throw error; }
118
135
  }
119
136
 
120
137
  /** The page's fixed step: the entered cell's lane advances on the page tick. */
121
138
  fixed(): void {
122
139
  const tick = this.tick++;
123
140
  for (const life of this.cells.values()) {
124
- if (life.failed !== null || !this.ports.active(life.cell.instance)) continue; // G663: no neighbour logic
125
- try { life.scripts.step(tick); } catch (error) { life.failed = error instanceof Error ? error.message : String(error); life.views.restore(); }
141
+ const { lane } = life;
142
+ if (lane === null || life.failed !== null || !this.ports.active(life.cell.instance)) continue; // G663: no neighbour logic
143
+ try { lane.scripts.step(tick); } catch (error) { life.failed = error instanceof Error ? error.message : String(error); lane.views.restore(); }
126
144
  }
127
145
  }
128
146
 
129
147
  /** The page's late phase: views back to base, follow the region (if admitted), then compose the scripts on top. */
130
148
  late(dt: number): void {
131
149
  for (const life of this.cells.values()) {
132
- life.views.restore();
150
+ life.lane?.views.restore();
133
151
  const region = this.ports.simulation(life.cell.instance), live = this.ports.active(life.cell.instance);
134
152
  // G663: a frozen cell draws none of its creatures and composes no lane
135
153
  if (!live) { for (const view of life.creatures.values()) view.mesh.visible = false; continue; }
@@ -141,11 +159,11 @@ export class NeighbourLife {
141
159
  view.phase = (view.phase + dt * Math.hypot(speed, strafe) * 0.6) % 1;
142
160
  view.driver.step({ dt, t: view.t, alive: sim?.alive ?? true, flinch: 0, attack: sim?.attackPhase ?? -1, speed, strafe, scale: sim?.scale ?? view.spawn.scale, phase: view.phase, state: sim?.state ?? 'idle' });
143
161
  }
144
- if (life.failed === null) life.views.apply(dt);
162
+ if (life.failed === null) life.lane?.views.apply(dt);
145
163
  }
146
164
  }
147
165
 
148
166
  state(): readonly NeighbourLifeCell[] {
149
- return [...this.cells.values()].map((life) => ({ instance: life.cell.instance, creatures: life.creatures.size, frozen: !this.ports.active(life.cell.instance), views: life.views.state(), failed: life.failed }));
167
+ return [...this.cells.values()].map((life) => ({ instance: life.cell.instance, creatures: life.creatures.size, frozen: !this.ports.active(life.cell.instance), views: life.lane?.views.state() ?? { targets: 0, posed: 0, particles: 0, capacity: 0, tick: 0 }, failed: life.failed }));
150
168
  }
151
169
  }
@@ -70,7 +70,10 @@ export function installGridReveal(host: GridRevealHost): () => boolean {
70
70
  let pathEnd: number | null = null, ringsAt: number | null = null, homeAt: number | null = null, endedAt: number | null = null;
71
71
  let layer: HTMLElement | null = null;
72
72
  let viewmodelWas = true;
73
- const wasEnabled = host.weapons.enabled, wasVisible = host.weapons.visible;
73
+ // read when the reveal begins; the end gives them back only if nothing turned them on meanwhile: the title's ENTER turns the
74
+ // weapons on after `entered` starts the reveal, and an end that restored the earlier "off" left them off for good (TEMPLATE-E2E
75
+ // TC-E1b: Brasscap's lever never fired on the grid; bare hands never showed it)
76
+ let wasEnabled = host.weapons.enabled, wasVisible = host.weapons.visible;
74
77
  const land = new Vector3(), landQ = new Quaternion(), sky = new Vector3(), skyQ = new Quaternion(), look = new Vector3(), fwd = new Vector3(), m = new Matrix4();
75
78
  const now = (): number => app.clock.mode === 'capture' ? app.clock.real * 1000 : diagnosticNow();
76
79
  const publish = (): void => {
@@ -82,7 +85,8 @@ export function installGridReveal(host: GridRevealHost): () => boolean {
82
85
  host.hudRoot.classList.remove('ws-grid-revealing', 'ws-grid-live');
83
86
  if (layer !== null) hudSlots.discard(layer);
84
87
  layer = null;
85
- host.weapons.setEnabled(wasEnabled); host.weapons.visible = wasVisible;
88
+ if (!host.weapons.enabled) host.weapons.setEnabled(wasEnabled);
89
+ if (!host.weapons.visible) host.weapons.visible = wasVisible;
86
90
  host.viewmodel.visible = viewmodelWas;
87
91
  publish();
88
92
  scope.dispose();
@@ -90,6 +94,7 @@ export function installGridReveal(host: GridRevealHost): () => boolean {
90
94
  const begin = (at: number): void => {
91
95
  started = at;
92
96
  host.canvas.style.visibility = ''; // this frame draws the sky pose (the late phase runs before the render)
97
+ wasEnabled = host.weapons.enabled; wasVisible = host.weapons.visible;
93
98
  host.weapons.setEnabled(false); host.weapons.visible = false;
94
99
  viewmodelWas = host.viewmodel.visible;
95
100
  host.hudRoot.classList.add('ws-grid-revealing');
@@ -107,10 +107,8 @@ import { leaseMapImage } from '../shardfile/mapImage';
107
107
  import { crossingSaveStatus, installBorderShimmer, type BorderShimmerState, type CrossingSaveStatus } from './borderShimmer';
108
108
  import { refusalReporter, saveFailedReporter } from './screenReports';
109
109
  import { GAME_STRINGS } from '../../../shared/game/strings';
110
- import { GridCellWaitingError, classifyRefusal, pageShardRefusals, refusalReason, type ShardRefusal } from './refusal';
110
+ import { classifyRefusal, pageShardRefusals, type ShardRefusal } from './refusal';
111
111
  import { tileRing } from '../shardfile/tileDriver';
112
- import { CellLoading, type CellLoadingInput } from './cellLoading';
113
- import { CellLoadingCard } from './cellScreens';
114
112
  import { readGridSeamData, type GridSeamAddress } from '../../../shared/game/grid/seamData';
115
113
  import { readCompiledGridStrips } from '../../../shared/game/grid/compiledStrips';
116
114
  import { startRoadGrain } from './roadGrainPreparation';
@@ -392,11 +390,6 @@ export class GridSession {
392
390
  private readonly farMissing = new Set<string>();
393
391
  /** each slug's shown name */
394
392
  private readonly names = new Map<string, string>();
395
- /** G555: the one step-by-step loading screen over a cell entry or re-entry that waits */
396
- private readonly cellLoading: CellLoading;
397
- private cellLoadingPolled = 0;
398
- /** when each cell's current wait began, so its screen counts only the hooks of this load */
399
- private readonly loadingSince = new Map<string, number>();
400
393
 
401
394
  /** Overlap only this page's actual initial-home metadata with remaining page setup. */
402
395
  startInitialHomeMetadata(): void {
@@ -690,10 +683,8 @@ export class GridSession {
690
683
  // GC12: drawn only while the traveller stands at that edge (the feet in the home frame)
691
684
  ports: { closed: (id) => this.live === null || !this.live.live.ready(id),
692
685
  feet: () => { const at = this.world(); return { x: at.x - home.origin.x, z: at.z - home.origin.z }; } } });
693
- // QA 2026-11-13: a waiting cell's loading steps on SHARD SELECT's loading card, inset over the live world
694
- this.cellLoading = new CellLoading(new CellLoadingCard(), (waiting) => this.neighbours.some(row => row.instance === waiting));
695
686
  setParkedMatricesFrozen(true); // G580 T2: a hidden parked world skips matrix updates during its warm-up
696
- host.scope.onDispose(() => { this.cellLoading.close(); if (host.heldFrame !== undefined) host.heldFrame.enabled = false; setWarmUpHeld(false); setParkedMatricesFrozen(false); setBuildHeldTimed(false); setBuildUrgent(false); });
687
+ host.scope.onDispose(() => { if (host.heldFrame !== undefined) host.heldFrame.enabled = false; setWarmUpHeld(false); setParkedMatricesFrozen(false); setBuildHeldTimed(false); setBuildUrgent(false); });
697
688
  // G78: a shimmer line at every shard border on its real ground; G119: SAVING… / SAVE FAILED, RETRY while a crossing waits
698
689
  const rows = new Map((edges ?? []).map((cell) => [cell.instance, cell.edges]));
699
690
  let status: CrossingSaveStatus = null, polled = 0;
@@ -972,62 +963,6 @@ export class GridSession {
972
963
  this.reportRefusal(cell.instance, cell.slug, refusal, error);
973
964
  this.refusals.set(cell.instance, refusal); this.issues.set(cell.instance, error instanceof Error ? error.message : String(error)); pageShardRefusals().note(cell.slug, refusal);
974
965
  }
975
- /**
976
- * G555's read-only port: the cell whose entry waits (the one the traveller is in before its gameplay is ready, else the
977
- * nearest unready cell within 12 m of its edge), with its readiness fences, its claims, its entered hooks since this wait
978
- * began and its refusal; null when none waits.
979
- */
980
- private cellLoadingInput(): CellLoadingInput | null {
981
- const live = this.live; if (live === null) return null;
982
- // GC6: a world built ahead whose entry still prepares holds its crossing on the road: the screen shows it
983
- const current = live.live.current(), ready = (id: string): boolean => live.live.ready(id) && !live.entryPending(id) && (current !== id || live.gameplayReady());
984
- let target: GridCell | undefined = current !== null && !ready(current) ? this.assembly.cell(current) : undefined;
985
- if (target === undefined) {
986
- const at = this.world();
987
- let best = 12;
988
- for (const cell of this.assembly.cells) {
989
- if (ready(cell.instance)) continue;
990
- const d = Math.hypot(Math.max(0, Math.abs(at.x - cell.origin.x) - CHUNK_HALF), Math.max(0, Math.abs(at.z - cell.origin.z) - CHUNK_HALF));
991
- if (d <= best) { best = d; target = cell; }
992
- }
993
- }
994
- if (target === undefined) { this.loadingSince.clear(); return null; }
995
- const id = target.instance, since = this.loadingSince.get(id) ?? diagnosticNow(); this.loadingSince.set(id, since);
996
- const raw = live.refusal(id), refusal = this.refusal(id);
997
- const reason = refusal !== null ? refusalReason(refusal)
998
- : raw instanceof GridCellWaitingError ? GAME_STRINGS.grid.waiting(this.shardName(id)) : null;
999
- let claimed = 0, product = false;
1000
- for (const entry of this.allocator.claims()) {
1001
- if (entry.owner === id) claimed += entry.bytes;
1002
- if (entry.owner === 'grid' && entry.id === `product:grid:${target.slug}`) { claimed += entry.bytes; product = true; }
1003
- }
1004
- // its entered hooks of this run: from its latest beforeWorld (a road-prepared world ran some before the screen opened)
1005
- const stages = live.live.readiness.status(id), timings = live.hookTimings(), own = timings.completed.filter(row => row.instance === id);
1006
- let run = -1; own.forEach((row, index) => { if (row.hook === 'beforeWorld') run = index; });
1007
- const hooks = new Set((run === -1 ? own.filter(row => row.start >= since) : own.slice(run)).map(row => row.hook));
1008
- const hook = timings.current?.instance === id ? timings.current.hook : null;
1009
- return { instance: id, slug: target.slug, name: this.shardName(id), refusal: reason, product: product || stages.runtime || stages.ready,
1010
- claimedMB: claimed / 1e6, requested: stages.requested, runtime: stages.runtime, colliders: stages.colliders, sim: stages.sim,
1011
- hooks, hook, hybrid: hooks.size > 0 || hook !== null, entered: current === id, gameplayReady: current === id && live.gameplayReady(),
1012
- warm: live.warmPreparation(id) };
1013
- }
1014
- /** At most four times a second: the loading screen reads the allocator and the live session. */
1015
- private stepCellLoading(): void {
1016
- const now = diagnosticNow(); if (now - this.cellLoadingPolled < 250) return;
1017
- this.cellLoadingPolled = now; this.cellLoading.step(this.cellLoadingInput());
1018
- // G580 T2 (Developer): the traveller waits at the wall while its screen shows, so its warm-up may issue more a frame
1019
- // G580 T2 / T5: a held traveller's warm-up issues more programs a frame and its builds run a bigger budget
1020
- setWarmUpHeld(this.cellLoading.open !== null);
1021
- setBuildHeldTimed(this.cellLoading.open !== null);
1022
- // GC6: a world the traveller heads into, or the road (where its entry prepares), builds with the urgent budget
1023
- const live = this.live;
1024
- setBuildUrgent(live !== null && (live.live.building() || live.entriesPending()));
1025
- }
1026
- private refusal(instance: string): ShardRefusal | null {
1027
- const live = this.live?.refusal(instance);
1028
- return this.refusals.get(instance) ?? (live === undefined ? null : classifyRefusal(live));
1029
- }
1030
- private shardName(instance: string): string { const slug = this.assembly.cell(instance).slug; return this.names.get(slug) ?? slug; }
1031
966
 
1032
967
  /** Complete deferred native seams before a distant entry or road recovery. One page promise, no second scheduler. */
1033
968
  prepareOuterStrips(): Promise<void> {
@@ -1188,8 +1123,7 @@ export class GridSession {
1188
1123
  if (!this.initialFarReady && this.host.backgroundReady?.() !== false && this.rings.ready()) this.initialFarReady = true;
1189
1124
  this.roadTiles?.step({ x: at.x, z: at.z, vx: this.velocity.x * clamp, vz: this.velocity.z * clamp });
1190
1125
  for (const cell of this.neighbours) if (this.placeholderBlocksTiles(cell.instance)) this.rings.retireRefinement(cell.instance);
1191
- this.stepCellLoading();
1192
- if (this.host.heldFrame !== undefined) this.host.heldFrame.enabled = this.cellLoading.open !== null && this.live?.travelState().crossing.phase === 'preparing';
1126
+ if (this.host.heldFrame !== undefined) this.host.heldFrame.enabled = false;
1193
1127
  this.shimmer.step();
1194
1128
  const active = this.live === null ? this.home.instance : this.live.live.current();
1195
1129
  const eye = this.host.eye?.();
@@ -1258,7 +1192,7 @@ export class GridSession {
1258
1192
  pitch: this.assembly.pitch,
1259
1193
  home: this.home.instance, inside: gridCells.cell?.instance ?? null, feet: { x: Math.round(at.x * 100) / 100, z: Math.round(at.z * 100) / 100 },
1260
1194
  cells: this.assembly.cells.map((cell) => { const d = drawn(cell.instance); return { instance: cell.instance, slug: cell.slug, cell: cell.cell, shows: shows(cell.instance, d), drawn: d }; }),
1261
- strips: this.strips.length, road: this.road, seams: this.seams, softWalls: this.softWalls.state(), shimmer: this.shimmer.state(), cellLoading: this.cellLoading.open, cellStage: this.cellLoading.stage, cellStep: this.cellLoading.now, hybrid: this.live?.hybridState() ?? null, ringsReady: this.rings.ready(), ringsWait: { cells: this.rings.waiting(), far: this.rings.farPlan(), preparation: this.farPreparation(), waits: { count: pending.length, oldest: pending.map(({ label, kind, ageMs }) => ({ label, kind, ageMs })).sort((a, b) => b.ageMs - a.ageMs).slice(0, 16) } },
1195
+ strips: this.strips.length, road: this.road, seams: this.seams, softWalls: this.softWalls.state(), shimmer: this.shimmer.state(), cellLoading: null, cellStage: null, cellStep: null, hybrid: this.live?.hybridState() ?? null, ringsReady: this.rings.ready(), ringsWait: { cells: this.rings.waiting(), far: this.rings.farPlan(), preparation: this.farPreparation(), waits: { count: pending.length, oldest: pending.map(({ label, kind, ageMs }) => ({ label, kind, ageMs })).sort((a, b) => b.ageMs - a.ageMs).slice(0, 16) } },
1262
1196
  residentMB: Math.round(cost.accounted / 1e4) / 100, playingMB: Math.round(cost.playing / 1e4) / 100, envelopeMB: Math.round(this.allocator.envelope() / 1e4) / 100,
1263
1197
  accountedBytes: cost.accounted,
1264
1198
  rings: { frame: stats.frame, far: stats.resident.far, l1: stats.resident.l1, l0: stats.resident.l0, refused: stats.refused, inFlight: stats.inFlight, queued: stats.queued,
@@ -403,6 +403,12 @@ export function registerWeaponFamily(registry: Map<string, ItemFamily>, id: stri
403
403
  registry.set(id, family);
404
404
  }
405
405
 
406
+ /** The icons a declared item row may name (`ui.icon`), as the page's catalogue draws them. */
407
+ export const DECLARED_ITEM_ICONS = ['lock', 'check', 'poi', 'you', 'map', 'pack', 'star', 'book', 'heart', 'pin', 'laurel', 'sword', 'glyph', 'coin', 'purse', 'crossbow', 'rifle', 'lever', 'longbow', 'grapple', 'horse'] as const;
408
+ /** A declared item row's icon, refused when the catalogue draws no such icon. */
409
+ export function declaredItemIcon(name: string): (typeof DECLARED_ITEM_ICONS)[number] {
410
+ const id = DECLARED_ITEM_ICONS.find((entry) => entry === name); if (id === undefined) throw new Error(`Unknown catalogue item icon ${name}`); return id;
411
+ }
406
412
  /** Explicit built-in item family registry, injected into the full loader; importing does not install content. */
407
413
  export function declaredKitItemFamilies(): ReadonlyMap<string, ItemFamily> {
408
414
  return new Map<string, ItemFamily>([
@@ -15,7 +15,8 @@ import { saveEnvironment } from '@wildshard/engine/saves/environment';
15
15
  import { jsonSlot } from '@wildshard/engine/saves/slots';
16
16
  import { syncPageRewards } from '../../../shared/game/saves';
17
17
  import type { SaveStorage } from '@wildshard/engine/saves/store';
18
- import { atMostLeaveWait, holdLeaving } from '@wildshard/engine/boot/lastEnd';
18
+ import { atMostLeaveWait, holdLeaving, markUnload } from '@wildshard/engine/boot/lastEnd';
19
+ import { dropTabArrival, setTitleArrival } from '@wildshard/engine/boot/titleArrival';
19
20
  import { countedWait } from '@wildshard/engine/boot/waits';
20
21
  import { contentURL } from '@wildshard/engine/boot/contentBase';
21
22
  import { diagnosticNow } from '@wildshard/engine/core/clock';
@@ -128,7 +129,16 @@ function releaseKeep(): ReleaseKeep {
128
129
  };
129
130
  }
130
131
  /** E7.2d: the page's seat in the one world, in a shell of the same shape. */
131
- interface OnlineModule { readonly startOnline: (config: BuildWorld & { keep: ReleaseKeep; loaded: string; build: string; identity: (name?: string) => NetIdentity; grid?: { readonly cell: string; readonly cells: readonly string[]; readonly placed: (cell: string, at: { readonly x: number; readonly y: number; readonly z: number; readonly yaw: number }) => void; readonly reenter: (cell: string) => void; readonly goto?: boolean } }) => Promise<Shell> }
132
+ /** FM3 mode 23: how the online shell leaves this document on purpose, through the page's own saves (shell.ts `OnlineLeaving`). */
133
+ interface OnlineLeaving { readonly arrive: (slug: string) => void; readonly unarrive: () => void; readonly unload: (reason: string) => void;
134
+ readonly reloadStale: () => Promise<boolean>; readonly reloadByHand: () => Promise<void>; readonly settle: () => void }
135
+ const onlineLeaving: OnlineLeaving = {
136
+ arrive: slug => { setTitleArrival({ slug, mode: 'enter' }, { tab: true }); }, unarrive: dropTabArrival, unload: reason => { markUnload(reason); },
137
+ reloadStale: async () => (await import('@wildshard/engine/boot/browserChunkRecovery')).reloadRefusedBuild(true),
138
+ reloadByHand: async () => { await (await import('@wildshard/engine/boot/browserChunkRecovery')).reloadPastWorker(); },
139
+ settle: () => { void (async () => { (await import('@wildshard/engine/boot/browserChunkRecovery')).settleRefusedBuild(); })(); },
140
+ };
141
+ interface OnlineModule { readonly startOnline: (config: BuildWorld & { keep: ReleaseKeep; leaving: OnlineLeaving; loaded: string; build: string; identity: (name?: string) => NetIdentity; grid?: { readonly cell: string; readonly cells: readonly string[]; readonly placed: (cell: string, at: { readonly x: number; readonly y: number; readonly z: number; readonly yaw: number }) => void; readonly reenter: (cell: string) => void; readonly goto?: boolean } }) => Promise<Shell> }
132
142
  interface Shell { readonly redials?: true; devColliders?: (name: string, boxes: readonly DevBox[]) => void; pause: () => void; hold: (on: boolean) => void; bossGod: () => void; raise: (flag: string) => void; join: (id: string, x: number, y: number, z: number) => { readonly client: NetClient; readonly move: (x: number, y: number, z: number) => void }; readonly client: NetClient; readonly booted: Promise<{ readonly restored: boolean }>; place: (x: number, y: number, z: number, yaw: number) => void; hardHits: (by: number) => void; ready: () => void; leave?: () => Promise<void>; save: () => Promise<{ readonly tick: number; readonly ok: boolean }>; probe: () => Promise<{ readonly tickMs: number }>; dispose: () => void }
133
143
 
134
144
  const SAVE_EVERY_MS = 30_000;
@@ -351,7 +361,7 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
351
361
  // a page that left while it asked never joins (Codex review): a cancelled load must not take the device's seat
352
362
  if (!answered || scope.disposed) throw new Error('The page left before it joined the world');
353
363
  const { grid } = ports, booted = grid?.booted;
354
- return startOnline({ ...world, keep: releaseKeep(), loaded: slug, build, identity: name => deviceIdentity(storage, savePrefix, name),
364
+ return startOnline({ ...world, keep: releaseKeep(), leaving: onlineLeaving, loaded: slug, build, identity: name => deviceIdentity(storage, savePrefix, name),
355
365
  ...(grid === null || booted === undefined ? {} : { grid: { cell: booted, cells: grid.cells.map(cell => cell.instance), placed: (cell, at) => { grid.serverPlace?.(cell, at); }, reenter: cell => { grid.reenter?.(cell); },
356
366
  ...(pageGoto() === booted ? { goto: true } : {}) } }) });
357
367
  };
@@ -179,10 +179,32 @@ export function connectOnline(config: OnlineConfig, view: OnlineView): OnlineShe
179
179
  dispose: () => { records?.dispose(); redial.dispose(); client.dispose(); link?.close('disposed'); } };
180
180
  }
181
181
 
182
- const reloadStale = async (): Promise<boolean> => (await import('@wildshard/engine/boot/browserChunkRecovery')).reloadRefusedBuild(true);
183
- const reloadByHand = async (): Promise<void> => { await (await import('@wildshard/engine/boot/browserChunkRecovery')).reloadPastWorker(); };
182
+ /** FM3's proof (mode 23, 2026-11-15): how the page leaves this document on purpose. This bundle's saves have no storage (OF4's
183
+ * `keep`), so the tap it hands the next document (`setTitleArrival`), the unload it marks (`lastEnd`) and the reload claims it
184
+ * settles were written nowhere: the new-build Reload came back as a "player reload" and landed on the title. The page lends its own
185
+ * (clientWorker.ts `onlineLeaving`); this module's copies are the fallback for a page that lends none (tests). */
186
+ export interface OnlineLeaving {
187
+ /** QA row 16: the tap that brought the player here, for this tab's next document only */
188
+ readonly arrive: (slug: string) => void;
189
+ /** that tap, when the reload it was for didn't happen */
190
+ readonly unarrive: () => void;
191
+ /** the game is about to navigate on purpose (lastEnd) */
192
+ readonly unload: (reason: string) => void;
193
+ /** J54/J174: reload into the server's build, once per tab; false when there is none to reload into, or this tab already did */
194
+ readonly reloadStale: () => Promise<boolean>;
195
+ /** a player's tap on a stale tab: the next document comes from the network */
196
+ readonly reloadByHand: () => Promise<void>;
197
+ /** a seat on this build settles the reload that brought this tab here */
198
+ readonly settle: () => void;
199
+ }
200
+ const OWN_LEAVING: OnlineLeaving = {
201
+ arrive: slug => { setTitleArrival({ slug, mode: 'enter' }, { tab: true }); }, unarrive: dropTabArrival, unload: reason => { markUnload(reason); },
202
+ reloadStale: async () => (await import('@wildshard/engine/boot/browserChunkRecovery')).reloadRefusedBuild(true),
203
+ reloadByHand: async () => { await (await import('@wildshard/engine/boot/browserChunkRecovery')).reloadPastWorker(); },
204
+ settle: () => { void (async () => { (await import('@wildshard/engine/boot/browserChunkRecovery')).settleRefusedBuild(); })(); },
205
+ };
184
206
  /** A seat on this build settles any reload that brought this tab here, so a sitting can ride more than one deploy. */
185
- async function settled(booted: OnlineShell['booted']): Promise<void> { await booted; (await import('@wildshard/engine/boot/browserChunkRecovery')).settleRefusedBuild(); }
207
+ async function settled(booted: OnlineShell['booted'], leaving: OnlineLeaving): Promise<void> { await booted; leaving.settle(); }
186
208
  /** J174: the next build's files, while play goes on. The worker that installs is what the reload lands on. */
187
209
  function preload(): void {
188
210
  if ('serviceWorker' in navigator) void navigator.serviceWorker.getRegistration().then(found => found?.update()).catch(() => undefined);
@@ -210,6 +232,8 @@ export interface StartOnline {
210
232
  * a second store writing the page's device save would drop the keys it doesn't define. */
211
233
  readonly keep?: ReleaseKeep;
212
234
  readonly recordTag?:string;
235
+ /** mode 23: how the page leaves on purpose, in its own saves (see OnlineLeaving) */
236
+ readonly leaving?: OnlineLeaving;
213
237
  }
214
238
  /** E7.5 prep: ask the page to leave for the Connection doctor, saying which screen asked. The page's own bundle answers
215
239
  * (src/client/engine/ui/errorScreen.ts): it holds the save hold and the loading card's report, which this module can't see. */
@@ -294,17 +318,17 @@ async function askWorld(config: { readonly release: string; readonly key: string
294
318
  /** Enter the one world this build names. A stale tab reloads into the server's build once, and only then gives up. */
295
319
  export async function startOnline(config: StartOnline): Promise<OnlineShell> {
296
320
  // OF4: a verified kept release file dials at once (offline too), and the fresh read follows; with none, the page waits for the read
297
- const { release: at, key, keep, identity, recordTag, grid, ...link } = config;
321
+ const { release: at, key, keep, identity, recordTag, grid, leaving = OWN_LEAVING, ...link } = config;
298
322
  // FM5: with no kept copy and no file, the page says why (offline, the file's server down or busy, a portal, a bad signature) and
299
323
  // reads again by release.ts's policy until a verified file answers; Title screen stops the load
300
324
  const waiting = new Scope('online.release-wait');
301
- const toTitle = (): void => { markUnload('release page: title screen'); location.replace(new URL('/', location.origin).toString()); };
325
+ const toTitle = (): void => { leaving.unload('release page: title screen'); location.replace(new URL('/', location.origin).toString()); };
302
326
  let dial: Awaited<ReturnType<typeof releaseToDial>>;
303
327
  try { dial = await releaseToDial(at, key, { keep: keep ?? NO_KEEP, wait: releaseScreens(waiting, { doctor, title: toTitle }) }); } finally { waiting.dispose(); }
304
328
  const { file: release, fresh } = dial, { socket } = release;
305
329
  // QA row 16: a level page enters only from a tap. A reload this page makes itself carries the tap that brought it here.
306
- const entering = (slug: string): void => { setTitleArrival({ slug, mode: 'enter' }, { tab: true }); };
307
- const stale = async (): Promise<boolean> => { entering(link.loaded); const going = await reloadStale(); if (!going) dropTabArrival(); return going; };
330
+ const entering = (slug: string): void => { leaving.arrive(slug); };
331
+ const stale = async (): Promise<boolean> => { entering(link.loaded); const going = await leaving.reloadStale(); if (!going) leaving.unarrive(); return going; };
308
332
  // only a fresh read says the world moved on: a kept copy's build is the past, and an offline page can't reload anyway
309
333
  if (fresh === null && release.engineBuild !== link.build) await stale();
310
334
  if (socket === undefined) throw new Error('The release file names no address');
@@ -321,23 +345,23 @@ export async function startOnline(config: StartOnline): Promise<OnlineShell> {
321
345
  const screens = linkScreens(scope, {
322
346
  retry: () => { shellNow?.retry(); }, dialNow: () => { shellNow?.dialNow(); }, doctor,
323
347
  // Play here / Play again reload into the world: the tap that brought the player here comes along (QA row 16)
324
- reload: () => { entering(link.loaded); void reloadByHand(); },
348
+ reload: () => { entering(link.loaded); void leaving.reloadByHand(); },
325
349
  progress: () => shellNow?.progress() ?? { dials: 0, nextDialMs: null, downMs: 0 }, why: () => shellNow?.why() ?? 'closed',
326
350
  // FM4b modes 21 and 22: the Slow and Unstable chips read the link's own measurements
327
351
  stats: () => shellNow?.client.stats,
328
352
  });
329
353
  // `reload` is the one ending a screen doesn't answer: the page reloads into the world's build, once (J174)
330
- const ended = async (): Promise<void> => { if (!await stale()) newBuildPanel(scope, stale, () => { entering(link.loaded); void reloadByHand(); }); };
354
+ const ended = async (): Promise<void> => { if (!await stale()) newBuildPanel(scope, stale, () => { entering(link.loaded); void leaving.reloadByHand(); }); };
331
355
  const telemetry=onlineTelemetry(),tag=recordTag??release.channel;
332
356
  const shell = connectOnline({ ...link, ...(grid === undefined ? {} : { gridCell: grid.cell, gridCells: grid.cells }), socket: gotoSocket(socket, goto), address: () => gotoSocket(dialing, goto), identity: named,record:{install:telemetry.install,session:crypto.randomUUID(),send:telemetry.send,...(tag===undefined?{}:{tag})} }, {
333
357
  link: (state, reason) => { waitingForSeat = state === 'full'; screens.link(state, reason); if (state === 'ended' && reason === 'reload') void ended(); },
334
358
  // The cut (5.5): an old server refused a v1 hello. Reload only into another build; on this one, the server is updating.
335
- cut: () => { void reloadStale(); },
359
+ cut: () => { void leaving.reloadStale(); },
336
360
  countdown: said => { screens.countdown(said); preload(); },
337
361
  placed: (cell, stand) => { if (stand !== undefined) grid?.placed(cell, stand); },
338
362
  // A grid page re-enters the grid in the seat's cell: the tap that brought it here comes along (QA row 16), and the URL stays bare.
339
- regrid: cell => { entering(link.loaded); markUnload(`online seat in another grid cell (${cell})`); grid?.reenter(cell); },
340
- elsewhere: seat => { entering(seat); const url = new URL(location.href); url.searchParams.set('chunk', seat); markUnload(`online seat elsewhere (${seat})`); location.replace(url); },
363
+ regrid: cell => { entering(link.loaded); leaving.unload(`online seat in another grid cell (${cell})`); grid?.reenter(cell); },
364
+ elsewhere: seat => { entering(seat); const url = new URL(location.href); url.searchParams.set('chunk', seat); leaving.unload(`online seat elsewhere (${seat})`); location.replace(url); },
341
365
  });
342
366
  shellNow = shell;
343
367
  // the fresh read behind a kept copy: another build reloads into it, as a fresh read before the dial would (two reloads share one
@@ -351,7 +375,7 @@ export async function startOnline(config: StartOnline): Promise<OnlineShell> {
351
375
  });
352
376
  // a tap the world must hear waits for the link: the hold card says so, and the tap is never sent late
353
377
  shell.client.gateActions(what => screens.allow(what));
354
- void settled(shell.booted);
378
+ void settled(shell.booted, leaving);
355
379
  const chat = chatLines(scope, shell.client, document.body, screens.holdChat);
356
380
  voiceUi(scope, new VoiceChat(scope, shell.voice), chat);
357
381
  scope.listen(window,'pagehide',()=>{shell.flushRecords();});