@glassly/miniapp-cli 0.1.15-dev.0 → 0.1.15

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.
@@ -0,0 +1,59 @@
1
+ /// <reference types="bun-types" />
2
+
3
+ import {expect, mock, test} from "bun:test"
4
+ import {mkdtempSync} from "fs"
5
+ import {tmpdir} from "os"
6
+ import {join, resolve} from "path"
7
+ import {MiniappRequestType} from "@glassly/miniapp"
8
+
9
+ import {SIM_DEVICES, simDevice} from "./device.js"
10
+ import {SimHost} from "./host.js"
11
+ import {createSimStorage} from "./storage.js"
12
+
13
+ // A stand-in background that connects, then draws on the schedule each test sets.
14
+ let schedule: (draw: () => void) => () => void = () => () => {}
15
+ mock.module(resolve(import.meta.dir, "../dev.ts"), () => ({runBuild: async () => {}}))
16
+ mock.module(resolve(import.meta.dir, "sim.ts"), () => ({
17
+ readManifest: () => ({name: "Fixture", packageName: "com.example.fixture", entry: {background: "unused.js"}}),
18
+ loadHostModules: async () => ({
19
+ SimHost,
20
+ simDevice,
21
+ SIM_DEVICES,
22
+ createSimStorage,
23
+ createScreenRenderer: async () => ({update: () => {}, png: async () => new Uint8Array([1])}),
24
+ startBackground: (_bundle: string, callbacks: {onBridge: (raw: string) => void}) => {
25
+ const send = (payload: object) => callbacks.onBridge(JSON.stringify({payload}))
26
+ queueMicrotask(() => send({type: MiniappRequestType.CONNECT}))
27
+ let n = 0
28
+ const stop = schedule(() =>
29
+ send({type: MiniappRequestType.RENDER, view: "main", elements: [{type: "text", id: "t", text: `frame ${++n}`, box: {x: 0, y: 0, w: 200, h: 40}}]}),
30
+ )
31
+ return {send: () => {}, stop}
32
+ },
33
+ }),
34
+ }))
35
+ const {simShots} = await import("./shots.js")
36
+ const out = () => mkdtempSync(join(tmpdir(), "glassly-shots-test-"))
37
+
38
+ test("a first frame drawn after the quiet interval is still waited for", async () => {
39
+ schedule = (draw) => {
40
+ const timer = setTimeout(draw, 300)
41
+ return () => clearTimeout(timer)
42
+ }
43
+ const {shots} = await simShots({out: out(), devices: ["g2"], settleMs: 80, timeoutMs: 2000})
44
+ expect(shots[0]).toMatchObject({device: "g2", file: expect.stringMatching(/g2\.png$/)})
45
+ expect(shots[0].error).toBeUndefined()
46
+ })
47
+
48
+ test("a display that never settles, or never draws, fails that device", async () => {
49
+ schedule = (draw) => {
50
+ const timer = setInterval(draw, 20)
51
+ return () => clearInterval(timer)
52
+ }
53
+ const busy = await simShots({out: out(), devices: ["g2"], settleMs: 80, timeoutMs: 300})
54
+ expect(busy.shots[0].error).toBe("the display was still changing at the timeout")
55
+
56
+ schedule = () => () => {}
57
+ const blank = await simShots({out: out(), devices: ["g2", "mentra-live"], settleMs: 50, timeoutMs: 300})
58
+ expect(blank.shots.map((shot) => shot.error ?? shot.note)).toEqual(["the miniapp drew nothing before the timeout", "no display"])
59
+ })
@@ -0,0 +1,161 @@
1
+ import {mkdirSync, writeFileSync} from "fs"
2
+ import {join, resolve} from "path"
3
+
4
+ import {runBuild} from "../dev.js"
5
+ import type {BackgroundHandle} from "./background.js"
6
+ import type {ScreenRenderer} from "./screenshot.js"
7
+ import {loadHostModules, readManifest} from "./sim.js"
8
+
9
+ export const CANNOT_STAND_IN_FOR_URL =
10
+ "https://docs.glasslyos.com/app-devs/getting-started/simulator#what-the-simulator-cannot-stand-in-for"
11
+
12
+ export interface ShotsOptions {
13
+ cwd?: string
14
+ out?: string
15
+ devices?: string[]
16
+ say?: string
17
+ settleMs?: number
18
+ timeoutMs?: number
19
+ scale?: number
20
+ }
21
+
22
+ export interface Shot {
23
+ device: string
24
+ label: string
25
+ file: string | null
26
+ note?: string
27
+ error?: string
28
+ }
29
+
30
+ type Modules = Awaited<ReturnType<typeof loadHostModules>>
31
+
32
+ /** Runs the miniapp on each device in turn, headless, and saves what each one shows once the frame settles. */
33
+ export async function simShots(options: ShotsOptions = {}): Promise<{shots: Shot[]; index: string}> {
34
+ const cwd = resolve(options.cwd ?? process.cwd())
35
+ const manifest = readManifest(cwd)
36
+ const modules = await loadHostModules()
37
+ const ids = options.devices?.length ? options.devices : Object.keys(modules.SIM_DEVICES)
38
+ const devices = ids.map((id) => modules.simDevice(id))
39
+ const unavailable = await modules.createScreenRenderer()
40
+ if (typeof unavailable === "string") throw new Error(`Screenshots are unavailable: ${unavailable}`)
41
+
42
+ console.log(`Building ${manifest.name} (${manifest.packageName})...`)
43
+ await runBuild(cwd)
44
+ const bundle = resolve(cwd, "dist", manifest.entry.background)
45
+ const out = resolve(options.out ?? "glassly-sim-shots")
46
+ mkdirSync(out, {recursive: true})
47
+
48
+ const shots: Shot[] = []
49
+ for (const device of devices) {
50
+ // A fresh renderer per device: each host numbers its snapshots from zero.
51
+ const screen = (await modules.createScreenRenderer()) as ScreenRenderer
52
+ const shot = await shootDevice(modules, screen, manifest, bundle, device, out, options)
53
+ shots.push(shot)
54
+ const result = shot.error ? `failed: ${shot.error}` : shot.file ? `${device.id}.png` : shot.note
55
+ console.log(`${device.id.padEnd(15)} ${result}`)
56
+ }
57
+ const index = join(out, "index.html")
58
+ writeFileSync(index, indexPage(manifest.name, shots))
59
+ return {shots, index}
60
+ }
61
+
62
+ async function shootDevice(
63
+ modules: Modules,
64
+ screen: ScreenRenderer,
65
+ manifest: ReturnType<typeof readManifest>,
66
+ bundle: string,
67
+ device: Modules["SIM_DEVICES"][string],
68
+ out: string,
69
+ options: ShotsOptions,
70
+ ): Promise<Shot> {
71
+ const settleMs = options.settleMs ?? 800
72
+ const deadline = Date.now() + (options.timeoutMs ?? 15_000)
73
+ const errors: string[] = []
74
+ let changedAt = Date.now()
75
+ let background: BackgroundHandle | null = null
76
+ const host = new modules.SimHost({
77
+ manifest,
78
+ device,
79
+ storage: modules.createSimStorage(),
80
+ toBackground: (raw) => background?.send(raw),
81
+ emit: (event) => {
82
+ if (event.type === "display") {
83
+ screen.update(event.snapshot)
84
+ changedAt = Date.now()
85
+ }
86
+ },
87
+ })
88
+ host.backgroundStarted()
89
+ background = modules.startBackground(bundle, {
90
+ onBridge: (raw) => host.fromBackground(raw),
91
+ onLog: () => {},
92
+ onError: (message, stack) => errors.push((stack || message).split("\n")[0]),
93
+ onCrash: () => errors.push("the background script failed to start"),
94
+ })
95
+ const shot: Shot = {device: device.id, label: device.label, file: null}
96
+ try {
97
+ const failed = () => errors.length > 0
98
+ while (!host.status().connected && !failed() && Date.now() < deadline) await Bun.sleep(25)
99
+ if (!failed() && !host.status().connected) throw new Error("the miniapp never connected")
100
+ if (options.say && !failed()) {
101
+ const listening = () => (host.status().subscriptions as string[]).some((s) => s.startsWith("transcription"))
102
+ const until = Math.min(deadline, Date.now() + 3_000)
103
+ while (!listening() && !failed() && Date.now() < until) await Bun.sleep(25)
104
+ host.transcription(options.say, {isFinal: true})
105
+ }
106
+ changedAt = Date.now()
107
+ const drew = () => (host.status().display as {frames: number}).frames > 0
108
+ if (device.scene) {
109
+ while (!drew() && !failed() && Date.now() < deadline) await Bun.sleep(25)
110
+ if (!failed() && !drew()) throw new Error("the miniapp drew nothing before the timeout")
111
+ }
112
+ const quiet = () => Date.now() - changedAt >= settleMs && Date.now() >= host.displaySettlesAt()
113
+ while (!quiet() && !failed() && Date.now() < deadline) await Bun.sleep(25)
114
+ if (failed()) throw new Error(errors[0])
115
+ if (!quiet()) throw new Error("the display was still changing at the timeout")
116
+ const snapshot = host.snapshot()
117
+ if (!snapshot.canvas) {
118
+ shot.note = "no display"
119
+ } else {
120
+ screen.update(snapshot)
121
+ shot.file = join(out, `${device.id}.png`)
122
+ writeFileSync(shot.file, await screen.png(options.scale ?? 2))
123
+ }
124
+ } catch (error) {
125
+ shot.error = (error as Error).message
126
+ } finally {
127
+ background.stop()
128
+ host.backgroundStopped(false)
129
+ }
130
+ return shot
131
+ }
132
+
133
+ function escape(text: string): string {
134
+ return text.replace(/[&<>"]/g, (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;"})[c] ?? c)
135
+ }
136
+
137
+ function indexPage(name: string, shots: Shot[]): string {
138
+ const cards = shots
139
+ .map((shot) => {
140
+ const body = shot.error
141
+ ? `<p class="error">Failed: ${escape(shot.error)}</p>`
142
+ : shot.file
143
+ ? `<img src="${shot.device}.png" alt="${escape(shot.label)}">`
144
+ : `<p>${escape(shot.note ?? "")}</p>`
145
+ return `<figure><figcaption><code>${shot.device}</code> ${escape(shot.label)}</figcaption>${body}</figure>`
146
+ })
147
+ .join("\n")
148
+ return `<!doctype html>
149
+ <meta charset="utf-8">
150
+ <title>${escape(name)} on every device</title>
151
+ <style>
152
+ body{font:15px/1.5 system-ui,sans-serif;margin:24px;background:#111;color:#eee}
153
+ figure{margin:0 0 28px}img{display:block;max-width:100%;border:1px solid #333}
154
+ code{color:#9fe870}.error{color:#ff8a80}a{color:#8ab4f8}
155
+ </style>
156
+ <h1>${escape(name)} on every device</h1>
157
+ <p>Screenshots use a generic font and show what the Glassly App sends each model.
158
+ <a href="${CANNOT_STAND_IN_FOR_URL}">What the simulator cannot stand in for</a>.</p>
159
+ ${cards}
160
+ `
161
+ }
package/src/sim/sim.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import {spawn} from "child_process"
2
2
  import {createHash} from "crypto"
