@marimo-team/islands 0.23.7-dev55 → 0.23.7-dev57

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.
Files changed (29) hide show
  1. package/dist/{chat-ui-DCyW3OUK.js → chat-ui-D3XBept8.js} +3 -3
  2. package/dist/{code-visibility-CJ7U5FE0.js → code-visibility-PjV7HUDZ.js} +10624 -1451
  3. package/dist/{formats-CpgZM9BM.js → formats-Dsy9kkZu.js} +1 -1
  4. package/dist/{html-to-image-40ZXSWP-.js → html-to-image-CpggM7u1.js} +1 -1
  5. package/dist/main.js +1353 -9989
  6. package/dist/{process-output-CCeeXIBd.js → process-output-X8TR20AK.js} +1 -1
  7. package/dist/{reveal-component-Bopa1DsA.js → reveal-component-Phd-LTXq.js} +3 -3
  8. package/dist/{toDate-CJWlVNGD.js → toDate-CIpC_34u.js} +30 -17
  9. package/dist/{vega-component-BtvQ-Kc4.js → vega-component-cSdqoAxe.js} +2 -2
  10. package/package.json +1 -1
  11. package/src/components/data-table/__tests__/column-header.test.tsx +106 -1
  12. package/src/components/data-table/__tests__/filter-pill-editor.test.tsx +88 -2
  13. package/src/components/data-table/__tests__/filters.test.ts +84 -13
  14. package/src/components/data-table/column-header.tsx +152 -26
  15. package/src/components/data-table/date-filter-inputs.tsx +325 -0
  16. package/src/components/data-table/filter-pill-editor.tsx +139 -30
  17. package/src/components/data-table/filter-pills.tsx +31 -57
  18. package/src/components/data-table/filters.ts +88 -66
  19. package/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx +1 -1
  20. package/src/core/runtime/__tests__/runtime.test.ts +38 -17
  21. package/src/core/runtime/runtime.ts +57 -34
  22. package/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx +5 -4
  23. package/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts +18 -54
  24. package/src/core/websocket/transports/__tests__/ws.test.ts +125 -0
  25. package/src/core/websocket/transports/basic.ts +1 -3
  26. package/src/core/websocket/transports/transport.ts +0 -1
  27. package/src/core/websocket/transports/ws.ts +96 -0
  28. package/src/core/websocket/useMarimoKernelConnection.tsx +30 -26
  29. package/src/core/websocket/useWebSocket.tsx +3 -18
@@ -12,7 +12,11 @@ import { Badge } from "../ui/badge";
12
12
  import { Button } from "../ui/button";
13
13
  import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
14
14
  import { FilterPillEditor } from "./filter-pill-editor";
15
- import type { ColumnFilterValue } from "./filters";
15
+ import {
16
+ type ColumnFilterValue,
17
+ dateToISODate,
18
+ dateToISODateTime,
19
+ } from "./filters";
16
20
  import { OPERATOR_LABELS } from "./operator-labels";
17
21
  import { stringifyUnknownValue } from "./utils";
18
22
 
