@lowdefy/server-dev 0.0.0-experimental-20261117131515 → 0.0.0-experimental-20261119084338

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 (71) hide show
  1. package/client/recorder/createRecorder.test.mjs +51 -0
  2. package/lib/docs/addNestedEndpoints.js +1 -2
  3. package/lib/docs/addNestedEndpoints.test.mjs +1 -1
  4. package/lib/docs/addWriteFlags.js +1 -2
  5. package/lib/docs/browserCrash.chromium.test.mjs +109 -0
  6. package/lib/{server/isRoutineStep.js → docs/browserCrashError.js} +13 -7
  7. package/lib/docs/checkStepReferences.js +22 -2
  8. package/lib/docs/createBrowserLifecycle.js +54 -4
  9. package/lib/docs/createBrowserLifecycle.test.mjs +97 -3
  10. package/lib/docs/createDevServerHost.js +134 -34
  11. package/lib/docs/createDevServerHost.test.mjs +157 -0
  12. package/lib/docs/createDocsMcpServer.js +33 -3
  13. package/lib/docs/createDocsMcpServer.test.mjs +4 -3
  14. package/lib/docs/createDocsMcpServerRunJourney.test.mjs +110 -0
  15. package/lib/docs/createInProcessRequest.js +3 -1
  16. package/lib/docs/devToolDefinitions.js +12 -3
  17. package/lib/docs/findSentPlaceholder.js +45 -0
  18. package/lib/docs/getBrowser.js +15 -3
  19. package/lib/docs/getBrowser.test.mjs +49 -0
  20. package/lib/docs/observe/createJourneyAppErrors.js +2 -2
  21. package/lib/docs/observe/evaluateInvariants.js +5 -2
  22. package/lib/docs/observe/evaluateInvariants.test.mjs +54 -0
  23. package/lib/docs/rails/authEngineActions.test.mjs +2 -0
  24. package/lib/docs/rails/checkAuthActionsRan.js +20 -13
  25. package/lib/docs/rails/checkAuthActionsRan.test.mjs +34 -16
  26. package/lib/docs/rails/checkPressRails.js +115 -0
  27. package/lib/docs/rails/checkPressRails.test.mjs +210 -0
  28. package/lib/docs/rails/checkStepRails.js +113 -0
  29. package/lib/docs/rails/checkStepRails.test.mjs +207 -0
  30. package/lib/docs/runJourney.js +60 -7
  31. package/lib/docs/runJourney.test.mjs +115 -8
  32. package/lib/docs/runJourneyCall.js +11 -7
  33. package/lib/docs/runJourneyCall.test.mjs +19 -17
  34. package/lib/docs/runJourneyDataSet.test.mjs +63 -2
  35. package/lib/docs/runJourneyHeadless.js +34 -3
  36. package/lib/docs/runJourneyHeadless.test.mjs +114 -0
  37. package/lib/docs/runJourneySteps.js +435 -68
  38. package/lib/docs/runJourneyWebhook.js +66 -0
  39. package/lib/docs/serverErrorStore.js +5 -1
  40. package/lib/docs/serverErrorStore.test.mjs +8 -0
  41. package/lib/{docs/rails/readBuiltArtifact.js → server/JOURNEY_REQUEST_ID_HEADER.js} +7 -13
  42. package/lib/server/auth/getAuth.js +8 -0
  43. package/lib/server/createLowdefyContext.js +8 -6
  44. package/lib/server/createLowdefyContext.test.mjs +102 -2
  45. package/lib/server/log/createHandleError.js +34 -2
  46. package/lib/server/log/createHandleError.test.mjs +79 -1
  47. package/lib/server/mutants/walkArtifact.js +1 -1
  48. package/package.json +41 -41
  49. package/package.original.json +41 -41
  50. package/src/app.js +5 -0
  51. package/src/app.viewSession.test.mjs +197 -0
  52. package/src/html/renderDevPage.js +14 -12
  53. package/src/middleware/errorHandler.js +17 -1
  54. package/src/middleware/errorHandler.test.mjs +36 -0
  55. package/src/middleware/refuseViewSession.js +43 -0
  56. package/src/routes/docs/journey.js +20 -1
  57. package/src/routes/docs/journey.test.mjs +105 -1
  58. package/src/routes/endpoints.js +4 -0
  59. package/src/routes/endpointsTextAnswer.test.mjs +20 -2
  60. package/lib/docs/expectAnswerError.js +0 -38
  61. package/lib/docs/expectAnswerStatus.js +0 -33
  62. package/lib/docs/expectJourneyDb.js +0 -98
  63. package/lib/docs/expectJourneyDb.test.mjs +0 -115
  64. package/lib/docs/pageBlocks.js +0 -47
  65. package/lib/docs/rails/checkClickRails.js +0 -56
  66. package/lib/docs/rails/createDataSetRails.js +0 -82
  67. package/lib/docs/rails/createDataSetRails.test.mjs +0 -173
  68. package/lib/docs/rails/findExternalBlocks.js +0 -147
  69. package/lib/docs/rails/findExternalBlocks.test.mjs +0 -255
  70. package/lib/docs/readRoutineSteps.js +0 -45
  71. package/src/lib/safeScriptJson.js +0 -38