3
- import {closeSync, openSync, existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, watch, writeFileSync, type FSWatcher} from "fs"
3
+ import {closeSync, openSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, unlinkSync, watch, writeFileSync, type FSWatcher} from "fs"
4
4
  import {createRequire} from "module"
5
5
  import os from "os"
6
6
  import {dirname, join, resolve} from "path"
@@ -17,6 +17,8 @@ const REBUILD_DEBOUNCE_MS = 150
17
17
 
18
18
  export interface SimOptions {
19
19
  cwd?: string
20
+ /** Other miniapp folders installed beside the one under test. */
21
+ with?: string[]
20
22
  port?: number
21
23
  device?: string
22
24
  open?: boolean
@@ -33,6 +35,28 @@ export interface SimRecord {
33
35
 
34
36
  const COLOR = {reset: "\x1b[0m", dim: "\x1b[2m", red: "\x1b[31m", yellow: "\x1b[33m", magenta: "\x1b[35m", cyan: "\x1b[36m"}
35
37
 
38
+ /** Where a miniapp's simulated storage, settings and memory live between runs, one folder per project. */
39
+ export function simStateDir(packageName: string, cwd: string): string {
40
+ return join(os.homedir(), ".glassly", "sim", packageName, createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 12))
41
+ }
42
+
43
+ /** Clears a miniapp's simulator state: through the running simulator when there is one, else on disk. */
44
+ export async function simReset(cwd: string): Promise<string> {
45
+ const manifest = readManifest(resolve(cwd))
46
+ const running = listSimRecords().find((record) => record.cwd === resolve(cwd))
47
+ if (running) {
48
+ const response = await fetch(`http://127.0.0.1:${running.port}/api/reset`, {
49
+ method: "POST",
50
+ headers: {"content-type": "application/json"},
51
+ body: "{}",
52
+ })
53
+ if (!response.ok) throw new Error(`The simulator answered ${response.status} to reset`)
54
+ } else {
55
+ for (const name of ["storage.json", "settings.json", "memory.json"]) rmSync(join(simStateDir(manifest.packageName, cwd), name), {force: true})
56
+ }
57
+ return simStateDir(manifest.packageName, cwd)
58
+ }
59
+
36
60
  export function simRecordDir(): string {
37
61
  return join(os.tmpdir(), "glassly-sim")
38
62
  }
@@ -93,11 +117,11 @@ export async function simDetached(options: {cwd?: string; command: string[]; tim
93
117
  }
94
118
  const record = listSimRecords().find((candidate) => candidate.cwd === cwd)
95
119
  if (record) {
96
- const answered = await fetch(`http://127.0.0.1:${record.port}/api/status`).then(
97
- (response) => response.ok,
98
- () => false,
120
+ const status = await fetch(`http://127.0.0.1:${record.port}/api/status`).then(
121
+ (response) => (response.ok ? (response.json() as Promise<DetachedStatus>) : null),
122
+ () => null,
99
123
  )
100
- if (answered) return {...record, logPath, alreadyRunning: false}
124
+ if (status && (await firstFrame(record.port, status))) return {...record, logPath, alreadyRunning: false}
101
125
  }
102
126
  await Bun.sleep(150)
103
127
  }
@@ -105,6 +129,29 @@ export async function simDetached(options: {cwd?: string; command: string[]; tim
105
129
  throw new Error(`The simulator did not come up in time. Its output is in ${logPath}`)
106
130
  }
107
131
 
132
+ interface DetachedStatus {
133
+ background: string
134
+ device: {canvas: unknown}
135
+ display: {frames: number}
136
+ }
137
+
138
+ const FIRST_FRAME_WAIT_MS = 5_000
139
+
140
+ /** Returns once the miniapp has drawn, stopped, or had a few seconds to; false to keep polling. */
141
+ async function firstFrame(port: number, status: DetachedStatus): Promise<boolean> {
142
+ const deadline = Date.now() + FIRST_FRAME_WAIT_MS
143
+ let current: DetachedStatus | null = status
144
+ while (current && current.background === "running" && current.device.canvas && current.display.frames === 0) {
145
+ if (Date.now() > deadline) return true
146
+ await Bun.sleep(100)
147
+ current = await fetch(`http://127.0.0.1:${port}/api/status`).then(
148
+ (response) => (response.ok ? (response.json() as Promise<DetachedStatus>) : null),
149
+ () => null,
150
+ )
151
+ }
152
+ return current !== null
153
+ }
154
+
108
155
  function canListen(port: number): boolean {
109
156
  try {
110
157
  Bun.serve({hostname: "127.0.0.1", port, fetch: () => new Response()}).stop(true)
@@ -133,7 +180,7 @@ function printLog(entry: SimLogEntry): void {
133
180
  console.log(`${COLOR.dim}${time}${COLOR.reset} ${tag} ${color}${entry.message}${color ? COLOR.reset : ""}`)
134
181
  }
135
182
 
136
- function readManifest(cwd: string): SimManifest & {entry: {background: string; ui?: string}} {
183
+ export function readManifest(cwd: string): SimManifest & {entry: {background: string; ui?: string}} {
137
184
  const path = resolve(cwd, "miniapp.json")
138
185
  if (!existsSync(path)) throw new Error(`miniapp.json not found in ${cwd}`)
139
186
  let manifest: Record<string, unknown>
@@ -155,12 +202,13 @@ function readManifest(cwd: string): SimManifest & {entry: {background: string; u
155
202
  * The host modules import SDK exports an older @glassly/miniapp lacks, so
156
203
  * they load only after that check has produced a clear message.
157
204
  */
158
- async function loadHostModules() {
205
+ export async function loadHostModules() {
159
206
  const require = createRequire(import.meta.url)
160
207
  try {
161
208
  require.resolve("@glassly/miniapp/host")
162
- if (typeof (require("@glassly/miniapp/display") as {processScene?: unknown}).processScene !== "function") {
163
- throw new Error("no scene pipeline")
209
+ const display = require("@glassly/miniapp/display") as {processScene?: unknown; textProfileFor?: unknown}
210
+ if (typeof display.processScene !== "function" || typeof display.textProfileFor !== "function") {
211
+ throw new Error("no scene pipeline or text profiles")
164
212
  }
165
213
  } catch {
166
214
  let found = "no @glassly/miniapp installed"
@@ -174,15 +222,16 @@ async function loadHostModules() {
174
222
  `Run \`glassly update\` and try again.`,
175
223
  )
176
224
  }
177
- const [host, server, background, device, storage, screenshot] = await Promise.all([
225
+ const [host, registry, server, background, device, storage, screenshot] = await Promise.all([
178
226
  import("./host.js"),
227
+ import("./registry.js"),
179
228
  import("./server.js"),
180
229
  import("./background.js"),
181
230
  import("./device.js"),
182
231
  import("./storage.js"),
183
232
  import("./screenshot.js"),
184
233
  ])
185
- return {...host, ...server, ...background, ...device, ...storage, ...screenshot}
234
+ return {...host, ...registry, ...server, ...background, ...device, ...storage, ...screenshot}
186
235
  }
187
236
 
188
237
  async function buildPage(): Promise<{html: string; js: string; css: string}> {
@@ -201,6 +250,7 @@ export async function sim(options: SimOptions = {}): Promise<void> {
201
250
  const manifest = readManifest(cwd)
202
251
  const modules = await loadHostModules()
203
252
  const device = modules.simDevice(options.device)
253
+ const stateDir = simStateDir(manifest.packageName, cwd)
204
254
 
205
255
  console.log(`Building ${manifest.name} (${manifest.packageName})...`)
206
256
  await runBuild(cwd)
@@ -217,10 +267,19 @@ export async function sim(options: SimOptions = {}): Promise<void> {
217
267
 
218
268
  let background: BackgroundHandle | null = null
219
269
  let server: ReturnType<typeof modules.startSimServer> | null = null
270
+ const others = new Map<string, {start: () => void; stop: () => void}>()
271
+ const registry = new modules.SimRegistry({
272
+ launch: (packageName) => (packageName === manifest.packageName ? startBackground() : others.get(packageName)?.start()),
273
+ halt: (packageName) => (packageName === manifest.packageName ? stopBackground(false) : others.get(packageName)?.stop()),
274
+ })
220
275
  const host = new modules.SimHost({
221
276
  manifest,
222
277
  device,
223
- storage: modules.createSimStorage(join(os.homedir(), ".glassly", "sim", manifest.packageName, "storage.json")),
278
+ registry,
279
+ storage: modules.createSimStorage(join(stateDir, "storage.json")),
280
+ settings: modules.createSimStorage(join(stateDir, "settings.json")),
281
+ memory: modules.createSimStorage(join(stateDir, "memory.json")),
282
+ stateDir,
224
283
  toBackground: (raw) => background?.send(raw),
225
284
  emit: (event: SimHostEvent) => {
226
285
  if (event.type === "log") printLog(event.entry)
@@ -249,6 +308,48 @@ export async function sim(options: SimOptions = {}): Promise<void> {
249
308
  })
250
309
  }
251
310
 
311
+ for (const dir of options.with ?? []) {
312
+ const otherCwd = resolve(cwd, dir)
313
+ const other = readManifest(otherCwd)
314
+ console.log(`Building ${other.name} (${other.packageName}) beside it...`)
315
+ await runBuild(otherCwd)
316
+ const otherState = simStateDir(other.packageName, otherCwd)
317
+ let worker: BackgroundHandle | null = null
318
+ const tag = (message: string) => `[${other.name}] ${message}`
319
+ const otherHost: InstanceType<typeof modules.SimHost> = new modules.SimHost({
320
+ manifest: other,
321
+ device,
322
+ registry,
323
+ storage: modules.createSimStorage(join(otherState, "storage.json")),
324
+ settings: modules.createSimStorage(join(otherState, "settings.json")),
325
+ memory: modules.createSimStorage(join(otherState, "memory.json")),
326
+ stateDir: otherState,
327
+ toBackground: (raw) => worker?.send(raw),
328
+ emit: (event: SimHostEvent) => {
329
+ if (event.type === "log") host.log(event.entry.source, event.entry.level, tag(event.entry.message))
330
+ if (event.type === "exit") stop()
331
+ },
332
+ })
333
+ const stop = () => {
334
+ worker?.stop()
335
+ worker = null
336
+ otherHost.backgroundStopped(false)
337
+ }
338
+ others.set(other.packageName, {
339
+ start: () => {
340
+ worker?.stop()
341
+ otherHost.backgroundStarted()
342
+ worker = modules.startBackground(resolve(otherCwd, "dist", other.entry.background), {
343
+ onBridge: (raw) => otherHost.fromBackground(raw),
344
+ onLog: (level, args) => otherHost.log("background", level, modules.formatLogArgs(args)),
345
+ onError: (message, stack) => otherHost.log("background", "error", stack || message),
346
+ onCrash: stop,
347
+ })
348
+ },
349
+ stop,
350
+ })
351
+ }
352
+
252
353
  const port = pickPort(options.port ?? DEFAULT_SIM_PORT)
253
354
  let watcher: FSWatcher | null = null
254
355
  let shuttingDown = false
@@ -257,6 +358,7 @@ export async function sim(options: SimOptions = {}): Promise<void> {
257
358
  shuttingDown = true
258
359
  watcher?.close()
259
360
  background?.stop()
361
+ for (const other of others.values()) other.stop()
260
362
  server?.stop()
261
363
  try {
262
364
  unlinkSync(simRecordPath(cwd))
@@ -2,20 +2,21 @@ import {existsSync, mkdirSync, readFileSync, writeFileSync} from "fs"
2
2
  import {dirname} from "path"
3
3
 
4
4
  export interface SimStorage {
5
- get(key: string): string | null
6
- set(key: string, value: string | null): void
5
+ get(key: string): unknown
6
+ has(key: string): boolean
7
+ set(key: string, value: unknown): void
7
8
  delete(key: string): void
8
9
  keys(): string[]
9
- getAll(): Record<string, string>
10
+ getAll(): Record<string, unknown>
10
11
  clear(): void
11
12
  }
12
13
 
13
14
  export function createSimStorage(path?: string): SimStorage {
14
- let values: Record<string, string> = {}
15
+ let values: Record<string, unknown> = {}
15
16
  if (path && existsSync(path)) {
16
17
  try {
17
18
  const parsed = JSON.parse(readFileSync(path, "utf-8"))
18
- if (parsed && typeof parsed === "object") values = parsed as Record<string, string>
19
+ if (parsed && typeof parsed === "object") values = parsed as Record<string, unknown>
19
20
  } catch {
20
21
  values = {}
21
22
  }
@@ -27,9 +28,9 @@ export function createSimStorage(path?: string): SimStorage {
27
28
  }
28
29
  return {
29
30
  get: (key) => (key in values ? values[key] : null),
31
+ has: (key) => key in values,
30
32
  set(key, value) {
31
- if (value === null) delete values[key]
32
- else values[key] = value
33
+ values[key] = value
33
34
  persist()
34
35
  },
35
36
  delete(key) {