@@ -82,13 +86,6 @@ const FilterPill = <TData,>({
82
86
  return null;
83
87
  }
84
88
 
85
- // this is temporary, with more operator & datatype support this goes away
86
- const isReadOnly =
87
- "type" in value &&
88
- (value.type === "date" ||
89
- value.type === "datetime" ||
90
- value.type === "time");
91
-
92
89
  const twoSegment = formatted.value === undefined;
93
90
 
94
91
  const handleRemove = (e: React.MouseEvent) => {
@@ -130,20 +127,8 @@ const FilterPill = <TData,>({
130
127
  </Button>
131
128
  );
132
129
 
133
- if (isReadOnly) {
134
- return (
135
- <Badge
136
- variant="outline"
137
- className="bg-background border-border text-foreground"
138
- >
139
- {segments}
140
- {removeButton}
141
- </Badge>
142
- );
143
- }
144
-
145
130
  return (
146
- <Popover open={open} onOpenChange={setOpen} modal={true}>
131
+ <Popover open={open} onOpenChange={setOpen} modal={false}>
147
132
  <Badge
148
133
  variant="outline"
149
134
  className={cn(
@@ -249,23 +234,31 @@ function formatValue(
249
234
  };
250
235
  }
251
236
  }
252
- if (value.type === "date") {
253
- return formatMinMaxLegacy(
254
- value.min?.toISOString(),
255
- value.max?.toISOString(),
256
- );
257
- }
258
- if (value.type === "time") {
259
- return formatMinMaxLegacy(
260
- value.min ? timeFormatter.format(value.min) : undefined,
261
- value.max ? timeFormatter.format(value.max) : undefined,
262
- );
263
- }
264
- if (value.type === "datetime") {
265
- return formatMinMaxLegacy(
266
- value.min?.toISOString(),
267
- value.max?.toISOString(),
268
- );
237
+ if (
238
+ value.type === "date" ||
239
+ value.type === "datetime" ||
240
+ value.type === "time"
241
+ ) {
242
+ const format =
243
+ value.type === "time"
244
+ ? (d: Date) => timeFormatter.format(d)
245
+ : value.type === "date"
246
+ ? dateToISODate
247
+ : dateToISODateTime;
248
+ switch (value.operator) {
249
+ case "between":
250
+ return {
251
+ operator: OPERATOR_LABELS.between.toLowerCase(),
252
+ value: `${format(value.min)} - ${format(value.max)}`,
253
+ };
254
+ case "==":
255
+ case "!=":
256
+ case ">":
257
+ case ">=":
258
+ case "<":
259
+ case "<=":
260
+ return { operator: value.operator, value: format(value.value) };
261
+ }
269
262
  }
270
263
  if (value.type === "boolean") {
271
264
  return { operator: `is ${value.value ? "True" : "False"}` };
@@ -282,22 +275,3 @@ function formatValue(
282
275
  logNever(value);
283
276
  return undefined;
284
277
  }
285
-
286
- function formatMinMaxLegacy(
287
- min: string | number | undefined,
288
- max: string | number | undefined,
289
- ): FormattedFilter | undefined {
290
- if (min === undefined && max === undefined) {
291
- return;
292
- }
293
- if (min === max) {
294
- return { operator: "==", value: String(min) };
295
- }
296
- if (min === undefined) {
297
- return { operator: "<=", value: String(max) };
298
- }
299
- if (max === undefined) {
300
- return { operator: ">=", value: String(min) };
301
- }
302
- return { operator: "between", value: `${min} - ${max}` };
303
- }
@@ -51,6 +51,15 @@ export const TEXT_SCALAR_OPS = [
51
51
  "ends_with",
52
52
  ] as const;
53
53
 
54
+ export const DATETIME_COMPARISON_OPS = [
55
+ "==",
56
+ "!=",
57
+ ">",
58
+ ">=",
59
+ "<",
60
+ "<=",
61
+ ] as const;
62
+
54
63
  export const NUMBER_OPS = [
55
64
  "between",
56
65
  ...NUMBER_COMPARISON_OPS,
@@ -62,11 +71,26 @@ export const TEXT_OPS = [
62
71
  "is_empty",
63
72
  ...NULLISH_OPS,
64
73
  ] as const;
74
+ export const DATETIME_OPS = [
75
+ "between",
76
+ ...DATETIME_COMPARISON_OPS,
77
+ ...NULLISH_OPS,
78
+ ] as const;
65
79
 
66
80
  export type NullishOp = (typeof NULLISH_OPS)[number];
67
81
  export type MembershipOp = (typeof MEMBERSHIP_OPS)[number];
68
82
  export type NumberComparisonOp = (typeof NUMBER_COMPARISON_OPS)[number];
69
83
  export type TextScalarOp = (typeof TEXT_SCALAR_OPS)[number];
84
+ export type DatetimeComparisonOp = (typeof DATETIME_COMPARISON_OPS)[number];
85
+
86
+ const makeOpGuard = <T extends OperatorType>(ops: readonly T[]) => {
87
+ const set = new Set<OperatorType>(ops);
88
+ return (op: OperatorType): op is T => set.has(op);
89
+ };
90
+
91
+ export const isNumberComparisonOp = makeOpGuard(NUMBER_COMPARISON_OPS);
92
+ export const isTextScalarOp = makeOpGuard(TEXT_SCALAR_OPS);
93
+ export const isDatetimeComparisonOp = makeOpGuard(DATETIME_COMPARISON_OPS);
70
94
 
71
95
  interface NullishOpts {
72
96
  operator: NullishOp;
@@ -83,6 +107,11 @@ type TextFilterOpts =
83
107
  | { operator: "is_empty" }
84
108
  | NullishOpts;
85
109
 
110
+ type DateLikeFilterOpts =
111
+ | { operator: "between"; min: Date; max: Date }
112
+ | { operator: DatetimeComparisonOp; value: Date }
113
+ | NullishOpts;
114
+
86
115
  // Filter is a factory function that creates a filter object
87
116
  export const Filter = {
88
117
  number(opts: NumberFilterOpts) {
@@ -97,19 +126,19 @@ export const Filter = {
97
126
  ...opts,
98
127
  } as const;
99
128
  },
100
- date(opts: { min?: Date; max?: Date; operator?: OperatorType }) {
129
+ date(opts: DateLikeFilterOpts) {
101
130
  return {
102
131
  type: "date",
103
132
  ...opts,
104
133
  } as const;
105
134
  },
106
- datetime(opts: { min?: Date; max?: Date; operator?: OperatorType }) {
135
+ datetime(opts: DateLikeFilterOpts) {
107
136
  return {
108
137
  type: "datetime",
109
138
  ...opts,
110
139
  } as const;
111
140
  },
112
- time(opts: { min?: Date; max?: Date; operator?: OperatorType }) {
141
+ time(opts: DateLikeFilterOpts) {
113
142
  return {
114
143
  type: "time",
115
144
  ...opts,
@@ -135,6 +164,26 @@ export type ColumnFilterForType<T extends FilterType> = T extends FilterType
135
164
  ? Extract<ColumnFilterValue, { type: T }>
136
165
  : never;
137
166
 
167
+ function pad2(n: number): string {
168
+ return n.toString().padStart(2, "0");
169
+ }
170
+
171
+ function pad4(n: number): string {
172
+ return n.toString().padStart(4, "0");
173
+ }
174
+
175
+ export function dateToISODate(d: Date): string {
176
+ return `${pad4(d.getFullYear())}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
177
+ }
178
+
179
+ export function dateToISOTime(d: Date): string {
180
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
181
+ }
182
+
183
+ export function dateToISODateTime(d: Date): string {
184
+ return `${dateToISODate(d)}T${dateToISOTime(d)}`;
185
+ }
186
+
138
187
  function isNullishFilter(
139
188
  filter: ColumnFilterValue,
140
189
  ): filter is Extract<
@@ -235,71 +284,44 @@ export function filterToFilterCondition(
235
284
  default:
236
285
  assertNever(filter);
237
286
  }
238
- case "datetime": {
239
- const conditions: FilterConditionType[] = [];
240
- if (filter.min !== undefined) {
241
- conditions.push({
242
- column_id: columnId,
243
- operator: ">=",
244
- value: filter.min.toISOString(),
245
- type: "condition",
246
- negate: false,
247
- });
248
- }
249
- if (filter.max !== undefined) {
250
- conditions.push({
251
- column_id: columnId,
252
- operator: "<=",
253
- value: filter.max.toISOString(),
254
- type: "condition",
255
- negate: false,
256
- });
257
- }
258
- return conditions;
259
- }
260
- case "date": {
261
- const conditions: FilterConditionType[] = [];
262
- if (filter.min !== undefined) {
263
- conditions.push({
264
- column_id: columnId,
265
- operator: ">=",
266
- value: filter.min.toISOString(),
267
- type: "condition",
268
- negate: false,
269
- });
270
- }
271
- if (filter.max !== undefined) {
272
- conditions.push({
273
- column_id: columnId,
274
- operator: "<=",
275
- value: filter.max.toISOString(),
276
- type: "condition",
277
- negate: false,
278
- });
279
- }
280
- return conditions;
281
- }
287
+ case "date":
288
+ case "datetime":
282
289
  case "time": {
283
- const conditions: FilterConditionType[] = [];
284
- if (filter.min !== undefined) {
285
- conditions.push({
286
- column_id: columnId,
287
- operator: ">=",
288
- value: filter.min.toISOString(),
289
- type: "condition",
290
- negate: false,
291
- });
292
- }
293
- if (filter.max !== undefined) {
294
- conditions.push({
295
- column_id: columnId,
296
- operator: "<=",
297
- value: filter.max.toISOString(),
298
- type: "condition",
299
- negate: false,
300
- });
290
+ const encode =
291
+ filter.type === "date"
292
+ ? dateToISODate
293
+ : filter.type === "time"
294
+ ? dateToISOTime
295
+ : dateToISODateTime;
296
+ switch (filter.operator) {
297
+ case "between":
298
+ return [
299
+ {
300
+ column_id: columnId,
301
+ operator: "between",
302
+ value: { min: encode(filter.min), max: encode(filter.max) },
303
+ type: "condition",
304
+ negate: false,
305
+ },
306
+ ];
307
+ case "==":
308
+ case "!=":
309
+ case ">":
310
+ case ">=":
311
+ case "<":
312
+ case "<=":
313
+ return [
314
+ {
315
+ column_id: columnId,
316
+ operator: filter.operator,
317
+ value: encode(filter.value),
318
+ type: "condition",
319
+ negate: false,
320
+ },
321
+ ];
322
+ default:
323
+ assertNever(filter);
301
324
  }
302
- return conditions;
303
325
  }
304
326
  case "boolean":
305
327
  if (filter.value) {
@@ -57,7 +57,7 @@ export const BackendConnectionStatus: React.FC = () => {
57
57
  }
58
58
 
59
59
  try {
60
- const isHealthy = await runtime.isHealthy();
60
+ const isHealthy = await runtime.probeHealth();
61
61
  setConnectionStatus(isHealthy ? "healthy" : "unhealthy");
62
62
  return {
63
63
  isHealthy,
@@ -275,14 +275,14 @@ describe("RuntimeManager", () => {
275
275
  });
276
276
  });
277
277
 
278
- describe("isHealthy", () => {
278
+ describe("probeHealth", () => {
279
279
  it("should return true for successful health check", async () => {
280
280
  global.fetch = vi.fn().mockResolvedValue({
281
281
  ok: true,
282
282
  });
283
283
 
284
284
  const runtime = new RuntimeManager(mockConfig);
285
- const result = await runtime.isHealthy();
285
+ const result = await runtime.probeHealth();
286
286
 
287
287
  expect(result).toBe(true);
288
288
  expect(fetch).toHaveBeenCalledWith("https://example.com/health");
@@ -294,7 +294,7 @@ describe("RuntimeManager", () => {
294
294
  });
295
295
 
296
296
  const runtime = new RuntimeManager(mockConfig);
297
- const result = await runtime.isHealthy();
297
+ const result = await runtime.probeHealth();
298
298
 
299
299
  expect(result).toBe(false);
300
300
  });
@@ -304,11 +304,32 @@ describe("RuntimeManager", () => {
304
304
  global.fetch = vi.fn().mockRejectedValue(error);
305
305
 
306
306
  const runtime = new RuntimeManager(mockConfig);
307
- const result = await runtime.isHealthy();
307
+ const result = await runtime.probeHealth();
308
308
 
309
309
  expect(result).toBe(false);
310
310
  });
311
311
 
312
+ it("should not mutate config.url on redirect", async () => {
313
+ global.fetch = vi.fn().mockResolvedValue({
314
+ ok: true,
315
+ redirected: true,
316
+ url: "https://sandbox.example.com/health?some_value=abc123",
317
+ });
318
+
319
+ const runtime = new RuntimeManager(
320
+ {
321
+ ...mockConfig,
322
+ url: "https://backend.example.com/lazy?some_value=abc123",
323
+ },
324
+ true,
325
+ );
326
+ const result = await runtime.probeHealth();
327
+ expect(result).toBe(true);
328
+ expect(runtime.httpURL.hostname).toBe("backend.example.com");
329
+ });
330
+ });
331
+
332
+ describe("reconcileFromHealth", () => {
312
333
  it("should update config.url on redirect, stripping /health from pathname", async () => {
313
334
  global.fetch = vi.fn().mockResolvedValue({
314
335
  ok: true,
@@ -323,7 +344,7 @@ describe("RuntimeManager", () => {
323
344
  },
324
345
  true, // lazy — don't call init() in constructor
325
346
  );
326
- const result = await runtime.isHealthy();
347
+ const result = await runtime.reconcileFromHealth();
327
348
 
328
349
  expect(result).toBe(true);
329
350
  // Should strip /health from pathname but preserve query params
@@ -342,7 +363,7 @@ describe("RuntimeManager", () => {
342
363
  it("should resolve immediately if healthy", async () => {
343
364
  const runtime = new RuntimeManager(mockConfig, true);
344
365
 
345
- vi.spyOn(runtime, "isHealthy").mockResolvedValue(true);
366
+ vi.spyOn(runtime, "reconcileFromHealth").mockResolvedValue(true);
346
367
  runtime.init();
347
368
 
348
369
  await expect(runtime.waitForHealthy()).resolves.toBeUndefined();
@@ -351,7 +372,7 @@ describe("RuntimeManager", () => {
351
372
  it("should retry and eventually succeed", async () => {
352
373
  const runtime = new RuntimeManager(mockConfig, true);
353
374
  const healthySpy = vi
354
- .spyOn(runtime, "isHealthy")
375
+ .spyOn(runtime, "reconcileFromHealth")
355
376
  .mockResolvedValueOnce(false)
356
377
  .mockResolvedValueOnce(false)
357
378
  .mockResolvedValueOnce(true);
@@ -364,7 +385,7 @@ describe("RuntimeManager", () => {
364
385
 
365
386
  it("should throw after max retries", async () => {
366
387
  const runtime = new RuntimeManager(mockConfig, true);
367
- vi.spyOn(runtime, "isHealthy").mockResolvedValue(false);
388
+ vi.spyOn(runtime, "reconcileFromHealth").mockResolvedValue(false);
368
389
  runtime.init({ disableRetryDelay: true });
369
390
 
370
391
  await expect(runtime.waitForHealthy()).rejects.toThrow(
@@ -431,7 +452,7 @@ describe("RuntimeManager", () => {
431
452
  // Mock failed health check
432
453
  global.fetch = vi.fn().mockResolvedValue({ ok: false });
433
454
 
434
- await runtime.isHealthy();
455
+ await runtime.reconcileFromHealth();
435
456
 
436
457
  baseElement = document.querySelector("base");
437
458
  expect(baseElement).toBeNull();
@@ -443,7 +464,7 @@ describe("RuntimeManager", () => {
443
464
  // Mock successful health check
444
465
  global.fetch = vi.fn().mockResolvedValue({ ok: true });
445
466
 
446
- await runtime.isHealthy();
467
+ await runtime.reconcileFromHealth();
447
468
 
448
469
  const baseElement = document.querySelector("base");
449
470
  expect(baseElement).toBeTruthy();
@@ -461,7 +482,7 @@ describe("RuntimeManager", () => {
461
482
  // Mock successful health check
462
483
  global.fetch = vi.fn().mockResolvedValue({ ok: true });
463
484
 
464
- await runtime.isHealthy();
485
+ await runtime.reconcileFromHealth();
465
486
 
466
487
  const baseElement = document.querySelector("base");
467
488
  expect(baseElement).toBe(existingBase); // Should be the same element
@@ -483,7 +504,7 @@ describe("RuntimeManager", () => {
483
504
  // Mock successful health check
484
505
  global.fetch = vi.fn().mockResolvedValue({ ok: true });
485
506
 
486
- await runtime.isHealthy();
507
+ await runtime.reconcileFromHealth();
487
508
 
488
509
  const baseElement = document.querySelector("base");
489
510
  expect(baseElement).toBeTruthy();
@@ -524,11 +545,11 @@ describe("RuntimeManager", () => {
524
545
  });
525
546
 
526
547
  const wsUrl = runtime.getWsURL("test" as SessionId);
527
- const httpUrl = runtime.formatHttpURL(
528
- "api/test",
529
- new URLSearchParams(),
530
- false,
531
- );
548
+ const httpUrl = runtime.formatHttpURL({
549
+ path: "api/test",
550
+ searchParams: new URLSearchParams(),
551
+ restrictToKnownQueryParams: false,
552
+ });
532
553
 
533
554
  // Should preserve base URL query params
534
555
  expect(wsUrl.searchParams.get("base_param")).toBe("existing");
@@ -44,17 +44,22 @@ export class RuntimeManager {
44
44
  return this.httpURL.origin === window.location.origin;
45
45
  }
46
46
 
47
+ private get isServerless(): boolean {
48
+ return isWasm() || isIslands() || isStaticNotebook();
49
+ }
50
+
47
51
  /**
48
52
  * The base URL of the runtime.
49
53
  */
50
- formatHttpURL(
51
- path?: string,
52
- searchParams?: URLSearchParams,
54
+ formatHttpURL({
55
+ path = "",
56
+ searchParams,
53
57
  restrictToKnownQueryParams = true,
54
- ): URL {
55
- if (!path) {
56
- path = "";
57
- }
58
+ }: {
59
+ path?: string;
60
+ searchParams?: URLSearchParams;
61
+ restrictToKnownQueryParams?: boolean;
62
+ }): URL {
58
63
  // URL may be something like "http://localhost:8000?auth=123"
59
64
  const baseUrl = this.httpURL;
60
65
  const currentParams = new URLSearchParams(window.location.search);
@@ -84,11 +89,11 @@ export class RuntimeManager {
84
89
  formatWsURL(path: string, searchParams?: URLSearchParams): URL {
85
90
  // We don't restrict to known query parameters, since mo.query_params()
86
91
  // can accept arbitrary parameters.
87
- const url = this.formatHttpURL(
92
+ const url = this.formatHttpURL({
88
93
  path,
89
94
  searchParams,
90
- /* restrictToKnownQueryParams =*/ false,
91
- );
95
+ restrictToKnownQueryParams: false,
96
+ });
92
97
 
93
98
  // For cross-origin runtimes, pass the auth token as a query parameter.
94
99
  // WebSocket connections cannot send custom headers (no Authorization
@@ -168,45 +173,63 @@ export class RuntimeManager {
168
173
  }
169
174
 
170
175
  getAiURL(path: "completion" | "chat"): URL {
171
- return this.formatHttpURL(`/api/ai/${path}`);
176
+ return this.formatHttpURL({ path: `/api/ai/${path}` });
172
177
  }
173
178
 
174
179
  /**
175
180
  * The URL of the health check endpoint.
176
181
  */
177
182
  healthURL(): URL {
178
- return this.formatHttpURL("/health");
183
+ return this.formatHttpURL({ path: "/health" });
179
184
  }
180
185
 
181
- async isHealthy(): Promise<boolean> {
182
- // Always healthy if WASM, Islands, or a static notebook (no server)
183
- if (isWasm() || isIslands() || isStaticNotebook()) {
184
- return true;
185
- }
186
-
186
+ private async fetchHealth(): Promise<Response | null> {
187
187
  try {
188
- const response = await fetch(this.healthURL().toString());
189
- // If there is a redirect, update the URL in the config
190
- if (response.redirected) {
191
- Logger.debug(`Runtime redirected to ${response.url}`);
192
- // strip /health from the URL, using URL parsing to handle query params
193
- const redirected = new URL(response.url);
194
- redirected.pathname = redirected.pathname.replace(/\/health$/, "");
195
- this.config.url = redirected.toString();
196
- }
197
-
198
- const success = response.ok;
199
- if (success) {
200
- this.setDOMBaseUri(this.config.url);
201
- }
202
- return success;
188
+ return await fetch(this.healthURL().toString());
203
189
  } catch (error) {
204
190
  Logger.error(
205
191
  `Failed to check health: ${error instanceof Error ? error.message : "Unknown error"}`,
206
192
  { cause: error },
207
193
  );
194
+ return null;
195
+ }
196
+ }
197
+
198
+ async reconcileFromHealth(): Promise<boolean> {
199
+ // Always healthy if WASM, Islands, or a static notebook (no server)
200
+ if (this.isServerless) {
201
+ return true;
202
+ }
203
+
204
+ const response = await this.fetchHealth();
205
+
206
+ if (!response) {
208
207
  return false;
209
208
  }
209
+
210
+ if (response.redirected) {
211
+ Logger.debug(`Runtime redirected to ${response.url}`);
212
+ // strip /health from the URL, using URL parsing to handle query params
213
+ const redirected = new URL(response.url);
214
+ redirected.pathname = redirected.pathname.replace(/\/health$/, "");
215
+ this.config.url = redirected.toString();
216
+ }
217
+
218
+ if (response.ok) {
219
+ this.setDOMBaseUri(this.config.url);
220
+ }
221
+
222
+ return response.ok;
223
+ }
224
+
225
+ async probeHealth(): Promise<boolean> {
226
+ // Always healthy if WASM, Islands, or a static notebook (no server)
227
+ if (this.isServerless) {
228
+ return true;
229
+ }
230
+
231
+ const response = await this.fetchHealth();
232
+ return response?.ok ?? false;
210
233
  }
211
234
 
212
235
  /**
@@ -251,7 +274,7 @@ export class RuntimeManager {
251
274
  const growthFactor = 1.2;
252
275
  const maxDelay = 2000;
253
276
 
254
- while (!(await this.isHealthy())) {
277
+ while (!(await this.reconcileFromHealth())) {
255
278
  if (retries >= maxRetries) {
256
279
  Logger.error(`Failed to connect after ${maxRetries} retries`);
257
280
  this.initialHealthyCheck.reject(
@@ -35,7 +35,6 @@ import { useConnectionTransport } from "../useWebSocket";
35
35
 
36
36
  interface MockTransport {
37
37
  readyState: 0 | 1 | 2 | 3;
38
- retryCount: number;
39
38
  reconnect: ReturnType<typeof vi.fn>;
40
39
  close: ReturnType<typeof vi.fn>;
41
40
  send: ReturnType<typeof vi.fn>;
@@ -48,7 +47,6 @@ function makeTransport(
48
47
  ): MockTransport {
49
48
  return {
50
49
  readyState,
51
- retryCount: 0,
52
50
  reconnect: vi.fn(),
53
51
  close: vi.fn(),
54
52
  send: vi.fn(),
@@ -57,9 +55,12 @@ function makeTransport(
57
55
  };
58
56
  }
59
57
 
60
- function makeRuntimeManager(isHealthy = vi.fn().mockResolvedValue(true)) {
58
+ function makeRuntimeManager(
59
+ reconcileFromHealth = vi.fn().mockResolvedValue(true),
60
+ ) {
61
61
  return {
62
- isHealthy,
62
+ reconcileFromHealth,
63
+ probeHealth: vi.fn().mockResolvedValue(true),
63
64
  getWsURL: () => new URL("ws://localhost/ws"),
64
65
  waitForHealthy: vi.fn().mockResolvedValue(undefined),
65
66
  isSameOrigin: true,