@wildshard/engine 0.1.20 → 0.1.21

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 (59) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +1 -0
  3. package/package.json +2 -1
  4. package/scripts/chaos-proxy-core.mjs +14 -1
  5. package/scripts/chaos-proxy-proof.mjs +22 -0
  6. package/scripts/failmode-cases.d.mts +8 -0
  7. package/scripts/failmode-cases.mjs +97 -0
  8. package/scripts/failmode-proof.mjs +532 -0
  9. package/scripts/grid-crossing-nightly.mjs +5 -4
  10. package/scripts/grid-crossing-report.mjs +5 -2
  11. package/scripts/grid-crossing-tour.mjs +25 -8
  12. package/scripts/hover-speed-probe.mjs +136 -0
  13. package/scripts/net-lag-proof.mjs +3 -2
  14. package/scripts/online-rig.mjs +9 -7
  15. package/scripts/release-cook.mjs +109 -0
  16. package/scripts/vps/rebuild.sh +35 -9
  17. package/scripts/vps/wildshard-apply.mjs +5 -1
  18. package/scripts/vps/wildshard-config +117 -1
  19. package/src/client/engine/boot/contentRead.ts +54 -5
  20. package/src/client/engine/boot/gpuFiles.ts +3 -3
  21. package/src/client/engine/boot/leaveAfterPaint.ts +4 -1
  22. package/src/client/engine/core/shadowLayer.ts +18 -0
  23. package/src/client/engine/explore/pick.ts +13 -1
  24. package/src/client/engine/net/predictor.ts +12 -4
  25. package/src/client/engine/player/TouchControls.ts +3 -2
  26. package/src/client/engine/render/families/sceneSurface.ts +3 -1
  27. package/src/client/engine/telemetry/browserErrors.ts +3 -1
  28. package/src/client/engine/ui/ErrorModal.ts +1 -1
  29. package/src/client/engine/ui/Loading.ts +14 -2
  30. package/src/client/engine/ui/errorScreen.ts +51 -9
  31. package/src/client/engine/ui/hoverBoost.ts +31 -4
  32. package/src/client/engine/ui/styles/touch.css +6 -0
  33. package/src/client/game/boot/spawnDownload.ts +44 -6
  34. package/src/client/game/grid/live.ts +2 -2
  35. package/src/client/game/grid/liveSession.ts +2 -2
  36. package/src/client/game/grid/session.ts +2 -0
  37. package/src/client/game/grid/shardfileFar.ts +13 -2
  38. package/src/client/game/shardfile/clientSource.ts +7 -3
  39. package/src/client/game/shardfile/clientWorker.ts +4 -4
  40. package/src/client/game/shardfile/groundMerge.ts +5 -3
  41. package/src/client/host/online/linkScreens.ts +12 -6
  42. package/src/client/host/online/reconnectStrip.ts +3 -2
  43. package/src/client/host/online/release.ts +87 -16
  44. package/src/client/host/online/releaseScreens.ts +108 -0
  45. package/src/client/host/online/shell.ts +11 -1
  46. package/src/client/host/online/voice.ts +45 -1
  47. package/src/client/host/online/voiceUi.ts +24 -6
  48. package/src/server/engine/sim/playerSim.ts +1 -1
  49. package/src/server/game/grid/simulation.ts +12 -6
  50. package/src/server/host/dedicated/cellHost.ts +7 -0
  51. package/src/server/host/dedicated/cellWorker.ts +1 -1
  52. package/src/server/host/dedicated/dedicatedRoom.ts +14 -1
  53. package/src/server/host/dedicated/roadRoom.ts +3 -0
  54. package/src/server/host/standalone/gridServer.ts +1 -1
  55. package/src/shared/engine/boot/loadingWaits.ts +10 -2
  56. package/src/shared/engine/core/config.ts +3 -0
  57. package/src/shared/engine/player/hoverSpeed.ts +3 -3
  58. package/src/shared/engine/strings.ts +12 -1
  59. package/src/shared/game/grid/rules.ts +12 -0
@@ -5,6 +5,9 @@
5
5
  # write the settings, restart the channel once, roll back if
6
6
  # it does not come up healthy
7
7
  # wildshard-config split <channel> setup.sh's: move the settings out of <channel>.env, once
8
+ # wildshard-config cook <tag> AUTO-RELEASE AR4 (J355): move the cook worker to vX.Y.Z and
9
+ # the build a signed release names for it; roll back on failure
10
+ # wildshard-config show cook print the cook worker's tag and build
8
11
  # Settings live in /etc/wildshard/<channel>.settings (640 root:wildshard-<channel>), which the units read after <channel>.env.
9
12
  # Secrets stay in the root-only .env, and this never prints one or writes one (it reads only the placement rows there, for
10
13
  # the pair check below): only the keys in SETTINGS below, each
@@ -167,11 +170,124 @@ def restart(channel):
167
170
  return healthy(channel)
168
171
 
169
172
 
