@specter-automation/test 1.0.107 → 1.0.109

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.
@@ -134,7 +134,10 @@ export declare class ActorLocator<T = any> extends SpecterLocator<T> {
134
134
  /**
135
135
  * Waits for a Gameplay Attribute to reach a specific value, tracking its history.
136
136
  */
137
- waitForAttributeValue(attributeSet: string, attributeName: string, expectedValue: number, timeout?: number): Promise<{
137
+ waitForAttributeValue(attributeSet: string, attributeName: string, expectedValue: number, options?: {
138
+ timeout?: number;
139
+ tolerance?: number;
140
+ } | number): Promise<{
138
141
  finalValue: number;
139
142
  history: number[];
140
143
  }>;
@@ -383,38 +383,87 @@ class ActorLocator extends specter_locator_1.SpecterLocator {
383
383
  /**
384
384
  * Waits for a Gameplay Attribute to reach a specific value, tracking its history.
385
385
  */
386
- async waitForAttributeValue(attributeSet, attributeName, expectedValue, timeout = 5000) {
386
+ async waitForAttributeValue(attributeSet, attributeName, expectedValue, options) {
387
387
  const { test } = await Promise.resolve().then(() => __importStar(require('@playwright/test')));
388
388
  const { SpecterEventType } = await Promise.resolve().then(() => __importStar(require('../specter-client')));
389
+ const timeout = typeof options === 'number' ? options : (options?.timeout ?? 5000);
390
+ const tolerance = typeof options === 'object' ? (options.tolerance ?? 0.01) : 0.01;
391
+ const isMatch = (val) => {
392
+ if (val === expectedValue)
393
+ return true;
394
+ return Math.abs(val - expectedValue) <= tolerance;
395
+ };
389
396
  return await test.step(`Specter: Wait For Attribute [${attributeSet}.${attributeName} == ${expectedValue}]`, async () => {
390
397
  let lastValue;
391
398
  let history = [];
392
399
  try {
393
- lastValue = await this.getAttributeValue(attributeSet, attributeName);
394
- if (lastValue !== undefined)
395
- history.push(lastValue);
396
- if (lastValue === expectedValue) {
397
- return { finalValue: lastValue, history };
400
+ try {
401
+ lastValue = await this.getAttributeValue(attributeSet, attributeName);
402
+ if (lastValue !== undefined && !isNaN(lastValue)) {
403
+ history.push(lastValue);
404
+ if (isMatch(lastValue)) {
405
+ return { finalValue: lastValue, history };
406
+ }
407
+ }
408
+ }
409
+ catch {
410
+ // Suppress initial read error if transient
398
411
  }
399
412
  return await new Promise((resolve, reject) => {
400
413
  let timeoutId;
414
+ let pollIntervalId;
415
+ let isResolved = false;
416
+ const cleanup = () => {
417
+ if (isResolved)
418
+ return;
419
+ isResolved = true;
420
+ clearTimeout(timeoutId);
421
+ clearInterval(pollIntervalId);
422
+ this.transport.removeEventListener('GLOBAL_timeline-event', listener);
423
+ };
401
424
  const listener = (event) => {
425
+ if (isResolved)
426
+ return;
402
427
  if (event.eventType === SpecterEventType.GameplayAttribute &&
403
428
  (event.eventName === attributeName || event.eventName.includes(attributeName))) {
404
429
  const val = parseFloat(event.newValue);
405
- history.push(val);
406
- if (val === expectedValue) {
407
- clearTimeout(timeoutId);
408
- this.transport.removeEventListener('GLOBAL_timeline-event', listener);
409
- resolve({ finalValue: val, history });
430
+ if (!isNaN(val)) {
431
+ history.push(val);
432
+ lastValue = val;
433
+ if (isMatch(val)) {
434
+ cleanup();
435
+ resolve({ finalValue: val, history });
436
+ }
410
437
  }
411
438
  }
412
439
  };
440
+ this.transport.registerEventListener('GLOBAL_timeline-event', listener);
441
+ pollIntervalId = setInterval(async () => {
442
+ if (isResolved)
443
+ return;
444
+ try {
445
+ const val = await this.getAttributeValue(attributeSet, attributeName);
446
+ if (isResolved)
447
+ return;
448
+ if (val !== undefined && !isNaN(val)) {
449
+ if (lastValue !== val) {
450
+ history.push(val);
451
+ }
452
+ lastValue = val;
453
+ if (isMatch(val)) {
454
+ cleanup();
455
+ resolve({ finalValue: val, history });
456
+ }
457
+ }
458
+ }
459
+ catch {
460
+ // Transient poll errors suppressed
461
+ }
462
+ }, 100);
413
463
  timeoutId = setTimeout(() => {
414
- this.transport.removeEventListener('GLOBAL_timeline-event', listener);
464
+ cleanup();
415
465
  reject(new Error(`Timed out after ${timeout}ms waiting for GAS Attribute '${attributeName}' to reach value '${expectedValue}'.\nHistory: [${history.join(', ')}]`));
416
466
  }, timeout);
417
- this.transport.registerEventListener('GLOBAL_timeline-event', listener);
418
467
  });
419
468
  }
420
469
  catch (e) {
@@ -100,6 +100,11 @@ export declare class SpecterTransport {
100
100
  clientName?: string;
101
101
  private pendingRequests;
102
102
  private eventListeners;
103
+ recentEvents: Array<{
104
+ eventKey: string;
105
+ data: any;
106
+ timestamp: number;
107
+ }>;
103
108
  static getInstance(url?: string): SpecterTransport;
104
109
  get port(): string;
105
110
  get friendlyPortTag(): string;
@@ -116,6 +121,18 @@ export declare class SpecterTransport {
116
121
  * Cleans up an event listener.
117
122
  */
118
123
  removeEventListener(eventKey: string, callback: (data: any) => void): void;
124
+ /**
125
+ * Records an unsolicited event into the circular ring buffer.
126
+ */
127
+ recordRecentEvent(eventKey: string, data: any): void;
128
+ /**
129
+ * Returns recent events matching the eventKey, optionally filtered to events since a given timestamp.
130
+ */
131
+ getRecentEvents(eventKey?: string, sinceTimestamp?: number): Array<{
132
+ eventKey: string;
133
+ data: any;
134
+ timestamp: number;
135
+ }>;
119
136
  }
120
137
  export interface LoadMapOptions {
121
138
  gameMode?: string;
@@ -40,6 +40,8 @@ class SpecterTransport {
40
40
  // The Enterprise Fix: Routing responses to the correct Promise
41
41
  pendingRequests = new Map();
42
42
  eventListeners = new Map();
43
+ // Buffered recent events to eliminate race conditions between event arrival and listener attachment
44
+ recentEvents = [];
43
45
  static getInstance(url = 'ws://127.0.0.1:8080') {
44
46
  if (!SpecterTransport.instance) {
45
47
  SpecterTransport.instance = new SpecterTransport(url);
@@ -148,6 +150,8 @@ class SpecterTransport {
148
150
  this.currentMap = responseObj.data.map;
149
151
  }
150
152
  const eventKey = `${responseObj.locatorId}_${responseObj.eventName}`;
153
+ // Buffer recent events with timestamps to eliminate race conditions
154
+ this.recordRecentEvent(eventKey, responseObj.data);
151
155
  // If a test script is currently waiting for this event...
152
156
  if (this.eventListeners.has(eventKey)) {
153
157
  const callbacks = this.eventListeners.get(eventKey);
@@ -240,6 +244,27 @@ class SpecterTransport {
240
244
  }
241
245
  }
242
246
  }
247
+ /**
248
+ * Records an unsolicited event into the circular ring buffer.
249
+ */
250
+ recordRecentEvent(eventKey, data) {
251
+ this.recentEvents.push({ eventKey, data, timestamp: Date.now() });
252
+ if (this.recentEvents.length > 200) {
253
+ this.recentEvents.shift();
254
+ }
255
+ }
256
+ /**
257
+ * Returns recent events matching the eventKey, optionally filtered to events since a given timestamp.
258
+ */
259
+ getRecentEvents(eventKey, sinceTimestamp) {
260
+ return this.recentEvents.filter(e => {
261
+ if (eventKey && e.eventKey !== eventKey)
262
+ return false;
263
+ if (sinceTimestamp !== undefined && e.timestamp < sinceTimestamp)
264
+ return false;
265
+ return true;
266
+ });
267
+ }
243
268
  }
244
269
  exports.SpecterTransport = SpecterTransport;
245
270
  class SpecterWorld {
@@ -1,9 +1,11 @@
1
1
  import { SpecterLocator, ActorLocator } from '../core/locators';
2
- import { SpecterTimelineEvent } from '../core/specter-client';
3
2
  declare global {
4
3
  namespace PlaywrightTest {
5
4
  interface Matchers<R, T> {
6
- toHaveAttributeValue(attributeSet: string, attributeName: string, expectedValue: number): T extends SpecterLocator ? Promise<R> : never;
5
+ toHaveAttributeValue(attributeSet: string, attributeName: string, expectedValue: number, options?: {
6
+ timeout?: number;
7
+ tolerance?: number;
8
+ }): T extends SpecterLocator ? Promise<R> : never;
7
9
  toHaveAttributeChange(attributeSet: string, attributeName: string, expectedChange: {
8
10
  delta?: number;
9
11
  instigator?: string | ActorLocator;
@@ -32,13 +34,18 @@ declare global {
32
34
  }
33
35
  }
34
36
  export interface GasMatchers {
35
- toHaveAttributeValue(attributeSet: string, attributeName: string, expectedValue: number): Promise<void>;
37
+ toHaveAttributeValue(attributeSet: string, attributeName: string, expectedValue: number, options?: {
38
+ timeout?: number;
39
+ tolerance?: number;
40
+ }): Promise<void>;
36
41
  toHaveAttributeChange(attributeSet: string, attributeName: string, expectedChange: {
37
42
  delta?: number;
38
43
  instigator?: string | ActorLocator;
39
44
  effectCauser?: string | ActorLocator;
40
45
  gameplayEffect?: string;
41
46
  ability?: string;
47
+ timeout?: number;
48
+ tolerance?: number;
42
49
  }, triggerAction?: () => Promise<void>): Promise<void>;
43
50
  toHaveGameplayTag(tag: string): Promise<void>;
44
51
  toHaveGameplayEffect(effectClassPath: string): Promise<void>;
@@ -59,13 +66,11 @@ export interface GasMatchers {
59
66
  toHaveAllGameplayTags(tags: string[]): Promise<void>;
60
67
  }
61
68
  export declare const gasExpect: import("playwright/test").Expect<{
62
- toHaveAttributeValue(this: import("playwright/test").ExpectMatcherState, locator: ActorLocator, attributeSet: string, attributeName: string, expectedValue: number): Promise<{
63
- pass: true;
64
- message: () => string;
65
- actual: any;
66
- expected: number;
67
- } | {
68
- pass: false;
69
+ toHaveAttributeValue(this: import("playwright/test").ExpectMatcherState, locator: ActorLocator, attributeSet: string, attributeName: string, expectedValue: number, options?: {
70
+ timeout?: number;
71
+ tolerance?: number;
72
+ }): Promise<{
73
+ pass: boolean;
69
74
  message: () => string;
70
75
  actual: any;
71
76
  expected: number;
@@ -76,16 +81,20 @@ export declare const gasExpect: import("playwright/test").Expect<{
76
81
  effectCauser?: string | ActorLocator;
77
82
  gameplayEffect?: string;
78
83
  ability?: string;
84
+ timeout?: number;
85
+ tolerance?: number;
79
86
  }, triggerAction?: () => Promise<void>): Promise<{
80
87
  pass: boolean;
81
88
  message: () => string;
82
- actual: SpecterTimelineEvent | undefined;
89
+ actual: any;
83
90
  expected: {
84
91
  delta?: number;
85
92
  instigator?: string | ActorLocator;
86
93
  effectCauser?: string | ActorLocator;
87
94
  gameplayEffect?: string;
88
95
  ability?: string;
96
+ timeout?: number;
97
+ tolerance?: number;
89
98
  };
90
99
  }>;
91
100
  toHaveGameplayTag(this: import("playwright/test").ExpectMatcherState, locator: ActorLocator, tag: string): Promise<{
@@ -37,70 +37,117 @@ exports.gasExpect = void 0;
37
37
  const test_1 = __importStar(require("@playwright/test"));
38
38
  const specter_client_1 = require("../core/specter-client");
39
39
  exports.gasExpect = test_1.expect.extend({
40
- async toHaveAttributeValue(locator, attributeSet, attributeName, expectedValue) {
40
+ async toHaveAttributeValue(locator, attributeSet, attributeName, expectedValue, options) {
41
41
  const assertionName = 'toHaveAttributeValue';
42
42
  const isNot = this.isNot;
43
43
  const prefix = isNot ? 'not.toHaveAttributeValue' : 'toHaveAttributeValue';
44
+ const timeout = options?.timeout ?? 5000;
45
+ const tolerance = options?.tolerance ?? 0.01;
44
46
  const stepName = `${prefix}('${attributeSet}', '${attributeName}', ${expectedValue}) @ ${locator.toString()}`;
47
+ const isMatch = (val) => {
48
+ if (val === expectedValue)
49
+ return true;
50
+ return Math.abs(val - expectedValue) <= tolerance;
51
+ };
45
52
  return await test_1.default.step(stepName, async () => {
46
53
  let lastValue;
47
54
  let valueHistory = [];
48
55
  try {
49
- // 1. Check the current value immediately (no polling loop)
50
- lastValue = await locator.getAttributeValue(attributeSet, attributeName);
51
- if (lastValue !== undefined)
52
- valueHistory.push(lastValue);
53
- if (lastValue === expectedValue) {
54
- return {
55
- pass: true,
56
- message: () => 'passed',
57
- actual: lastValue,
58
- expected: expectedValue
59
- };
56
+ // 1. Check the current value immediately (try once)
57
+ try {
58
+ lastValue = await locator.getAttributeValue(attributeSet, attributeName);
59
+ if (lastValue !== undefined && !isNaN(lastValue)) {
60
+ valueHistory.push(lastValue);
61
+ if (isMatch(lastValue)) {
62
+ return {
63
+ pass: !isNot,
64
+ message: () => 'passed',
65
+ actual: lastValue,
66
+ expected: expectedValue
67
+ };
68
+ }
69
+ }
70
+ }
71
+ catch (initialErr) {
72
+ // Suppress initial read error if transient, but proceed to listen
60
73
  }
61
- // 2. If it doesn't match, wait for the telemetry event
74
+ // 2. If it does not match immediately, listen for the live attribute change event
62
75
  const transport = locator.transport;
63
- const timeout = 5000;
64
- // Wait for the live broadcast
65
76
  const finalValue = await new Promise((resolve, reject) => {
66
77
  let timeoutId;
78
+ let pollIntervalId;
79
+ let isResolved = false;
80
+ const cleanup = () => {
81
+ if (isResolved)
82
+ return;
83
+ isResolved = true;
84
+ clearTimeout(timeoutId);
85
+ clearInterval(pollIntervalId);
86
+ if (transport && typeof transport.removeEventListener === 'function') {
87
+ transport.removeEventListener('GLOBAL_timeline-event', listener);
88
+ }
89
+ };
67
90
  const listener = (event) => {
68
- // DEBUG LOGGING TO HELP IDENTIFY MISMATCHES
69
- console.log(`[Specter Debug] Received Event: type=${event.eventType}, name=${event.eventName}, value=${event.newValue}, instigator=${event.instigator}, effectCauser=${event.effectCauser}, gameplayEffect=${event.gameplayEffect}, ability=${event.ability}`);
91
+ if (isResolved)
92
+ return;
70
93
  if (event.eventType === specter_client_1.SpecterEventType.GameplayAttribute &&
71
94
  (event.eventName === attributeName || event.eventName.includes(attributeName))) {
72
95
  const val = parseFloat(event.newValue);
73
- valueHistory.push(val); // Track history!
74
- if (val === expectedValue) {
75
- clearTimeout(timeoutId);
76
- transport.removeEventListener('GLOBAL_timeline-event', listener);
77
- resolve(val);
78
- }
79
- else {
80
- // Keep track of the latest value we saw during the wait
96
+ if (!isNaN(val)) {
97
+ valueHistory.push(val);
81
98
  lastValue = val;
99
+ if (isMatch(val)) {
100
+ cleanup();
101
+ resolve(val);
102
+ }
82
103
  }
83
104
  }
84
105
  };
106
+ // Register event listener immediately to catch incoming push events
107
+ if (transport && typeof transport.registerEventListener === 'function') {
108
+ transport.registerEventListener('GLOBAL_timeline-event', listener);
109
+ }
110
+ // Parallel polling fallback in case the event was already broadcast or missed
111
+ pollIntervalId = setInterval(async () => {
112
+ if (isResolved)
113
+ return;
114
+ try {
115
+ const val = await locator.getAttributeValue(attributeSet, attributeName);
116
+ if (isResolved)
117
+ return;
118
+ if (val !== undefined && !isNaN(val)) {
119
+ if (lastValue !== val) {
120
+ valueHistory.push(val);
121
+ }
122
+ lastValue = val;
123
+ if (isMatch(val)) {
124
+ cleanup();
125
+ resolve(val);
126
+ }
127
+ }
128
+ }
129
+ catch {
130
+ // Transient poll errors are suppressed during wait
131
+ }
132
+ }, 100);
85
133
  timeoutId = setTimeout(() => {
86
- transport.removeEventListener('GLOBAL_timeline-event', listener);
134
+ cleanup();
87
135
  reject(new Error(`Timed out after ${timeout}ms waiting for GAS Attribute '${attributeName}' to reach value '${expectedValue}'`));
88
136
  }, timeout);
89
- transport.registerEventListener('GLOBAL_timeline-event', listener);
90
137
  });
91
138
  return {
92
- pass: true,
139
+ pass: !isNot,
93
140
  message: () => 'passed',
94
141
  actual: finalValue,
95
142
  expected: expectedValue
96
143
  };
97
144
  }
98
145
  catch (e) {
99
- if (!e.message.includes('Timed out')) {
146
+ if (!e.message?.includes('Timed out')) {
100
147
  throw e;
101
148
  }
102
149
  return {
103
- pass: false,
150
+ pass: isNot,
104
151
  message: () => `${this.utils.matcherHint(assertionName, locator.toString(), expectedValue.toString())}\n\n` +
105
152
  `Expected: ${this.utils.printExpected(expectedValue)}\n` +
106
153
  `Received: ${lastValue !== undefined ? this.utils.printReceived(lastValue) : 'Timeout'}\n` +
@@ -115,6 +162,9 @@ exports.gasExpect = test_1.expect.extend({
115
162
  const assertionName = 'toHaveAttributeChange';
116
163
  const isNot = this.isNot;
117
164
  const prefix = isNot ? 'not.toHaveAttributeChange' : 'toHaveAttributeChange';
165
+ const timeout = expectedChange.timeout ?? 10000;
166
+ const tolerance = expectedChange.tolerance ?? 0.01;
167
+ const startTime = Date.now();
118
168
  // Format expectations for description
119
169
  const expectedParts = [];
120
170
  if (expectedChange.delta !== undefined)
@@ -134,97 +184,228 @@ exports.gasExpect = test_1.expect.extend({
134
184
  const stepName = `${prefix}('${attributeSet}', '${attributeName}', { ${expectedParts.join(', ')} }) @ ${locator.toString()}`;
135
185
  return await test_1.default.step(stepName, async () => {
136
186
  const transport = locator.transport;
137
- const timeout = 10000;
138
- // Trigger C++ tracking of this attribute by reading its value once
139
- await locator.getAttributeValue(attributeSet, attributeName);
140
- // Resolve target expected names for locators
141
- let expectedInstigatorName;
142
- if (expectedChange.instigator) {
143
- if (typeof expectedChange.instigator === 'string') {
144
- expectedInstigatorName = expectedChange.instigator;
145
- }
146
- else {
147
- expectedInstigatorName = await expectedChange.instigator.getObjectName();
187
+ let lastEvent;
188
+ let lastFailedReasons = [];
189
+ let initialValue;
190
+ // Synchronously register live listener immediately to capture all events during setup & action
191
+ const capturedEvents = [];
192
+ let onLiveEvent = null;
193
+ const liveListener = (event) => {
194
+ capturedEvents.push(event);
195
+ if (onLiveEvent) {
196
+ onLiveEvent(event);
148
197
  }
198
+ };
199
+ if (transport && typeof transport.registerEventListener === 'function') {
200
+ transport.registerEventListener('GLOBAL_timeline-event', liveListener);
149
201
  }
150
- let expectedEffectCauserName;
151
- if (expectedChange.effectCauser) {
152
- if (typeof expectedChange.effectCauser === 'string') {
153
- expectedEffectCauserName = expectedChange.effectCauser;
202
+ try {
203
+ // In parallel: resolve initial value and locator names
204
+ const [resolvedInitialVal, expectedInstigatorName, expectedEffectCauserName] = await Promise.all([
205
+ locator.getAttributeValue(attributeSet, attributeName).catch(() => undefined),
206
+ expectedChange.instigator
207
+ ? (typeof expectedChange.instigator === 'string' ? Promise.resolve(expectedChange.instigator) : expectedChange.instigator.getObjectName().catch(() => undefined))
208
+ : Promise.resolve(undefined),
209
+ expectedChange.effectCauser
210
+ ? (typeof expectedChange.effectCauser === 'string' ? Promise.resolve(expectedChange.effectCauser) : expectedChange.effectCauser.getObjectName().catch(() => undefined))
211
+ : Promise.resolve(undefined),
212
+ ]);
213
+ initialValue = resolvedInitialVal;
214
+ // Evaluates whether an event matches all expected criteria
215
+ const evaluateEvent = (event) => {
216
+ if (event.eventType !== specter_client_1.SpecterEventType.GameplayAttribute && event.eventType !== 'GameplayAttribute') {
217
+ return false;
218
+ }
219
+ if (event.eventName !== attributeName && !event.eventName?.includes(attributeName)) {
220
+ return false;
221
+ }
222
+ lastEvent = event;
223
+ lastFailedReasons = [];
224
+ let isMatch = true;
225
+ // 1. Delta check
226
+ if (expectedChange.delta !== undefined) {
227
+ const oldVal = parseFloat(event.oldValue);
228
+ const newVal = parseFloat(event.newValue);
229
+ const actualDelta = newVal - oldVal;
230
+ const expDelta = expectedChange.delta;
231
+ // Check signed delta match, or magnitude match (e.g. damage written as positive vs negative)
232
+ const deltaMatch = Math.abs(actualDelta - expDelta) <= tolerance ||
233
+ Math.abs(Math.abs(actualDelta) - Math.abs(expDelta)) <= tolerance;
234
+ if (!deltaMatch) {
235
+ isMatch = false;
236
+ lastFailedReasons.push(`delta (expected: ${expDelta}, actual: ${actualDelta})`);
237
+ }
238
+ }
239
+ // 2. Instigator check
240
+ if (expectedInstigatorName !== undefined) {
241
+ const inst = (event.instigator || '').trim();
242
+ if (!inst || (!inst.includes(expectedInstigatorName) && !expectedInstigatorName.includes(inst))) {
243
+ isMatch = false;
244
+ lastFailedReasons.push(`instigator (expected to include: '${expectedInstigatorName}', actual: '${event.instigator}')`);
245
+ }
246
+ }
247
+ // 3. Effect Causer check
248
+ if (expectedEffectCauserName !== undefined) {
249
+ const causer = (event.effectCauser || '').trim();
250
+ if (!causer || (!causer.includes(expectedEffectCauserName) && !expectedEffectCauserName.includes(causer))) {
251
+ isMatch = false;
252
+ lastFailedReasons.push(`effectCauser (expected to include: '${expectedEffectCauserName}', actual: '${event.effectCauser}')`);
253
+ }
254
+ }
255
+ // 4. Gameplay Effect check
256
+ if (expectedChange.gameplayEffect !== undefined) {
257
+ if (!event.gameplayEffect || (!event.gameplayEffect.includes(expectedChange.gameplayEffect) && !expectedChange.gameplayEffect.includes(event.gameplayEffect))) {
258
+ isMatch = false;
259
+ lastFailedReasons.push(`gameplayEffect (expected to include: '${expectedChange.gameplayEffect}', actual: '${event.gameplayEffect}')`);
260
+ }
261
+ }
262
+ // 5. Ability check
263
+ if (expectedChange.ability !== undefined) {
264
+ if (!event.ability || (!event.ability.includes(expectedChange.ability) && !expectedChange.ability.includes(event.ability))) {
265
+ isMatch = false;
266
+ lastFailedReasons.push(`ability (expected to include: '${expectedChange.ability}', actual: '${event.ability}')`);
267
+ }
268
+ }
269
+ return isMatch;
270
+ };
271
+ // --- 1. TRY ONCE IMMEDIATELY ---
272
+ // A. Check events captured in real-time during setup
273
+ for (const ev of capturedEvents) {
274
+ if (evaluateEvent(ev)) {
275
+ return {
276
+ pass: !isNot,
277
+ message: () => 'passed',
278
+ actual: ev,
279
+ expected: expectedChange
280
+ };
281
+ }
154
282
  }
155
- else {
156
- expectedEffectCauserName = await expectedChange.effectCauser.getObjectName();
283
+ // B. Check transport recent events ring buffer (events from just before or during call)
284
+ if (transport && typeof transport.getRecentEvents === 'function') {
285
+ const recent = transport.getRecentEvents('GLOBAL_timeline-event', startTime - 3000);
286
+ for (const item of recent) {
287
+ if (evaluateEvent(item.data)) {
288
+ return {
289
+ pass: !isNot,
290
+ message: () => 'passed',
291
+ actual: item.data,
292
+ expected: expectedChange
293
+ };
294
+ }
295
+ }
157
296
  }
158
- }
159
- let matchEvent;
160
- let lastEvent;
161
- let lastFailedReasons = [];
162
- try {
163
- // Wait for the timeline event matching the criteria
164
- const matchPromise = new Promise((resolve, reject) => {
165
- let timeoutId;
166
- const listener = (event) => {
167
- if (event.eventType === specter_client_1.SpecterEventType.GameplayAttribute &&
168
- (event.eventName === attributeName || event.eventName.includes(attributeName))) {
169
- lastEvent = event;
170
- lastFailedReasons = [];
171
- let isMatch = true;
172
- // 1. Delta check
173
- if (expectedChange.delta !== undefined) {
174
- const oldVal = parseFloat(event.oldValue);
175
- const newVal = parseFloat(event.newValue);
176
- const actualDelta = newVal - oldVal;
177
- // Use close comparison for floats (e.g. within 0.01 tolerance)
178
- if (Math.abs(actualDelta - expectedChange.delta) > 0.01) {
179
- isMatch = false;
180
- lastFailedReasons.push(`delta (expected: ${expectedChange.delta}, actual: ${actualDelta})`);
181
- }
182
- }
183
- // 2. Instigator check
184
- if (expectedInstigatorName !== undefined) {
185
- if (event.instigator !== expectedInstigatorName && !event.instigator?.includes(expectedInstigatorName)) {
186
- isMatch = false;
187
- lastFailedReasons.push(`instigator (expected to include: '${expectedInstigatorName}', actual: '${event.instigator}')`);
188
- }
189
- }
190
- // 3. Effect Causer check
191
- if (expectedEffectCauserName !== undefined) {
192
- if (event.effectCauser !== expectedEffectCauserName && !event.effectCauser?.includes(expectedEffectCauserName)) {
193
- isMatch = false;
194
- lastFailedReasons.push(`effectCauser (expected to include: '${expectedEffectCauserName}', actual: '${event.effectCauser}')`);
195
- }
196
- }
197
- // 4. Gameplay Effect check
198
- if (expectedChange.gameplayEffect !== undefined) {
199
- if (event.gameplayEffect !== expectedChange.gameplayEffect && !event.gameplayEffect?.includes(expectedChange.gameplayEffect)) {
200
- isMatch = false;
201
- lastFailedReasons.push(`gameplayEffect (expected to include: '${expectedChange.gameplayEffect}', actual: '${event.gameplayEffect}')`);
202
- }
297
+ // --- 2. EXECUTE TRIGGER ACTION IF PROVIDED ---
298
+ if (triggerAction) {
299
+ await triggerAction();
300
+ // Re-check captured events immediately after trigger action completes
301
+ for (const ev of capturedEvents) {
302
+ if (evaluateEvent(ev)) {
303
+ return {
304
+ pass: !isNot,
305
+ message: () => 'passed',
306
+ actual: ev,
307
+ expected: expectedChange
308
+ };
309
+ }
310
+ }
311
+ }
312
+ // --- 3. HANDLE DELTA: 0 (assertion that value has not changed) ---
313
+ if (expectedChange.delta === 0) {
314
+ const observationMs = Math.min(timeout, 500);
315
+ await new Promise(r => setTimeout(r, observationMs));
316
+ // Verify whether any conflicting attribute change events arrived
317
+ const conflictingEvent = capturedEvents.find(ev => (ev.eventType === specter_client_1.SpecterEventType.GameplayAttribute || ev.eventType === 'GameplayAttribute') &&
318
+ (ev.eventName === attributeName || ev.eventName?.includes(attributeName)) &&
319
+ parseFloat(ev.oldValue) !== parseFloat(ev.newValue));
320
+ if (!conflictingEvent) {
321
+ const currentVal = await locator.getAttributeValue(attributeSet, attributeName).catch(() => initialValue);
322
+ if (initialValue !== undefined && currentVal !== undefined) {
323
+ const delta = currentVal - initialValue;
324
+ if (Math.abs(delta) <= tolerance) {
325
+ return {
326
+ pass: !isNot,
327
+ message: () => 'passed',
328
+ actual: { delta, value: currentVal },
329
+ expected: expectedChange
330
+ };
203
331
  }
204
- // 5. Ability check
205
- if (expectedChange.ability !== undefined) {
206
- if (event.ability !== expectedChange.ability && !event.ability?.includes(expectedChange.ability)) {
207
- isMatch = false;
208
- lastFailedReasons.push(`ability (expected to include: '${expectedChange.ability}', actual: '${event.ability}')`);
332
+ }
333
+ else if (currentVal !== undefined) {
334
+ return {
335
+ pass: !isNot,
336
+ message: () => 'passed',
337
+ actual: { delta: 0, value: currentVal },
338
+ expected: expectedChange
339
+ };
340
+ }
341
+ }
342
+ }
343
+ // --- 4. LISTEN FOR ATTRIBUTE CHANGE EVENT WITH POLLING FALLBACK ---
344
+ const matchEvent = await new Promise((resolve, reject) => {
345
+ let timeoutId;
346
+ let pollIntervalId;
347
+ let isResolved = false;
348
+ const cleanup = () => {
349
+ if (isResolved)
350
+ return;
351
+ isResolved = true;
352
+ clearTimeout(timeoutId);
353
+ clearInterval(pollIntervalId);
354
+ };
355
+ onLiveEvent = (event) => {
356
+ if (isResolved)
357
+ return;
358
+ if (evaluateEvent(event)) {
359
+ cleanup();
360
+ resolve(event);
361
+ }
362
+ };
363
+ // Check any events that arrived right as onLiveEvent was wired
364
+ for (const ev of capturedEvents) {
365
+ if (evaluateEvent(ev)) {
366
+ cleanup();
367
+ resolve(ev);
368
+ return;
369
+ }
370
+ }
371
+ // Parallel polling fallback
372
+ pollIntervalId = setInterval(async () => {
373
+ if (isResolved)
374
+ return;
375
+ try {
376
+ const currentVal = await locator.getAttributeValue(attributeSet, attributeName);
377
+ if (isResolved)
378
+ return;
379
+ if (currentVal !== undefined && initialValue !== undefined && expectedChange.delta !== undefined) {
380
+ const actualDelta = currentVal - initialValue;
381
+ const expDelta = expectedChange.delta;
382
+ const deltaMatch = Math.abs(actualDelta - expDelta) <= tolerance ||
383
+ Math.abs(Math.abs(actualDelta) - Math.abs(expDelta)) <= tolerance;
384
+ if (deltaMatch) {
385
+ // If no specific instigator/causer was demanded, or if we saw an event matching them:
386
+ if (!expectedInstigatorName && !expectedEffectCauserName && !expectedChange.gameplayEffect && !expectedChange.ability) {
387
+ cleanup();
388
+ resolve(lastEvent || {
389
+ timestamp: Date.now(),
390
+ eventName: attributeName,
391
+ eventType: specter_client_1.SpecterEventType.GameplayAttribute,
392
+ oldValue: String(initialValue),
393
+ newValue: String(currentVal),
394
+ description: `Attribute ${attributeName} changed by ${actualDelta}`,
395
+ });
396
+ }
209
397
  }
210
398
  }
211
- if (isMatch) {
212
- clearTimeout(timeoutId);
213
- transport.removeEventListener('GLOBAL_timeline-event', listener);
214
- resolve(event);
215
- }
216
399
  }
217
- };
400
+ catch {
401
+ // Transient poll errors are suppressed during wait
402
+ }
403
+ }, 100);
218
404
  timeoutId = setTimeout(() => {
219
- transport.removeEventListener('GLOBAL_timeline-event', listener);
405
+ cleanup();
220
406
  reject(new Error(`Timed out after ${timeout}ms waiting for attribute change event on '${attributeName}'`));
221
407
  }, timeout);
222
- transport.registerEventListener('GLOBAL_timeline-event', listener);
223
408
  });
224
- if (triggerAction) {
225
- await triggerAction();
226
- }
227
- matchEvent = await matchPromise;
228
409
  return {
229
410
  pass: !isNot,
230
411
  message: () => 'passed',
@@ -233,7 +414,7 @@ exports.gasExpect = test_1.expect.extend({
233
414
  };
234
415
  }
235
416
  catch (e) {
236
- if (!e.message.includes('Timed out')) {
417
+ if (!e.message?.includes('Timed out')) {
237
418
  throw e;
238
419
  }
239
420
  let failureDetails = `Last checked event: ${lastEvent ? JSON.stringify(lastEvent, null, 2) : 'None received'}`;
@@ -250,6 +431,11 @@ exports.gasExpect = test_1.expect.extend({
250
431
  expected: expectedChange
251
432
  };
252
433
  }
434
+ finally {
435
+ if (transport && typeof transport.removeEventListener === 'function') {
436
+ transport.removeEventListener('GLOBAL_timeline-event', liveListener);
437
+ }
438
+ }
253
439
  });
254
440
  },
255
441
  async toHaveGameplayTag(locator, tag) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@specter-automation/test",
3
- "version": "1.0.107",
3
+ "version": "1.0.109",
4
4
  "description": "Playwright integration for Unreal Engine automation via Specter",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",