@@ -18,6 +18,8 @@
18
18
  */
19
19
 
20
20
  import { vi, afterEach, beforeEach, expect, test } from 'vitest';
21
+ import { getTrace } from '@lowdefy/engine';
22
+ import { formatSessionLog, validateTraceRecord } from '@lowdefy/node-utils';
21
23
 
22
24
  import createRecorder from './createRecorder.js';
23
25
 
@@ -316,3 +318,52 @@ test('a page shown with no pageview pending records nothing', async () => {
316
318
  await window.__lowdefyRecorder.flush();
317
319
  expect(fetch).not.toHaveBeenCalled();
318
320
  });
321
+
322
+ test('a recorded click on a Modal OK button in its portal is a { blockId, control } click step', async () => {
323
+ window.history.replaceState({}, '', '/tickets');
324
+ document.body.innerHTML = `
325
+ <div id="bl-page"><div id="bl-delete_modal"></div></div>
326
+ <div class="ant-modal-root"><div role="dialog" class="ant-modal"><div class="ant-modal-footer">
327
+ <button data-lf-block="delete_modal" data-lf-control="cancel"><span>Cancel</span></button>
328
+ <button data-lf-block="delete_modal" data-lf-control="ok"><span id="ok">OK</span></button>
329
+ </div></div></div>`;
330
+ const lowdefy = {
331
+ basePath: '',
332
+ contexts: {
333
+ 'page:tickets': {
334
+ pageId: 'tickets',
335
+ _internal: { RootSlots: { map: { delete_modal: { type: 'Modal' } } } },
336
+ },
337
+ },
338
+ home: {},
339
+ user: { roles: [] },
340
+ _internal: { globals: { window } },
341
+ };
342
+ recorder = createRecorder({
343
+ basePath: '',
344
+ lowdefy,
345
+ recording: { enabled: true },
346
+ window,
347
+ getTrace,
348
+ });
349
+ recorder.pageview({ path: 'tickets' });
350
+ recorder.pageShown(page('tickets'));
351
+ document.getElementById('ok').click();
352
+ await window.__lowdefyRecorder.flush();
353
+ // The dev server stamps the source on each record it writes.
354
+ const records = sentBodies()[0].records.map((record) => ({ ...record, source: 'dev' }));
355
+ const click = records.find((record) => record.kind === 'click');
356
+ expect(click.target).toEqual({
357
+ block_id: 'delete_modal',
358
+ block_type: 'Modal',
359
+ row: null,
360
+ row_key: null,
361
+ column: null,
362
+ control: 'ok',
363
+ text: null,
364
+ nth: null,
365
+ option: false,
366
+ });
367
+ expect(validateTraceRecord({ record: click })).toEqual({});
368
+ expect(formatSessionLog({ records }).lines).toContain('click delete_modal control ok');
369
+ });
@@ -15,8 +15,7 @@
15
15
  */
16
16
 
17
17
  import { type } from '@lowdefy/helpers';
18
-
19
- import readRoutineSteps from './readRoutineSteps.js';
18
+ import { readRoutineSteps } from '@lowdefy/node-utils';
20
19
 
21
20
  // The browser never sees a routine's CallApi, in-process or detached, so the
22
21
  // endpoints a journey reached through one are added from config: every
@@ -17,7 +17,7 @@
17
17
  import addNestedEndpoints from './addNestedEndpoints.js';
18
18
  import addWriteFlags from './addWriteFlags.js';
19
19
  import collectExercised from './collectExercised.js';
20
- import readRoutineSteps from './readRoutineSteps.js';
20
+ import { readRoutineSteps } from '@lowdefy/node-utils';
21
21
  import { expect, test } from 'vitest';
