@sirenodeck/sirenodeck 0.4.0 → 0.4.1
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.
- package/config-ui/vite.config.ts +2 -0
- package/dist/main.mjs +345 -30
- package/frontend/vite.config.ts +2 -0
- package/package.json +1 -1
- package/src/api/protocol-internal.ts +4 -0
- package/src/cli/commands/run.ts +4 -0
- package/src/cli/commands/status-probes.ts +126 -0
- package/src/cli/commands/status.ts +166 -16
- package/src/outputClient/real.ts +18 -1
- package/src/render/browser-renderer.ts +68 -12
- package/src/render/ws-bridge.ts +2 -0
- package/src/util/build-fingerprint.ts +32 -0
- package/src/util/daemon-control.ts +41 -0
- package/src/util/runtime-health.ts +57 -0
- package/src/util/runtime-identity.ts +25 -0
- package/src/vite/component-identity.ts +48 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import WebSocket from "ws"
|
|
2
|
+
import { PROTOCOL_VERSION } from "@/render/protocol"
|
|
3
|
+
|
|
4
|
+
export type ProbeResult = "responding" | "unreachable" | "unknown"
|
|
5
|
+
export interface BuildIdentity {
|
|
6
|
+
version: string
|
|
7
|
+
buildId: string | null
|
|
8
|
+
}
|
|
9
|
+
const parseIdentity = (value: unknown): BuildIdentity | null => {
|
|
10
|
+
if (!value || typeof value !== "object") return null
|
|
11
|
+
const v = value as Record<string, unknown>
|
|
12
|
+
if (
|
|
13
|
+
typeof v.version !== "string" ||
|
|
14
|
+
!(typeof v.buildId === "string" || v.buildId === null)
|
|
15
|
+
)
|
|
16
|
+
return null
|
|
17
|
+
return { version: v.version, buildId: v.buildId }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const probeWebIdentity = async (
|
|
21
|
+
value: string,
|
|
22
|
+
component: "frontend" | "config-ui",
|
|
23
|
+
): Promise<BuildIdentity | null> => {
|
|
24
|
+
const base = localUrl(value, ["http:", "https:"])
|
|
25
|
+
if (!base) return null
|
|
26
|
+
try {
|
|
27
|
+
const response = await fetch(
|
|
28
|
+
new URL("/assets/sirenodeck-build.json", base),
|
|
29
|
+
{ signal: AbortSignal.timeout(1500), redirect: "manual" },
|
|
30
|
+
)
|
|
31
|
+
if (
|
|
32
|
+
!response.ok ||
|
|
33
|
+
!response.headers.get("content-type")?.includes("application/json")
|
|
34
|
+
)
|
|
35
|
+
return null
|
|
36
|
+
const body: unknown = await response.json()
|
|
37
|
+
if (
|
|
38
|
+
!body ||
|
|
39
|
+
typeof body !== "object" ||
|
|
40
|
+
!("component" in body) ||
|
|
41
|
+
body.component !== component
|
|
42
|
+
)
|
|
43
|
+
return null
|
|
44
|
+
return parseIdentity(body)
|
|
45
|
+
} catch {
|
|
46
|
+
return null
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Only contact local endpoints: runtime state may be stale or externally supplied.
|
|
51
|
+
const localUrl = (value: string, protocols: readonly string[]): URL | null => {
|
|
52
|
+
try {
|
|
53
|
+
const url = new URL(value)
|
|
54
|
+
if (!protocols.includes(url.protocol)) return null
|
|
55
|
+
if (!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) return null
|
|
56
|
+
return url
|
|
57
|
+
} catch {
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export const probeHttp = async (value: string): Promise<ProbeResult> => {
|
|
63
|
+
const url = localUrl(value, ["http:", "https:"])
|
|
64
|
+
if (!url) return "unknown"
|
|
65
|
+
try {
|
|
66
|
+
const response = await fetch(url, {
|
|
67
|
+
signal: AbortSignal.timeout(1500),
|
|
68
|
+
redirect: "manual",
|
|
69
|
+
})
|
|
70
|
+
return response.ok ? "responding" : "unreachable"
|
|
71
|
+
} catch {
|
|
72
|
+
return "unreachable"
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const probeBridgeInfo = (
|
|
77
|
+
value: string,
|
|
78
|
+
token: string | null,
|
|
79
|
+
): Promise<{ status: ProbeResult; identity: BuildIdentity | null }> => {
|
|
80
|
+
const url = localUrl(value, ["ws:", "wss:"])
|
|
81
|
+
if (!url || token === null)
|
|
82
|
+
return Promise.resolve({ status: "unknown", identity: null })
|
|
83
|
+
return new Promise((resolve) => {
|
|
84
|
+
const socket = new WebSocket(url)
|
|
85
|
+
const timer = setTimeout(() => finish("unreachable"), 1500)
|
|
86
|
+
let finished = false
|
|
87
|
+
const finish = (
|
|
88
|
+
result: ProbeResult,
|
|
89
|
+
identity: BuildIdentity | null = null,
|
|
90
|
+
): void => {
|
|
91
|
+
if (finished) return
|
|
92
|
+
finished = true
|
|
93
|
+
clearTimeout(timer)
|
|
94
|
+
socket.terminate()
|
|
95
|
+
resolve({ status: result, identity })
|
|
96
|
+
}
|
|
97
|
+
socket.on("open", () =>
|
|
98
|
+
socket.send(
|
|
99
|
+
JSON.stringify({ type: "hello", version: PROTOCOL_VERSION, token }),
|
|
100
|
+
),
|
|
101
|
+
)
|
|
102
|
+
socket.on("message", (data) => {
|
|
103
|
+
try {
|
|
104
|
+
const message = JSON.parse(data.toString()) as {
|
|
105
|
+
type?: string
|
|
106
|
+
version?: number
|
|
107
|
+
build?: unknown
|
|
108
|
+
}
|
|
109
|
+
if (message.type === "hello-ack")
|
|
110
|
+
finish(
|
|
111
|
+
message.version === PROTOCOL_VERSION ? "responding" : "unreachable",
|
|
112
|
+
parseIdentity(message.build),
|
|
113
|
+
)
|
|
114
|
+
} catch {
|
|
115
|
+
finish("unreachable")
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
socket.on("error", () => finish("unreachable"))
|
|
119
|
+
socket.on("close", () => finish("unreachable"))
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const probeBridge = async (
|
|
124
|
+
value: string,
|
|
125
|
+
token: string | null,
|
|
126
|
+
): Promise<ProbeResult> => (await probeBridgeInfo(value, token)).status
|
|
@@ -10,6 +10,14 @@ import {
|
|
|
10
10
|
resolveDaemonPaths,
|
|
11
11
|
} from "@/util/daemon"
|
|
12
12
|
import { listDevices } from "@/device"
|
|
13
|
+
import { requestDaemonHealth, requestDaemonToken } from "@/util/daemon-control"
|
|
14
|
+
import {
|
|
15
|
+
probeBridgeInfo,
|
|
16
|
+
probeHttp,
|
|
17
|
+
probeWebIdentity,
|
|
18
|
+
type BuildIdentity,
|
|
19
|
+
} from "./status-probes"
|
|
20
|
+
import { runtimeIdentity } from "@/util/runtime-identity"
|
|
13
21
|
|
|
14
22
|
import { cancel, intro, log, outro } from "@/cli/prompt"
|
|
15
23
|
|
|
@@ -28,6 +36,39 @@ const formatUptime = (ms: number): string => {
|
|
|
28
36
|
return `${seconds}s`
|
|
29
37
|
}
|
|
30
38
|
|
|
39
|
+
const group = (title: string, details: readonly string[]): string =>
|
|
40
|
+
[
|
|
41
|
+
title,
|
|
42
|
+
...details.map((detail, i) => {
|
|
43
|
+
const separator = detail.indexOf(": ")
|
|
44
|
+
const formatted =
|
|
45
|
+
separator < 0
|
|
46
|
+
? detail
|
|
47
|
+
: `${detail.slice(0, separator + 2)}${colorize(detail.slice(separator + 2), 97)}`
|
|
48
|
+
return `${i === details.length - 1 ? "└─" : "├─"} ${formatted}`
|
|
49
|
+
}),
|
|
50
|
+
].join("\n")
|
|
51
|
+
|
|
52
|
+
const colorize = (value: string, color: number): string => {
|
|
53
|
+
const enabled =
|
|
54
|
+
process.env.NO_COLOR === undefined &&
|
|
55
|
+
process.env.FORCE_COLOR !== "0" &&
|
|
56
|
+
(process.stdout.isTTY ||
|
|
57
|
+
(process.env.FORCE_COLOR !== undefined && process.env.FORCE_COLOR !== ""))
|
|
58
|
+
return enabled
|
|
59
|
+
? `\u001b[${color}m${value.replaceAll("\u001b[39m", `\u001b[${color}m`)}\u001b[39m`
|
|
60
|
+
: value
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const coloredStatus = (value: string): string => {
|
|
64
|
+
const color = /^(running|ready|healthy|responding|same source)/i.test(value)
|
|
65
|
+
? 32
|
|
66
|
+
: /^(failed|unreachable|MISMATCH|stale)/i.test(value)
|
|
67
|
+
? 31
|
|
68
|
+
: 33
|
|
69
|
+
return colorize(value, color)
|
|
70
|
+
}
|
|
71
|
+
|
|
31
72
|
export const status = async ({ logger }: StatusOptions): Promise<void> => {
|
|
32
73
|
void logger // kept for callers that want pino logs out-of-band
|
|
33
74
|
|
|
@@ -37,6 +78,16 @@ export const status = async ({ logger }: StatusOptions): Promise<void> => {
|
|
|
37
78
|
if (pid === null) {
|
|
38
79
|
intro("sirenodeck status")
|
|
39
80
|
log.error("Daemon is not running")
|
|
81
|
+
for (const component of [
|
|
82
|
+
"Core",
|
|
83
|
+
"Bridge",
|
|
84
|
+
"Frontend",
|
|
85
|
+
"Config UI",
|
|
86
|
+
"Renderer",
|
|
87
|
+
"Device",
|
|
88
|
+
]) {
|
|
89
|
+
log.info(`${component}: unknown (daemon not running)`)
|
|
90
|
+
}
|
|
40
91
|
cancel("✗ No daemon process found")
|
|
41
92
|
return
|
|
42
93
|
}
|
|
@@ -50,11 +101,16 @@ export const status = async ({ logger }: StatusOptions): Promise<void> => {
|
|
|
50
101
|
|
|
51
102
|
intro("sirenodeck status")
|
|
52
103
|
|
|
104
|
+
let daemonDetails: string[] = []
|
|
53
105
|
if (alive) {
|
|
54
106
|
const startedAt = state?.startedAt ?? null
|
|
55
107
|
const uptime =
|
|
56
108
|
startedAt !== null ? formatUptime(Date.now() - startedAt) : "—"
|
|
57
|
-
|
|
109
|
+
daemonDetails = [
|
|
110
|
+
`PID: ${pid}`,
|
|
111
|
+
`Uptime: ${uptime}`,
|
|
112
|
+
`Children: ${childPids.length > 0 ? `${childPids.length} (${childPids.join(", ")})` : "none tracked"}`,
|
|
113
|
+
]
|
|
58
114
|
} else {
|
|
59
115
|
log.warn(`Status: stale pid file (pid ${pid} not alive)`)
|
|
60
116
|
}
|
|
@@ -64,7 +120,7 @@ export const status = async ({ logger }: StatusOptions): Promise<void> => {
|
|
|
64
120
|
typeof flags?.deviceModel === "string" ? flags.deviceModel : "mk2"
|
|
65
121
|
|
|
66
122
|
if (isEmulator) {
|
|
67
|
-
log.info(
|
|
123
|
+
log.info(group("Device", [`Mode: emulator`, `Model: ${deviceModel}`]))
|
|
68
124
|
} else {
|
|
69
125
|
let hardwareLabel = "—"
|
|
70
126
|
try {
|
|
@@ -77,33 +133,127 @@ export const status = async ({ logger }: StatusOptions): Promise<void> => {
|
|
|
77
133
|
// permission errors. Fall through to the "—" placeholder — status
|
|
78
134
|
// must not blow up if device detection is unavailable.
|
|
79
135
|
}
|
|
80
|
-
log.info(
|
|
136
|
+
log.info(group("Device", [`Mode: hardware`, `Model: ${hardwareLabel}`]))
|
|
81
137
|
}
|
|
82
138
|
|
|
83
139
|
const remoteOn = state?.remote === true || flags?.remote === true
|
|
84
|
-
log.info(`Remote: ${remoteOn ? "on" : "off"}`)
|
|
85
|
-
|
|
86
|
-
log.info(`Config: ${configPath ?? "—"}`)
|
|
87
|
-
|
|
88
140
|
const theme = state?.theme ?? "default"
|
|
89
|
-
log.info(
|
|
141
|
+
log.info(
|
|
142
|
+
group("Configuration", [
|
|
143
|
+
`Config: ${configPath ?? "—"}`,
|
|
144
|
+
`Theme: ${theme}`,
|
|
145
|
+
`Remote: ${remoteOn ? "on" : "off"}`,
|
|
146
|
+
]),
|
|
147
|
+
)
|
|
90
148
|
|
|
91
|
-
if (childPids.length > 0) {
|
|
149
|
+
if (!alive && childPids.length > 0) {
|
|
92
150
|
log.info(`Children: ${childPids.length} (${childPids.join(", ")})`)
|
|
93
|
-
} else {
|
|
151
|
+
} else if (!alive) {
|
|
94
152
|
log.info("Children: none tracked")
|
|
95
153
|
}
|
|
96
154
|
|
|
97
155
|
if (alive && state !== null) {
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
156
|
+
const [
|
|
157
|
+
token,
|
|
158
|
+
health,
|
|
159
|
+
frontend,
|
|
160
|
+
configUi,
|
|
161
|
+
frontendIdentity,
|
|
162
|
+
configUiIdentity,
|
|
163
|
+
] = await Promise.all([
|
|
164
|
+
requestDaemonToken(paths),
|
|
165
|
+
requestDaemonHealth(paths),
|
|
166
|
+
probeHttp(state.frontendUrl),
|
|
167
|
+
state.configUiUrl
|
|
168
|
+
? probeHttp(state.configUiUrl)
|
|
169
|
+
: Promise.resolve("unknown" as const),
|
|
170
|
+
probeWebIdentity(state.frontendUrl, "frontend"),
|
|
171
|
+
state.configUiUrl
|
|
172
|
+
? probeWebIdentity(state.configUiUrl, "config-ui")
|
|
173
|
+
: Promise.resolve(null),
|
|
174
|
+
])
|
|
175
|
+
const bridge = await probeBridgeInfo(state.wsUrl, token)
|
|
176
|
+
const identityLabel = (identity: BuildIdentity | null): string => {
|
|
177
|
+
if (!identity) return "version/build unknown"
|
|
178
|
+
const matches =
|
|
179
|
+
identity.buildId && health?.identity?.buildId
|
|
180
|
+
? identity.buildId === health.identity.buildId &&
|
|
181
|
+
identity.version === health.identity.version
|
|
182
|
+
? "same source as daemon"
|
|
183
|
+
: "MISMATCH"
|
|
184
|
+
: "comparison unknown"
|
|
185
|
+
return `${identity.version} build ${identity.buildId?.slice(0, 12) ?? "unknown"} (${coloredStatus(matches)})`
|
|
186
|
+
}
|
|
187
|
+
log.info(
|
|
188
|
+
group(`Daemon: ${coloredStatus("running")}`, [
|
|
189
|
+
...daemonDetails,
|
|
190
|
+
`Version: ${identityLabel(health?.identity ?? null)}`,
|
|
191
|
+
]),
|
|
192
|
+
)
|
|
193
|
+
log.info(group("CLI", [`Version: ${identityLabel(runtimeIdentity)}`]))
|
|
194
|
+
log.info(
|
|
195
|
+
group(`Core: ${coloredStatus(health?.core ?? "unknown")}`, [
|
|
196
|
+
`Version: ${identityLabel(health?.identity ?? null)}`,
|
|
197
|
+
]),
|
|
198
|
+
)
|
|
199
|
+
log.info(
|
|
200
|
+
group(`Bridge: ${coloredStatus(bridge.status)}`, [
|
|
201
|
+
`Check: authenticated WebSocket handshake`,
|
|
202
|
+
`URL: ${state.wsUrl}`,
|
|
203
|
+
`Version: ${identityLabel(bridge.identity)}`,
|
|
204
|
+
]),
|
|
205
|
+
)
|
|
206
|
+
log.info(
|
|
207
|
+
group(`Frontend: ${coloredStatus(frontend)}`, [
|
|
208
|
+
`Check: HTTP`,
|
|
209
|
+
`URL: ${state.frontendUrl}`,
|
|
210
|
+
`Version: ${identityLabel(frontendIdentity)}`,
|
|
211
|
+
]),
|
|
212
|
+
)
|
|
213
|
+
log.info(
|
|
214
|
+
group(`Config UI: ${coloredStatus(configUi)}`, [
|
|
215
|
+
`Check: HTTP`,
|
|
216
|
+
...(state.configUiUrl ? [`URL: ${state.configUiUrl}`] : []),
|
|
217
|
+
`Version: ${identityLabel(configUiIdentity)}`,
|
|
218
|
+
]),
|
|
219
|
+
)
|
|
220
|
+
if (isEmulator) {
|
|
221
|
+
log.info("Renderer: not applicable (emulator mode)")
|
|
222
|
+
} else {
|
|
223
|
+
const rendererState =
|
|
224
|
+
health?.renderer?.state === "healthy" &&
|
|
225
|
+
health.renderer.lastFrameAt !== null &&
|
|
226
|
+
Date.now() - health.renderer.lastFrameAt > 10_000
|
|
227
|
+
? "degraded (no recent frame)"
|
|
228
|
+
: (health?.renderer?.state ?? "unknown")
|
|
229
|
+
const lastFrame = health?.renderer?.lastFrameAt
|
|
230
|
+
? new Date(health.renderer.lastFrameAt).toISOString()
|
|
231
|
+
: "unknown"
|
|
232
|
+
log.info(
|
|
233
|
+
group(`Renderer: ${coloredStatus(rendererState)}`, [
|
|
234
|
+
`Last frame: ${lastFrame}`,
|
|
235
|
+
`Version: ${identityLabel(health?.identity ?? null)}`,
|
|
236
|
+
]),
|
|
237
|
+
)
|
|
102
238
|
}
|
|
103
|
-
log.info(`Bridge URL : ${state.wsUrl}`)
|
|
104
239
|
outro("✓ Status snapshot")
|
|
105
240
|
} else {
|
|
106
|
-
|
|
241
|
+
if (alive)
|
|
242
|
+
log.info(group(`Daemon: ${coloredStatus("running")}`, daemonDetails))
|
|
243
|
+
for (const component of [
|
|
244
|
+
"Core",
|
|
245
|
+
"Bridge",
|
|
246
|
+
"Frontend",
|
|
247
|
+
"Config UI",
|
|
248
|
+
"Renderer",
|
|
249
|
+
]) {
|
|
250
|
+
log.info(`${component}: unknown (runtime state unavailable)`)
|
|
251
|
+
}
|
|
252
|
+
cancel(
|
|
253
|
+
alive
|
|
254
|
+
? "✗ Daemon is running but runtime state is unavailable"
|
|
255
|
+
: "✗ Stale pid file — daemon process is not running",
|
|
256
|
+
)
|
|
107
257
|
}
|
|
108
258
|
}
|
|
109
259
|
|
package/src/outputClient/real.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs"
|
|
|
2
2
|
import { fileURLToPath } from "node:url"
|
|
3
3
|
|
|
4
4
|
import type pino from "pino"
|
|
5
|
+
import sharp from "sharp"
|
|
5
6
|
|
|
6
7
|
import { createGestureDetector } from "@/core/gesture-state"
|
|
7
8
|
import { pushBlackFrame } from "@/device/black-frame"
|
|
@@ -294,10 +295,26 @@ export class RealOutputClient implements OutputClient {
|
|
|
294
295
|
|
|
295
296
|
logger.info({ frontendUrl }, "real mode: frontend URL")
|
|
296
297
|
|
|
298
|
+
let rendererFailed = false
|
|
297
299
|
renderer = new BrowserRenderer({
|
|
298
300
|
frontendUrl: `${frontendUrl}${frontendUrl.includes("?") ? "&" : "?"}compact=1`,
|
|
299
301
|
device,
|
|
300
302
|
logger,
|
|
303
|
+
onFatalCrash: async () => {
|
|
304
|
+
rendererFailed = true
|
|
305
|
+
try {
|
|
306
|
+
const svg = Buffer.from(
|
|
307
|
+
'<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72"><rect width="72" height="72" fill="#7f1d1d"/><text x="36" y="28" fill="white" text-anchor="middle" font-family="sans-serif" font-weight="bold" font-size="12">RENDER</text><text x="36" y="47" fill="white" text-anchor="middle" font-family="sans-serif" font-weight="bold" font-size="12">ERROR</text></svg>',
|
|
308
|
+
)
|
|
309
|
+
const pixels = await sharp(svg).removeAlpha().raw().toBuffer()
|
|
310
|
+
for (let i = 0; i < device.getKeyCount(); i++)
|
|
311
|
+
await device.fillKeyBuffer(i, pixels)
|
|
312
|
+
} catch (err) {
|
|
313
|
+
logger.error({ err }, "failed to display renderer error")
|
|
314
|
+
} finally {
|
|
315
|
+
opts.onChildCrash?.()
|
|
316
|
+
}
|
|
317
|
+
},
|
|
301
318
|
...(opts.intervalMs !== undefined
|
|
302
319
|
? { intervalMs: opts.intervalMs }
|
|
303
320
|
: {}),
|
|
@@ -330,7 +347,7 @@ export class RealOutputClient implements OutputClient {
|
|
|
330
347
|
wsUrl: opts.bridge.url,
|
|
331
348
|
childPids,
|
|
332
349
|
async pushBlackFrame(): Promise<void> {
|
|
333
|
-
await pushBlackFrame(device, logger)
|
|
350
|
+
if (!rendererFailed) await pushBlackFrame(device, logger)
|
|
334
351
|
},
|
|
335
352
|
async pushRawImage(filePath: string): Promise<void> {
|
|
336
353
|
try {
|
|
@@ -7,6 +7,7 @@ import type pino from "pino"
|
|
|
7
7
|
|
|
8
8
|
import { BufferChangeTracker } from "./buffer-hash"
|
|
9
9
|
import { CadenceTimer, EventDebouncer } from "./screenshot-cadence"
|
|
10
|
+
import { runtimeHealth } from "@/util/runtime-health"
|
|
10
11
|
|
|
11
12
|
export interface PlaywrightLike {
|
|
12
13
|
chromium: {
|
|
@@ -48,6 +49,7 @@ export interface BrowserRendererOptions {
|
|
|
48
49
|
readonly intervalMs?: number
|
|
49
50
|
readonly eventDebounceMs?: number
|
|
50
51
|
readonly playwrightFactory?: () => PlaywrightLike | Promise<PlaywrightLike>
|
|
52
|
+
readonly onFatalCrash?: () => Promise<void>
|
|
51
53
|
}
|
|
52
54
|
|
|
53
55
|
const DEFAULT_INTERVAL_MS = 500
|
|
@@ -77,6 +79,7 @@ export class BrowserRenderer {
|
|
|
77
79
|
private context: ContextLike | null = null
|
|
78
80
|
private page: PageLike | null = null
|
|
79
81
|
private running = false
|
|
82
|
+
private recovering: Promise<void> | null = null
|
|
80
83
|
private readonly logger: pino.Logger
|
|
81
84
|
|
|
82
85
|
constructor(private readonly options: BrowserRendererOptions) {
|
|
@@ -126,14 +129,7 @@ export class BrowserRenderer {
|
|
|
126
129
|
}
|
|
127
130
|
throw err
|
|
128
131
|
}
|
|
129
|
-
|
|
130
|
-
const vpWidth = columns * BUTTON_SIZE_PX
|
|
131
|
-
const vpHeight = rows * BUTTON_SIZE_PX
|
|
132
|
-
this.context = await this.browser.newContext({
|
|
133
|
-
viewport: { width: vpWidth, height: vpHeight },
|
|
134
|
-
})
|
|
135
|
-
this.page = await this.context.newPage()
|
|
136
|
-
await this.page.goto(this.options.frontendUrl, { waitUntil: "networkidle" })
|
|
132
|
+
await this.openPage()
|
|
137
133
|
if (this.pubSub) {
|
|
138
134
|
this.subscriptions.push(
|
|
139
135
|
{
|
|
@@ -152,6 +148,17 @@ export class BrowserRenderer {
|
|
|
152
148
|
this.running = true
|
|
153
149
|
}
|
|
154
150
|
|
|
151
|
+
private async openPage(): Promise<void> {
|
|
152
|
+
const { columns, rows } = gridForKeyCount(this.options.device.getKeyCount())
|
|
153
|
+
const vpWidth = columns * BUTTON_SIZE_PX
|
|
154
|
+
const vpHeight = rows * BUTTON_SIZE_PX
|
|
155
|
+
this.context = await this.browser!.newContext({
|
|
156
|
+
viewport: { width: vpWidth, height: vpHeight },
|
|
157
|
+
})
|
|
158
|
+
this.page = await this.context.newPage()
|
|
159
|
+
await this.page.goto(this.options.frontendUrl, { waitUntil: "networkidle" })
|
|
160
|
+
}
|
|
161
|
+
|
|
155
162
|
/**
|
|
156
163
|
* Repaints every key on the next tick.
|
|
157
164
|
*
|
|
@@ -172,9 +179,12 @@ export class BrowserRenderer {
|
|
|
172
179
|
this.debouncer.dispose()
|
|
173
180
|
for (const sub of this.subscriptions) sub.unsubscribe()
|
|
174
181
|
this.subscriptions.length = 0
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
182
|
+
await this.recovering
|
|
183
|
+
await Promise.allSettled([
|
|
184
|
+
this.page?.close(),
|
|
185
|
+
this.context?.close(),
|
|
186
|
+
this.browser?.close(),
|
|
187
|
+
])
|
|
178
188
|
this.page = null
|
|
179
189
|
this.context = null
|
|
180
190
|
this.browser = null
|
|
@@ -182,8 +192,43 @@ export class BrowserRenderer {
|
|
|
182
192
|
|
|
183
193
|
private static readonly BLANK_THRESHOLD = 20
|
|
184
194
|
|
|
195
|
+
private async recover(): Promise<void> {
|
|
196
|
+
runtimeHealth.setRenderer("recovering")
|
|
197
|
+
const factory =
|
|
198
|
+
this.options.playwrightFactory ??
|
|
199
|
+
(async (): Promise<PlaywrightLike> =>
|
|
200
|
+
(await import("playwright")) as PlaywrightLike)
|
|
201
|
+
for (let attempt = 1; attempt <= 3 && this.running; attempt++) {
|
|
202
|
+
await Promise.allSettled([
|
|
203
|
+
this.page?.close(),
|
|
204
|
+
this.context?.close(),
|
|
205
|
+
this.browser?.close(),
|
|
206
|
+
])
|
|
207
|
+
this.page = null
|
|
208
|
+
this.context = null
|
|
209
|
+
this.browser = null
|
|
210
|
+
if (!this.running) break
|
|
211
|
+
try {
|
|
212
|
+
const playwright = await factory()
|
|
213
|
+
this.browser = await playwright.chromium.launch({ headless: true })
|
|
214
|
+
await this.openPage()
|
|
215
|
+
await this.page!.screenshot({ type: "png" })
|
|
216
|
+
this.tracker.reset()
|
|
217
|
+
this.logger.info({ attempt }, "browser renderer recovered")
|
|
218
|
+
return
|
|
219
|
+
} catch (err) {
|
|
220
|
+
this.logger.warn({ err, attempt }, "browser renderer recovery failed")
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (this.running) {
|
|
224
|
+
this.cadence.stop()
|
|
225
|
+
runtimeHealth.setRenderer("failed")
|
|
226
|
+
await this.options.onFatalCrash?.()
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
185
230
|
private async tick(source: "timer" | "event"): Promise<void> {
|
|
186
|
-
if (!this.page) return
|
|
231
|
+
if (!this.page || this.recovering) return
|
|
187
232
|
try {
|
|
188
233
|
const png = await this.page.screenshot({ type: "png" })
|
|
189
234
|
const { columns, rows } = gridForKeyCount(
|
|
@@ -231,8 +276,19 @@ export class BrowserRenderer {
|
|
|
231
276
|
)
|
|
232
277
|
}
|
|
233
278
|
}
|
|
279
|
+
runtimeHealth.setRenderer("healthy", Date.now())
|
|
234
280
|
} catch (err) {
|
|
235
281
|
this.logger.warn({ err, source }, "renderer tick failed")
|
|
282
|
+
if (
|
|
283
|
+
/target crashed|target page, context or browser has been closed/i.test(
|
|
284
|
+
(err as Error).message,
|
|
285
|
+
)
|
|
286
|
+
) {
|
|
287
|
+
this.recovering ??= this.recover().finally(() => {
|
|
288
|
+
this.recovering = null
|
|
289
|
+
})
|
|
290
|
+
await this.recovering
|
|
291
|
+
}
|
|
236
292
|
}
|
|
237
293
|
}
|
|
238
294
|
}
|
package/src/render/ws-bridge.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Server as HttpServer } from "node:http"
|
|
2
2
|
import { WebSocketServer, type WebSocket } from "ws"
|
|
3
3
|
import type pino from "pino"
|
|
4
|
+
import { runtimeIdentity } from "@/util/runtime-identity"
|
|
4
5
|
|
|
5
6
|
import type { DeviceDescriptor } from "@/device/registry"
|
|
6
7
|
import { createLogger } from "@/util/logger"
|
|
@@ -161,6 +162,7 @@ export const startWsBridge = (options: WsBridgeOptions): Promise<WsBridge> => {
|
|
|
161
162
|
const ack = helloAckMessageSchema.parse({
|
|
162
163
|
type: "hello-ack",
|
|
163
164
|
version: PROTOCOL_VERSION,
|
|
165
|
+
build: runtimeIdentity,
|
|
164
166
|
...(currentDevice !== null ? { device: currentDevice } : {}),
|
|
165
167
|
config:
|
|
166
168
|
currentTheme !== undefined ? { theme: currentTheme.name } : {},
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { readdirSync, readFileSync } from "node:fs"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
|
|
5
|
+
/** Fingerprint the source inputs shared by the CLI and its web surfaces. */
|
|
6
|
+
export const fingerprintBuildInputs = (root: string): string => {
|
|
7
|
+
const hash = createHash("sha256")
|
|
8
|
+
const visit = (relative: string): void => {
|
|
9
|
+
const entries = readdirSync(join(root, relative), {
|
|
10
|
+
withFileTypes: true,
|
|
11
|
+
}).sort((a, b) => a.name.localeCompare(b.name, "en"))
|
|
12
|
+
for (const entry of entries) {
|
|
13
|
+
if (
|
|
14
|
+
entry.name.startsWith(".") ||
|
|
15
|
+
["node_modules", "dist", "__tests__", "coverage"].includes(entry.name)
|
|
16
|
+
)
|
|
17
|
+
continue
|
|
18
|
+
const path = relative ? `${relative}/${entry.name}` : entry.name
|
|
19
|
+
if (entry.isDirectory()) visit(path)
|
|
20
|
+
else if (entry.isFile() && !/\.(test|spec)\.[^.]+$/.test(entry.name)) {
|
|
21
|
+
const contents = readFileSync(join(root, path))
|
|
22
|
+
hash.update(`${path.length}:${path}:${contents.length}:`)
|
|
23
|
+
hash.update(contents)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
for (const directory of ["src", "frontend", "config-ui"]) visit(directory)
|
|
28
|
+
const manifest = readFileSync(join(root, "package.json"))
|
|
29
|
+
hash.update(`package.json:${manifest.length}:`)
|
|
30
|
+
hash.update(manifest)
|
|
31
|
+
return hash.digest("hex")
|
|
32
|
+
}
|
|
@@ -6,6 +6,11 @@ import type pino from "pino"
|
|
|
6
6
|
|
|
7
7
|
import type { DaemonPaths } from "./daemon"
|
|
8
8
|
import { isSocketLive } from "./single-instance"
|
|
9
|
+
import {
|
|
10
|
+
runtimeHealth,
|
|
11
|
+
runtimeHealthSchema,
|
|
12
|
+
type RuntimeHealth,
|
|
13
|
+
} from "./runtime-health"
|
|
9
14
|
|
|
10
15
|
const GET_TOKEN = "get-token\n"
|
|
11
16
|
|
|
@@ -33,6 +38,8 @@ export const startDaemonControl = async (
|
|
|
33
38
|
socket.setEncoding("utf8")
|
|
34
39
|
socket.on("data", (data) => {
|
|
35
40
|
if (String(data).trim() === "get-token") socket.end(`${token}\n`)
|
|
41
|
+
else if (String(data).trim() === "get-health")
|
|
42
|
+
socket.end(`${JSON.stringify(runtimeHealth.snapshot())}\n`)
|
|
36
43
|
else socket.destroy()
|
|
37
44
|
})
|
|
38
45
|
})
|
|
@@ -83,3 +90,37 @@ export const requestDaemonToken = (
|
|
|
83
90
|
export const removeDaemonControl = (paths: DaemonPaths): void => {
|
|
84
91
|
if (existsSync(paths.controlSocket)) unlinkSync(paths.controlSocket)
|
|
85
92
|
}
|
|
93
|
+
|
|
94
|
+
export const requestDaemonHealth = (
|
|
95
|
+
paths: DaemonPaths,
|
|
96
|
+
timeoutMs = 1_000,
|
|
97
|
+
): Promise<RuntimeHealth | null> =>
|
|
98
|
+
new Promise((resolve) => {
|
|
99
|
+
if (!existsSync(paths.controlSocket)) return resolve(null)
|
|
100
|
+
const socket = connect(paths.controlSocket)
|
|
101
|
+
let data = ""
|
|
102
|
+
let settled = false
|
|
103
|
+
const finish = (value: RuntimeHealth | null): void => {
|
|
104
|
+
if (settled) return
|
|
105
|
+
settled = true
|
|
106
|
+
clearTimeout(timer)
|
|
107
|
+
socket.destroy()
|
|
108
|
+
resolve(value)
|
|
109
|
+
}
|
|
110
|
+
const timer = setTimeout(() => finish(null), timeoutMs)
|
|
111
|
+
socket.setEncoding("utf8")
|
|
112
|
+
socket.on("connect", () => socket.write("get-health\n"))
|
|
113
|
+
socket.on("data", (chunk) => {
|
|
114
|
+
data += chunk
|
|
115
|
+
if (!data.includes("\n")) return
|
|
116
|
+
try {
|
|
117
|
+
const parsed: unknown = JSON.parse(data.split("\n", 1)[0]!)
|
|
118
|
+
const result = runtimeHealthSchema.safeParse(parsed)
|
|
119
|
+
finish(result.success ? result.data : null)
|
|
120
|
+
} catch {
|
|
121
|
+
finish(null)
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
socket.on("error", () => finish(null))
|
|
125
|
+
socket.on("close", () => finish(null))
|
|
126
|
+
})
|