Line data Source code
1 : /**
2 : * Who may see the CRDT debug instrument, and how loud it is.
3 : *
4 : * The instrument used to be gated on `import.meta.env.DEV` alone, which is the
5 : * wrong audience: the people who need it are product testers driving a
6 : * STAGING build, where `DEV` is false. Opt-in is therefore explicit and
7 : * sticky — `?crdtDebug=1` turns it on for the origin until `?crdtDebug=0`
8 : * turns it off — so a tester can be handed a link rather than a build.
9 : *
10 : * The instrument is deliberately disabled on the production hostname
11 : * (review: dante01yoon on #16365, 2026-09-01). A link is something a tester
12 : * forwards, and a forwarded `?crdtDebug=1` landing on `cloud.comfy.org` would
13 : * flip the instrument on for whoever opens it there, with no re-review step —
14 : * unlike staging/testcloud/dev, where the audience is already internal. A
15 : * stale saved `Comfy.Agent.CrdtDebug.enabled=true` is also ignored there, so
16 : * neither query parameters nor persisted choices can retain debug events in
17 : * production.
18 : *
19 : * Verbosity is a separate axis on purpose. Turning the panel on should not
20 : * also flood the console: `?crdtDebug=trace` opts into the per-frame chatter,
21 : * while plain `1` keeps console output at the lifecycle level.
22 : */
23 2355 : const ENABLED_KEY = 'Comfy.Agent.CrdtDebug.enabled'
24 2355 : const LEVEL_KEY = 'Comfy.Agent.CrdtDebug.level'
25 2355 : const QUERY_PARAM = 'crdtDebug'
26 :
27 : /**
28 : * The one hostname this instrument must never silently light up on via a
29 : * forwarded link. Keep this list to confirmed production hosts only — every
30 : * other origin (staging, testcloud, PR previews, desktop, local) is where
31 : * the "hand a tester a link" workflow this gate exists for actually runs.
32 : */
33 2355 : const PRODUCTION_HOSTNAMES = new Set(['cloud.comfy.org'])
34 :
35 2 : export function isProductionHostname(
36 : hostname = window.location.hostname
37 : ): boolean {
38 2 : return PRODUCTION_HOSTNAMES.has(hostname)
39 : }
40 :
41 : /**
42 : * Console verbosity, ordered least-to-most chatty. `warn` is the floor: a
43 : * follower that refuses a doc or drops a human mint says so in every build,
44 : * because a silent divergence is the failure the whole instrument exists to
45 : * make visible.
46 : */
47 2355 : export const CRDT_LOG_LEVELS = ['warn', 'info', 'debug', 'trace'] as const
48 :
49 : export type CrdtLogLevel = (typeof CRDT_LOG_LEVELS)[number]
50 :
51 2355 : const DEFAULT_LEVEL: CrdtLogLevel = 'info'
52 :
53 1 : export function resolveDebugPanelEnabled(
54 : productGateEnabled: boolean,
55 : debugOverrideEnabled = isCrdtDebugEnabled()
56 : ): boolean {
57 1 : return productGateEnabled && debugOverrideEnabled
58 : }
59 :
60 : /**
61 : * Cached because {@link isLevelEnabled} runs on the CRDT hot path — once per
62 : * outbound frame, per applied frame and per minted op — and an uncached read
63 : * would put a synchronous `localStorage.getItem` on each of them, for
64 : * opted-out users most of all.
65 : */
66 2355 : let cachedEnabled: boolean | null = null
67 2355 : let cachedStoredEnabled: string | null | undefined
68 2355 : let cachedLevel: CrdtLogLevel | null = null
69 :
70 0 : function isLogLevel(value: unknown): value is CrdtLogLevel {
71 0 : return (CRDT_LOG_LEVELS as readonly unknown[]).includes(value)
72 : }
73 :
74 1 : function readStorage(key: string): string | null {
75 1 : try {
76 1 : return window.localStorage.getItem(key)
77 : } catch {
78 0 : return null
79 : }
80 : }
81 :
82 0 : function writeStorage(key: string, value: string | null): void {
83 0 : try {
84 0 : if (value === null) window.localStorage.removeItem(key)
85 0 : else window.localStorage.setItem(key, value)
86 : } catch {
87 : // Private mode / quota: the override simply does not persist.
88 : }
89 : }
90 :
91 1 : function readQueryParam(): string | null {
92 1 : try {
93 1 : return new URLSearchParams(window.location.search).get(QUERY_PARAM)
94 : } catch {
95 0 : return null
96 : }
97 : }
98 :
99 : /**
100 : * Fold `?crdtDebug=…` into storage exactly once per load, so the choice
101 : * survives the reloads a debugging session is made of.
102 : *
103 : * Accepts `0`/`false`/`off` to disable, a level name to enable at that level,
104 : * and any other non-empty value to enable at the current level.
105 : *
106 : * Two things it deliberately does NOT do. It never writes the level unless
107 : * the parameter names one — otherwise reloading a bookmarked `?crdtDebug=1`
108 : * would silently reset a verbosity the tester chose in the panel, on the
109 : * reload that reproducing a subscribe bug requires. And it strips itself from
110 : * the URL afterwards, so a later "hide" is not undone by the next reload of
111 : * the same link: the parameter is an instruction, not a standing order.
112 : */
113 1 : function applyQueryOverride(): void {
114 1 : const raw = readQueryParam()
115 1 : if (raw === null) return
116 0 : const value = raw.trim().toLowerCase()
117 0 : if (value === '') return
118 1 : const disabling = value === '0' || value === 'false' || value === 'off'
119 : // Opting OUT via the link must always work, on every origin — only the
120 : // enabling path is production-blocked. Otherwise a prod link with a typo'd
121 : // value could enable the instrument with no way to hand out a link back.
122 1 : if (!disabling && isProductionHostname()) {
123 0 : consumeQueryParam()
124 0 : return
125 : }
126 0 : setCrdtDebugEnabled(!disabling)
127 1 : if (!disabling && isLogLevel(value)) setCrdtLogLevel(value)
128 0 : consumeQueryParam()
129 : }
130 :
131 0 : function consumeQueryParam(): void {
132 0 : try {
133 0 : const url = new URL(window.location.href)
134 0 : url.searchParams.delete(QUERY_PARAM)
135 0 : window.history.replaceState(window.history.state, '', url)
136 : } catch {
137 : // No History API (or an opaque origin): the flag simply stays in the URL.
138 : }
139 : }
140 :
141 : /**
142 : * Applies a pending `?crdtDebug` link and follows cross-tab preference changes
143 : * until the returned disposer runs.
144 : */
145 1 : export function startCrdtDebugGate(): () => void {
146 1 : clearCachedPreferences()
147 1 : applyQueryOverride()
148 1 : const onStorage = (event: StorageEvent) => {
149 1 : if (
150 : event.key === null ||
151 : event.key === ENABLED_KEY ||
152 : event.key === LEVEL_KEY
153 : )
154 0 : clearCachedPreferences()
155 : }
156 1 : window.addEventListener('storage', onStorage)
157 1 : return () => window.removeEventListener('storage', onStorage)
158 : }
159 :
160 1 : function clearCachedPreferences(): void {
161 1 : cachedEnabled = null
162 1 : cachedStoredEnabled = undefined
163 1 : cachedLevel = null
164 : }
165 :
166 : /**
167 : * Whether the CRDT debug instrument (panel + console tracing) is available.
168 : *
169 : * Production is always disabled, including stale persisted choices from an
170 : * older build. Elsewhere, an explicit opt-out wins over `DEV` so a developer
171 : * chasing a rendering bug can silence the instrument without editing code.
172 : */
173 2 : export function isCrdtDebugEnabled(): boolean {
174 2 : if (isProductionHostname()) return false
175 2 : if (cachedEnabled === null) {
176 1 : const stored = readStoredEnabled()
177 1 : cachedEnabled =
178 : stored === 'true'
179 : ? true
180 : : stored === 'false'
181 : ? false
182 : : import.meta.env.DEV
183 : }
184 2 : return cachedEnabled
185 : }
186 :
187 1 : function readStoredEnabled(): string | null {
188 1 : if (cachedStoredEnabled === undefined)
189 1 : cachedStoredEnabled = readStorage(ENABLED_KEY)
190 1 : return cachedStoredEnabled
191 : }
192 :
193 0 : export function setCrdtDebugEnabled(enabled: boolean): void {
194 0 : cachedEnabled = enabled
195 0 : cachedStoredEnabled = String(enabled)
196 0 : writeStorage(ENABLED_KEY, String(enabled))
197 : }
198 :
199 : /**
200 : * Whether the user turned the instrument OFF, as opposed to never having said.
201 : * The ring buffer records for the never-said case — a tester who opens the
202 : * panel after something breaks needs the run-up — but an explicit "off" should
203 : * buy silence, not just a quiet console.
204 : */
205 0 : export function isCrdtDebugOptedOut(): boolean {
206 0 : return !isCrdtDebugEnabled() && readStoredEnabled() === 'false'
207 : }
208 :
209 0 : export function crdtLogLevel(): CrdtLogLevel {
210 0 : if (cachedLevel === null) {
211 0 : const stored = readStorage(LEVEL_KEY)
212 0 : cachedLevel = isLogLevel(stored) ? stored : DEFAULT_LEVEL
213 : }
214 0 : return cachedLevel
215 : }
216 :
217 0 : export function setCrdtLogLevel(level: CrdtLogLevel): void {
218 0 : cachedLevel = level
219 0 : writeStorage(LEVEL_KEY, level)
220 : }
221 :
222 : /** Whether `level` should reach the console at the current verbosity. */
223 0 : export function isLevelEnabled(level: CrdtLogLevel): boolean {
224 0 : if (level === 'warn') return true
225 0 : if (!isCrdtDebugEnabled()) return false
226 0 : return (
227 : CRDT_LOG_LEVELS.indexOf(level) <= CRDT_LOG_LEVELS.indexOf(crdtLogLevel())
228 : )
229 : }
|