File size: 12,153 Bytes
753ebc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import {base64ToBytes, type MiniappSession} from "@mentra/miniapp/background"

import {ONSET_PHRASE_PCM_BASE64, ONSET_PHRASE_SAMPLE_RATE} from "../onsetPhrasePcm"
import type {Channels} from "../../shared/channels"

/**

 * TesterController — the SDK Tester surface's background half.

 *

 * The UI tester pages can't call `session.*` directly (they're inside a

 * WebView, no native access). Two patterns:

 *

 *   1. **Subscribe-based testers** (Storage / Transcription / IMU /

 *      Location / Microphone / System / Glasses / Phone).

 *      UI sends `tester:start` → we open a subscription that pipes events

 *      back as streamed `tester:event` with `{iface, kind, payload}`.

 *      UI sends `tester:stop` to release.

 *

 *   2. **Imperative testers** (Display / Led / Speaker / Phone fire /

 *      Storage gets). UI calls `await mentra.request("tester:invoke", ...)`

 *      and we dispatch to `session[iface][method](...args)` via the new

 *      `session.ui.handle` API. The return value flows back through the

 *      SDK's RPC reply; errors throw on the UI side automatically.

 */

type Send = <C extends keyof Channels & string>(channel: C, payload: Channels[C]) => void

const ONSET_SAMPLE_RATE = 16000
const ONSET_CLICK_STARTS_MS = [0, 300, 600, 900]
const ONSET_CLICK_MS = 40
const ONSET_CLICK_HZ = 2400

/** Four loud beeps. Sample 0 of the first beep is already at full level. */
function buildOnsetClicks(sampleRate: number): Uint8Array {
  const frames = sampleRate // one second
  const pcm = new Uint8Array(frames * 2)
  const view = new DataView(pcm.buffer)
  const clickFrames = Math.floor((sampleRate * ONSET_CLICK_MS) / 1000)
  for (const startMs of ONSET_CLICK_STARTS_MS) {
    const start = Math.floor((sampleRate * startMs) / 1000)
    for (let i = 0; i < clickFrames; i++) {
      const sample = Math.sin((2 * Math.PI * ONSET_CLICK_HZ * i) / sampleRate)
      view.setInt16((start + i) * 2, Math.round(sample * 0.7 * 0x7fff), true)
    }
  }
  return pcm
}

async function playPcm(

  session: MiniappSession,

  pcm: Uint8Array,

  sampleRate: 16000 | 24000 | 48000,

): Promise<{durationMs?: number; chunks: number}> {
  const writer = await session.speaker.createStream({sampleRate, stopOtherAudio: true})
  try {
    const chunkBytes = Math.floor(sampleRate / 10) * 2
    let chunks = 0
    for (let offset = 0; offset < pcm.length; offset += chunkBytes) {
      await writer.write(pcm.subarray(offset, Math.min(pcm.length, offset + chunkBytes)))
      chunks++
    }
    const {durationMs} = await writer.close()
    return {durationMs, chunks}
  } catch (err) {
    await writer.abort().catch(() => {})
    throw err
  }
}

async function playOnsetClicks(session: MiniappSession): Promise<{durationMs?: number; chunks: number}> {
  return playPcm(session, buildOnsetClicks(ONSET_SAMPLE_RATE), ONSET_SAMPLE_RATE)
}

export class TesterController {
  private subscriptions: Map<string, () => void> = new Map()
  private unsubs: Array<() => void> = []
  private subscribed = false

  constructor(private readonly session: MiniappSession) {}

