@fliwright/tdd 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +29 -2
- package/dist/baseline/AppCapabilityResetAdapter.d.ts +6 -0
- package/dist/baseline/AppCapabilityResetAdapter.js +41 -0
- package/dist/baseline/BaselineManager.d.ts +67 -0
- package/dist/baseline/BaselineManager.js +145 -0
- package/dist/baseline/StorageResetAdapter.d.ts +19 -0
- package/dist/baseline/StorageResetAdapter.js +43 -0
- package/dist/daemon/DaemonTransport.d.ts +37 -0
- package/dist/daemon/DaemonTransport.js +1 -0
- package/dist/daemon/FlutterDaemonController.d.ts +20 -0
- package/dist/daemon/FlutterDaemonController.js +120 -0
- package/dist/daemon/FlutterDaemonEndpointSource.d.ts +23 -0
- package/dist/daemon/FlutterDaemonEndpointSource.js +37 -0
- package/dist/daemon/ReloadStrategy.d.ts +28 -0
- package/dist/daemon/ReloadStrategy.js +72 -0
- package/dist/daemon/SubprocessDaemonTransport.d.ts +32 -0
- package/dist/daemon/SubprocessDaemonTransport.js +171 -0
- package/dist/diagnostics/TddFailureContext.d.ts +56 -0
- package/dist/diagnostics/TddFailureContext.js +220 -0
- package/dist/executor/FocusedRerunRecipe.d.ts +7 -0
- package/dist/executor/FocusedRerunRecipe.js +64 -0
- package/dist/executor/PersistentTestExecutor.d.ts +56 -0
- package/dist/executor/PersistentTestExecutor.js +235 -0
- package/dist/executor/TestRunResults.d.ts +13 -0
- package/dist/executor/TestRunResults.js +19 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +13 -0
- package/dist/runtime/TddRuntime.d.ts +73 -0
- package/dist/runtime/TddRuntime.js +552 -0
- package/dist/types.d.ts +139 -0
- package/dist/types.js +2 -0
- package/package.json +42 -3
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import { waitForVmServiceEndpoint, EndpointLeaseManager, FliwrightDriver, VmServiceEndpointResolver, explicitEndpointSource } from '@fliwright/core';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { FlutterDaemonController } from '../daemon/FlutterDaemonController.js';
|
|
5
|
+
import { FlutterDaemonEndpointSource } from '../daemon/FlutterDaemonEndpointSource.js';
|
|
6
|
+
import { SubprocessDaemonTransport } from '../daemon/SubprocessDaemonTransport.js';
|
|
7
|
+
import { decideSync, looksStructuralAfterReload } from '../daemon/ReloadStrategy.js';
|
|
8
|
+
import { PersistentTestExecutor } from '../executor/PersistentTestExecutor.js';
|
|
9
|
+
import { BaselineManager } from '../baseline/BaselineManager.js';
|
|
10
|
+
import { buildTddFailureContext } from '../diagnostics/TddFailureContext.js';
|
|
11
|
+
import { DEFAULT_CYCLE_TIMEOUT_MS } from '../types.js';
|
|
12
|
+
const defaultBaseline = {
|
|
13
|
+
homeRoute: '/',
|
|
14
|
+
resetCategories: ['navigation', 'mock'],
|
|
15
|
+
};
|
|
16
|
+
export class TddRuntime {
|
|
17
|
+
daemon;
|
|
18
|
+
executor;
|
|
19
|
+
driverFactory;
|
|
20
|
+
injectedBaseline;
|
|
21
|
+
baseline;
|
|
22
|
+
driver;
|
|
23
|
+
app;
|
|
24
|
+
vmServiceUrl;
|
|
25
|
+
configRoot;
|
|
26
|
+
sharedConfig;
|
|
27
|
+
startAppParams;
|
|
28
|
+
defaultScenarioName;
|
|
29
|
+
baselineConfig = defaultBaseline;
|
|
30
|
+
focusedTest;
|
|
31
|
+
lastResult;
|
|
32
|
+
started = false;
|
|
33
|
+
launchMode = 'attach';
|
|
34
|
+
driverConnections = 0;
|
|
35
|
+
startSignature;
|
|
36
|
+
updatedAtMs = Date.now();
|
|
37
|
+
// Serializes runtime/app state mutations (design §8: only one operation at a time). This covers
|
|
38
|
+
// cycle(), manual sync, scenario updates, reconnect, and stop so an agent cannot reload/restart or
|
|
39
|
+
// swap baselines mid-rerun.
|
|
40
|
+
endpointLeases = new EndpointLeaseManager();
|
|
41
|
+
operationChain = Promise.resolve();
|
|
42
|
+
statusFilePath;
|
|
43
|
+
// Serializes best-effort status-file writes so concurrent snapshots never interleave bytes.
|
|
44
|
+
statusWriteChain = Promise.resolve();
|
|
45
|
+
constructor(deps = {}) {
|
|
46
|
+
this.daemon = deps.daemon ?? new FlutterDaemonController(new SubprocessDaemonTransport());
|
|
47
|
+
this.executor = deps.executor ?? new PersistentTestExecutor();
|
|
48
|
+
this.driverFactory = deps.driverFactory ?? (() => new FliwrightDriver({
|
|
49
|
+
cacheRoot: this.sharedConfig?.cacheRoot,
|
|
50
|
+
projectRoot: this.configRoot && (/\.[cm]?[jt]s$/.test(this.configRoot) ? dirname(this.configRoot) : this.configRoot),
|
|
51
|
+
}));
|
|
52
|
+
this.injectedBaseline = deps.baseline;
|
|
53
|
+
this.baseline = deps.baseline;
|
|
54
|
+
}
|
|
55
|
+
async start(opts) {
|
|
56
|
+
const startSignature = startOptsSignature(opts);
|
|
57
|
+
if (this.started) {
|
|
58
|
+
if (this.startSignature !== startSignature) {
|
|
59
|
+
throw new Error('TddRuntime is already started with different options. Stop it before reconfiguring.');
|
|
60
|
+
}
|
|
61
|
+
return this.snapshot();
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
this.baselineConfig = opts.baselineConfig ?? defaultBaseline;
|
|
65
|
+
this.launchMode = opts.launchMode ?? (opts.app ? 'start' : 'attach');
|
|
66
|
+
this.startSignature = startSignature;
|
|
67
|
+
this.configRoot = opts.configRoot;
|
|
68
|
+
this.sharedConfig = opts.sharedConfig;
|
|
69
|
+
this.startAppParams = opts.app;
|
|
70
|
+
this.statusFilePath = opts.statusFilePath;
|
|
71
|
+
let vmServiceUrl = opts.vmServiceUrl;
|
|
72
|
+
if (opts.app) {
|
|
73
|
+
await this.daemon.start();
|
|
74
|
+
const source = new FlutterDaemonEndpointSource({ controller: this.daemon, ...opts.app });
|
|
75
|
+
const endpoint = await source.acquire();
|
|
76
|
+
this.app = source.lastApp;
|
|
77
|
+
vmServiceUrl = endpoint.url;
|
|
78
|
+
this.launchMode = 'start';
|
|
79
|
+
}
|
|
80
|
+
if (!vmServiceUrl) {
|
|
81
|
+
throw new Error('TddRuntime.start requires either app start params or vmServiceUrl.');
|
|
82
|
+
}
|
|
83
|
+
this.vmServiceUrl = vmServiceUrl;
|
|
84
|
+
this.defaultScenarioName = opts.defaultScenario;
|
|
85
|
+
this.driver = this.driverFactory();
|
|
86
|
+
await this.verifyManagedEndpoint(vmServiceUrl);
|
|
87
|
+
await this.driver.connect(vmServiceUrl);
|
|
88
|
+
this.driverConnections += 1;
|
|
89
|
+
this.baseline = this.baseline ?? this.injectedBaseline ?? new BaselineManager(this.driver);
|
|
90
|
+
await this.executor.boot({ sharedConfig: this.sharedConfig, scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach',
|
|
91
|
+
defaultScenario: opts.defaultScenario,
|
|
92
|
+
configRoot: opts.configRoot,
|
|
93
|
+
vmServiceUrl,
|
|
94
|
+
});
|
|
95
|
+
this.started = true;
|
|
96
|
+
this.markUpdated();
|
|
97
|
+
this.persistStatus();
|
|
98
|
+
return this.snapshot();
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
await this.executor.dispose().catch(() => undefined);
|
|
102
|
+
await this.cleanupStartedResources().catch(() => undefined);
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Interrupt owned transports/execution; the operation chain still drains before reuse. */
|
|
107
|
+
async cancel() {
|
|
108
|
+
await Promise.allSettled([
|
|
109
|
+
this.driver?.dispose({ signal: AbortSignal.abort() }),
|
|
110
|
+
this.executor.dispose(),
|
|
111
|
+
this.daemon.dispose(),
|
|
112
|
+
]);
|
|
113
|
+
}
|
|
114
|
+
/** Wait for real work, including a cycle whose caller already received timeout. */
|
|
115
|
+
async whenIdle() { await this.operationChain; }
|
|
116
|
+
async focus(file, testName) {
|
|
117
|
+
this.focusedTest = { file, testName };
|
|
118
|
+
this.markUpdated();
|
|
119
|
+
this.persistStatus();
|
|
120
|
+
}
|
|
121
|
+
/** Select the named scenario that Vitest fixtures prepare before every attempt. */
|
|
122
|
+
async setDefaultScenario(name) {
|
|
123
|
+
return this.enqueueOperation(async () => {
|
|
124
|
+
if (!this.started)
|
|
125
|
+
throw new Error('TddRuntime is not started.');
|
|
126
|
+
await this.executor.dispose();
|
|
127
|
+
await this.executor.boot({ sharedConfig: this.sharedConfig,
|
|
128
|
+
scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach',
|
|
129
|
+
configRoot: this.configRoot, vmServiceUrl: this.vmServiceUrl, defaultScenario: name });
|
|
130
|
+
this.defaultScenarioName = name;
|
|
131
|
+
this.markUpdated();
|
|
132
|
+
this.persistStatus();
|
|
133
|
+
return this.snapshot();
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
async setBaselineConfig(config) {
|
|
137
|
+
return await this.enqueueOperation(async () => {
|
|
138
|
+
this.baselineConfig = config;
|
|
139
|
+
this.markUpdated();
|
|
140
|
+
this.persistStatus();
|
|
141
|
+
return this.snapshot();
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
async syncApp(sync) {
|
|
145
|
+
return await this.enqueueOperation(async () => {
|
|
146
|
+
if (!this.started)
|
|
147
|
+
throw new Error('TddRuntime is not started.');
|
|
148
|
+
const lastSync = await this.controlPhase(() => this.sync(sync));
|
|
149
|
+
this.markUpdated();
|
|
150
|
+
this.persistStatus();
|
|
151
|
+
return {
|
|
152
|
+
lastSync,
|
|
153
|
+
snapshot: this.snapshot(),
|
|
154
|
+
};
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
async cycle(testName, opts = {}) {
|
|
158
|
+
// Serialize overlapping cycles (design §8): each cycle runs to completion before the next starts.
|
|
159
|
+
// The caller's promise (deferred) is resolved separately so a timeout can return early, while the
|
|
160
|
+
// chain task keeps awaiting the real body — guaranteeing the single-threaded executor is never
|
|
161
|
+
// overlapped by the next cycle even after a timeout.
|
|
162
|
+
const deferred = makeDeferred();
|
|
163
|
+
const task = () => this.runCycleWithEscalation(testName, opts, deferred);
|
|
164
|
+
const run = this.operationChain.then(task, task);
|
|
165
|
+
this.operationChain = run.then(noop, noop);
|
|
166
|
+
return deferred.promise;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Reconnect after a VM disconnect (design §8). Daemon-start relaunches the app and rebinds to the
|
|
170
|
+
* fresh VM service; attach retries the original URL. If the URL changed, the executor is rebooted
|
|
171
|
+
* so fixtures pick up the new `FLIWRIGHT_VM_SERVICE_URL`. Throws on failure; the caller surfaces a
|
|
172
|
+
* structured error. Awaited on the cycle chain so it never races an in-flight rerun.
|
|
173
|
+
*/
|
|
174
|
+
async reconnect() {
|
|
175
|
+
return await this.enqueueOperation(async () => this.reconnectNow());
|
|
176
|
+
}
|
|
177
|
+
async reconnectNow() {
|
|
178
|
+
if (!this.started)
|
|
179
|
+
throw new Error('TddRuntime is not started; nothing to reconnect.');
|
|
180
|
+
await this.driver?.dispose().catch(() => undefined);
|
|
181
|
+
this.driver = undefined;
|
|
182
|
+
let vmServiceUrl = this.vmServiceUrl;
|
|
183
|
+
if (this.startAppParams) {
|
|
184
|
+
await this.daemon.start().catch(() => undefined);
|
|
185
|
+
const source = new FlutterDaemonEndpointSource({ controller: this.daemon, ...this.startAppParams });
|
|
186
|
+
const endpoint = await source.acquire();
|
|
187
|
+
this.app = source.lastApp;
|
|
188
|
+
vmServiceUrl = endpoint.url;
|
|
189
|
+
}
|
|
190
|
+
if (!vmServiceUrl)
|
|
191
|
+
throw new Error('Cannot reconnect: no VM service URL is available.');
|
|
192
|
+
const urlChanged = vmServiceUrl !== this.vmServiceUrl;
|
|
193
|
+
this.vmServiceUrl = vmServiceUrl;
|
|
194
|
+
if (urlChanged && this.configRoot) {
|
|
195
|
+
// Fixtures read FLIWRIGHT_VM_SERVICE_URL at run time; reboot so the new URL propagates.
|
|
196
|
+
await this.executor.dispose().catch(() => undefined);
|
|
197
|
+
await this.executor.boot({ sharedConfig: this.sharedConfig, scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach',
|
|
198
|
+
configRoot: this.configRoot,
|
|
199
|
+
defaultScenario: this.defaultScenarioName,
|
|
200
|
+
vmServiceUrl,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
this.driver = this.driverFactory();
|
|
204
|
+
await this.verifyManagedEndpoint(vmServiceUrl);
|
|
205
|
+
await this.driver.connect(vmServiceUrl);
|
|
206
|
+
this.driverConnections += 1;
|
|
207
|
+
this.baseline = this.injectedBaseline ?? new BaselineManager(this.driver);
|
|
208
|
+
this.markUpdated();
|
|
209
|
+
this.persistStatus();
|
|
210
|
+
return this.snapshot();
|
|
211
|
+
}
|
|
212
|
+
async verifyManagedEndpoint(vmServiceUrl) {
|
|
213
|
+
if (!(this.driver instanceof FliwrightDriver))
|
|
214
|
+
return;
|
|
215
|
+
if (this.launchMode === 'start')
|
|
216
|
+
await waitForVmServiceEndpoint({ url: vmServiceUrl, kind: 'direct-vm', source: 'managed-launch', scope: 'execution-worker', acquiredAt: new Date().toISOString() });
|
|
217
|
+
await new VmServiceEndpointResolver([
|
|
218
|
+
explicitEndpointSource(vmServiceUrl, { source: 'flutter-daemon', scope: 'execution-worker' }),
|
|
219
|
+
], { persistWorkspaceCache: false }).acquire();
|
|
220
|
+
}
|
|
221
|
+
async runCycleWithEscalation(testName, opts, deferred) {
|
|
222
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_CYCLE_TIMEOUT_MS;
|
|
223
|
+
const deadline = new AbortController();
|
|
224
|
+
const attempts = [];
|
|
225
|
+
const requestedSync = opts.sync === 'auto' ? decideSync(opts.changes) : opts.sync ?? 'none';
|
|
226
|
+
const runAll = async () => {
|
|
227
|
+
const first = await this.performCycle(testName, requestedSync, opts.fullReset, deadline.signal);
|
|
228
|
+
attempts.push({ ...first, requestedSync });
|
|
229
|
+
deadline.signal.throwIfAborted();
|
|
230
|
+
if ((opts.autoEscalate ?? true) && looksStructuralAfterReload(first) && this.canRestart()) {
|
|
231
|
+
const retryStartedAt = Date.now();
|
|
232
|
+
try {
|
|
233
|
+
const escalated = await this.performCycle(testName, 'restart', true, deadline.signal);
|
|
234
|
+
attempts.push({ ...escalated, requestedSync: 'restart' });
|
|
235
|
+
if (escalated.lastSync === 'restart')
|
|
236
|
+
return { ...escalated, attempts, syncEscalated: true };
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
deadline.signal.throwIfAborted();
|
|
240
|
+
// Keep the first result as the primary failure if the retry cannot produce a test result.
|
|
241
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
242
|
+
attempts.push({
|
|
243
|
+
status: 'red', file: first.file, testName: first.testName, durationMs: Date.now() - retryStartedAt,
|
|
244
|
+
requestedSync: 'restart', lastSync: 'restart', baselineVersion: this.baseline?.version ?? first.baselineVersion,
|
|
245
|
+
failure: { message },
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return { ...first, attempts };
|
|
250
|
+
};
|
|
251
|
+
// Resolve the caller early. Keep the queue occupied until the active stage finishes.
|
|
252
|
+
let timeoutResult;
|
|
253
|
+
const timer = setTimeout(() => {
|
|
254
|
+
deadline.abort();
|
|
255
|
+
timeoutResult = { ...this.timeoutResult(testName, timeoutMs), attempts: attempts.slice() };
|
|
256
|
+
this.lastResult = timeoutResult;
|
|
257
|
+
this.markUpdated();
|
|
258
|
+
this.persistStatus();
|
|
259
|
+
deferred.resolve(timeoutResult);
|
|
260
|
+
}, timeoutMs);
|
|
261
|
+
try {
|
|
262
|
+
const result = await runAll();
|
|
263
|
+
deadline.signal.throwIfAborted();
|
|
264
|
+
this.lastResult = result;
|
|
265
|
+
this.markUpdated();
|
|
266
|
+
this.persistStatus();
|
|
267
|
+
deferred.resolve(result);
|
|
268
|
+
return result;
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
if (timeoutResult) {
|
|
272
|
+
if (timeoutResult.attempts?.length !== attempts.length) {
|
|
273
|
+
timeoutResult = { ...timeoutResult, attempts };
|
|
274
|
+
this.lastResult = timeoutResult;
|
|
275
|
+
this.markUpdated();
|
|
276
|
+
this.persistStatus();
|
|
277
|
+
}
|
|
278
|
+
return timeoutResult;
|
|
279
|
+
}
|
|
280
|
+
deferred.reject(error);
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
clearTimeout(timer);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
timeoutResult(testName, timeoutMs) {
|
|
288
|
+
const focused = this.focusedTest;
|
|
289
|
+
const file = focused?.file ?? '<unknown>';
|
|
290
|
+
const actualName = testName ?? focused?.testName;
|
|
291
|
+
const baselineVersion = this.baseline?.version ?? 0;
|
|
292
|
+
const message = `TDD cycle exceeded the ${timeoutMs}ms budget and was returned as a timeout.`;
|
|
293
|
+
return {
|
|
294
|
+
status: 'red',
|
|
295
|
+
testName: actualName,
|
|
296
|
+
file,
|
|
297
|
+
durationMs: timeoutMs,
|
|
298
|
+
lastSync: 'none',
|
|
299
|
+
baselineVersion,
|
|
300
|
+
failure: { message },
|
|
301
|
+
failureContext: buildTddFailureContext({
|
|
302
|
+
file,
|
|
303
|
+
testName: actualName,
|
|
304
|
+
message,
|
|
305
|
+
kind: 'timeout',
|
|
306
|
+
baselineVersion,
|
|
307
|
+
}),
|
|
308
|
+
unsupportedState: undefined,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
async performCycle(testName, requestedSync, fullReset, deadline) {
|
|
312
|
+
if (!this.started)
|
|
313
|
+
throw new Error('TddRuntime is not started.');
|
|
314
|
+
const focused = this.focusedTest;
|
|
315
|
+
if (!focused)
|
|
316
|
+
throw new Error('No focused test. Call focus(file, testName) before cycle().');
|
|
317
|
+
const actualTestName = testName ?? focused.testName;
|
|
318
|
+
const startedAt = Date.now();
|
|
319
|
+
let lastSync = 'none';
|
|
320
|
+
try {
|
|
321
|
+
lastSync = await this.controlPhase(() => {
|
|
322
|
+
deadline.throwIfAborted();
|
|
323
|
+
return this.sync(requestedSync);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
deadline.throwIfAborted();
|
|
328
|
+
const baselineVersion = this.baseline?.version ?? 0;
|
|
329
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
330
|
+
return {
|
|
331
|
+
status: 'red',
|
|
332
|
+
testName: actualTestName,
|
|
333
|
+
file: focused.file,
|
|
334
|
+
durationMs: Date.now() - startedAt,
|
|
335
|
+
lastSync,
|
|
336
|
+
baselineVersion,
|
|
337
|
+
failure: { message },
|
|
338
|
+
failureContext: buildTddFailureContext({
|
|
339
|
+
file: focused.file,
|
|
340
|
+
testName: actualTestName,
|
|
341
|
+
message,
|
|
342
|
+
kind: 'test-error',
|
|
343
|
+
lastSync,
|
|
344
|
+
baselineVersion,
|
|
345
|
+
}),
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
deadline.throwIfAborted();
|
|
349
|
+
const resetReport = this.defaultScenarioName
|
|
350
|
+
? { version: this.requireBaseline().version, unsupported: [] }
|
|
351
|
+
: await this.controlPhase(() => {
|
|
352
|
+
deadline.throwIfAborted();
|
|
353
|
+
return this.requireBaseline().reset(this.baselineConfig, { full: fullReset ?? lastSync === 'restart' });
|
|
354
|
+
});
|
|
355
|
+
deadline.throwIfAborted();
|
|
356
|
+
const outcome = await this.executor.rerun(focused.file, actualTestName);
|
|
357
|
+
const unsupportedState = resetReport.unsupported;
|
|
358
|
+
const failureContext = outcome.status === 'red'
|
|
359
|
+
? buildTddFailureContext({
|
|
360
|
+
file: focused.file,
|
|
361
|
+
testName: outcome.testName ?? actualTestName,
|
|
362
|
+
message: outcome.failure?.message,
|
|
363
|
+
lastSync,
|
|
364
|
+
baselineVersion: resetReport.version,
|
|
365
|
+
unsupportedState,
|
|
366
|
+
source: outcome.failureDetails?.source,
|
|
367
|
+
assertion: outcome.failureDetails?.assertion,
|
|
368
|
+
artifacts: outcome.failureDetails?.artifacts,
|
|
369
|
+
})
|
|
370
|
+
: undefined;
|
|
371
|
+
return {
|
|
372
|
+
status: outcome.status,
|
|
373
|
+
testName: outcome.testName ?? actualTestName,
|
|
374
|
+
file: focused.file,
|
|
375
|
+
durationMs: Date.now() - startedAt,
|
|
376
|
+
lastSync,
|
|
377
|
+
baselineVersion: resetReport.version,
|
|
378
|
+
failure: outcome.failure,
|
|
379
|
+
failureContext,
|
|
380
|
+
timelinePath: outcome.timelinePath ?? outcome.failureDetails?.artifacts?.timelinePath,
|
|
381
|
+
timelineNodeId: outcome.timelineNodeId ?? outcome.failureDetails?.artifacts?.timelineNodeId,
|
|
382
|
+
unsupportedState,
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Best-effort, non-blocking dump of {@link snapshot} to {@link statusFilePath}, serialized so
|
|
387
|
+
* concurrent writes never interleave. Read-only monitors (VS Code TDD Loop panel) poll this file
|
|
388
|
+
* instead of opening a second driver connection. Never throws; failures are swallowed.
|
|
389
|
+
*/
|
|
390
|
+
persistStatus() {
|
|
391
|
+
this.persistStatusTo(this.statusFilePath);
|
|
392
|
+
}
|
|
393
|
+
persistStatusTo(statusFilePath) {
|
|
394
|
+
if (!statusFilePath)
|
|
395
|
+
return;
|
|
396
|
+
const snapshot = this.snapshot();
|
|
397
|
+
this.statusWriteChain = this.statusWriteChain.then(async () => {
|
|
398
|
+
try {
|
|
399
|
+
await mkdir(dirname(statusFilePath), { recursive: true });
|
|
400
|
+
await writeFile(statusFilePath, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
/* best-effort: a missing status file just means the monitor shows "no snapshot" */
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/** Current endpoint for an owning CLI host; changes after managed reconnect. */
|
|
408
|
+
get endpoint() { return this.vmServiceUrl; }
|
|
409
|
+
snapshot() {
|
|
410
|
+
return {
|
|
411
|
+
connected: this.started,
|
|
412
|
+
daemonStatus: this.started ? 'running' : 'stopped',
|
|
413
|
+
appId: this.app?.appId,
|
|
414
|
+
supportsRestart: this.started ? (this.app?.supportsRestart ?? false) : false,
|
|
415
|
+
launchMode: this.launchMode,
|
|
416
|
+
restartCapable: this.launchMode === 'start' && (this.app?.supportsRestart ?? false),
|
|
417
|
+
driverConnections: this.driverConnections,
|
|
418
|
+
fixtureDriverSharing: 'vm-service-url',
|
|
419
|
+
notes: [
|
|
420
|
+
'Vitest 5.0.5 runs tests in worker processes, so live FliwrightDriver objects are not shared across the executor boundary.',
|
|
421
|
+
'The TDD runtime injects FLIWRIGHT_VM_SERVICE_URL so fixtures connect to the same app VM service.',
|
|
422
|
+
],
|
|
423
|
+
focusedTest: this.focusedTest,
|
|
424
|
+
lastResult: this.lastResult,
|
|
425
|
+
baselineVersion: this.baseline?.version ?? 0,
|
|
426
|
+
unsupportedState: this.lastResult?.unsupportedState,
|
|
427
|
+
updatedAtMs: this.updatedAtMs,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
async stop(opts = {}) {
|
|
431
|
+
await this.enqueueOperation(async () => {
|
|
432
|
+
const statusFilePath = this.statusFilePath;
|
|
433
|
+
try {
|
|
434
|
+
await this.executor.dispose();
|
|
435
|
+
}
|
|
436
|
+
finally {
|
|
437
|
+
await this.cleanupStartedResources(opts);
|
|
438
|
+
}
|
|
439
|
+
// Publish a final "stopped" snapshot so monitors reflect the halted runtime.
|
|
440
|
+
this.markUpdated();
|
|
441
|
+
this.persistStatusTo(statusFilePath);
|
|
442
|
+
await this.statusWriteChain;
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
markUpdated() {
|
|
446
|
+
this.updatedAtMs = Date.now();
|
|
447
|
+
}
|
|
448
|
+
enqueueOperation(task) {
|
|
449
|
+
const run = this.operationChain.then(task, task);
|
|
450
|
+
this.operationChain = run.then(noop, noop);
|
|
451
|
+
return run;
|
|
452
|
+
}
|
|
453
|
+
async controlPhase(work) {
|
|
454
|
+
return this.vmServiceUrl ? this.endpointLeases.run(this.vmServiceUrl, work) : work();
|
|
455
|
+
}
|
|
456
|
+
async sync(sync) {
|
|
457
|
+
if (sync === 'none')
|
|
458
|
+
return 'none';
|
|
459
|
+
if (!this.app) {
|
|
460
|
+
if (sync === 'restart')
|
|
461
|
+
throw new Error('Hot restart requires a daemon-started app.');
|
|
462
|
+
const driver = this.requireDriver();
|
|
463
|
+
if (!driver.reloadSources)
|
|
464
|
+
throw new Error('Connected driver does not support hot reload.');
|
|
465
|
+
await driver.reloadSources();
|
|
466
|
+
return 'reload';
|
|
467
|
+
}
|
|
468
|
+
if (sync === 'reload') {
|
|
469
|
+
await this.daemon.reload(this.app.appId);
|
|
470
|
+
return 'reload';
|
|
471
|
+
}
|
|
472
|
+
await this.daemon.restart(this.app.appId);
|
|
473
|
+
return 'restart';
|
|
474
|
+
}
|
|
475
|
+
/** True only when a daemon-started app advertised restart support (gates auto-escalation). */
|
|
476
|
+
canRestart() {
|
|
477
|
+
return this.launchMode === 'start' && (this.app?.supportsRestart ?? false);
|
|
478
|
+
}
|
|
479
|
+
requireDriver() {
|
|
480
|
+
if (!this.driver)
|
|
481
|
+
throw new Error('TddRuntime driver is not connected.');
|
|
482
|
+
return this.driver;
|
|
483
|
+
}
|
|
484
|
+
requireBaseline() {
|
|
485
|
+
if (!this.baseline)
|
|
486
|
+
throw new Error('TddRuntime baseline is not initialized.');
|
|
487
|
+
return this.baseline;
|
|
488
|
+
}
|
|
489
|
+
async cleanupStartedResources(opts = {}) {
|
|
490
|
+
try {
|
|
491
|
+
await this.driver?.dispose();
|
|
492
|
+
}
|
|
493
|
+
finally {
|
|
494
|
+
try {
|
|
495
|
+
if (!opts.keepAppAlive && this.app)
|
|
496
|
+
await this.daemon.stop(this.app.appId);
|
|
497
|
+
}
|
|
498
|
+
finally {
|
|
499
|
+
try {
|
|
500
|
+
await this.daemon.dispose(opts);
|
|
501
|
+
}
|
|
502
|
+
finally {
|
|
503
|
+
this.driver = undefined;
|
|
504
|
+
this.app = undefined;
|
|
505
|
+
this.vmServiceUrl = undefined;
|
|
506
|
+
this.configRoot = undefined;
|
|
507
|
+
this.sharedConfig = undefined;
|
|
508
|
+
this.defaultScenarioName = undefined;
|
|
509
|
+
this.startAppParams = undefined;
|
|
510
|
+
this.baseline = undefined;
|
|
511
|
+
this.focusedTest = undefined;
|
|
512
|
+
this.lastResult = undefined;
|
|
513
|
+
this.startSignature = undefined;
|
|
514
|
+
this.launchMode = 'attach';
|
|
515
|
+
this.started = false;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
function startOptsSignature(opts) {
|
|
522
|
+
return JSON.stringify({
|
|
523
|
+
app: opts.app
|
|
524
|
+
? {
|
|
525
|
+
deviceId: opts.app.deviceId,
|
|
526
|
+
flutterArgs: opts.app.flutterArgs,
|
|
527
|
+
mode: opts.app.mode,
|
|
528
|
+
projectId: opts.app.projectId,
|
|
529
|
+
target: opts.app.target ?? 'lib/main.dart',
|
|
530
|
+
}
|
|
531
|
+
: undefined,
|
|
532
|
+
configRoot: opts.configRoot,
|
|
533
|
+
sharedConfig: opts.sharedConfig,
|
|
534
|
+
launchMode: opts.launchMode ?? (opts.app ? 'start' : 'attach'),
|
|
535
|
+
baselineConfig: opts.baselineConfig ?? defaultBaseline,
|
|
536
|
+
defaultScenario: opts.defaultScenario,
|
|
537
|
+
statusFilePath: opts.statusFilePath,
|
|
538
|
+
vmServiceUrl: opts.vmServiceUrl,
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
function noop() {
|
|
542
|
+
/* chain keeper: swallows task rejections so the mutex never wedges */
|
|
543
|
+
}
|
|
544
|
+
function makeDeferred() {
|
|
545
|
+
let resolve;
|
|
546
|
+
let reject;
|
|
547
|
+
const promise = new Promise((res, rej) => {
|
|
548
|
+
resolve = res;
|
|
549
|
+
reject = rej;
|
|
550
|
+
});
|
|
551
|
+
return { promise, resolve, reject };
|
|
552
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { PersistentTestExecutor } from './executor/PersistentTestExecutor.js';
|
|
2
|
+
import type { ResetContext } from './baseline/BaselineManager.js';
|
|
3
|
+
import type { AppHandle, AppStartParams } from './daemon/DaemonTransport.js';
|
|
4
|
+
import type { TddFailureContext } from './diagnostics/TddFailureContext.js';
|
|
5
|
+
export type ResetCategory = 'navigation' | 'riverpod' | 'mock' | 'storage' | 'secureStorage' | 'authTokens' | 'webview' | 'localDb' | 'timers' | 'isolates' | 'permissions';
|
|
6
|
+
/** Low-level reset options. Business setup uses a named TestScenario via defaultScenario. */
|
|
7
|
+
export interface BaselineConfig {
|
|
8
|
+
homeRoute: string;
|
|
9
|
+
resetCategories: ResetCategory[];
|
|
10
|
+
riverpodOverrides?: unknown[];
|
|
11
|
+
mockProfile?: string;
|
|
12
|
+
mockDir?: string;
|
|
13
|
+
storageSeed?: Record<string, unknown>;
|
|
14
|
+
}
|
|
15
|
+
export interface ResetAdapterResult {
|
|
16
|
+
category: ResetCategory;
|
|
17
|
+
status: 'ok' | 'skipped' | 'unsupported';
|
|
18
|
+
message?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface ResetReport {
|
|
21
|
+
version: number;
|
|
22
|
+
full: boolean;
|
|
23
|
+
results: ResetAdapterResult[];
|
|
24
|
+
unsupported: ResetCategory[];
|
|
25
|
+
}
|
|
26
|
+
export interface RuntimeSnapshot {
|
|
27
|
+
connected: boolean;
|
|
28
|
+
daemonStatus: 'running' | 'stopped' | 'unknown';
|
|
29
|
+
appId?: string;
|
|
30
|
+
supportsRestart: boolean;
|
|
31
|
+
launchMode: 'start' | 'attach';
|
|
32
|
+
restartCapable: boolean;
|
|
33
|
+
driverConnections: number;
|
|
34
|
+
fixtureDriverSharing: 'vm-service-url';
|
|
35
|
+
notes?: string[];
|
|
36
|
+
focusedTest?: {
|
|
37
|
+
file: string;
|
|
38
|
+
testName?: string;
|
|
39
|
+
};
|
|
40
|
+
lastResult?: TddCycleResult;
|
|
41
|
+
baselineVersion: number;
|
|
42
|
+
unsupportedState?: ResetCategory[];
|
|
43
|
+
updatedAtMs?: number;
|
|
44
|
+
}
|
|
45
|
+
export interface StartOpts {
|
|
46
|
+
sharedConfig?: Partial<import('@fliwright/core').FliwrightProjectConfig>;
|
|
47
|
+
app?: AppStartParams;
|
|
48
|
+
vmServiceUrl?: string;
|
|
49
|
+
configRoot: string;
|
|
50
|
+
launchMode?: 'start' | 'attach';
|
|
51
|
+
baselineConfig?: BaselineConfig;
|
|
52
|
+
defaultScenario?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Optional path the runtime writes its {@link RuntimeSnapshot} to after each state change
|
|
55
|
+
* (start/focus/cycle/reconnect/stop), as a best-effort, non-blocking JSON dump. Lets read-only
|
|
56
|
+
* monitors (e.g. the VS Code TDD Loop panel) observe the loop without a second driver connection.
|
|
57
|
+
* Defaults to `~/.fliwright/<project-path>/runtime/tdd-status.json` when set by the CLI layer.
|
|
58
|
+
*/
|
|
59
|
+
statusFilePath?: string;
|
|
60
|
+
}
|
|
61
|
+
export interface CycleOpts {
|
|
62
|
+
/** How to sync the app before this cycle. `'auto'` decides from {@link changes} (design §6.4). */
|
|
63
|
+
sync?: 'none' | 'reload' | 'restart' | 'auto';
|
|
64
|
+
fullReset?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* File paths changed since the last sync. Used only when {@link sync} is `'auto'` to choose
|
|
67
|
+
* reload vs restart via `decideSync`. Ignored for explicit sync levels.
|
|
68
|
+
*/
|
|
69
|
+
changes?: string[];
|
|
70
|
+
/**
|
|
71
|
+
* When true (default), a `reload` cycle that fails with a structural-looking error is retried
|
|
72
|
+
* once with a hot restart + full reset, if the runtime can restart. Set false to keep the raw
|
|
73
|
+
* reload result. Design §6.4 fallback-escalation rule.
|
|
74
|
+
*/
|
|
75
|
+
autoEscalate?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Per-cycle wall-clock budget (ms) covering sync + reset + rerun. On expiry the caller receives a
|
|
78
|
+
* red `timeout` result immediately, but the in-flight body is allowed to finish so the next cycle
|
|
79
|
+
* never overlaps the single-threaded executor. Design §8 Timeout. Default {@link DEFAULT_CYCLE_TIMEOUT_MS}.
|
|
80
|
+
*/
|
|
81
|
+
timeoutMs?: number;
|
|
82
|
+
}
|
|
83
|
+
/** Default per-cycle timeout (design §8). Generous: real reruns are sub-second; restarts are seconds. */
|
|
84
|
+
export declare const DEFAULT_CYCLE_TIMEOUT_MS = 60000;
|
|
85
|
+
export interface TddCycleResult {
|
|
86
|
+
status: 'red' | 'green';
|
|
87
|
+
testName?: string;
|
|
88
|
+
file: string;
|
|
89
|
+
durationMs: number;
|
|
90
|
+
lastSync: 'reload' | 'restart' | 'none';
|
|
91
|
+
/** True only when an automatic reload failure retry escalated this cycle to one restart. */
|
|
92
|
+
syncEscalated?: boolean;
|
|
93
|
+
/** Ordered results for the completed attempts in this cycle, including failed restart retries. */
|
|
94
|
+
attempts?: TddCycleAttempt[];
|
|
95
|
+
baselineVersion: number;
|
|
96
|
+
failure?: {
|
|
97
|
+
message?: string;
|
|
98
|
+
};
|
|
99
|
+
failureContext?: TddFailureContext;
|
|
100
|
+
/** Existing per-test timeline produced by @fliwright/vitest, available for both red and green runs. */
|
|
101
|
+
timelinePath?: string;
|
|
102
|
+
timelineNodeId?: string;
|
|
103
|
+
unsupportedState?: ResetCategory[];
|
|
104
|
+
}
|
|
105
|
+
export interface TddCycleAttempt extends Omit<TddCycleResult, 'attempts' | 'syncEscalated'> {
|
|
106
|
+
/** Resolved sync mode requested for this attempt. `lastSync` records the confirmed mode. */
|
|
107
|
+
requestedSync: TddCycleResult['lastSync'];
|
|
108
|
+
}
|
|
109
|
+
export interface TddSyncResult {
|
|
110
|
+
lastSync: TddCycleResult['lastSync'];
|
|
111
|
+
snapshot: RuntimeSnapshot;
|
|
112
|
+
}
|
|
113
|
+
export interface TddRuntimeDeps {
|
|
114
|
+
daemon?: {
|
|
115
|
+
start(): Promise<void>;
|
|
116
|
+
startApp(params: AppStartParams): Promise<AppHandle>;
|
|
117
|
+
reload(appId: string): Promise<void>;
|
|
118
|
+
restart(appId: string): Promise<void>;
|
|
119
|
+
stop(appId: string): Promise<void>;
|
|
120
|
+
dispose(options?: {
|
|
121
|
+
keepAppAlive?: boolean;
|
|
122
|
+
}): Promise<void>;
|
|
123
|
+
};
|
|
124
|
+
executor?: Pick<PersistentTestExecutor, 'boot' | 'rerun' | 'dispose'>;
|
|
125
|
+
driverFactory?: () => ResetContext['driver'] & {
|
|
126
|
+
connect(vmServiceUrl: string): Promise<void>;
|
|
127
|
+
dispose(options?: {
|
|
128
|
+
signal?: AbortSignal;
|
|
129
|
+
}): Promise<void>;
|
|
130
|
+
/** Resolves on confirmed VM reload, rejects if reload fails. */
|
|
131
|
+
reloadSources?(): Promise<unknown>;
|
|
132
|
+
};
|
|
133
|
+
baseline?: {
|
|
134
|
+
reset(scenario: BaselineConfig, opts: {
|
|
135
|
+
full?: boolean;
|
|
136
|
+
}): Promise<ResetReport>;
|
|
137
|
+
get version(): number;
|
|
138
|
+
};
|
|
139
|
+
}
|
package/dist/types.js
ADDED