Khunndev Cursor commited on
Commit
0758854
·
1 Parent(s): e205988

Fix server mode sticking and results canvas layout above dock.

Browse files

Stop silent local fallback when server is selected, retry health checks, and fit the result image in the viewport above the bottom action bar.

Co-authored-by: Cursor <cursoragent@cursor.com>

frontend/src/App.tsx CHANGED
@@ -4,7 +4,7 @@ import { ASSETS } from './lib/assets'
4
  import { assignDiameterGroups, countByGroup } from './lib/clustering'
5
  import { getActiveBackend, isLowMemoryDevice, loadModel, runDetection } from './lib/inference'
6
  import { loadInferenceMode, saveInferenceMode } from './lib/inferenceSettings'
7
- import { getServerBackend, isServerDetectAvailable, serverDetect } from './lib/serverDetect'
8
  import { t } from './lib/i18n'
9
  import type { Detection, DiameterGroup, InferenceMode, Lang } from './lib/types'
10
  import { StepCapture } from './components/StepCapture'
@@ -69,23 +69,16 @@ export default function App() {
69
  setEngine('checking')
70
  setStatus(mode === 'local' ? t(lang, 'loadingModel') : '')
71
 
72
- const serverOk = await isServerDetectAvailable().catch(() => false)
73
  setServerAvailable(serverOk)
74
 
75
  if (mode === 'server') {
76
  if (serverOk) {
77
  setEngine('server')
78
  setStatus('')
79
- return
80
- }
81
- // server preferred but unreachable — try loading the on-device model
82
- try {
83
- await loadModel(setStatus)
84
- setEngine('local')
85
- setStatus('')
86
- } catch (err: unknown) {
87
  setEngine('none')
88
- setModelError(err instanceof Error ? err.message : String(err))
89
  setStatus('')
90
  }
91
  return
@@ -114,6 +107,24 @@ export default function App() {
114
  void initEngine()
115
  }, [initEngine, inferenceMode])
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  const handleInferenceMode = (mode: InferenceMode) => {
118
  saveInferenceMode(mode)
119
  setInferenceMode(mode)
@@ -158,23 +169,26 @@ export default function App() {
158
  setStatus(t(lang, 'processing'))
159
  navigate('counting')
160
 
161
- let usedBackend = inferenceMode === 'server' && serverAvailable ? 'server' : getActiveBackend()
162
-
163
  try {
164
  let dets: Detection[]
165
- const useServer = inferenceMode === 'server' && serverAvailable
166
-
167
- if (useServer) {
 
 
 
 
 
 
 
168
  if (!imageFile) throw new Error('Image unavailable for server detection')
 
169
  try {
170
  dets = await detectServer(imageFile)
171
- usedBackend = getServerBackend()
172
- } catch (serverErr) {
173
- setStatus(t(lang, 'fallbackLocal'))
174
- dets = await detectLocal(image)
175
- usedBackend = getActiveBackend()
176
- if (usedBackend === 'loading') throw serverErr
177
  }
 
178
  } else {
179
  const megapixels = (imageDims.w * imageDims.h) / 1_000_000
180
  const offloadHeavy =
 
4
  import { assignDiameterGroups, countByGroup } from './lib/clustering'
5
  import { getActiveBackend, isLowMemoryDevice, loadModel, runDetection } from './lib/inference'
6
  import { loadInferenceMode, saveInferenceMode } from './lib/inferenceSettings'
7
+ import { getServerBackend, probeServerDetect, serverDetect } from './lib/serverDetect'
8
  import { t } from './lib/i18n'
9
  import type { Detection, DiameterGroup, InferenceMode, Lang } from './lib/types'
10
  import { StepCapture } from './components/StepCapture'
 
69
  setEngine('checking')
70
  setStatus(mode === 'local' ? t(lang, 'loadingModel') : '')
71
 
72
+ const serverOk = await probeServerDetect()
73
  setServerAvailable(serverOk)
74
 
75
  if (mode === 'server') {
76
  if (serverOk) {
77
  setEngine('server')
78
  setStatus('')
79
+ } else {
 
 
 
 
 
 
 
80
  setEngine('none')
81
+ setModelError(t(lang, 'serverUnavailable'))
82
  setStatus('')
83
  }
84
  return
 
107
  void initEngine()
108
  }, [initEngine, inferenceMode])
109
 
110
+ // Re-probe server when opening preview (recovers from cold-start / flaky health checks).
111
+ useEffect(() => {
112
+ if (step !== 'preview' || inferenceMode !== 'server') return
113
+
114
+ let cancelled = false
115
+ void (async () => {
116
+ const ok = await probeServerDetect()
117
+ if (cancelled) return
118
+ setServerAvailable(ok)
119
+ setEngine(ok ? 'server' : 'none')
120
+ setModelError(ok ? '' : t(lang, 'serverUnavailable'))
121
+ })()
122
+
123
+ return () => {
124
+ cancelled = true
125
+ }
126
+ }, [step, inferenceMode, lang])
127
+
128
  const handleInferenceMode = (mode: InferenceMode) => {
129
  saveInferenceMode(mode)
130
  setInferenceMode(mode)
 
169
  setStatus(t(lang, 'processing'))
170
  navigate('counting')
171
 
 
 
172
  try {
173
  let dets: Detection[]
174
+ let usedBackend: string
175
+
176
+ if (inferenceMode === 'server') {
177
+ const serverOk = await probeServerDetect({ retries: 3 })
178
+ setServerAvailable(serverOk)
179
+ if (!serverOk) {
180
+ setEngine('none')
181
+ throw new Error(t(lang, 'serverUnavailable'))
182
+ }
183
+ setEngine('server')
184
  if (!imageFile) throw new Error('Image unavailable for server detection')
185
+
186
  try {
187
  dets = await detectServer(imageFile)
188
+ } catch {
189
+ throw new Error(t(lang, 'serverCountFailed'))
 
 
 
 
190
  }
191
+ usedBackend = getServerBackend()
192
  } else {
193
  const megapixels = (imageDims.w * imageDims.h) / 1_000_000
194
  const offloadHeavy =
frontend/src/components/ResultCanvas.tsx CHANGED
@@ -174,12 +174,33 @@ function drawCircle(
174
  // component
175
  // ---------------------------------------------------------------------------
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  interface Props {
178
  image: HTMLImageElement
179
  detections: Detection[]
180
  groups: DiameterGroup[]
181
  tool: ToolMode
182
  selectedGroupId: number
 
183
  onUpdate: (dets: Detection[]) => void
184
  onCanvasReady?: (canvas: HTMLCanvasElement | null) => void
185
  onAnimationComplete?: () => void
@@ -193,6 +214,7 @@ export function ResultCanvas({
193
  groups,
194
  tool,
195
  selectedGroupId,
 
196
  onUpdate,
197
  onCanvasReady,
198
  onAnimationComplete,
@@ -234,8 +256,22 @@ export function ResultCanvas({
234
  // lets all drawing below keep using natural-pixel coordinates. CSS
235
  // width:100% then scales the buffer to the display width.
236
  const rs = computeRenderScale(image.naturalWidth, image.naturalHeight)
237
- const displayW = canvas.parentElement?.clientWidth ?? image.naturalWidth
238
- const displayPx = displayW / image.naturalWidth // CSS px per natural px
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  const natW = image.naturalWidth
240
  const natH = image.naturalHeight
241
  canvas.width = Math.round(natW * rs)
@@ -318,7 +354,16 @@ export function ResultCanvas({
318
  rafRef.current = requestAnimationFrame(frame)
319
  return () => cancelAnimationFrame(rafRef.current)
320
  // eslint-disable-next-line react-hooks/exhaustive-deps
321
- }, [image, detections, groups])
 
 
 
 
 
 
 
 
 
322
 
323
  // -------------------------------------------------------------------------
324
  // interactive phase – re-render on detections / groups change
@@ -339,8 +384,24 @@ export function ResultCanvas({
339
  canvas.width = scaledW
340
  canvas.height = Math.round(natH * rs)
341
  }
342
- const displayW = canvas.parentElement?.clientWidth ?? natW
343
- const displayPx = displayW / natW
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  ctx.setTransform(rs, 0, 0, rs, 0, 0)
345
 
346
  ctx.clearRect(0, 0, natW, natH)
@@ -373,7 +434,7 @@ export function ResultCanvas({
373
  ctx.strokeRect(area.x1, area.y1, area.x2 - area.x1, area.y2 - area.y1)
374
  ctx.restore()
375
  }
376
- }, [animating, image, detections, groups])
377
 
378
  // -------------------------------------------------------------------------
379
  // direct canvas redraw — does NOT go through React state / onUpdate
@@ -389,8 +450,8 @@ export function ResultCanvas({
389
  const rs = computeRenderScale(image.naturalWidth, image.naturalHeight)
390
  const natW = image.naturalWidth
391
  const natH = image.naturalHeight
392
- const displayW = canvas.parentElement?.clientWidth ?? natW
393
- const displayPx = displayW / natW
394
  const dense = detections.length > 300
395
  const showLabels = detections.length <= 3000
396
  const minR = (dense ? 5 : 7) / displayPx
 
174
  // component
175
  // ---------------------------------------------------------------------------
176
 
177
+ function computeFitSize(
178
+ imageW: number,
179
+ imageH: number,
180
+ bounds: { w: number; h: number } | null,
181
+ parentW: number,
182
+ ): { cssW: number; cssH: number; displayPx: number } {
183
+ const aspect = imageH / Math.max(imageW, 1)
184
+ if (!bounds || bounds.w <= 0 || bounds.h <= 0) {
185
+ const cssW = parentW
186
+ return { cssW, cssH: cssW * aspect, displayPx: cssW / imageW }
187
+ }
188
+ let cssW = bounds.w
189
+ let cssH = cssW * aspect
190
+ if (cssH > bounds.h) {
191
+ cssH = bounds.h
192
+ cssW = cssH / aspect
193
+ }
194
+ return { cssW, cssH, displayPx: cssW / imageW }
195
+ }
196
+
197
  interface Props {
198
  image: HTMLImageElement
199
  detections: Detection[]
200
  groups: DiameterGroup[]
201
  tool: ToolMode
202
  selectedGroupId: number
203
+ displayBounds?: { w: number; h: number } | null
204
  onUpdate: (dets: Detection[]) => void
205
  onCanvasReady?: (canvas: HTMLCanvasElement | null) => void
206
  onAnimationComplete?: () => void
 
214
  groups,
215
  tool,
216
  selectedGroupId,
217
+ displayBounds,
218
  onUpdate,
219
  onCanvasReady,
220
  onAnimationComplete,
 
256
  // lets all drawing below keep using natural-pixel coordinates. CSS
257
  // width:100% then scales the buffer to the display width.
258
  const rs = computeRenderScale(image.naturalWidth, image.naturalHeight)
259
+ const parentW = canvas.parentElement?.clientWidth ?? image.naturalWidth
260
+ const { cssW, cssH, displayPx } = computeFitSize(
261
+ image.naturalWidth,
262
+ image.naturalHeight,
263
+ displayBounds ?? null,
264
+ parentW,
265
+ )
266
+ const container = containerRef.current
267
+ if (container) {
268
+ container.style.width = displayBounds ? `${cssW}px` : '100%'
269
+ container.style.height = displayBounds ? `${cssH}px` : 'auto'
270
+ container.style.margin = displayBounds ? '0 auto' : ''
271
+ container.style.maxHeight = displayBounds ? `${cssH}px` : ''
272
+ }
273
+ canvas.style.width = displayBounds ? `${cssW}px` : '100%'
274
+ canvas.style.height = displayBounds ? `${cssH}px` : 'auto'
275
  const natW = image.naturalWidth
276
  const natH = image.naturalHeight
277
  canvas.width = Math.round(natW * rs)
 
354
  rafRef.current = requestAnimationFrame(frame)
355
  return () => cancelAnimationFrame(rafRef.current)
356
  // eslint-disable-next-line react-hooks/exhaustive-deps
357
+ }, [image, detections, groups, displayBounds])
358
+
359
+ // Reset pan/zoom when the canvas is re-fitted above the results dock.
360
+ useEffect(() => {
361
+ if (!displayBounds) return
362
+ transformRef.current = { scale: 1, tx: 0, ty: 0 }
363
+ setDisplayScale(1)
364
+ const canvas = canvasRef.current
365
+ if (canvas) canvas.style.transform = ''
366
+ }, [displayBounds?.w, displayBounds?.h])
367
 
368
  // -------------------------------------------------------------------------
369
  // interactive phase – re-render on detections / groups change
 
384
  canvas.width = scaledW
385
  canvas.height = Math.round(natH * rs)
386
  }
387
+ const parentW = canvas.parentElement?.clientWidth ?? natW
388
+ const { cssW, cssH, displayPx } = computeFitSize(natW, natH, displayBounds ?? null, parentW)
389
+ const container = containerRef.current
390
+ if (container && displayBounds) {
391
+ container.style.width = `${cssW}px`
392
+ container.style.height = `${cssH}px`
393
+ container.style.margin = '0 auto'
394
+ container.style.maxHeight = `${cssH}px`
395
+ canvas.style.width = `${cssW}px`
396
+ canvas.style.height = `${cssH}px`
397
+ } else if (container) {
398
+ container.style.width = '100%'
399
+ container.style.height = 'auto'
400
+ container.style.margin = ''
401
+ container.style.maxHeight = ''
402
+ canvas.style.width = '100%'
403
+ canvas.style.height = 'auto'
404
+ }
405
  ctx.setTransform(rs, 0, 0, rs, 0, 0)
406
 
407
  ctx.clearRect(0, 0, natW, natH)
 
434
  ctx.strokeRect(area.x1, area.y1, area.x2 - area.x1, area.y2 - area.y1)
435
  ctx.restore()
436
  }
437
+ }, [animating, image, detections, groups, displayBounds])
438
 
439
  // -------------------------------------------------------------------------
440
  // direct canvas redraw — does NOT go through React state / onUpdate
 
450
  const rs = computeRenderScale(image.naturalWidth, image.naturalHeight)
451
  const natW = image.naturalWidth
452
  const natH = image.naturalHeight
453
+ const parentW = canvas.parentElement?.clientWidth ?? natW
454
+ const { displayPx } = computeFitSize(natW, natH, displayBounds ?? null, parentW)
455
  const dense = detections.length > 300
456
  const showLabels = detections.length <= 3000
457
  const minR = (dense ? 5 : 7) / displayPx
frontend/src/components/ResultsDock.tsx CHANGED
@@ -51,7 +51,7 @@ export function ResultsDock({
51
 
52
  return (
53
  <div
54
- className="rise-enter shrink-0 border-t border-[var(--hairline)] bg-[var(--header-bg)] shadow-[0_-4px_24px_rgba(15,23,42,0.06)]"
55
  style={{ paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))' }}
56
  >
57
  {/* count + groups */}
 
51
 
52
  return (
53
  <div
54
+ className="rise-enter native-scroll max-h-[46vh] shrink-0 overflow-y-auto border-t border-[var(--hairline)] bg-[var(--header-bg)] shadow-[0_-4px_24px_rgba(15,23,42,0.06)]"
55
  style={{ paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))' }}
56
  >
57
  {/* count + groups */}
frontend/src/components/StepResults.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { useRef, useState } from 'react'
2
  import { t } from '../lib/i18n'
3
  import type { Detection, DiameterGroup, Lang, ToolMode } from '../lib/types'
4
  import { ResultCanvas } from './ResultCanvas'
@@ -35,16 +35,41 @@ export function StepResults({
35
  const [exportOpen, setExportOpen] = useState(false)
36
  const countDisplayRef = useRef<HTMLSpanElement>(null)
37
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  return (
40
- <div className="flex flex-1 flex-col overflow-hidden bg-[var(--bg)]">
41
- <div className="native-scroll relative min-h-0 flex-1 overflow-y-auto px-2 pt-2">
 
 
 
42
  <ResultCanvas
43
  image={image}
44
  detections={detections}
45
  groups={groups}
46
  tool={tool}
47
  selectedGroupId={selectedGroupId}
 
48
  onUpdate={onUpdate}
49
  onCanvasReady={(c) => { canvasRef.current = c }}
50
  onAnimationComplete={() => setAnimDone(true)}
@@ -52,7 +77,7 @@ export function StepResults({
52
  />
53
 
54
  {!animDone && (
55
- <div className="pointer-events-none absolute left-1/2 top-3 -translate-x-1/2">
56
  <div className="rounded-full border border-[var(--hairline)] bg-[var(--surface)]/95 px-5 py-2 shadow-[var(--shadow-md)] backdrop-blur-sm">
57
  <span
58
  ref={countDisplayRef}
 
1
+ import { useEffect, useRef, useState } from 'react'
2
  import { t } from '../lib/i18n'
3
  import type { Detection, DiameterGroup, Lang, ToolMode } from '../lib/types'
4
  import { ResultCanvas } from './ResultCanvas'
 
35
  const [exportOpen, setExportOpen] = useState(false)
36
  const countDisplayRef = useRef<HTMLSpanElement>(null)
37
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
38
+ const viewportRef = useRef<HTMLDivElement>(null)
39
+ const [viewportSize, setViewportSize] = useState<{ w: number; h: number } | null>(null)
40
+
41
+ useEffect(() => {
42
+ const el = viewportRef.current
43
+ if (!el || !animDone) {
44
+ setViewportSize(null)
45
+ return
46
+ }
47
+
48
+ const measure = () => {
49
+ const w = el.clientWidth
50
+ const h = el.clientHeight
51
+ if (w > 0 && h > 0) setViewportSize({ w, h })
52
+ }
53
+
54
+ measure()
55
+ const ro = new ResizeObserver(measure)
56
+ ro.observe(el)
57
+ return () => ro.disconnect()
58
+ }, [animDone])
59
 
60
  return (
61
+ <div className="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto] overflow-hidden bg-[var(--bg)]">
62
+ <div
63
+ ref={viewportRef}
64
+ className="relative flex min-h-0 items-center justify-center overflow-hidden px-2 pt-2 pb-1"
65
+ >
66
  <ResultCanvas
67
  image={image}
68
  detections={detections}
69
  groups={groups}
70
  tool={tool}
71
  selectedGroupId={selectedGroupId}
72
+ displayBounds={viewportSize}
73
  onUpdate={onUpdate}
74
  onCanvasReady={(c) => { canvasRef.current = c }}
75
  onAnimationComplete={() => setAnimDone(true)}
 
77
  />
78
 
79
  {!animDone && (
80
+ <div className="pointer-events-none absolute left-1/2 top-3 z-10 -translate-x-1/2">
81
  <div className="rounded-full border border-[var(--hairline)] bg-[var(--surface)]/95 px-5 py-2 shadow-[var(--shadow-md)] backdrop-blur-sm">
82
  <span
83
  ref={countDisplayRef}
frontend/src/lib/i18n.ts CHANGED
@@ -32,6 +32,7 @@ const messages = {
32
  inferenceServerHint: 'Recommended — works on all phones',
33
  inferenceLocalHint: 'Offline — needs a capable device',
34
  serverUnavailable: 'Server unavailable',
 
35
  processing: 'Processing...',
36
  pleaseWait: 'This may take a moment on large photos.',
37
  total: 'Total pipes',
@@ -92,6 +93,7 @@ const messages = {
92
  inferenceServerHint: 'แนะนำ — ใช้ได้ทุกเครื่อง',
93
  inferenceLocalHint: 'ออฟไลน์ — ต้องใช้เครื่องที่รองรับ',
94
  serverUnavailable: 'เซิร์ฟเวอร์ไม่พร้อม',
 
95
  processing: 'กำลังประมวลผล...',
96
  pleaseWait: 'รูปขนาดใหญ่อาจใช้เวลาสักครู่',
97
  total: 'จำนวนท่อรวม',
 
32
  inferenceServerHint: 'Recommended — works on all phones',
33
  inferenceLocalHint: 'Offline — needs a capable device',
34
  serverUnavailable: 'Server unavailable',
35
+ serverCountFailed: 'Server counting failed. Check your connection and try again.',
36
  processing: 'Processing...',
37
  pleaseWait: 'This may take a moment on large photos.',
38
  total: 'Total pipes',
 
93
  inferenceServerHint: 'แนะนำ — ใช้ได้ทุกเครื่อง',
94
  inferenceLocalHint: 'ออฟไลน์ — ต้องใช้เครื่องที่รองรับ',
95
  serverUnavailable: 'เซิร์ฟเวอร์ไม่พร้อม',
96
+ serverCountFailed: 'นับบนเซิร์ฟเวอร์ไม่สำเร็จ กรุณาตรวจสอบการเชื่อมต่อแล้วลองใหม่',
97
  processing: 'กำลังประมวลผล...',
98
  pleaseWait: 'รูปขนาดใหญ่อาจใช้เวลาสักครู่',
99
  total: 'จำนวนท่อรวม',
frontend/src/lib/serverDetect.ts CHANGED
@@ -28,11 +28,11 @@ export function getServerBackend(): string {
28
  * Probe whether the server-side detection fallback is reachable and ready.
29
  * Returns false on any network error (e.g. installed PWA running offline).
30
  */
31
- export async function isServerDetectAvailable(timeoutMs = 4000): Promise<boolean> {
32
  try {
33
  const controller = new AbortController()
34
  const timer = setTimeout(() => controller.abort(), timeoutMs)
35
- const res = await fetch('/health', { signal: controller.signal })
36
  clearTimeout(timer)
37
  if (!res.ok) return false
38
  const data = (await res.json()) as { server_detect?: boolean }
@@ -42,7 +42,28 @@ export async function isServerDetectAvailable(timeoutMs = 4000): Promise<boolean
42
  }
43
  }
44
 
45
- export async function serverDetect(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  file: Blob,
47
  options?: {
48
  useTiling?: boolean
@@ -85,3 +106,30 @@ export async function serverDetect(
85
  groupId: 0,
86
  }))
87
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  * Probe whether the server-side detection fallback is reachable and ready.
29
  * Returns false on any network error (e.g. installed PWA running offline).
30
  */
31
+ export async function isServerDetectAvailable(timeoutMs = 8000): Promise<boolean> {
32
  try {
33
  const controller = new AbortController()
34
  const timer = setTimeout(() => controller.abort(), timeoutMs)
35
+ const res = await fetch('/health', { signal: controller.signal, cache: 'no-store' })
36
  clearTimeout(timer)
37
  if (!res.ok) return false
38
  const data = (await res.json()) as { server_detect?: boolean }
 
42
  }
43
  }
44
 
45
+ /** Health probe with retries — HF cold starts can miss a single 4s check. */
46
+ export async function probeServerDetect(options?: {
47
+ timeoutMs?: number
48
+ retries?: number
49
+ delayMs?: number
50
+ }): Promise<boolean> {
51
+ const retries = options?.retries ?? 3
52
+ const timeoutMs = options?.timeoutMs ?? 8000
53
+ const delayMs = options?.delayMs ?? 600
54
+
55
+ for (let i = 0; i < retries; i++) {
56
+ if (await isServerDetectAvailable(timeoutMs)) return true
57
+ if (i < retries - 1) {
58
+ await new Promise((r) => setTimeout(r, delayMs * (i + 1)))
59
+ }
60
+ }
61
+ return false
62
+ }
63
+
64
+ const SERVER_DETECT_RETRIES = 2
65
+
66
+ async function serverDetectOnce(
67
  file: Blob,
68
  options?: {
69
  useTiling?: boolean
 
106
  groupId: 0,
107
  }))
108
  }
109
+
110
+ export async function serverDetect(
111
+ file: Blob,
112
+ options?: {
113
+ useTiling?: boolean
114
+ filterOutliers?: boolean
115
+ onProgress?: (msg: string) => void
116
+ retries?: number
117
+ },
118
+ ): Promise<Detection[]> {
119
+ const retries = options?.retries ?? SERVER_DETECT_RETRIES
120
+ let lastErr: unknown
121
+
122
+ for (let attempt = 0; attempt <= retries; attempt++) {
123
+ try {
124
+ return await serverDetectOnce(file, options)
125
+ } catch (err) {
126
+ lastErr = err
127
+ if (attempt < retries) {
128
+ options?.onProgress?.('Retrying server…')
129
+ await new Promise((r) => setTimeout(r, 800 * (attempt + 1)))
130
+ }
131
+ }
132
+ }
133
+
134
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))
135
+ }