  /** Idempotent — safe to call multiple times. */
  start(): void {
    if (this.subscribed) return
    this.subscribed = true

    const ui = this.session.ui as unknown as {
      send: Send
      on: <C extends keyof Channels & string>(channel: C, cb: (p: Channels[C]) => void) => () => void
      handle: <C extends keyof Channels & string>(

        channel: C,

        handler: (payload: unknown, ctx?: {signal: AbortSignal}) => Promise<unknown> | unknown,

      ) => () => void
    }

    // Track every UI listener (including the broadcast tester:start/stop
    // ones) in `unsubs` so stop() detaches them and a restart can't stack
    // duplicate handlers or leak the previous tester:invoke handle.
    this.unsubs.push(
      ui.on("tester:start", ({iface}) => {
        if (this.subscriptions.has(iface)) return
        const unsub = this.openSubscription(iface, ui.send)
        if (unsub) this.subscriptions.set(iface, unsub)
      }),
    )

    this.unsubs.push(
      ui.on("tester:stop", ({iface}) => {
        const unsub = this.subscriptions.get(iface)
        if (!unsub) return
        try {
          unsub()
        } catch {
          /* ignore */
        }
        this.subscriptions.delete(iface)
      }),
    )

    // The single imperative-dispatch handler. Used by every fire-style
    // tester page. Replaces the old `tester:fire` + `tester:event{kind:result}`
    // muxed-into-stream pattern.
    this.unsubs.push(
      ui.handle("tester:invoke", async (payload) => {
        const {iface, method, args} = payload as {iface: string; method: string; args?: unknown[]}
        const module = (this.session as unknown as Record<string, unknown>)[iface] as
          | Record<string, unknown>
          | undefined
        if (!module) throw new Error(`unknown iface "${iface}"`)
        const fn = module[method] as ((...a: unknown[]) => unknown) | undefined
        if (typeof fn !== "function") throw new Error(`unknown method "${iface}.${method}"`)
        return await Promise.resolve(fn.apply(module, args ?? []))
      }),
    )

    this.unsubs.push(
      ui.handle("tester:calendar-list", async (payload) => {
        const {startsAt, endsAt, limit} = payload as {startsAt: string; endsAt: string; limit?: number}
        return await this.session.phone.calendar.listEvents({startsAt, endsAt, limit})
      }),
    )

    // speaker.createStream E2E: generate a sine tone background-side and pump
    // it through the live PCM stream. Runs here (not tester:invoke) because
    // the SpeakerStreamWriter can't cross the bridge — only a summary returns.
    // Writes are awaited, so the host's backpressure ceiling paces the loop.
    this.unsubs.push(
      ui.handle("tester:speaker-stream-tone", async (payload) => {
        const {
          seconds = 5,
          freqHz = 440,
          sampleRate = 16000,
        } = (payload ?? {}) as {seconds?: number; freqHz?: number; sampleRate?: 16000 | 24000 | 48000}

        const writer = await this.session.speaker.createStream({sampleRate})
        try {
          // 100ms chunks of 16-bit LE mono sine.
          const chunkFrames = Math.floor(sampleRate / 10)
          const totalChunks = Math.max(1, Math.round(seconds * 10))
          let phase = 0
          const phaseStep = (2 * Math.PI * freqHz) / sampleRate
          let last = {bufferedMs: 0}
          for (let i = 0; i < totalChunks; i++) {
            const buf = new Uint8Array(chunkFrames * 2)
            const view = new DataView(buf.buffer)
            for (let f = 0; f < chunkFrames; f++) {
              // 0.25 amplitude so it isn't ear-splitting through the glasses.
              view.setInt16(f * 2, Math.round(Math.sin(phase) * 0x2000), true)
              phase += phaseStep
            }
            last = await writer.write(buf)
          }
          const {durationMs} = await writer.close()
          return {streamId: writer.streamId, durationMs, chunks: totalChunks, lastBufferedMs: last.bufferedMs}
        } catch (err) {
          await writer.abort().catch(() => {})
          throw err
        }
      }),
    )

    // OS-2022: first samples of miniapp audio can be missing after the glasses
    // speaker has gone idle. The click train starts at full amplitude so a
    // missing opening beep is audible. The second pass starts immediately.
    this.unsubs.push(
      ui.handle("tester:speaker-onset-test", async (payload) => {
        const {kind = "clicks", idleMs = 6000} = (payload ?? {}) as {
          kind?: "clicks" | "speech"
          idleMs?: number
        }
        const waitMs = Math.max(0, Math.min(30000, Math.round(idleMs)))
        await new Promise((resolve) => setTimeout(resolve, waitMs))

        if (kind === "speech") {
          // Phone TTS is not used. Cloud download failed on this phone and the
          // offline voice model is not installed, so speak() produced silence.
          const phrase = base64ToBytes(ONSET_PHRASE_PCM_BASE64)
          const first = await playPcm(this.session, phrase, ONSET_PHRASE_SAMPLE_RATE)
          const second = await playPcm(this.session, phrase, ONSET_PHRASE_SAMPLE_RATE)
          return {kind, idleMs: waitMs, first, second}
        }

        const first = await playOnsetClicks(this.session)
        const second = await playOnsetClicks(this.session)
        return {kind: "clicks" as const, idleMs: waitMs, first, second}
      }),
    )
  }