173
+ # AUTO-RELEASE AR4 (J355): the cook worker's two non-secret keys. They go to /etc/wildshard/cook.settings (640
174
+ # root:wildshard-cook), which its unit and rebuild.sh read after the root-only cook.env (the notify token and R2 writer keys,
175
+ # never read here), so they win. The build is never the caller's: wildshard-apply's verify reads it from a signed channel
176
+ # release that names the tag, after checking GitHub's tag points at it. rebuild.sh --cook then moves the checkout, installs,
177
+ # restarts the worker and waits for its /health.
178
+ COOK_KEYS = ('COOK_ENGINE_REF', 'WILDSHARD_BUILD')
179
+ COOK_TAG = r'v[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}'
180
+ COOK_HEADER = ['# AUTO-RELEASE AR4 (J355): the cook worker\'s engine tag and build, read after cook.env. Change them with',
181
+ '# `sudo wildshard-config cook <tag>`; the secrets stay in cook.env.']
182
+ CLEAN = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'HOME': '/root', 'LANG': 'C.UTF-8'}
183
+
184
+
185
+ def helper(name):
186
+ """A root-owned helper, or the test's stand-in (never as root)."""
187
+ if TEST:
188
+ return os.environ.get(f'WILDSHARD_CONFIG_TEST_{name.upper()}', '/nonexistent')
189
+ return {'apply': '/usr/local/sbin/wildshard-apply', 'rebuild': '/opt/wildshard-vps/rebuild.sh'}[name]
190
+
191
+
192
+ def helper_env():
193
+ if not TEST:
194
+ return dict(CLEAN)
195
+ return {**CLEAN, 'PATH': os.environ.get('PATH', CLEAN['PATH']),
196
+ **{key: value for key, value in os.environ.items() if key.startswith(('WILDSHARD_APPLY_TEST', 'WILDSHARD_CONFIG_TEST'))}}
197
+
198
+
199
+ def cook_rebuild():
200
+ """rebuild.sh's cook step alone, as root, from the root-owned copy. It exits non-zero unless the worker answers /health.
201
+ It runs in its own session with SIGPIPE and SIGHUP ignored (restore_signals=False keeps them so), so a dropped ssh
202
+ caller can't kill it halfway through a checkout or an install."""
203
+ return subprocess.run(['bash' if TEST else '/usr/bin/bash', helper('rebuild'), '--cook'], cwd='/', env=helper_env(),
204
+ restore_signals=False, start_new_session=True).returncode == 0
205
+
206
+
207
+ def say(line, error=False):
208
+ """Print, but never let a caller that went away stop a move or its rollback."""
209
+ try:
210
+ print(line, file=sys.stderr if error else sys.stdout, flush=True)
211
+ except OSError:
212
+ pass
213
+
214
+
215
+ def show_cook():
216
+ rows = [row for row in read_rows(f'{ETC}/cook.settings') if key_of(row) in COOK_KEYS]
217
+ for row in rows:
218
+ print(row)
219
+ if not rows:
220
+ print('note no cook.settings: the cook worker runs what cook.env names')
221
+ return 0
222
+
223
+
224
+ def cook(args):
225
+ if len(args) != 2 or re.fullmatch(COOK_TAG, args[1]) is None:
226
+ stop('usage: wildshard-config cook vX.Y.Z')
227
+ tag, rebuild = args[1], helper('rebuild')
228
+ try:
229
+ with open(rebuild, encoding='utf-8') as handle:
230
+ knows = '[ "$1" = --cook ]' in handle.read()
231
+ except OSError:
232
+ knows = False
233
+ if not knows:
234
+ stop(f'{rebuild} has no --cook yet: apply a signed tag that carries it first (wildshard-apply <tag> harden)')
235
+ checked = subprocess.run([helper('apply'), tag, 'verify'], cwd='/', env=helper_env(), capture_output=True, text=True)
236
+ found = re.search(r'^commit\s+([0-9a-f]{40})$', checked.stdout, re.M)
237
+ if checked.returncode != 0 or found is None:
238
+ reason = ((checked.stderr or checked.stdout).strip().splitlines() or ['no commit'])[-1]
239
+ stop(f'{tag} is not a tag a signed release names: {reason}')
240
+ commit = found.group(1)
241
+ # One move at a time, held through the rebuild and any rollback, as `set` holds its channel.
242
+ import fcntl
243
+ lock = os.fdopen(os.open(f'{ETC}/.cook.settings.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600), 'w')
244
+ fcntl.flock(lock, fcntl.LOCK_EX)
245
+ # From here on a dropped caller changes nothing: no hangup, no broken pipe, and any failure rolls back.
246
+ import signal
247
+ signal.signal(signal.SIGHUP, signal.SIG_IGN)
248
+ signal.signal(signal.SIGPIPE, signal.SIG_IGN)
249
+ path = f'{ETC}/cook.settings'
250
+ before = read_rows(path)
251
+ rows = [row for row in (list(before) or list(COOK_HEADER)) if key_of(row) not in COOK_KEYS]
252
+ rows += [f'COOK_ENGINE_REF={tag}', f'WILDSHARD_BUILD={commit}']
253
+ try:
254
+ if rows == before:
255
+ say(f'ok cook.settings already names {tag}')
256
+ else:
257
+ write_rows(path, rows, 'cook')
258
+ say(f'doing cook {tag} at {commit}')
259
+ if cook_rebuild():
260
+ say(f'ok the cook worker runs {tag} ({commit[:8]})')
261
+ return 0
262
+ except BaseException:
263
+ pass
264
+ if rows == before:
265
+ say(f'stop the cook worker is not healthy on {tag}: look at journalctl -u wildshard-cook', error=True)
266
+ return 2
267
+ # It did not come back: the old tag goes back and is rebuilt, so a bad move never leaves the cook down.
268
+ if before:
269
+ write_rows(path, before, 'cook')
270
+ elif os.path.exists(path):
271
+ os.unlink(path)
272
+ say(f'undo the cook worker did not come up on {tag}; the old tag is back', error=True)
273
+ if not cook_rebuild():
274
+ say('stop the cook worker is not healthy on its old tag either: look at journalctl -u wildshard-cook', error=True)
275
+ return 2
276
+ return 1
277
+
278
+
170
279
  def main(argv):
171
280
  production = '--production' in argv
172
281
  args = [arg for arg in argv if arg != '--production']
282
+ if args and args[0] == 'cook':
283
+ return cook(args)
284
+ if args[:2] == ['show', 'cook'] and len(args) == 2:
285
+ return show_cook()
286
+ if args[:2] == ['set', 'cook']:
287
+ stop('the cook worker moves with: wildshard-config cook vX.Y.Z')
173
288
  if not args or args[0] not in ('show', 'set', 'split'):
174
- stop('usage: wildshard-config show <channel> | set <channel> <KEY> <value> [<KEY> <value>]... [--production] | split <channel>')
289
+ stop('usage: wildshard-config show <channel> | set <channel> <KEY> <value> [<KEY> <value>]... [--production] | split <channel> '
290
+ '| cook vX.Y.Z | show cook')
175
291
  verb = args[0]
176
292
  if len(args) < 2 or args[1] not in CHANNELS:
177
293
  stop('the channel is production or staging')
@@ -3,17 +3,43 @@ import { captureBrowserError, engineScreenTags } from '../telemetry/browserError
3
3
  import { beginLoadingWait, finishLoadingWait } from '../../../shared/engine/boot/loadingWaits';
4
4
  import { currentLoadingTimeline } from '../../../shared/engine/boot/timeline';
5
5
  import { bootProgress } from '../../../shared/engine/boot/timing';
6
+ import { diagnosticNow } from '../../../shared/engine/core/clock';
6
7
 
7
8
  /** A missing or interrupted transport, never a parsed-content or admission refusal. */
8
9
  export class ContentReadError extends Error {
9
10
  readonly url: string;
10
11
  /** RL8: the server answered that the file is not there (404, or the HTML fallback): a retry of the same URL can't help */
11
12
  readonly missing: boolean;
12
- constructor(url: string, detail: string, cause?: unknown, missing = false) {
13
+ /** FM6: the HTTP status the server answered, its `Retry-After` in ms (seconds or a date, at most 10 min), and whether the bytes
14
+ * arrived but failed their length check (mode 44). Null and false when not measured. */
15
+ readonly status: number | null;
16
+ readonly retryAfterMs: number | null;
17
+ readonly broken: boolean;
18
+ constructor(url: string, detail: string, cause?: unknown, missing = false, measured: { status?: number; retryAfterMs?: number | null; broken?: boolean } = {}) {
13
19
  super(`Read failed: ${new URL(url, 'https://content.invalid').pathname} · ${detail}`, { cause });
14
20
  this.name = 'ContentReadError'; this.url = url; this.missing = missing;
21
+ this.status = measured.status ?? null; this.retryAfterMs = measured.retryAfterMs ?? null; this.broken = measured.broken ?? false;
15
22
  }
16
23
  }
24
+ /** FM6 mode 34: a `Retry-After` of seconds or an HTTP date, in ms from `now`; anything else (or past 10 min) is no answer. */
25
+ export function contentRetryAfterMs(header: string | null, now: number = Date.now()): number | null {
26
+ if (header === null) return null;
27
+ const text = header.trim(), ms = /^\d{1,6}$/u.test(text) ? Number(text) * 1000 : /[a-z]/iu.test(text) ? Date.parse(text) - now : Number.NaN;
28
+ return Number.isFinite(ms) && ms >= 0 && ms <= 600_000 ? Math.round(ms) : null;
29
+ }
30
+ /** The spawn book (`assets/spawn/packs-<build>.json`): mode 35 names it apart from the packs it lists. */
31
+ const BOOK = /(?:^|\/)assets\/spawn\/packs-[^/]+\.json$/u;
32
+ /** FM6: the catalogue's ids for a failed read, and the line a player reads (meta MMO-FAILURE-MODES-PLAN modes 33 to 35, 44). The
33
+ * address and raw detail stay in the error for Copy diagnostics. */
34
+ export function contentFailure(error: ContentReadError): { readonly failmode: string; readonly line: string } {
35
+ const book = BOOK.test(new URL(error.url, 'https://content.invalid').pathname);
36
+ if (book) return { failmode: 'book-5xx', line: 'The world\'s book didn\'t arrive' };
37
+ if (error.status === 429) return { failmode: 'packs-429', line: 'Download paused · the server is busy' };
38
+ if (error.broken) return { failmode: 'packs-5xx pack-broken', line: 'Download paused · a file didn\'t verify' };
39
+ if (error.missing) return { failmode: 'packs-5xx', line: 'Download paused · a file isn\'t there' };
40
+ if (error.status !== null) return { failmode: 'packs-5xx', line: 'Download paused · the server had an error' };
41
+ return { failmode: 'packs-5xx', line: 'Download paused · the connection dropped' };
42
+ }
17
43
  export interface ContentReadOptions {
18
44
  fetch: (url: string, init: RequestInit) => Promise<Response>;
19
45
  signal?: AbortSignal;
@@ -38,10 +64,11 @@ function html(bytes: Uint8Array): boolean {
38
64
  async function body(response: Response, url: string, maximum: number, read?: (bytes: number) => void, expected?: number,
39
65
  received?: (response: Response) => void): Promise<Uint8Array<ArrayBuffer>> {
40
66
  const sizeError = (): Error => expected === undefined ? new Error('Content wire size exceeds cap')
41
- : new ContentReadError(url, 'byte length differs from manifest');
67
+ : new ContentReadError(url, 'byte length differs from manifest', undefined, false, { broken: true });
42
68
  if (!response.ok || /\btext\/html\b/iu.test(response.headers.get('content-type') ?? '')) {
43
69
  await response.body?.cancel().catch(() => undefined);
44
- throw new ContentReadError(url, response.ok ? 'missing content (HTML response)' : `HTTP ${response.status}`, undefined, response.ok || response.status === 404);
70
+ throw new ContentReadError(url, response.ok ? 'missing content (HTML response)' : `HTTP ${response.status}`, undefined, response.ok || response.status === 404,
71
+ response.ok ? {} : { status: response.status, retryAfterMs: contentRetryAfterMs(response.headers.get('retry-after')) });
45
72
  }
46
73
  const length = response.headers.get('content-length');
47
74
  if (length !== null && (!/^\d+$/u.test(length) || Number(length) > maximum)) {
@@ -94,7 +121,13 @@ function shellRetry(scope: Scope, error: ContentReadError, retry: () => void): v
94
121
  const button = document.querySelector<HTMLButtonElement>('.ws-load .ws-load-retry');
95
122
  if (button === null) return;
96
123
  const foot = document.querySelector<HTMLElement>('.ws-load [data-el="foot"]');
97
- if (foot !== null) foot.textContent = error.message;
124
+ // FM6: the shell's foot says what failed in a player's words with the catalogue's id, as Loading's does (the FM3 proof caught
125
+ // START's boot tables showing their address and HTTP status here); the address stays in the error for Copy diagnostics
126
+ if (foot !== null) {
127
+ const failure = contentFailure(error);
128
+ foot.textContent = failure.line; foot.dataset['failmode'] = failure.failmode;
129
+ scope.onDispose(() => { if (foot.dataset['failmode'] === failure.failmode) delete foot.dataset['failmode']; });
130
+ }
98
131
  button.hidden = false;
99
132
  scope.listen(button, 'click', retry);
100
133
  }
@@ -122,7 +155,7 @@ async function retryFromCard(error: ContentReadError, signal?: AbortSignal): Pro
122
155
  reportStall(target, error, timeline?.snapshot().current ?? null);
123
156
  id = beginLoadingWait(error.message, { kind: 'file', resource: error.url,
124
157
  owner: timeline?.waitOwner ?? null, step: timeline?.snapshot().current ?? null,
125
- retry: () => {for (const retry of pending) retry();}, retryNavigation: false });
158
+ retry: () => {for (const retry of pending) retry();}, retryNavigation: false, ...contentFailure(error) });
126
159
  shellRetry(scope, error, () => {for (const retry of pending) retry();});
127
160
  });
128
161
  } finally {
@@ -133,6 +166,20 @@ async function retryFromCard(error: ContentReadError, signal?: AbortSignal): Pro
133
166
  }
134
167
  }