22
22
 
23
23
  function callApi({ id, endpointId, detached }) {
@@ -15,8 +15,7 @@
15
15
  */
16
16
 
17
17
  import { type } from '@lowdefy/helpers';
18
-
19
- import readRoutineSteps from './readRoutineSteps.js';
18
+ import { readRoutineSteps } from '@lowdefy/node-utils';
20
19
 
21
20
  // A request writes when its type declares meta.checkWrite: true. An endpoint
22
21
  // writes when a step of its routine has such a type, or when an endpoint it
@@ -0,0 +1,109 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+
21
+ import { vi, afterAll, expect, test } from 'vitest';
22
+
23
+ // A real Chromium whose renderers exit as they start, so newPage answers `Target crashed` while
24
+ // the browser process stays up and connected. openPage must say the browser crashed, and the next
25
+ // getBrowser must hand out a new browser whose openPage works. The first browser launched runs
26
+ // every renderer through a launcher that exits at once; the ones after it launch as usual.
27
+ // Skipped when no Chromium can be launched, and on Windows, which runs no shell script.
28
+ vi.doMock('../build/config.js', () => ({ default: {} }));
29
+
30
+ let directory = null;
31
+ let deadRenderer = null;
32
+
33
+ const launched = [];
34
+ vi.doMock('playwright-core', async (importOriginal) => {
35
+ const playwright = await importOriginal();
36
+ const chromium = new Proxy(playwright.chromium, {
37
+ get(target, property) {
38
+ if (property !== 'launch') {
39
+ return Reflect.get(target, property, target);
40
+ }
41
+ return async (options = {}) => {
42
+ const args =
43
+ launched.length === 0
44
+ ? [...(options.args ?? []), `--renderer-cmd-prefix=${deadRenderer}`]
45
+ : options.args;
46
+ const browser = await target.launch({ ...options, args });
47
+ launched.push(browser);
48
+ return browser;
49
+ };
50
+ },
51
+ });
52
+ return { ...playwright, chromium };
53
+ });
54
+
55
+ const { getBrowser, openPage } = await import('./getBrowser.js');
56
+
57
+ const origin = 'http://127.0.0.1:4019';
58
+
59
+ let crashing = null;
60
+ if (process.platform !== 'win32') {
61
+ directory = fs.mkdtempSync(path.join(os.tmpdir(), 'lowdefy-browser-crash-'));
62
+ deadRenderer = path.join(directory, 'dead-renderer.sh');
63
+ fs.writeFileSync(deadRenderer, '#!/bin/sh\nexit 1\n', { mode: 0o755 });
64
+ try {
65
+ crashing = await getBrowser({ origin });
66
+ } catch {
67
+ crashing = null;
68
+ }
69
+ }
70
+ // A file whose tests are all skipped runs no afterAll.
71
+ function removeDirectory() {
72
+ if (directory !== null) {
73
+ fs.rmSync(directory, { recursive: true, force: true });
74
+ }
75
+ }
76
+ if (crashing === null) {
77
+ removeDirectory();
78
+ }
79
+ const chromiumTest = crashing === null ? test.skip : test;
80
+
81
+ afterAll(async () => {
82
+ await Promise.all(launched.map((browser) => browser.close().catch(() => {})));
83
+ removeDirectory();
84
+ });
85
+
86
+ chromiumTest(
87
+ 'a browser whose renderers crash is replaced, and the next openPage works',
88
+ async () => {
89
+ // A page-less openPage goes as far as newPage, whose renderer exits as it starts.
90
+ // An Error, so the whole message must match, not only part of it.
91
+ await expect(openPage({ browser: crashing, origin })).rejects.toThrow(
92
+ new Error(
93
+ 'The headless browser crashed (browserContext.newPage: Target crashed); it is relaunched for the next call.'
94
+ )
95
+ );
96
+ expect(crashing.isConnected()).toBe(true);
97
+
98
+ const fresh = await getBrowser({ origin });
99
+ expect(fresh).not.toBe(crashing);
100
+
101
+ const { context, page } = await openPage({ browser: fresh, origin });
102
+ try {
103
+ expect(await page.evaluate(() => 1 + 1)).toBe(2);
104
+ } finally {
105
+ await context.close();
106
+ }
107
+ },
108
+ 10000
109
+ );
@@ -16,12 +16,18 @@
16
16
 
17
17
  import { type } from '@lowdefy/helpers';
18
18
 
19
- // A step of a built endpoint routine. The build gives every step a stepId
20
- // (the id the config wrote; its id becomes the scoped endpoint:<id>:<step>),
21
- // so a node with a string type and stepId is a step, and a control object
22
- // (`:if`, `:try`, ...) or a step's own properties never is.
23
- function isRoutineStep(node) {
24
- return type.isObject(node) && type.isString(node.type) && type.isString(node.stepId);
19
+ // A browser can break while it stays connected: newContext and newPage then
20
+ // answer `Target crashed` on every call. Such a browser is retired, so the
21
+ // next getBrowser() launches a new one, and the call that hit it says so.
22
+ function browserCrashError({ error, browser, lifecycle }) {
23
+ if (!type.isString(error?.message) || !error.message.includes('Target crashed')) {
24
+ return error;
25
+ }
26
+ lifecycle.retire(browser);
27
+ return new Error(
28
+ `The headless browser crashed (${error.message.trim()}); it is relaunched for the next call.`,
29
+ { cause: error }
30
+ );
25
31
  }
26
32
 
27
- export default isRoutineStep;
33
+ export default browserCrashError;
@@ -15,11 +15,10 @@
15
15
  */
16
16
 
17
17
  import { type } from '@lowdefy/helpers';
18
- import { getStepKey, normaliseBlockId } from '@lowdefy/node-utils';
18
+ import { getStepKey, normaliseBlockId, pageBlocks } from '@lowdefy/node-utils';
19
19
 
20
20
  import getPageConfig from './getPageConfig.js';
21
21
  import JourneyStepError from './JourneyStepError.js';
22
- import pageBlocks from './pageBlocks.js';
23
22
  import readBuildArtifact from './readBuildArtifact.js';
24
23
  import readPageArtifact from './readPageArtifact.js';
25
24
 
@@ -160,6 +159,23 @@ function checkEndpointId({ endpointId }) {
160
159
  });
161
160
  }