  stop(): void {
    for (const [, unsub] of this.subscriptions) {
      try {
        unsub()
      } catch {
        /* ignore */
      }
    }
    this.subscriptions.clear()
    for (const u of this.unsubs) {
      try {
        u()
      } catch {
        /* ignore */
      }
    }
    this.unsubs = []
    this.subscribed = false
  }

  /**

   * Open a per-iface subscription that pipes every event back to the UI

   * as `tester:event`. The `kind` field tells the UI which sub-channel

   * fired (transcription:final, location:update, ...) so a single tester

   * page can render a typed timeline.

   */
  private openSubscription(iface: string, send: Send): (() => void) | null {
    const emit = (kind: string, payload: unknown) => {
      send("tester:event", {iface, kind, payload})
    }
    switch (iface) {
      case "transcription":
        return this.session.transcription.on((data) => emit(data.isFinal ? "final" : "partial", data))
      case "translation":
        return this.session.translation.to("es-ES", (data) => emit("event", data))
      case "input": {
        const b = this.session.input.onButtonPress((data) => emit("button", data))
        const t = this.session.input.onTouch((data) => emit("touch", data))
        return () => {
          b()
          t()
        }
      }
      case "stream": {
        // Stream status (lifecycle + Cloudflare + coordinator-emitted errors)
        // arrives as a generic `stream_status` event stream. The coordinator
        // emits everything keyed by streamId so the UI can render a unified
        // timeline regardless of source.
        const s = this.session.events.subscribe("stream_status", (data) => emit("status", data))
        return () => s()
      }
      case "camera": {
        // Camera has no event stream — takePhoto() resolves via `kind:"result"`
        // through the generic dispatchAction path. Return a no-op subscriber
        // so the UI's "subscription open?" toggle is consistent.
        return () => {}
      }
      case "imu": {
        const h = this.session.imu.onHeadPosition((data) => emit("head", data))
        const a = this.session.imu.onAccel((data) => emit("accel", data))
        return () => {
          h()
          a()
        }
      }
      case "location":
        return this.session.location.onUpdate((data) => emit("update", data))
      case "mic": {
        const a = this.session.mic.onAudioChunk((data) => emit("audio", {data}))
        const v = this.session.mic.onVoiceActivity((data) => emit("vad", data))
        return () => {
          a()
          v()
        }
      }
      case "storage":
        return () => {}
      case "system":
        emit("opened", {note: "session.system has no event surface yet"})
        return () => {}
      case "glasses": {
        const b = this.session.glasses.onBattery((data) => emit("battery", data))
        const c = this.session.glasses.onConnection((data) => emit("connection", data))
        return () => {
          b()
          c()
        }
      }
      case "phone": {
        const n = this.session.phone.notifications.on((data) => emit("notification", data))
        const b = this.session.phone.onBattery((data) => emit("battery", data))
        return () => {
          n()
          b()
        }
      }
      default:
        return null
    }
  }
}