135
168
 
169
+ /** FM6 mode 34: the server's own wait, on the card as `packs-429` with its countdown; the read's signal cancels it. */
170
+ async function busyWait(error: ContentReadError, ms: number, signal?: AbortSignal): Promise<void> {
171
+ const scope = new Scope('content-read-busy'), timeline = currentLoadingTimeline();
172
+ const id = typeof document === 'undefined' ? undefined : beginLoadingWait(error.message, { kind: 'file', resource: error.url, owner: timeline?.waitOwner ?? null,
173
+ step: timeline?.snapshot().current ?? null, ...contentFailure(error), dueAt: diagnosticNow() + ms });
174
+ try {
175
+ await new Promise<void>((resolve, reject) => {
176
+ if (signal?.aborted === true) { reject(abortReason(signal)); return; }
177
+ if (signal !== undefined) scope.listen(signal, 'abort', () => { reject(abortReason(signal)); }, { once: true });
178
+ scope.timeout(ms, resolve);
179
+ });
180
+ } finally { if (id !== undefined) finishLoadingWait(id); scope.dispose(); }
181
+ }
182
+
136
183
  /** Read a complete bounded file. Retry one confirmed lost/missing transport immediately,
137
184
  * then leave the same load pending on RETRY. An optional first-party manifest
138
185
  * length shares this recovery; ordinary caps, parsing and hashes stay strict. */