162
161
 
162
+ // A webhook step posts to an endpoint declared `webhook`; the route answers any other as one that
163
+ // does not exist.
164
+ function checkWebhookId({ endpointId }) {
165
+ const endpoint = readBuildArtifact({ name: `api/${endpointId}.json` });
166
+ if (endpoint === null) {
167
+ checkEndpointId({ endpointId });
168
+ return;
169
+ }
170
+ if (type.isNone(endpoint.webhook) || endpoint.webhook === false) {
171
+ throw unknownReference({
172
+ message: `Endpoint "${endpointId}" is not a webhook endpoint: a webhook step posts to an endpoint declared "webhook". Call it with a "call" step instead.`,
173
+ expected: `a webhook endpoint "${endpointId}"`,
174
+ actual: `endpoint "${endpointId}" declares no "webhook"`,
175
+ });
176
+ }
177
+ }
178
+
163
179
  function checkPageId({ pageId }) {
164
180
  const registry = readBuildArtifact({ name: 'pageRegistry.json' });
165
181
  if (Object.prototype.hasOwnProperty.call(registry, pageId)) {
@@ -242,6 +258,10 @@ async function checkStepReferences({ journey, page, step }) {
242
258
  checkEndpointId({ endpointId: step.call.endpoint });
243
259
  return;
244
260
  }
261
+ if (key === 'webhook') {
262
+ checkWebhookId({ endpointId: step.webhook.endpoint });
263
+ return;
264
+ }
245
265
  if (key === 'request') {
246
266
  checkCallerName({ journey, key, name: step.request.as });
247
267
  const shownPage = await readShownPage({ page });
@@ -22,12 +22,33 @@ import { type } from '@lowdefy/helpers';
22
22
  // context, no launch in flight, and no getBrowser() call for idleTimeout ms.
23
23
  // The last one covers a caller between getBrowser() and its first
24
24
  // newContext, which holds the browser without a context yet.
25
+ //
26
+ // A browser can also break while it stays connected: its newContext or
27
+ // newPage answers `Target crashed` from then on. openPage reports that with
28
+ // retire(browser), and the next getBrowser() launches a new browser. The
29
+ // retired one closes once its last context closes, so calls already running
30
+ // on it end as they would have.
25
31
  function createBrowserLifecycle({ launch, idleTimeout }) {
26
32
  // Cached as a promise so concurrent calls awaiting a launch share it.
27
33
  let browserPromise = null;
34
+ // The browser browserPromise resolved to, null while a launch is in
35
+ // flight, so retire() can tell whether a browser is still the one handed out.
36
+ let currentBrowser = null;
28
37
  let launching = 0;
29
38
  let openContexts = 0;
30
39
  let idleTimer = null;
40
+ // Open contexts per browser with any open, so a retired browser closes when
41
+ // its last one does.
42
+ const contextsByBrowser = new Map();
43
+ const retired = new Set();
44
+
45
+ function closeRetiredIfUnused(browser) {
46
+ if (!retired.has(browser) || contextsByBrowser.has(browser)) {
47
+ return;
48
+ }
49
+ retired.delete(browser);
50
+ browser.close().catch(() => {});
51
+ }
31
52
 
32
53
  function closeIfIdle() {
33
54
  idleTimer = null;
@@ -36,6 +57,7 @@ function createBrowserLifecycle({ launch, idleTimeout }) {
36
57
  }
37
58
  const closing = browserPromise;
38
59
  browserPromise = null;
60
+ currentBrowser = null;
39
61
  closing.then((browser) => browser.close()).catch(() => {});
40
62
  }
41
63
 
@@ -50,7 +72,13 @@ function createBrowserLifecycle({ launch, idleTimeout }) {
50
72
  launching += 1;
51
73
  const launched = launch();
52
74
  browserPromise = launched;
75
+ currentBrowser = null;
53
76
  launched
77
+ .then((browser) => {
78
+ if (browserPromise === launched) {
79
+ currentBrowser = browser;
80
+ }
81
+ })
54
82
  .catch(() => {
55
83
  // Forget a failed launch so the next call retries instead of
56
84
  // replaying the rejection forever.
@@ -84,19 +112,41 @@ function createBrowserLifecycle({ launch, idleTimeout }) {
84
112
  return browserPromise;
85
113
  }
86
114
 
87
- // Counts a context until it closes. Playwright emits close for every way a
88
- // context ends: context.close(), browser.close() or a browser crash.
89
- function trackContext(context) {
115
+ // Stops handing out a browser that is connected but broken. Concurrent
116
+ // callers that hit the same crash share one relaunch: only the first call
117
+ // for the current browser retires it, and a browser already replaced is
118
+ // left alone.
119
+ function retire(browser) {
120
+ if (browser !== currentBrowser) {
121
+ return;
122
+ }
123
+ browserPromise = null;
124
+ currentBrowser = null;
125
+ retired.add(browser);
126
+ closeRetiredIfUnused(browser);
127
+ }
128
+
129
+ // Counts a context of browser until it closes. Playwright emits close for
130
+ // every way a context ends: context.close(), browser.close() or a browser crash.
131
+ function trackContext({ browser, context }) {
90
132
  openContexts += 1;
133
+ contextsByBrowser.set(browser, (contextsByBrowser.get(browser) ?? 0) + 1);
91
134
  context.on('close', () => {
92
135
  openContexts -= 1;
136
+ const left = contextsByBrowser.get(browser) - 1;
137
+ if (left === 0) {
138
+ contextsByBrowser.delete(browser);
139
+ } else {
140
+ contextsByBrowser.set(browser, left);
141
+ }
142
+ closeRetiredIfUnused(browser);
93
143
  if (openContexts === 0) {
94
144
  armIdleClose();
95
145
  }
96
146
  });
97
147
  }
98
148
 
99
- return { getBrowser, trackContext };
149
+ return { getBrowser, retire, trackContext };
100
150
  }
101
151
 
102
152
  export default createBrowserLifecycle;
@@ -104,7 +104,7 @@ test('the browser closes 90 s after the last context closes', async () => {
104
104
 
105
105
  await getBrowser();
106
106
  const context = createContext();
107
- trackContext(context);
107
+ trackContext({ browser, context });
108
108
  vi.advanceTimersByTime(IDLE * 2);
109
109
  await flush();
110
110
  expect(browser.close).not.toHaveBeenCalled();
@@ -147,8 +147,8 @@ test('a context still open keeps the browser open', async () => {
147
147
  await getBrowser();
148
148
  const first = createContext();
149
149
  const second = createContext();
150
- trackContext(first);
151
- trackContext(second);
150
+ trackContext({ browser, context: first });
151
+ trackContext({ browser, context: second });
152
152
  await first.close();
153
153
  vi.advanceTimersByTime(IDLE * 3);
154
154
  await flush();
@@ -226,3 +226,97 @@ test('getBrowser relaunches once for concurrent callers when the browser disconn
226
226
  expect(second).toBe(fresh);
227
227
  expect(launch).toHaveBeenCalledTimes(2);
228
228
  });
229
+
230
+ test('retire hands out a new browser on the next call while the crashed one stays connected', async () => {
231
+ const crashed = createFakeBrowser();
232
+ const fresh = createFakeBrowser();
233
+ const launch = vi.fn().mockResolvedValueOnce(crashed).mockResolvedValueOnce(fresh);
234
+ const { getBrowser, retire } = createBrowserLifecycle({ launch, idleTimeout: IDLE });
235
+
236
+ await getBrowser();
237
+ await flush();
238
+ retire(crashed);
239
+ await flush();
240
+
241
+ expect(crashed.isConnected()).toBe(true);
242
+ expect(crashed.close).toHaveBeenCalledTimes(1);
243
+ expect(await getBrowser()).toBe(fresh);
244
+ expect(launch).toHaveBeenCalledTimes(2);
245
+ });
246
+
247
+ test('concurrent calls that hit the same crash share one relaunch', async () => {
248
+ const crashed = createFakeBrowser();
249
+ const fresh = createFakeBrowser();
250
+ const launch = vi.fn().mockResolvedValueOnce(crashed).mockResolvedValueOnce(fresh);
251
+ const { getBrowser, retire } = createBrowserLifecycle({ launch, idleTimeout: IDLE });
252
+
253
+ await getBrowser();
254
+ await flush();
255
+ retire(crashed);
256
+ const [first, second] = await Promise.all([getBrowser(), getBrowser()]);
257
+ await flush();
258
+ // A late report of the same crash leaves the new browser alone.
259
+ retire(crashed);
260
+
261
+ expect(first).toBe(fresh);
262
+ expect(second).toBe(fresh);
263
+ expect(await getBrowser()).toBe(fresh);
264
+ expect(launch).toHaveBeenCalledTimes(2);
265
+ expect(crashed.close).toHaveBeenCalledTimes(1);
266
+ expect(fresh.close).not.toHaveBeenCalled();
267
+ });
268
+
269
+ test('a retired browser closes once its last open context closes', async () => {
270
+ const crashed = createFakeBrowser();
271
+ const fresh = createFakeBrowser();
272
+ const launch = vi.fn().mockResolvedValueOnce(crashed).mockResolvedValueOnce(fresh);
273
+ const { getBrowser, retire, trackContext } = createBrowserLifecycle({
274
+ launch,
275
+ idleTimeout: IDLE,
276
+ });
277
+
278
+ await getBrowser();
279
+ await flush();
280
+ // A journey still running on the crashed browser.
281
+ const running = createContext();
282
+ trackContext({ browser: crashed, context: running });
283
+ retire(crashed);
284
+ expect(await getBrowser()).toBe(fresh);
285
+ const freshContext = createContext();
286
+ trackContext({ browser: fresh, context: freshContext });
287
+ await flush();
288
+ expect(crashed.close).not.toHaveBeenCalled();
289
+
290
+ await running.close();
291
+ await flush();
292
+
293
+ expect(crashed.close).toHaveBeenCalledTimes(1);
294
+ expect(fresh.close).not.toHaveBeenCalled();
295
+ });
296
+
297
+ test('retire while a relaunch is in flight leaves the relaunch alone', async () => {
298
+ const crashed = createFakeBrowser();
299
+ const fresh = createFakeBrowser();
300
+ let finishLaunch;
301
+ const launch = vi
302
+ .fn()
303
+ .mockResolvedValueOnce(crashed)
304
+ .mockImplementationOnce(
305
+ () =>
306
+ new Promise((resolve) => {
307
+ finishLaunch = () => resolve(fresh);
308
+ })
309
+ );
310
+ const { getBrowser, retire } = createBrowserLifecycle({ launch, idleTimeout: IDLE });
311
+
312
+ await getBrowser();
313
+ await flush();
314
+ retire(crashed);
315
+ const pending = getBrowser();
316
+ retire(crashed);
317
+ finishLaunch();
318
+
319
+ expect(await pending).toBe(fresh);
320
+ expect(await getBrowser()).toBe(fresh);
321
+ expect(launch).toHaveBeenCalledTimes(2);
322
+ });