@@ -151,6 +198,8 @@ export async function readContent(url: string, maximum: number, options: Content
151
198
  options.signal?.throwIfAborted();
152
199
  if (!(error instanceof ContentReadError)) throw error;
153
200
  if (error.missing && options.missingThrows === true) throw error;
201
+ // FM6 mode 34: a 429 that says when waits that long before the retry the budget already allows; the count is unchanged
202
+ if (error.retryAfterMs !== null && error.retryAfterMs > 0) await busyWait(error, error.retryAfterMs, options.signal);
154
203
  if (!retried) { retried = true; }
155
204
  else {
156
205
  if (options.instead !== undefined && await options.instead(error)) throw error;
@@ -44,7 +44,7 @@
44
44
  import { GPU_FILES as ENGINE_GPU_FILES } from './ktx2.generated';
45
45
  import { TIER } from '../core/tier';
46
46
  import { pageURL } from './contentBase';
47
- import { CONTENT_CAPS, PAGE_LEVEL } from '../../../shared/engine/core/config';
47
+ import { PAGE_LEVEL, PHONE_PLAYING_BYTES } from '../../../shared/engine/core/config';
48
48
  import { harnessPins } from '../../../shared/engine/app/identity';
49
49
  import { ktx2Probe, ktx2ProbeResult, type Ktx2Probe } from '../render/ktx2Probe';
50
50
 
@@ -106,8 +106,8 @@ export function setDeviceTexForm(memory: DeviceTexForm | null): void { deviceFor
106
106
  /** G188's automatic tier policy: measured over-cap phone builds use KTX2 before the first visit, never desktop. */
107
107
  export function autoTexturePolicy(mode: TexMode | undefined, imagesFirstPlayingBytes?: number): { mode: TexMode; why: string } | undefined {
108
108
  if (imagesFirstPlayingBytes !== undefined && (!Number.isSafeInteger(imagesFirstPlayingBytes) || imagesFirstPlayingBytes < 0)) throw new RangeError('Invalid images-first playing estimate');
109
- if (TIER === 'phone' && imagesFirstPlayingBytes !== undefined && imagesFirstPlayingBytes > CONTENT_CAPS.playing) {
110
- return { mode: 'ktx2', why: `auto: images-first playing estimate ${imagesFirstPlayingBytes} exceeds ${CONTENT_CAPS.playing}` };
109
+ if (TIER === 'phone' && imagesFirstPlayingBytes !== undefined && imagesFirstPlayingBytes > PHONE_PLAYING_BYTES) {
110
+ return { mode: 'ktx2', why: `auto: images-first playing estimate ${imagesFirstPlayingBytes} exceeds ${PHONE_PLAYING_BYTES}` };
111
111
  }
112
112
  return mode === undefined ? undefined : { mode, why: 'auto: level tier texture policy' };
113
113
  }
@@ -1,4 +1,5 @@
1
1
  import { pageScope } from '../../../shared/engine/app/resources';
2
+ import { framesAvailable } from '../../../shared/engine/app/scopeEnvironment';
2
3
 
3
4
  /** iOS Simulator, 2026-11-09: WebKit stops painting a page as soon as a navigation starts in the same turn, so the load
4
5
  * failure screen's RELOAD showed no cover at all. Every reload the player asked for navigates one painted frame after the
@@ -11,6 +12,8 @@ export function leaveAfterPaint(go: () => void): void {
11
12
  if (pageScope.disposed || pageScope.disposing) { go(); return; }
12
13
  let gone = false;
13
14
  const once = (): void => { if (gone) return; gone = true; go(); };
14
- pageScope.raf(() => { pageScope.timeout(0, once); });
15
+ // FM3's proof (version-skew Reload, 2026-11-15): the online shell's graph runs this with no browser frame environment
16
+ // installed, and the bare frame throws, so Reload sat at RELOADING under 'Something broke'. No frames: the timer alone goes.
17
+ if (framesAvailable()) pageScope.raf(() => { pageScope.timeout(0, once); });
15
18
  pageScope.timeout(LEAVE_FRAME_MS, once);
16
19
  }
@@ -1,3 +1,5 @@
1
+ import type { Layers, Object3D } from 'three';
2
+
1
3
  /**
2
4
  * The layer of shadow-only casters: meshes drawn into the sun's shadow map and nowhere else (Cabin.ts's static depth
3
5
  * proxies, animalShadow.ts's one-draw animal casters). three.js tests a caster's layers against the VIEW camera in the
@@ -6,3 +8,19 @@
6
8
  * and only then. PINE-HOLLOW-REMASTER PH-P1 / P2.
7
9
  */
8
10
  export const SHADOW_LAYER = 9;
11
+
12
+ /**
13
+ * SHARD-SOURCE ss4d: the `userData` mark on a mesh that sits on SHADOW_LAYER only because a merge draws it for the view
14
+ * (`groundMerge.ts` `mergeView`, AP8's merged props). It is still a real surface: a tap in the World Explorer picks it
15
+ * (`explore/pick.ts`), where a true shadow-only caster (a cabin's depth proxy) stays unpickable.
16
+ */
17
+ export const MERGED_VIEW = 'mergedView';
18
+ /** The name of a merge's own view mesh (AP8): it stands in for its members, so a pick reads the member, never it. */
19
+ export const MERGED_COPY = 'props.merged';
20
+
21
+ /** Whether a raycast hit on `object` is a drawn surface for a raycaster on `view`'s layers: on one of them, or a merged
22
+ * member its merge draws. */
23
+ export function drawnSurface(object: Object3D, view: Layers): boolean {
24
+ if (object.name === MERGED_COPY) return false;
25
+ return object.layers.test(view) || object.userData[MERGED_VIEW] === true;
26
+ }
@@ -21,6 +21,7 @@
21
21
  * pickups do) is a few pixels wide, and the finger lands on the roof beside it.
22
22
  */
23
23
  import * as THREE from 'three';
24
+ import { drawnSurface, SHADOW_LAYER } from '../core/shadowLayer';
24
25
 
25
26
  /** something a tap can hit: an object (or a batch mesh) and how it maps to a catalog entry + a box */
26
27
  export interface SelectTarget {
@@ -55,6 +56,17 @@ const volume = (b: THREE.Box3): number => { b.getSize(_size); return _size.x * _
55
56
  export const MIN_PICK = 0.75;
56
57
  const tiny = (b: THREE.Box3): boolean => { b.getSize(_size); return Math.max(_size.x, _size.y, _size.z) <= MIN_PICK; };
57
58
 
59
+ /**
60
+ * The nearest drawn surface of `object` under the ray. SHARD-SOURCE ss4d: a merged prop (AP8) draws through its merge and
61
+ * keeps its own mesh on SHADOW_LAYER, which a raycaster on the view layer skips: the ray tests that layer too for the
62
+ * one call, and keeps only the hits on drawn surfaces (a shadow-only depth proxy is not one).
63
+ */
64
+ function drawnHit(ray: THREE.Raycaster, object: THREE.Object3D): THREE.Intersection | undefined {
65
+ const view = new THREE.Layers(); view.mask = ray.layers.mask;
66
+ ray.layers.enable(SHADOW_LAYER);
67
+ try { return ray.intersectObject(object, true).find((hit) => drawnSurface(hit.object, view)); } finally { ray.layers.mask = view.mask; }
68
+ }
69
+
58
70
  /** the target under the ray, or null (nothing hit, or a surface no target claims) */
59
71
  export function pickTarget(ray: THREE.Raycaster, targets: readonly SelectTarget[]): Picked | null {
60
72
  const byObject = new Map<THREE.Object3D, SelectTarget[]>();
@@ -65,7 +77,7 @@ export function pickTarget(ray: THREE.Raycaster, targets: readonly SelectTarget[
65
77
  let near: { mesh: THREE.Object3D; point: THREE.Vector3; d: number } | null = null;
66
78
  for (const object of byObject.keys()) {
67
79
  if (!shown(object)) continue;
68
- const hit = ray.intersectObject(object, true)[0];
80
+ const hit = drawnHit(ray, object);
69
81
  if (hit && (!near || hit.distance < near.d)) near = { mesh: hit.object, point: hit.point.clone(), d: hit.distance };
70
82
  }
71
83
  // a small copy the ray passes through before the surface it hits (E345: the minimum pick size)
@@ -97,6 +97,8 @@ function ownerTable(columns: readonly NetColumn<never>[]): OwnerTable {
97
97
  export class Predictor {
98
98
  /** Corrections taken, and steps replayed for them: what a proof page reports. */
99
99
  corrections = 0; replays = 0;
100
+ /** Server-owned transitions, kept separate from a failed local prediction in proof output. */
101
+ readonly authoritative = { leadEnds: 0, resets: 0 };
100
102
  /** What each correction disagreed on, and the widest gap at the acknowledged step. */
101
103
  readonly missed = { position: 0, grounded: 0, board: 0, swim: 0, ride: 0, gap: 0 };
102
104
  readonly misses: number[][] = [];
@@ -160,7 +162,8 @@ export class Predictor {
160
162
  if ((acked !== null && seqAfter(acked, lastSeq)) || (this.body.ride === null) !== (ridden === null)) return false;
161
163
  const led = this.flag(table.led, owner) === 1, resets = this.value(table.resets, owner);
162
164
  const boarded = (ridden !== null) !== this.aboard; // getting on or off is the server's word, not a wrong guess
163
- const forced = led || this.led || boarded || (this.resets !== null && this.resets !== resets);
165
+ const leadEnded = this.led && !led, reset = this.resets !== null && this.resets !== resets;
166
+ const forced = led || this.led || boarded || reset;
164
167
  this.led = led; this.resets = resets; this.aboard = ridden !== null;
165
168
  if (!forced && acked === lastSeq) return false;
166
169
  const { body, seqs, states, count, head } = this, offset = count === 0 ? -1 : (lastSeq - (seqs[head] ?? 0)) & 0xffff;
@@ -182,12 +185,17 @@ export class Predictor {
182
185
  this.save(run);
183
186
  }
184
187
  s.yaw = yaw; // the view is this client's own: the server sends it back later than the thumb has moved
185
- if (!led && !boarded) this.corrections++;
188
+ // The end of a server-led move and a server teleport must take the authoritative pose, but neither says the
189
+ // page predicted a command incorrectly. Counting them as corrections made Far Reach's boost report a false B2 miss.
190
+ if (leadEnded) this.authoritative.leadEnds++;
191
+ if (reset) this.authoritative.resets++;
192
+ const corrected = !forced && !led && !boarded;
193
+ if (corrected) this.corrections++;
186
194
  const offsetX = x - feet.x, offsetY = y - feet.y, offsetZ = z - feet.z, far = offsetX * offsetX + offsetY * offsetY + offsetZ * offsetZ > PREDICTION_SNAP * PREDICTION_SNAP;
187
195
  body.renderOffset.set(far ? 0 : offsetX, far ? 0 : offsetY, far ? 0 : offsetZ);
188
196
  this.glide = glidePace(body.renderOffset.length());
189
- if(!led&&!boarded)this.corrected?.({tick:tick??s.tick,mode:ride!==null?'ride':s.board.on?'board':s.swim.on?'swim':'foot',offset:Math.hypot(offsetX,offsetY,offsetZ),snapped:far});
190
- return !led && !boarded;
197
+ if(corrected)this.corrected?.({tick:tick??s.tick,mode:ride!==null?'ride':s.board.on?'board':s.swim.on?'swim':'foot',offset:Math.hypot(offsetX,offsetY,offsetZ),snapped:far});
198
+ return corrected;
191
199
  }
192
200
 
193
201
  /** A session's first frame: this body stands where the server says, with nothing to compare it to. */
@@ -1,5 +1,5 @@
1
1
  import { mountUi } from '../ui/ownership';
2
- import { mountBoostLook } from '../ui/hoverBoost';
2
+ import { mountBoostLook, mountBoostTag } from '../ui/hoverBoost';
3
3
  import { app } from '../app/runtime';
4
4
  import { capturePointer, listenDom, listenPage } from '../input/dom';
5
5
  import type { Action, TouchStack, TouchVerbSpec } from '../input/InputService';
@@ -155,7 +155,8 @@ export class TouchControls {
155
155
  this.weapons = weapons;
156
156
  this.lock = lock;
157
157
  this.active = force || IS_TOUCH;
158
- if (!this.active) return;
158
+ // QA 11-15 row 9: a keyboard page has no HOVER tab, so BOOST stands on the left edge by itself while boost is on
159
+ if (!this.active) { mountBoostTag(document.getElementById('hud') ?? document.body, player, app.events, this.scope); return; }
159
160
  const hud = document.getElementById('hud') ?? document.body;
160
161
  hud.classList.add('touch');
161
162
  const root = document.createElement('div');
@@ -41,7 +41,9 @@ const SWAY_VERTEX = /* glsl */`
41
41
  vec3 wsSwayAt = ( wsSwayM * vec4( transformed, 1.0 ) ).xyz;
42
42
  float wsSwayPh = wsSceneTime * wsSwayWind.z * 6.2831853 + wsSwayAt.x * 0.37 + wsSwayAt.z * 0.29;
43
43
  float wsSwayAmt = wsSway * ( 0.7 * sin( wsSwayPh ) + 0.3 * sin( wsSwayPh * 2.3 + 1.7 ) );
44
- vec3 wsSwayDir = transpose( mat3( wsSwayM ) ) * vec3( wsSwayWind.x, 0.0, wsSwayWind.y );
44
+ // the wind is a world direction and wsSway world metres: back into the mesh's own frame by the inverse, which (unlike
45
+ // the transpose) also undoes the mesh's scale, so a scaled frond still moves its declared metres
46
+ vec3 wsSwayDir = inverse( mat3( wsSwayM ) ) * vec3( wsSwayWind.x, 0.0, wsSwayWind.y );
45
47
  transformed += wsSwayDir * wsSwayAmt;
46
48
  }
47
49
  `;
@@ -45,11 +45,13 @@ export interface BrowserErrorTags {
45
45
  * once per cell a session; warning
46
46
  * map-tile-missing a full-map cell the world map atlas has no tile for, drawn as a plain plot or its own map instead
47
47
  * (game/grid/mapAtlas.ts; QA-FEEDBACK 2026-11-13 row 44), once per slug a page; warning
48
+ * release-unsigned FM5 mode 39's page, "Couldn't check the world": the release file failed its signature, so the page dials
49
+ * nothing (host/online/releaseScreens.ts), once a page
48
50
  * Not screens of a fault, so never reported: the player's own reload, back or exit (QA 11-12 row 35), "Playing somewhere else",
49
51
  * "The world is full", the reconnect banner (counted in `net` telemetry), title refusal lines and the Connection doctor.
50
52
  */
51
53
  export const ERROR_SCREENS = ['error-modal', 'stuck-step', 'glitch-chip', 'load-failure', 'title-drop', 'link-lost', 'link-refused', 'stale-build',
52
- 'loading-stall', 'stale-reload', 'self-reload', 'save-failed', 'cell-unavailable', 'map-tile-missing'] as const;
54
+ 'loading-stall', 'stale-reload', 'self-reload', 'save-failed', 'cell-unavailable', 'map-tile-missing', 'release-unsigned'] as const;
53
55
  /** S18: screens common enough on a bad network that each is a Sentry warning, never an error */
54
56
  export const WARNING_SCREENS: readonly ErrorScreen[] = ['loading-stall', 'stale-reload', 'self-reload', 'cell-unavailable', 'map-tile-missing'];
55
57
  export type ErrorScreen = typeof ERROR_SCREENS[number];
@@ -159,7 +159,7 @@ function build(): HTMLElement {
159
159
  const doctor = document.createElement('button');
160
160
  doctor.type = 'button'; doctor.className = 'doctor'; doctor.textContent = engineString('s_doctor_failed');
161
161
  q(el, '.title').after(doctor);
162
- scope.listen(doctor, 'click', () => { doctor.disabled = true; openDoctorPage('failed-join'); });
162
+ scope.listen(doctor, 'click', () => { doctor.disabled = true; void openDoctorPage('failed-join').then(left => { doctor.disabled = left; return left; }); });
163
163
  }
164
164
  // a dead loop can't be played on: KEEP PLAYING only acts while the loop still runs (it is hidden otherwise)
165
165
  scope.listen(q(el, '.keep'), 'click', () => { if (loopState() !== 'running') return; closeFatal(); document.dispatchEvent(new Event('ws:error-keep')); });
@@ -14,7 +14,7 @@ import { loadShellTemplate, START_STEPS, stopShellClock } from '../boot/shell';
14
14
  import { appIdentity } from '../../../shared/engine/app/identity';
15
15
  import { recordBootCheckpoint, recordBootProgress, startBoot } from '../boot/bootTrace';
16
16
  import { adoptLoadingWait } from '../boot/download';
17
- import { beginLoadingWait, reportLoadingWait, finishLoadingWait, loadingWaitState } from '../../../shared/engine/boot/loadingWaits';
17
+ import { beginLoadingWait, reportLoadingWait, finishLoadingWait, loadingWaitState, type LoadingWaitEntry } from '../../../shared/engine/boot/loadingWaits';
18
18
  import { loadingCacheText, loadingDownloadText, loadingDownloadFraction, loadingPrefetchFraction, loadingPrefetchText, type LoadingPrefetchSnapshot, type LoadingDownloadSnapshot } from '../boot/loadingDownloadText';
19
19
  import { LoadingTimeline, installLoadingTimeline, type LoadingPath, type LoadingRow, type LoadingGap } from '../../../shared/engine/boot/timeline';
20
20
  import {loadingFraction} from '../boot/weights';
@@ -579,7 +579,7 @@ export class Loading {
579
579
 
580
580
  private paintWaiting(timeline: TimelineSnapshot): void {
581
581
  if (this.view?.error || this.failedReason !== null) return;
582
- if (this.finished) { set(this.els.foot, ''); this.els.retry.hidden = true; setData(this.root, 'stalled', 'false'); return; }
582
+ if (this.finished) { set(this.els.foot, ''); delete this.els.foot.dataset['failmode']; this.els.retry.hidden = true; setData(this.root, 'stalled', 'false'); return; }
583
583
  const pending = this.scoped ? [] : loadingStepWaits(bootWaits(), timeline.display, timeline.current, this.timeline.waitOwner).filter(wait => wait.id !== this.waitId);
584
584
  const files = pending.filter(wait => wait.kind === 'file');
585
585
  // The outer admission promise has no file identity. Let the current
@@ -615,6 +615,18 @@ export class Loading {
615
615
  // A quiet phase still reports its actual age, without advancing a byte,
616
616
  // file or setup credit. Only an explicit failed-read retry capability offers
617
617
  // an action; a long pending operation remains pending.
618
+ // FM6 (meta MMO-FAILURE-MODES-PLAN modes 33 to 35, 43, 44): a failed read says what failed in a player's words, how long it has
619
+ // waited, and the retry actually scheduled; the catalogue's ids ride on the line. A RETRY wait wins over a note (storage full).
620
+ const said = (row: LoadingWaitEntry): boolean => row.failmode !== undefined && row.line !== undefined;
621
+ const pick = (rows: readonly LoadingWaitEntry[]): LoadingWaitEntry | undefined => rows.find(row => row.retry !== null) ?? rows.find(row => row.dueAt !== undefined) ?? rows[0];
622
+ const fault = pick(pending.filter(said)) ?? (stalled ? undefined : pick([...loadingWaitState().pending.values()].filter(row => said(row) && row.owner === null)));
623
+ if (fault?.failmode !== undefined && fault.line !== undefined) {
624
+ const due = fault.dueAt === undefined ? '' : ` · next try in ${String(Math.max(0, Math.ceil((fault.dueAt - now) / 1000)))} s`;
625
+ this.els.foot.dataset['failmode'] = fault.failmode;
626
+ set(this.els.foot, `${fault.line} · ${String(Math.floor(Math.max(0, now - fault.startedAt) / 1000))} s${due}`);
627
+ return;
628
+ }
629
+ delete this.els.foot.dataset['failmode'];
618
630
  set(this.els.foot, stalled ? `Waiting for ${label} · ${(quietMs / 1000).toFixed(1)} s` : !this.finished && quietMs >= 500
619
631
  ? `No reported progress for ${(quietMs / 1000).toFixed(1)} s · ${detail}` : detail);
620
632
  }
@@ -7,7 +7,7 @@ import { app } from '../app/runtime';
7
7
  import { uiScope, mountUi } from './ownership';
8
8
  import { listenTap } from '../input/dom';
9
9
  import { copyText, diagnosticsSource, DOCTOR_EARLIER_KEY } from './diagnosticsCopy';
10
- import type { Scope } from '../../../shared/engine/app/scope';
10
+ import { Scope } from '../../../shared/engine/app/scope';
11
11
 
12
12
  const scope = uiScope('loadFailure', app.engineScope);
13
13
 
@@ -28,19 +28,61 @@ export function doctorUrl(from: string, at: Location = location): string {
28
28
  return url.href;
29
29
  }
30
30
 
31
- /** Leave for the doctor: a held session saves first, and the page's report and the way back go with it. */
32
- export function openDoctorPage(from: string): void {
33
- const read = diagnosticsSource();
31
+ /** FM8 mode 14: how long the doctor's preflight may take before it counts as failed. */
32
+ const DOCTOR_PREFLIGHT_MS = 8000;
33
+ /** FM8 mode 14 (meta MMO-FAILURE-MODES-PLAN): a same-origin preflight of the doctor's own page. It says only that this one
34
+ * request answered now; it can't promise the document's later reads will, so a pass never claims more. Null when it answered. */
35
+ export async function doctorPreflight(url: string, read: typeof fetch = fetch, deadlineMs: number = DOCTOR_PREFLIGHT_MS): Promise<string | null> {
36
+ const abort = new AbortController(), timer = setTimeout(() => { abort.abort(); }, deadlineMs);
37
+ try {
38
+ const response = await read(url, { method: 'HEAD', cache: 'no-store', signal: abort.signal });
39
+ return response.ok ? null : engineString('s_doctor_http_status', [response.status]);
40
+ } catch { return abort.signal.aborted ? engineString('s_doctor_http_slow', [Math.round(deadlineMs / 1000)]) : engineString('s_doctor_http_none'); }
41
+ finally { clearTimeout(timer); }
42
+ }
43
+ /** The doctor-http card on screen, if any: a new one (or a repeated `ws:doctor`) closes it, scope and all. */
44
+ let doctorCardClose: (() => void) | null = null;
45
+ /** FM8 mode 14's card: the doctor didn't open, and this page stays as it was. Try again re-checks with the card up (a failure
46
+ * replaces it, a pass leaves the page); Back closes the card. */
47
+ function doctorHttpCard(measured: string, again: () => Promise<boolean>): void {
48
+ doctorCardClose?.();
49
+ const card = document.createElement('div'), box = document.createElement('div'), title = document.createElement('h1'), body = document.createElement('p');
50
+ const retry = document.createElement('button'), back = document.createElement('button'), details = document.createElement('details'), summary = document.createElement('summary'), fact = document.createElement('p');
51
+ card.dataset['failmode'] = 'doctor-http'; card.dataset['tone'] = 'warn'; card.setAttribute('role', 'alertdialog'); card.setAttribute('aria-modal', 'true'); card.setAttribute('aria-label', engineString('s_doctor_http_title'));
52
+ card.style.cssText = 'position:fixed;inset:0;z-index:2147482600;display:flex;align-items:center;justify-content:center;padding:16px;background:rgba(4,9,14,.62);color:#e6f2f8;font:12px/1.5 "JetBrains Mono",Menlo,monospace';
53
+ box.style.cssText = 'width:min(440px,100%);padding:22px 18px 16px;background:rgba(13,27,38,.92);border:1px solid rgba(143,227,255,.35);display:flex;flex-direction:column;gap:10px';
54
+ title.textContent = engineString('s_doctor_http_title'); title.style.cssText = 'margin:0;font:700 24px/1.1 Rajdhani,Bahnschrift,sans-serif;letter-spacing:.1em;text-transform:uppercase;color:#fff';
55
+ body.textContent = engineString('s_doctor_http_body'); body.style.margin = '0';
56
+ const button = 'min-height:48px;padding:13px 16px;cursor:pointer;font:700 12px/1 "JetBrains Mono",Menlo,monospace;letter-spacing:.22em;text-transform:uppercase;border:1px solid rgba(143,227,255,.35);background:rgba(13,27,38,.6);color:#e6f2f8';
57
+ retry.type = 'button'; retry.className = 'go'; retry.textContent = engineString('s_doctor_http_retry'); retry.style.cssText = `${button};border-color:#8fe3ff;background:rgba(143,227,255,.18)`;
58
+ back.type = 'button'; back.textContent = engineString('s_doctor_http_back'); back.style.cssText = button;
59
+ summary.textContent = engineString('s_doctor_http_details'); fact.textContent = engineString('s_doctor_http_fact', [measured]); fact.style.cssText = 'margin:8px 0 0;opacity:.6';
60
+ details.append(summary, fact);
61
+ const owner = new Scope('doctor-http', scope), close = (): void => { if (doctorCardClose === close) doctorCardClose = null; owner.dispose(); card.remove(); };
62
+ doctorCardClose = close;
63
+ owner.listen(retry, 'click', () => { retry.disabled = true; retry.textContent = engineString('s_doctor_http_checking'); void again(); });
64
+ owner.listen(back, 'click', close);
65
+ box.append(title, body, retry, back, details); card.append(box);
66
+ mountUi(card, owner, document.body);
67
+ retry.focus();
68
+ }
69
+
70
+ /** Leave for the doctor: a held session saves first, and the page's report and the way back go with it. FM8 mode 14: a doctor page
71
+ * that doesn't answer its preflight leaves this page as it was, with a card saying so. Resolves true when the page leaves. */
72
+ export async function openDoctorPage(from: string, read: typeof fetch = fetch): Promise<boolean> {
73
+ const url = doctorUrl(from), failed = await doctorPreflight(url, read);
74
+ if (failed !== null) { doctorHttpCard(failed, () => openDoctorPage(from, read)); return false; }
75
+ const report = diagnosticsSource();
34
76
  try {
35
77
  // oxlint-disable-next-line wildshard/no-raw-save -- one tab-scoped handoff key the doctor's page reads; that page loads no save service
36
- sessionStorage.setItem(DOCTOR_EARLIER_KEY, JSON.stringify({ earlier: read === null ? null : read(), back: `${location.pathname}${location.search}` }));
78
+ sessionStorage.setItem(DOCTOR_EARLIER_KEY, JSON.stringify({ earlier: report === null ? null : report(), back: `${location.pathname}${location.search}` }));
37
79
  } catch { /* storage refused: the doctor still runs, its report is just shorter */ }
38
- const url = doctorUrl(from);
39
80
  leaveSaved(() => { markUnload('doctor'); location.assign(url); });
81
+ return true;
40
82
  }
41
83
 
42
84
  // The online page's own module graph (src/client/host/online/shell.ts) asks by event: it can't share this bundle's save hold.
43
- scope.listen(document, 'ws:doctor', event => { openDoctorPage(event instanceof CustomEvent && typeof event.detail === 'string' ? event.detail : 'online'); });
85
+ scope.listen(document, 'ws:doctor', event => { void openDoctorPage(event instanceof CustomEvent && typeof event.detail === 'string' ? event.detail : 'online'); });
44
86
 
45
87
  /** Settings ▸ Connection: the doctor for everyone, beside Offline play (the title's Settings and the pause menu's saves). */
46
88
  export function buildConnectionRow(owner: Scope): HTMLElement {
@@ -48,7 +90,7 @@ export function buildConnectionRow(owner: Scope): HTMLElement {
48
90
  const label = document.createElement('div'); label.className = 'ws-gmenu-label'; label.textContent = engineString('s_doctor_title');
49
91
  const note = document.createElement('div'); note.className = 'ws-gmenu-note'; note.textContent = engineString('s_doctor_note');
50
92
  const go = document.createElement('button'); go.type = 'button'; go.className = 'ws-gmenu-btn ws-gmenu-doctor'; go.textContent = engineString('s_doctor_open');
51
- listenTap(owner, go, () => { go.disabled = true; openDoctorPage('settings'); });
93
+ listenTap(owner, go, () => { go.disabled = true; void openDoctorPage('settings').then(left => { go.disabled = left; return left; }); });
52
94
  box.append(label, note, go);
53
95
  return box;
54
96
  }
@@ -98,7 +140,7 @@ export function showLoadFailure(failure: LoadFailure): HTMLElement {
98
140
  const doctor = document.createElement('button');
99
141
  doctor.type = 'button'; doctor.className = 'ws-load-doctor'; doctor.textContent = engineString('s_doctor_failed');
100
142
  doctor.style.cssText = button;
101
- listenTap(scope, doctor, () => { doctor.disabled = true; openDoctorPage('ls4'); });
143
+ listenTap(scope, doctor, () => { doctor.disabled = true; void openDoctorPage('ls4').then(left => { doctor.disabled = left; return left; }); });
102
144
  actions.append(doctor);
103
145
  root.append(heading, context, message, stack, actions);
104
146
  mountUi(root, scope, document.body);