testdriverai 7.8.0-test.6 → 7.8.0-test.61
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/CHANGELOG.md +6 -0
- package/agent/index.js +10 -5
- package/agent/lib/commands.js +3 -2
- package/agent/lib/http.js +144 -0
- package/agent/lib/logger.js +15 -0
- package/agent/lib/sandbox.js +530 -207
- package/agent/lib/sdk.js +4 -2
- package/agent/lib/system.js +25 -65
- package/ai/skills/testdriver-cache/SKILL.md +221 -0
- package/ai/skills/testdriver-errors/SKILL.md +246 -0
- package/ai/skills/testdriver-events/SKILL.md +356 -0
- package/ai/skills/testdriver-find/SKILL.md +14 -20
- package/ai/skills/testdriver-mcp/SKILL.md +7 -0
- package/ai/skills/testdriver-provision/SKILL.md +331 -0
- package/ai/skills/testdriver-redraw/SKILL.md +214 -0
- package/ai/skills/testdriver-running-tests/SKILL.md +1 -1
- package/ai/skills/testdriver-screenshots/SKILL.md +184 -0
- package/docs/_data/examples-manifest.json +46 -46
- package/docs/_scripts/extract-example-urls.js +67 -72
- package/docs/changelog.mdx +151 -5
- package/docs/docs.json +46 -38
- package/docs/images/content/vscode/v7-chat.png +0 -0
- package/docs/images/content/vscode/v7-choose-agent.png +0 -0
- package/docs/images/content/vscode/v7-full.png +0 -0
- package/docs/images/content/vscode/v7-onboarding.png +0 -0
- package/docs/v7/cache.mdx +223 -0
- package/docs/v7/copilot/auto-healing.mdx +265 -0
- package/docs/v7/copilot/creating-tests.mdx +156 -0
- package/docs/v7/copilot/github.mdx +143 -0
- package/docs/v7/copilot/running-tests.mdx +149 -0
- package/docs/v7/copilot/setup.mdx +143 -0
- package/docs/v7/enterprise.mdx +3 -110
- package/docs/v7/errors.mdx +248 -0
- package/docs/v7/events.mdx +358 -0
- package/docs/v7/examples/ai.mdx +1 -1
- package/docs/v7/examples/assert.mdx +1 -1
- package/docs/v7/examples/captcha-api.mdx +1 -1
- package/docs/v7/examples/chrome-extension.mdx +1 -1
- package/docs/v7/examples/drag-and-drop.mdx +1 -1
- package/docs/v7/examples/element-not-found.mdx +1 -1
- package/docs/v7/examples/exec-output.mdx +85 -0
- package/docs/v7/examples/exec-pwsh.mdx +83 -0
- package/docs/v7/examples/focus-window.mdx +62 -0
- package/docs/v7/examples/hover-image.mdx +1 -1
- package/docs/v7/examples/hover-text.mdx +1 -1
- package/docs/v7/examples/installer.mdx +1 -1
- package/docs/v7/examples/launch-vscode-linux.mdx +1 -1
- package/docs/v7/examples/match-image.mdx +1 -1
- package/docs/v7/examples/press-keys.mdx +1 -1
- package/docs/v7/examples/scroll-keyboard.mdx +1 -1
- package/docs/v7/examples/scroll-until-image.mdx +1 -1
- package/docs/v7/examples/scroll-until-text.mdx +1 -1
- package/docs/v7/examples/scroll.mdx +1 -1
- package/docs/v7/examples/type.mdx +1 -1
- package/docs/v7/examples/windows-installer.mdx +1 -1
- package/docs/v7/find.mdx +14 -20
- package/docs/v7/{cloud.mdx → hosted.mdx} +43 -5
- package/docs/v7/mcp.mdx +9 -0
- package/docs/v7/provision.mdx +333 -0
- package/docs/v7/quickstart.mdx +30 -2
- package/docs/v7/redraw.mdx +216 -0
- package/docs/v7/running-tests.mdx +1 -1
- package/docs/v7/screenshots.mdx +186 -0
- package/docs/v7/self-hosted.mdx +127 -44
- package/docs/v7/test-results-json.mdx +258 -0
- package/examples/scroll-keyboard.test.mjs +1 -1
- package/interfaces/logger.js +0 -12
- package/interfaces/vitest-plugin.mjs +169 -50
- package/lib/core/Dashcam.js +30 -23
- package/lib/environments.json +18 -0
- package/lib/github-comment.mjs +58 -40
- package/lib/resolve-channel.js +4 -3
- package/lib/sentry.js +5 -0
- package/lib/vitest/hooks.mjs +63 -3
- package/{examples → manual}/drag-and-drop.test.mjs +1 -1
- package/mcp-server/dist/server.mjs +4 -0
- package/mcp-server/src/server.ts +5 -0
- package/package.json +3 -3
- package/sdk.d.ts +4 -0
- package/sdk.js +44 -14
- package/setup/aws/install-dev-runner.sh +79 -0
- package/setup/aws/spawn-runner.sh +165 -0
- package/vitest.config.mjs +22 -34
- package/vitest.runner.config.mjs +33 -0
- /package/{examples → manual}/flake-diffthreshold-001.test.mjs +0 -0
- /package/{examples → manual}/flake-diffthreshold-01.test.mjs +0 -0
- /package/{examples → manual}/flake-diffthreshold-05.test.mjs +0 -0
- /package/{examples → manual}/flake-noredraw-cache.test.mjs +0 -0
- /package/{examples → manual}/flake-noredraw-nocache.test.mjs +0 -0
- /package/{examples → manual}/flake-redraw-cache.test.mjs +0 -0
- /package/{examples → manual}/flake-redraw-nocache.test.mjs +0 -0
- /package/{examples → manual}/flake-rocket-match.test.mjs +0 -0
- /package/{examples → manual}/flake-shared.mjs +0 -0
- /package/{examples → manual}/no-provision.test.mjs +0 -0
- /package/{examples → manual}/scroll-until-text.test.mjs +0 -0
package/agent/lib/sandbox.js
CHANGED
|
@@ -1,93 +1,17 @@
|
|
|
1
|
-
const crypto = require("crypto");
|
|
2
1
|
const Ably = require("ably");
|
|
2
|
+
const axios = require("axios");
|
|
3
3
|
const { events } = require("../events");
|
|
4
4
|
const logger = require("./logger");
|
|
5
5
|
const { version } = require("../../package.json");
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
if (!sessionId) return {};
|
|
9
|
-
const traceId = crypto.createHash("md5").update(sessionId).digest("hex");
|
|
10
|
-
const spanId = crypto.randomBytes(8).toString("hex");
|
|
11
|
-
return {
|
|
12
|
-
"sentry-trace": traceId + "-" + spanId + "-1",
|
|
13
|
-
baggage:
|
|
14
|
-
"sentry-trace_id=" +
|
|
15
|
-
traceId +
|
|
16
|
-
",sentry-sample_rate=1.0,sentry-sampled=true",
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function httpPost(apiRoot, path, body, timeout) {
|
|
21
|
-
const http = require("http");
|
|
22
|
-
const https = require("https");
|
|
23
|
-
const url = new URL(apiRoot + path);
|
|
24
|
-
const transport = url.protocol === "https:" ? https : http;
|
|
25
|
-
const bodyStr = JSON.stringify(body);
|
|
26
|
-
|
|
27
|
-
return new Promise(function (resolve, reject) {
|
|
28
|
-
var timeoutId = timeout
|
|
29
|
-
? setTimeout(function () {
|
|
30
|
-
req.destroy();
|
|
31
|
-
reject(
|
|
32
|
-
new Error("HTTP request timed out after " + timeout + "ms"),
|
|
33
|
-
);
|
|
34
|
-
}, timeout)
|
|
35
|
-
: null;
|
|
36
|
-
|
|
37
|
-
var req = transport.request(
|
|
38
|
-
url,
|
|
39
|
-
{
|
|
40
|
-
method: "POST",
|
|
41
|
-
headers: {
|
|
42
|
-
"Content-Type": "application/json",
|
|
43
|
-
"Content-Length": Buffer.byteLength(bodyStr),
|
|
44
|
-
"Connection": "close",
|
|
45
|
-
},
|
|
46
|
-
},
|
|
47
|
-
function (res) {
|
|
48
|
-
var data = "";
|
|
49
|
-
res.on("data", function (chunk) {
|
|
50
|
-
data += chunk;
|
|
51
|
-
});
|
|
52
|
-
res.on("end", function () {
|
|
53
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
54
|
-
try {
|
|
55
|
-
var parsed = JSON.parse(data);
|
|
56
|
-
if (res.statusCode >= 400) {
|
|
57
|
-
var err = new Error(
|
|
58
|
-
parsed.errorMessage ||
|
|
59
|
-
parsed.message ||
|
|
60
|
-
"HTTP " + res.statusCode,
|
|
61
|
-
);
|
|
62
|
-
err.responseData = parsed;
|
|
63
|
-
reject(err);
|
|
64
|
-
} else {
|
|
65
|
-
resolve(parsed);
|
|
66
|
-
}
|
|
67
|
-
} catch (e) {
|
|
68
|
-
reject(new Error("Failed to parse API response: " + data));
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
},
|
|
72
|
-
);
|
|
73
|
-
req.on("error", function (err) {
|
|
74
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
75
|
-
reject(err);
|
|
76
|
-
});
|
|
77
|
-
req.write(bodyStr);
|
|
78
|
-
req.end();
|
|
79
|
-
});
|
|
80
|
-
}
|
|
6
|
+
const { withRetry, getSentryTraceHeaders } = require("./sdk");
|
|
7
|
+
const sentry = require("../../lib/sentry");
|
|
81
8
|
|
|
82
9
|
const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
83
10
|
class Sandbox {
|
|
84
11
|
constructor() {
|
|
85
12
|
this._ably = null;
|
|
86
|
-
this.
|
|
87
|
-
this.
|
|
88
|
-
this._ctrlChannel = null;
|
|
89
|
-
this._filesChannel = null;
|
|
90
|
-
this._channelNames = null;
|
|
13
|
+
this._sessionChannel = null;
|
|
14
|
+
this._channelName = null;
|
|
91
15
|
this.ps = {};
|
|
92
16
|
this._execBuffers = {}; // accumulate streamed exec.output chunks per requestId
|
|
93
17
|
this.heartbeat = null;
|
|
@@ -105,6 +29,13 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
105
29
|
this._lastConnectParams = null;
|
|
106
30
|
this._teamId = null;
|
|
107
31
|
this._sandboxId = null;
|
|
32
|
+
this._disconnectedAt = null; // tracks when Realtime connection dropped (for timeout extension on reconnect)
|
|
33
|
+
|
|
34
|
+
// Rate limiting state for Ably publishes (Ably limits to 50 msg/sec per connection)
|
|
35
|
+
this._publishLastTime = 0;
|
|
36
|
+
this._publishMinIntervalMs = 25; // 40 msg/sec max, safely under Ably's 50 limit
|
|
37
|
+
this._publishCount = 0;
|
|
38
|
+
this._publishWindowStart = Date.now();
|
|
108
39
|
}
|
|
109
40
|
|
|
110
41
|
getTraceId() {
|
|
@@ -118,7 +49,11 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
118
49
|
);
|
|
119
50
|
}
|
|
120
51
|
|
|
121
|
-
|
|
52
|
+
getPublishCount() {
|
|
53
|
+
return this._publishCount;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async _initAbly(ablyToken, channelName) {
|
|
122
57
|
if (this._ably) {
|
|
123
58
|
try {
|
|
124
59
|
this._ably.close();
|
|
@@ -126,48 +61,69 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
126
61
|
/* ignore */
|
|
127
62
|
}
|
|
128
63
|
}
|
|
129
|
-
this.
|
|
64
|
+
this._channelName = channelName;
|
|
130
65
|
var self = this;
|
|
131
66
|
|
|
132
67
|
this._ably = new Ably.Realtime({
|
|
133
|
-
authCallback: function (tokenParams, callback) {
|
|
134
|
-
|
|
68
|
+
authCallback: async function (tokenParams, callback) {
|
|
69
|
+
// On initial connect Ably may supply the token directly; on renewal
|
|
70
|
+
// we must fetch a fresh one from the API (the original token will
|
|
71
|
+
// have expired, causing 40143 token.unrecognized if reused).
|
|
72
|
+
try {
|
|
73
|
+
const response = await axios({
|
|
74
|
+
method: "post",
|
|
75
|
+
url: self.apiRoot + "/api/v7/sandbox/ably-token",
|
|
76
|
+
data: { apiKey: self.apiKey, sandboxId: self._sandboxId },
|
|
77
|
+
headers: { "Content-Type": "application/json" },
|
|
78
|
+
timeout: 15000,
|
|
79
|
+
});
|
|
80
|
+
callback(null, response.data.token);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
logger.warn("[ably] Token renewal failed, falling back to original token: " + (err.message || err));
|
|
83
|
+
callback(null, ablyToken);
|
|
84
|
+
}
|
|
135
85
|
},
|
|
136
86
|
clientId: "sdk-" + this._sandboxId,
|
|
87
|
+
echoMessages: false, // don't receive our own published messages
|
|
137
88
|
disconnectedRetryTimeout: 5000, // retry reconnect every 5s (default 15s)
|
|
138
89
|
suspendedRetryTimeout: 15000, // retry from suspended every 15s (default 30s)
|
|
139
90
|
});
|
|
140
91
|
|
|
92
|
+
logger.debug(`[realtime] Connecting as sdk-${this._sandboxId}...`);
|
|
93
|
+
|
|
141
94
|
await new Promise(function (resolve, reject) {
|
|
142
95
|
self._ably.connection.on("connected", resolve);
|
|
143
96
|
self._ably.connection.on("failed", function () {
|
|
144
|
-
reject(new Error("
|
|
97
|
+
reject(new Error("Realtime connection failed"));
|
|
145
98
|
});
|
|
146
99
|
setTimeout(function () {
|
|
147
|
-
reject(new Error("
|
|
100
|
+
reject(new Error("Realtime connection timeout"));
|
|
148
101
|
}, 30000);
|
|
149
102
|
});
|
|
150
103
|
|
|
151
|
-
this.
|
|
152
|
-
this._respChannel = this._ably.channels.get(channelNames.responses);
|
|
153
|
-
this._ctrlChannel = this._ably.channels.get(channelNames.control);
|
|
154
|
-
this._filesChannel = this._ably.channels.get(channelNames.files);
|
|
104
|
+
this._sessionChannel = this._ably.channels.get(channelName);
|
|
155
105
|
|
|
156
|
-
|
|
106
|
+
logger.debug(`[realtime] Channel initialized: ${channelName}`);
|
|
107
|
+
|
|
108
|
+
// Enter presence on the session channel so the API can count connected SDK clients
|
|
157
109
|
try {
|
|
158
|
-
await this.
|
|
110
|
+
await this._sessionChannel.presence.enter({
|
|
159
111
|
sandboxId: this._sandboxId,
|
|
160
112
|
connectedAt: Date.now(),
|
|
161
113
|
});
|
|
114
|
+
logger.debug(`[realtime] Entered presence on session channel (sandbox=${this._sandboxId})`);
|
|
162
115
|
} catch (e) {
|
|
163
116
|
// Non-fatal — presence is used for concurrency counting, not critical path
|
|
164
|
-
logger.warn("Failed to enter presence on
|
|
117
|
+
logger.warn("Failed to enter presence on session channel: " + (e.message || e));
|
|
165
118
|
}
|
|
166
119
|
|
|
167
|
-
|
|
120
|
+
// Save subscription references for historyBeforeSubscribe() during discontinuity recovery
|
|
121
|
+
this._onResponseMsg = function (msg) {
|
|
168
122
|
var message = msg.data;
|
|
169
123
|
if (!message) return;
|
|
170
124
|
|
|
125
|
+
logger.debug(`[realtime] Received response: type=${message.type || 'unknown'} (requestId=${message.requestId || 'none'})`);
|
|
126
|
+
|
|
171
127
|
if (message.type === "sandbox.progress") {
|
|
172
128
|
emitter.emit(events.sandbox.progress, {
|
|
173
129
|
step: message.step,
|
|
@@ -218,31 +174,53 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
218
174
|
}
|
|
219
175
|
|
|
220
176
|
if (!message.requestId || !self.ps[message.requestId]) {
|
|
221
|
-
var
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
177
|
+
var pendingIds = Object.keys(self.ps);
|
|
178
|
+
var pendingSummary = pendingIds.length > 0
|
|
179
|
+
? pendingIds.map(function (rid) {
|
|
180
|
+
var e = self.ps[rid];
|
|
181
|
+
return rid + '(' + (e && e.message ? e.message.type : '?') + ')';
|
|
182
|
+
}).join(', ')
|
|
183
|
+
: 'none';
|
|
184
|
+
logger.debug(
|
|
185
|
+
'[realtime] No pending promise for requestId=' + (message.requestId || 'null') +
|
|
186
|
+
' | response type=' + (message.type || 'unknown') +
|
|
187
|
+
' | error=' + (message.error ? (message.errorMessage || 'true') : 'false') +
|
|
188
|
+
' | currently pending: [' + pendingSummary + ']'
|
|
189
|
+
);
|
|
229
190
|
return;
|
|
230
191
|
}
|
|
231
192
|
|
|
232
193
|
if (message.error) {
|
|
233
|
-
var
|
|
234
|
-
|
|
235
|
-
|
|
194
|
+
var pendingEntry = self.ps[message.requestId];
|
|
195
|
+
var pendingMessage = pendingEntry && pendingEntry.message;
|
|
196
|
+
var pendingAge = pendingEntry && pendingEntry.startTime
|
|
197
|
+
? ((Date.now() - pendingEntry.startTime) / 1000).toFixed(1) + 's'
|
|
198
|
+
: '?';
|
|
199
|
+
logger.debug(
|
|
200
|
+
'[realtime] Promise REJECTED: requestId=' + message.requestId +
|
|
201
|
+
' | type=' + (pendingMessage ? pendingMessage.type : 'unknown') +
|
|
202
|
+
' | age=' + pendingAge +
|
|
203
|
+
' | error=' + (message.errorMessage || 'Sandbox error')
|
|
204
|
+
);
|
|
236
205
|
if (!pendingMessage || pendingMessage.type !== "output") {
|
|
237
206
|
emitter.emit(events.error.sandbox, message.errorMessage);
|
|
238
207
|
}
|
|
239
208
|
var error = new Error(message.errorMessage || "Sandbox error");
|
|
240
209
|
error.responseData = message;
|
|
241
210
|
delete self._execBuffers[message.requestId];
|
|
242
|
-
|
|
211
|
+
pendingEntry.reject(error);
|
|
243
212
|
} else {
|
|
244
213
|
emitter.emit(events.sandbox.received);
|
|
245
214
|
if (self.ps[message.requestId]) {
|
|
215
|
+
var resolveEntry = self.ps[message.requestId];
|
|
216
|
+
var resolveAge = resolveEntry.startTime
|
|
217
|
+
? ((Date.now() - resolveEntry.startTime) / 1000).toFixed(1) + 's'
|
|
218
|
+
: '?';
|
|
219
|
+
logger.debug(
|
|
220
|
+
'[realtime] Promise RESOLVED: requestId=' + message.requestId +
|
|
221
|
+
' | type=' + (resolveEntry.message ? resolveEntry.message.type : 'unknown') +
|
|
222
|
+
' | age=' + resolveAge
|
|
223
|
+
);
|
|
246
224
|
// Unwrap the result from the Ably response envelope
|
|
247
225
|
// The runner sends { requestId, type, result, success }
|
|
248
226
|
// But SDK commands expect just the result object
|
|
@@ -261,77 +239,230 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
261
239
|
}
|
|
262
240
|
}
|
|
263
241
|
delete self.ps[message.requestId];
|
|
264
|
-
}
|
|
242
|
+
};
|
|
243
|
+
this._responseSubscription = await this._sessionChannel.subscribe("response", this._onResponseMsg);
|
|
265
244
|
|
|
266
|
-
this.
|
|
245
|
+
this._onFileMsg = function (msg) {
|
|
267
246
|
var message = msg.data;
|
|
268
247
|
if (!message) return;
|
|
248
|
+
logger.debug(`[realtime] Received file: type=${message.type || 'unknown'} (requestId=${message.requestId || 'none'})`);
|
|
269
249
|
if (message.requestId && self.ps[message.requestId]) {
|
|
270
250
|
emitter.emit(events.sandbox.received);
|
|
271
251
|
self.ps[message.requestId].resolve(message);
|
|
272
252
|
delete self.ps[message.requestId];
|
|
273
253
|
}
|
|
274
254
|
emitter.emit(events.sandbox.file, message);
|
|
275
|
-
}
|
|
255
|
+
};
|
|
256
|
+
this._fileSubscription = await this._sessionChannel.subscribe("file", this._onFileMsg);
|
|
276
257
|
|
|
277
|
-
this.heartbeat = setInterval(function () {}, 5000);
|
|
258
|
+
this.heartbeat = setInterval(function () { }, 5000);
|
|
278
259
|
if (this.heartbeat.unref) this.heartbeat.unref();
|
|
279
260
|
|
|
261
|
+
// ─── Periodic stats logging ────────────────────────────────────────
|
|
262
|
+
this._statsInterval = setInterval(() => {
|
|
263
|
+
const connState = this._ably ? this._ably.connection.state : 'no-client';
|
|
264
|
+
const chState = this._sessionChannel ? this._sessionChannel.state : 'null';
|
|
265
|
+
const pendingIds = Object.keys(this.ps);
|
|
266
|
+
const pending = pendingIds.length;
|
|
267
|
+
logger.debug(`[realtime][stats] connection=${connState} | sandbox=${this._sandboxId} | pending=${pending} | channel=${chState}`);
|
|
268
|
+
if (pending > 0) {
|
|
269
|
+
const now = Date.now();
|
|
270
|
+
for (const rid of pendingIds) {
|
|
271
|
+
const entry = this.ps[rid];
|
|
272
|
+
if (!entry) continue;
|
|
273
|
+
const type = entry.message ? entry.message.type : 'unknown';
|
|
274
|
+
const ageSec = ((now - (entry.startTime || now)) / 1000).toFixed(1);
|
|
275
|
+
logger.debug(`[realtime][stats] pending: requestId=${rid} | type=${type} | age=${ageSec}s`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}, 10000);
|
|
279
|
+
if (this._statsInterval.unref) this._statsInterval.unref();
|
|
280
|
+
|
|
280
281
|
this._ably.connection.on("disconnected", function () {
|
|
281
|
-
logger.
|
|
282
|
+
logger.debug("[realtime] Connection: disconnected - will auto-reconnect");
|
|
283
|
+
self._disconnectedAt = Date.now();
|
|
282
284
|
});
|
|
283
285
|
|
|
284
286
|
this._ably.connection.on("connected", function () {
|
|
285
287
|
// Log reconnection so the user knows the blip was recovered
|
|
286
|
-
logger.
|
|
288
|
+
logger.debug("[realtime] Connection: reconnected");
|
|
289
|
+
// Extend any pending command timeouts by the disconnection duration so
|
|
290
|
+
// commands whose timer was counting down while the connection was down
|
|
291
|
+
// don't get incorrectly timed out.
|
|
292
|
+
if (self._disconnectedAt) {
|
|
293
|
+
var disconnectionDurationMs = Date.now() - self._disconnectedAt;
|
|
294
|
+
self._disconnectedAt = null;
|
|
295
|
+
var pendingIds = Object.keys(self.ps);
|
|
296
|
+
if (pendingIds.length > 0) {
|
|
297
|
+
logger.debug(
|
|
298
|
+
'[realtime] Extending ' + pendingIds.length + ' pending timeout(s) by ' +
|
|
299
|
+
disconnectionDurationMs + 'ms after disconnection'
|
|
300
|
+
);
|
|
301
|
+
for (var i = 0; i < pendingIds.length; i++) {
|
|
302
|
+
var entry = self.ps[pendingIds[i]];
|
|
303
|
+
if (entry && typeof entry.extendTimeout === 'function') {
|
|
304
|
+
entry.extendTimeout(disconnectionDurationMs);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
287
309
|
});
|
|
288
310
|
|
|
289
311
|
this._ably.connection.on("suspended", function () {
|
|
290
|
-
logger.
|
|
312
|
+
logger.debug("[realtime] Connection: suspended - connection lost for extended period, will keep retrying");
|
|
291
313
|
});
|
|
292
314
|
|
|
293
315
|
this._ably.connection.on("failed", function () {
|
|
316
|
+
logger.debug("[realtime] Connection: failed");
|
|
294
317
|
self.apiSocketConnected = false;
|
|
295
318
|
self.instanceSocketConnected = false;
|
|
296
|
-
emitter.emit(events.error.sandbox, "
|
|
319
|
+
emitter.emit(events.error.sandbox, "Realtime connection failed");
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
// ─── Channel discontinuity detection ──────────────────────────────
|
|
323
|
+
// Set up BEFORE subscribing so we catch any continuity loss during
|
|
324
|
+
// the initial attachment. Fires at the channel level, covering all
|
|
325
|
+
// message types (response, file, control).
|
|
326
|
+
this._sessionChannel.on(function (stateChange) {
|
|
327
|
+
var current = stateChange.current;
|
|
328
|
+
var previous = stateChange.previous;
|
|
329
|
+
var reason = stateChange.reason;
|
|
330
|
+
var reasonMsg = reason ? (reason.message || reason.code || String(reason)) : '';
|
|
331
|
+
|
|
332
|
+
if (current === 'attached' && stateChange.resumed === false && previous === 'attached') {
|
|
333
|
+
logger.debug('[realtime] Channel DISCONTINUITY detected (resumed=false)' + (reasonMsg ? ' — ' + reasonMsg : ''));
|
|
334
|
+
emitter.emit(events.sandbox.progress, {
|
|
335
|
+
step: 'discontinuity',
|
|
336
|
+
message: 'Recovering missed messages after connection interruption...',
|
|
337
|
+
});
|
|
338
|
+
self._recoverFromDiscontinuity();
|
|
339
|
+
}
|
|
297
340
|
});
|
|
298
341
|
}
|
|
299
342
|
|
|
300
343
|
/**
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
344
|
+
* Recover missed messages after a channel discontinuity.
|
|
345
|
+
* Uses historyBeforeSubscribe() on each subscription, which guarantees
|
|
346
|
+
* no gap between historical and live messages. Each recovered message
|
|
347
|
+
* is dispatched through the same handler that processes live messages
|
|
348
|
+
* so that pending promises are resolved/rejected correctly.
|
|
349
|
+
*/
|
|
350
|
+
async _recoverFromDiscontinuity() {
|
|
351
|
+
var subs = [
|
|
352
|
+
{ name: 'response', sub: this._responseSubscription, handler: this._onResponseMsg },
|
|
353
|
+
{ name: 'file', sub: this._fileSubscription, handler: this._onFileMsg },
|
|
354
|
+
];
|
|
355
|
+
var totalRecovered = 0;
|
|
356
|
+
for (var i = 0; i < subs.length; i++) {
|
|
357
|
+
var entry = subs[i];
|
|
358
|
+
if (!entry.sub) continue;
|
|
359
|
+
try {
|
|
360
|
+
logger.debug('[realtime] Discontinuity recovery: fetching historyBeforeSubscribe for ' + entry.name + '...');
|
|
361
|
+
var page = await entry.sub.historyBeforeSubscribe({ limit: 100 });
|
|
362
|
+
var recovered = 0;
|
|
363
|
+
while (page) {
|
|
364
|
+
// Replay each missed message through the handler so pending
|
|
365
|
+
// promises get resolved instead of timing out.
|
|
366
|
+
for (var j = 0; j < page.items.length; j++) {
|
|
367
|
+
recovered++;
|
|
368
|
+
try {
|
|
369
|
+
if (entry.handler) {
|
|
370
|
+
logger.debug('[realtime] Replaying recovered ' + entry.name + ' message (requestId=' + (page.items[j].data && page.items[j].data.requestId || 'none') + ')');
|
|
371
|
+
entry.handler(page.items[j]);
|
|
372
|
+
}
|
|
373
|
+
} catch (replayErr) {
|
|
374
|
+
logger.debug('[realtime] Error replaying recovered message: ' + (replayErr.message || replayErr));
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
page = page.hasNext() ? await page.next() : null;
|
|
378
|
+
}
|
|
379
|
+
totalRecovered += recovered;
|
|
380
|
+
logger.debug('[realtime] Discontinuity recovery: replayed ' + recovered + ' ' + entry.name + ' message(s) from gap');
|
|
381
|
+
} catch (err) {
|
|
382
|
+
logger.debug('[realtime] Discontinuity recovery failed for ' + entry.name + ': ' + (err.message || err));
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (totalRecovered > 0) {
|
|
386
|
+
logger.debug('[realtime] Recovered and replayed ' + totalRecovered + ' message(s) that were missed during connection interruption');
|
|
387
|
+
} else {
|
|
388
|
+
logger.debug('[realtime] Discontinuity recovery: no missed messages found');
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* POST to the API with retry for transient network errors (via withRetry)
|
|
394
|
+
* and infinite polling for CONCURRENCY_LIMIT_EXCEEDED (until vitest's
|
|
395
|
+
* testTimeout kills the test).
|
|
305
396
|
*/
|
|
306
397
|
async _httpPostWithConcurrencyRetry(path, body, timeout) {
|
|
307
|
-
var
|
|
398
|
+
var concurrencyRetryInterval = 10000; // 10 seconds between concurrency retries
|
|
308
399
|
var startTime = Date.now();
|
|
400
|
+
var sessionId = this.sessionInstance ? this.sessionInstance.get() : null;
|
|
401
|
+
|
|
402
|
+
var self = this;
|
|
403
|
+
var makeRequest = function () {
|
|
404
|
+
return axios({
|
|
405
|
+
method: "post",
|
|
406
|
+
url: self.apiRoot + path,
|
|
407
|
+
data: body,
|
|
408
|
+
headers: {
|
|
409
|
+
"Content-Type": "application/json",
|
|
410
|
+
"User-Agent": "TestDriverSDK/" + version + " (Node.js " + process.version + ")",
|
|
411
|
+
...getSentryTraceHeaders(sessionId),
|
|
412
|
+
},
|
|
413
|
+
timeout: timeout || 120000,
|
|
414
|
+
});
|
|
415
|
+
};
|
|
309
416
|
|
|
310
417
|
while (true) {
|
|
311
418
|
try {
|
|
312
|
-
|
|
419
|
+
var response = await withRetry(makeRequest, {
|
|
420
|
+
retryConfig: {
|
|
421
|
+
maxRetries: 3,
|
|
422
|
+
baseDelayMs: 2000,
|
|
423
|
+
retryableStatusCodes: [500, 502, 503, 504], // Don't retry 429 — handled below
|
|
424
|
+
},
|
|
425
|
+
onRetry: function (attempt, error, delayMs) {
|
|
426
|
+
var elapsed = Date.now() - startTime;
|
|
427
|
+
logger.warn(
|
|
428
|
+
"Transient network error: " + (error.message || error.code) +
|
|
429
|
+
" — POST " + path +
|
|
430
|
+
" — retry " + attempt + "/3" +
|
|
431
|
+
" in " + (delayMs / 1000).toFixed(1) + "s" +
|
|
432
|
+
" (" + Math.round(elapsed / 1000) + "s elapsed)...",
|
|
433
|
+
);
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
return response.data;
|
|
313
437
|
} catch (err) {
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
var elapsed = Date.now() - startTime;
|
|
323
|
-
|
|
324
|
-
logger.log(
|
|
325
|
-
"Concurrency limit reached — waiting " +
|
|
326
|
-
retryInterval / 1000 +
|
|
438
|
+
// Concurrency limit — poll forever until a slot opens
|
|
439
|
+
var responseData = err.response && err.response.data;
|
|
440
|
+
if (responseData && responseData.errorCode === "CONCURRENCY_LIMIT_EXCEEDED") {
|
|
441
|
+
var elapsed = Date.now() - startTime;
|
|
442
|
+
logger.log(
|
|
443
|
+
"Concurrency limit reached — waiting " +
|
|
444
|
+
concurrencyRetryInterval / 1000 +
|
|
327
445
|
"s for a slot to become available (" +
|
|
328
446
|
Math.round(elapsed / 1000) +
|
|
329
447
|
"s elapsed)...",
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
448
|
+
);
|
|
449
|
+
await new Promise(function (resolve) {
|
|
450
|
+
var t = setTimeout(resolve, concurrencyRetryInterval);
|
|
451
|
+
if (t.unref) t.unref();
|
|
452
|
+
});
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Non-retryable HTTP error — preserve responseData for callers
|
|
457
|
+
if (responseData) {
|
|
458
|
+
var httpErr = new Error(
|
|
459
|
+
responseData.errorMessage || responseData.message || "HTTP " + err.response.status,
|
|
460
|
+
);
|
|
461
|
+
httpErr.responseData = responseData;
|
|
462
|
+
throw httpErr;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
throw err;
|
|
335
466
|
}
|
|
336
467
|
}
|
|
337
468
|
}
|
|
@@ -362,6 +493,7 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
362
493
|
body.ci = message.ci;
|
|
363
494
|
if (message.ami) body.ami = message.ami;
|
|
364
495
|
if (message.instanceType) body.instanceType = message.instanceType;
|
|
496
|
+
if (message.e2bTemplateId) body.e2bTemplateId = message.e2bTemplateId;
|
|
365
497
|
if (message.keepAlive !== undefined) body.keepAlive = message.keepAlive;
|
|
366
498
|
}
|
|
367
499
|
|
|
@@ -390,14 +522,14 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
390
522
|
this._teamId = reply.teamId;
|
|
391
523
|
|
|
392
524
|
if (reply.ably && reply.ably.token) {
|
|
393
|
-
await this._initAbly(reply.ably.token, reply.ably.
|
|
525
|
+
await this._initAbly(reply.ably.token, reply.ably.channel);
|
|
394
526
|
this.instanceSocketConnected = true;
|
|
395
527
|
|
|
396
528
|
// Tell the runner to enable debug log forwarding if debug mode is on
|
|
397
529
|
var debugMode =
|
|
398
530
|
process.env.VERBOSE || process.env.TD_DEBUG;
|
|
399
|
-
if (debugMode && this.
|
|
400
|
-
this.
|
|
531
|
+
if (debugMode && this._sessionChannel) {
|
|
532
|
+
this._sessionChannel.publish("control", {
|
|
401
533
|
type: "debug",
|
|
402
534
|
enabled: true,
|
|
403
535
|
});
|
|
@@ -405,47 +537,64 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
405
537
|
}
|
|
406
538
|
|
|
407
539
|
if (message.type === "create") {
|
|
408
|
-
// E2B (Linux) sandboxes
|
|
409
|
-
//
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
return {
|
|
413
|
-
success: true,
|
|
414
|
-
sandbox: {
|
|
415
|
-
sandboxId: reply.sandboxId,
|
|
416
|
-
instanceId: reply.sandbox?.sandboxId || reply.sandboxId,
|
|
417
|
-
os: body.os || 'linux',
|
|
418
|
-
url: reply.url,
|
|
419
|
-
},
|
|
420
|
-
};
|
|
421
|
-
}
|
|
422
|
-
|
|
540
|
+
// E2B (Linux) sandboxes return a url directly.
|
|
541
|
+
// We still need to wait for runner.ready since sandbox-agent.js runs inside E2B.
|
|
542
|
+
const isE2B = !!reply.url;
|
|
543
|
+
|
|
423
544
|
const runnerIp = reply.runner && reply.runner.ip;
|
|
424
545
|
const noVncPort = reply.runner && reply.runner.noVncPort;
|
|
425
546
|
const runnerVncUrl = reply.runner && reply.runner.vncUrl;
|
|
426
547
|
|
|
427
|
-
|
|
548
|
+
// Log image version info (AMI for Windows, E2B template for Linux)
|
|
549
|
+
if (reply.imageVersion) {
|
|
550
|
+
if (isE2B) {
|
|
551
|
+
logger.log('E2B image version: v' + reply.imageVersion + (reply.e2bTemplateId ? ' (template: ' + reply.e2bTemplateId + ')' : ''));
|
|
552
|
+
} else {
|
|
553
|
+
logger.log('AMI image version: v' + reply.imageVersion + (reply.amiId ? ' (ami: ' + reply.amiId + ')' : ''));
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
if (!isE2B) {
|
|
558
|
+
logger.log(`Runner claimed — ip=${runnerIp || 'none'}, os=${reply.runner?.os || 'unknown'}, noVncPort=${noVncPort || 'not reported'}, vncUrl=${runnerVncUrl || 'not reported'}`);
|
|
559
|
+
}
|
|
428
560
|
|
|
429
|
-
//
|
|
430
|
-
//
|
|
431
|
-
//
|
|
561
|
+
// Wait for the runner agent to signal readiness before sending commands.
|
|
562
|
+
// Without this gate, commands published before the agent subscribes are lost.
|
|
563
|
+
// This applies to:
|
|
564
|
+
// - E2B Linux sandboxes (native runner agent via sandbox-agent.js)
|
|
565
|
+
// - Windows EC2 sandboxes without presence runners
|
|
566
|
+
// For presence-based Windows runners (reply.runner already set), the runner
|
|
567
|
+
// is already listening so we can skip the wait.
|
|
432
568
|
var self = this;
|
|
433
|
-
|
|
569
|
+
const needsReadyWait = this._sessionChannel && (isE2B || !reply.runner);
|
|
570
|
+
if (needsReadyWait) {
|
|
434
571
|
logger.log('Waiting for runner agent to signal readiness...');
|
|
435
|
-
|
|
572
|
+
// E2B (Linux) sandboxes need extra time: S3 upload + npm install can add 60-120s on top of sandbox boot
|
|
573
|
+
var readyTimeout = isE2B ? 300000 : 120000; // 5 min for E2B (S3+npm), 2 min for EC2
|
|
436
574
|
await new Promise(function (resolve, reject) {
|
|
437
575
|
var resolved = false;
|
|
438
576
|
function finish(data) {
|
|
439
577
|
if (resolved) return;
|
|
440
578
|
resolved = true;
|
|
441
579
|
clearTimeout(timer);
|
|
442
|
-
self.
|
|
580
|
+
self._sessionChannel.unsubscribe('control', onCtrl);
|
|
443
581
|
// Update runner info if provided
|
|
444
582
|
if (data && data.os) reply.runner = reply.runner || {};
|
|
445
583
|
if (data && data.os && reply.runner) reply.runner.os = data.os;
|
|
446
584
|
if (data && data.ip && reply.runner) reply.runner.ip = data.ip;
|
|
447
585
|
if (data && data.runnerVersion && reply.runner) reply.runner.version = data.runnerVersion;
|
|
586
|
+
// Persist version metadata for test result reporting
|
|
587
|
+
self._runnerVersionBefore = reply.imageVersion || null;
|
|
588
|
+
self._runnerVersionAfter = (data && data.runnerVersion) || reply.imageVersion || null;
|
|
589
|
+
self._wasUpdated = !!(data && data.runnerVersion && reply.imageVersion && data.runnerVersion !== reply.imageVersion);
|
|
448
590
|
logger.log('Runner agent ready (os=' + ((data && data.os) || 'unknown') + ', runner v' + ((data && data.runnerVersion) || 'unknown') + ')');
|
|
591
|
+
// Show upgrade info: if the runner's npm version differs from the baked image version,
|
|
592
|
+
// the runner was upgraded during provisioning.
|
|
593
|
+
var runnerVer = data && data.runnerVersion;
|
|
594
|
+
var imageVer = reply.imageVersion;
|
|
595
|
+
if (runnerVer && imageVer && runnerVer !== imageVer) {
|
|
596
|
+
logger.log('Runner upgraded during provisioning: v' + imageVer + ' \u2192 v' + runnerVer);
|
|
597
|
+
}
|
|
449
598
|
if (data && data.update) {
|
|
450
599
|
var u = data.update;
|
|
451
600
|
if (u.status === 'up-to-date') {
|
|
@@ -464,8 +613,13 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
464
613
|
var timer = setTimeout(function () {
|
|
465
614
|
if (!resolved) {
|
|
466
615
|
resolved = true;
|
|
467
|
-
self.
|
|
468
|
-
|
|
616
|
+
self._sessionChannel.unsubscribe('control', onCtrl);
|
|
617
|
+
var err = new Error('Runner agent did not signal readiness within ' + readyTimeout + 'ms');
|
|
618
|
+
sentry.captureException(err, {
|
|
619
|
+
tags: { phase: 'runner_ready', connection_type: 'create' },
|
|
620
|
+
extra: { readyTimeout: readyTimeout, sandboxId: reply.sandboxId },
|
|
621
|
+
});
|
|
622
|
+
reject(err);
|
|
469
623
|
}
|
|
470
624
|
}, readyTimeout);
|
|
471
625
|
if (timer.unref) timer.unref();
|
|
@@ -478,12 +632,12 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
478
632
|
finish(data);
|
|
479
633
|
}
|
|
480
634
|
};
|
|
481
|
-
self.
|
|
635
|
+
self._sessionChannel.subscribe('control', onCtrl);
|
|
482
636
|
|
|
483
637
|
// Also check channel history in case runner.ready was published
|
|
484
638
|
// before we subscribed (race condition on fast-booting agents).
|
|
485
639
|
try {
|
|
486
|
-
self.
|
|
640
|
+
self._sessionChannel.history({ limit: 50 }, function (err, page) {
|
|
487
641
|
if (err) {
|
|
488
642
|
logger.warn('History lookup failed (non-fatal): ' + (err.message || err));
|
|
489
643
|
return;
|
|
@@ -505,9 +659,13 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
505
659
|
});
|
|
506
660
|
}
|
|
507
661
|
// Prefer the full vncUrl reported by the runner (infrastructure-agnostic).
|
|
662
|
+
// For E2B sandboxes, use the url from the API reply.
|
|
508
663
|
// Fall back to constructing from ip + noVncPort for older runners.
|
|
509
664
|
let url;
|
|
510
|
-
if (
|
|
665
|
+
if (isE2B && reply.url) {
|
|
666
|
+
url = reply.url;
|
|
667
|
+
logger.log(`E2B sandbox ready — url=${url}`);
|
|
668
|
+
} else if (runnerVncUrl) {
|
|
511
669
|
url = runnerVncUrl;
|
|
512
670
|
logger.log(`Using runner-provided vncUrl: ${url}`);
|
|
513
671
|
} else if (runnerIp && noVncPort) {
|
|
@@ -529,6 +687,15 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
529
687
|
url: url,
|
|
530
688
|
vncPort: noVncPort || undefined,
|
|
531
689
|
runner: reply.runner,
|
|
690
|
+
// Extra metadata for test result reporting
|
|
691
|
+
amiId: reply.amiId || null,
|
|
692
|
+
e2bTemplateId: reply.e2bTemplateId || null,
|
|
693
|
+
imageVersion: reply.imageVersion || null,
|
|
694
|
+
runnerVersionBefore: this._runnerVersionBefore || reply.imageVersion || null,
|
|
695
|
+
runnerVersionAfter: this._runnerVersionAfter || reply.runner?.version || null,
|
|
696
|
+
wasUpdated: this._wasUpdated || false,
|
|
697
|
+
vncUrl: url || null,
|
|
698
|
+
channelName: this._channelName || null,
|
|
532
699
|
},
|
|
533
700
|
};
|
|
534
701
|
}
|
|
@@ -538,17 +705,22 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
538
705
|
// provision the config to the instance via SSM (client-side).
|
|
539
706
|
// This runs from the user's infrastructure where AWS permissions exist,
|
|
540
707
|
// rather than from the API server.
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
708
|
+
// NOTE: For direct connections, the user MUST provide the AWS instanceId
|
|
709
|
+
// because the API only knows the sandboxId, not the actual EC2 instance ID.
|
|
710
|
+
var instanceId = message.instanceId;
|
|
711
|
+
if (reply.agentConfig && instanceId) {
|
|
712
|
+
logger.log('Provisioning agent config to instance ' + instanceId + ' via SSM...');
|
|
713
|
+
await this._provisionAgentConfig(instanceId, reply.agentConfig);
|
|
544
714
|
logger.log('Agent config provisioned successfully.');
|
|
715
|
+
} else if (reply.agentConfig && !instanceId) {
|
|
716
|
+
logger.log('Warning: agentConfig returned but no instanceId provided - cannot provision via SSM');
|
|
545
717
|
}
|
|
546
718
|
|
|
547
719
|
// If the API returned agent credentials (reply.agent present),
|
|
548
720
|
// wait for the runner agent to signal readiness before sending commands.
|
|
549
721
|
// Without this gate, commands published before the agent subscribes are lost.
|
|
550
722
|
var self = this;
|
|
551
|
-
if (reply.agent && this.
|
|
723
|
+
if (reply.agent && this._sessionChannel) {
|
|
552
724
|
logger.log('Waiting for runner agent to signal readiness (direct connection)...');
|
|
553
725
|
var readyTimeout = 120000; // 120s — allows for SSM provisioning + agent startup
|
|
554
726
|
await new Promise(function (resolve, reject) {
|
|
@@ -557,7 +729,7 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
557
729
|
if (resolved) return;
|
|
558
730
|
resolved = true;
|
|
559
731
|
clearTimeout(timer);
|
|
560
|
-
self.
|
|
732
|
+
self._sessionChannel.unsubscribe('control', onCtrl);
|
|
561
733
|
logger.log('Runner agent ready (direct, os=' + ((data && data.os) || 'unknown') + ', runner v' + ((data && data.runnerVersion) || 'unknown') + ')');
|
|
562
734
|
if (data && data.update) {
|
|
563
735
|
var u = data.update;
|
|
@@ -577,8 +749,13 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
577
749
|
var timer = setTimeout(function () {
|
|
578
750
|
if (!resolved) {
|
|
579
751
|
resolved = true;
|
|
580
|
-
self.
|
|
581
|
-
|
|
752
|
+
self._sessionChannel.unsubscribe('control', onCtrl);
|
|
753
|
+
var err = new Error('Runner agent did not signal readiness within ' + readyTimeout + 'ms (direct connection)');
|
|
754
|
+
sentry.captureException(err, {
|
|
755
|
+
tags: { phase: 'runner_ready', connection_type: 'direct' },
|
|
756
|
+
extra: { readyTimeout: readyTimeout, sandboxId: reply.sandboxId, instanceId: message.instanceId },
|
|
757
|
+
});
|
|
758
|
+
reject(err);
|
|
582
759
|
}
|
|
583
760
|
}, readyTimeout);
|
|
584
761
|
if (timer.unref) timer.unref();
|
|
@@ -591,12 +768,12 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
591
768
|
finish(data);
|
|
592
769
|
}
|
|
593
770
|
};
|
|
594
|
-
self.
|
|
771
|
+
self._sessionChannel.subscribe('control', onCtrl);
|
|
595
772
|
|
|
596
773
|
// Also check channel history in case runner.ready was published
|
|
597
774
|
// before we subscribed (race condition on fast-booting agents).
|
|
598
775
|
try {
|
|
599
|
-
self.
|
|
776
|
+
self._sessionChannel.history({ limit: 50 }, function (err, page) {
|
|
600
777
|
if (err) {
|
|
601
778
|
logger.warn('History lookup failed (non-fatal): ' + (err.message || err));
|
|
602
779
|
return;
|
|
@@ -638,7 +815,7 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
638
815
|
_sendAbly(message, timeout) {
|
|
639
816
|
if (timeout === undefined) timeout = 300000;
|
|
640
817
|
|
|
641
|
-
if (!this.
|
|
818
|
+
if (!this._sessionChannel || !this._ably) {
|
|
642
819
|
return Promise.reject(
|
|
643
820
|
new Error("Sandbox not connected (no Ably client)"),
|
|
644
821
|
);
|
|
@@ -666,7 +843,7 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
666
843
|
function onFailed() {
|
|
667
844
|
clearTimeout(timer);
|
|
668
845
|
self._ably.connection.off("connected", onConnected);
|
|
669
|
-
reject(new Error("
|
|
846
|
+
reject(new Error("Realtime connection failed while waiting to send"));
|
|
670
847
|
}
|
|
671
848
|
self._ably.connection.once("connected", onConnected);
|
|
672
849
|
self._ably.connection.once("failed", onFailed);
|
|
@@ -724,21 +901,41 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
724
901
|
|
|
725
902
|
var requestId = message.requestId;
|
|
726
903
|
|
|
727
|
-
|
|
904
|
+
// timeoutId and timeoutExpiresAt are declared as vars so they can be
|
|
905
|
+
// updated by extendTimeout() (closure mutation).
|
|
906
|
+
var timeoutId;
|
|
907
|
+
var timeoutExpiresAt;
|
|
908
|
+
|
|
909
|
+
var timeoutFn = function () {
|
|
728
910
|
if (self.ps[requestId]) {
|
|
911
|
+
var pendingIds = Object.keys(self.ps);
|
|
912
|
+
var pendingSummary = pendingIds.map(function (rid) {
|
|
913
|
+
var e = self.ps[rid];
|
|
914
|
+
var age = e && e.startTime ? ((Date.now() - e.startTime) / 1000).toFixed(1) + 's' : '?';
|
|
915
|
+
return rid + '(' + (e && e.message ? e.message.type : '?') + ', ' + age + ')';
|
|
916
|
+
}).join(', ');
|
|
917
|
+
logger.error(
|
|
918
|
+
'[realtime] Promise TIMEOUT: requestId=' + requestId +
|
|
919
|
+
' | type=' + message.type +
|
|
920
|
+
' | timeout=' + timeout + 'ms' +
|
|
921
|
+
' | all pending: [' + pendingSummary + ']'
|
|
922
|
+
);
|
|
729
923
|
delete self.ps[requestId];
|
|
730
924
|
delete self._execBuffers[requestId];
|
|
731
925
|
rejectPromise(
|
|
732
926
|
new Error(
|
|
733
927
|
"Sandbox message '" +
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
928
|
+
message.type +
|
|
929
|
+
"' timed out after " +
|
|
930
|
+
timeout +
|
|
931
|
+
"ms",
|
|
738
932
|
),
|
|
739
933
|
);
|
|
740
934
|
}
|
|
741
|
-
}
|
|
935
|
+
};
|
|
936
|
+
|
|
937
|
+
timeoutId = setTimeout(timeoutFn, timeout);
|
|
938
|
+
timeoutExpiresAt = Date.now() + timeout;
|
|
742
939
|
if (timeoutId.unref) timeoutId.unref();
|
|
743
940
|
|
|
744
941
|
this.ps[requestId] = {
|
|
@@ -751,16 +948,35 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
751
948
|
clearTimeout(timeoutId);
|
|
752
949
|
rejectPromise(error);
|
|
753
950
|
},
|
|
951
|
+
/**
|
|
952
|
+
* Extend the pending timeout by disconnectionDurationMs — called on Ably reconnect
|
|
953
|
+
* to compensate for time spent disconnected.
|
|
954
|
+
*/
|
|
955
|
+
extendTimeout: function (disconnectionDurationMs) {
|
|
956
|
+
clearTimeout(timeoutId);
|
|
957
|
+
// Clamp remaining to 0 so a command whose timer expired during the
|
|
958
|
+
// outage still gets the full disconnection duration as its new budget.
|
|
959
|
+
var remaining = Math.max(0, timeoutExpiresAt - Date.now());
|
|
960
|
+
// Minimum 5s remaining after extension to allow the response to arrive.
|
|
961
|
+
var MIN_REMAINING_MS = 5000;
|
|
962
|
+
var newRemaining = Math.max(remaining + disconnectionDurationMs, MIN_REMAINING_MS);
|
|
963
|
+
timeoutExpiresAt = Date.now() + newRemaining;
|
|
964
|
+
timeoutId = setTimeout(timeoutFn, newRemaining);
|
|
965
|
+
if (timeoutId.unref) timeoutId.unref();
|
|
966
|
+
logger.log(
|
|
967
|
+
'[realtime] Extended timeout for requestId=' + requestId +
|
|
968
|
+
' by ' + disconnectionDurationMs + 'ms (new remaining: ' + Math.round(newRemaining / 1000) + 's)'
|
|
969
|
+
);
|
|
970
|
+
},
|
|
754
971
|
message: message,
|
|
755
972
|
startTime: Date.now(),
|
|
756
973
|
};
|
|
757
974
|
|
|
758
975
|
if (message.type === "output") {
|
|
759
|
-
p.catch(function () {});
|
|
976
|
+
p.catch(function () { });
|
|
760
977
|
}
|
|
761
978
|
|
|
762
|
-
this.
|
|
763
|
-
.publish("command", message)
|
|
979
|
+
this._throttledPublish(this._sessionChannel, "command", message)
|
|
764
980
|
.then(function () {
|
|
765
981
|
emitter.emit(events.sandbox.sent, message);
|
|
766
982
|
})
|
|
@@ -777,6 +993,53 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
777
993
|
return p;
|
|
778
994
|
}
|
|
779
995
|
|
|
996
|
+
/**
|
|
997
|
+
* Throttled publish to stay under Ably's 50 msg/sec per-connection limit.
|
|
998
|
+
* Also tracks and logs the current publish rate for debugging.
|
|
999
|
+
* @param {Object} channel - Ably channel to publish on
|
|
1000
|
+
* @param {string} eventName - Event name for the publish
|
|
1001
|
+
* @param {Object} message - Message payload
|
|
1002
|
+
* @returns {Promise} - Resolves when publish completes
|
|
1003
|
+
*/
|
|
1004
|
+
async _throttledPublish(channel, eventName, message) {
|
|
1005
|
+
var self = this;
|
|
1006
|
+
var now = Date.now();
|
|
1007
|
+
|
|
1008
|
+
// Rate limiting: wait if too soon since last publish
|
|
1009
|
+
var elapsed = now - this._publishLastTime;
|
|
1010
|
+
if (elapsed < this._publishMinIntervalMs) {
|
|
1011
|
+
var waitMs = this._publishMinIntervalMs - elapsed;
|
|
1012
|
+
await new Promise(function (resolve) {
|
|
1013
|
+
var timer = setTimeout(resolve, waitMs);
|
|
1014
|
+
if (timer.unref) timer.unref();
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
this._publishLastTime = Date.now();
|
|
1018
|
+
|
|
1019
|
+
// Metrics: track messages per second
|
|
1020
|
+
this._publishCount++;
|
|
1021
|
+
var windowElapsed = Date.now() - this._publishWindowStart;
|
|
1022
|
+
if (windowElapsed >= 1000) {
|
|
1023
|
+
var rate = (this._publishCount / windowElapsed) * 1000;
|
|
1024
|
+
var rateStr = rate.toFixed(1);
|
|
1025
|
+
|
|
1026
|
+
// Log rate - warning if approaching limit, debug otherwise
|
|
1027
|
+
if (rate > 45) {
|
|
1028
|
+
logger.warn("Ably publish rate: " + rateStr + " msg/sec (approaching 50/sec limit)");
|
|
1029
|
+
} else if (process.env.VERBOSE || process.env.TD_DEBUG) {
|
|
1030
|
+
logger.log("Ably publish rate: " + rateStr + " msg/sec");
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
// Reset window
|
|
1034
|
+
this._publishCount = 0;
|
|
1035
|
+
this._publishWindowStart = Date.now();
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
return channel.publish(eventName, message).then(function () {
|
|
1039
|
+
logger.debug(`[realtime] Published: channel=${channel.name.split(':').pop()}, event=${eventName}, type=${message.type || 'unknown'} (requestId=${message.requestId || 'none'})`);
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
|
|
780
1043
|
async auth(apiKey) {
|
|
781
1044
|
this.apiKey = apiKey;
|
|
782
1045
|
var sessionId = this.sessionInstance
|
|
@@ -803,7 +1066,7 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
803
1066
|
logger.log("Trace Report (Share When Reporting Bugs):");
|
|
804
1067
|
logger.log(
|
|
805
1068
|
"https://testdriver.sentry.io/explore/traces/trace/" +
|
|
806
|
-
|
|
1069
|
+
reply.traceId,
|
|
807
1070
|
);
|
|
808
1071
|
}
|
|
809
1072
|
|
|
@@ -846,7 +1109,7 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
846
1109
|
this._sandboxId = reply.sandboxId;
|
|
847
1110
|
|
|
848
1111
|
if (reply.ably && reply.ably.token) {
|
|
849
|
-
await this._initAbly(reply.ably.token, reply.ably.
|
|
1112
|
+
await this._initAbly(reply.ably.token, reply.ably.channel);
|
|
850
1113
|
}
|
|
851
1114
|
|
|
852
1115
|
this.setConnectionParams({
|
|
@@ -895,38 +1158,43 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
895
1158
|
clearInterval(this.heartbeat);
|
|
896
1159
|
this.heartbeat = null;
|
|
897
1160
|
}
|
|
1161
|
+
if (this._statsInterval) {
|
|
1162
|
+
clearInterval(this._statsInterval);
|
|
1163
|
+
this._statsInterval = null;
|
|
1164
|
+
}
|
|
898
1165
|
|
|
899
1166
|
// Send end-session control message to runner before disconnecting
|
|
900
|
-
if (this.
|
|
1167
|
+
if (this._sessionChannel && this._ably?.connection?.state === 'connected') {
|
|
901
1168
|
try {
|
|
902
|
-
|
|
1169
|
+
logger.debug('[realtime] Publishing control: type=end-session');
|
|
1170
|
+
await this._sessionChannel.publish('control', { type: 'end-session' });
|
|
903
1171
|
} catch (e) {
|
|
904
1172
|
// Ignore - best effort
|
|
905
1173
|
}
|
|
906
1174
|
}
|
|
907
1175
|
|
|
908
|
-
// Leave presence on
|
|
909
|
-
if (this.
|
|
1176
|
+
// Leave presence on session channel
|
|
1177
|
+
if (this._sessionChannel) {
|
|
910
1178
|
try {
|
|
911
|
-
|
|
1179
|
+
logger.debug('[realtime] Leaving presence on session channel');
|
|
1180
|
+
await this._sessionChannel.presence.leave();
|
|
912
1181
|
} catch (e) {
|
|
913
1182
|
// ignore - best effort, Ably will auto-leave on disconnect
|
|
914
1183
|
}
|
|
915
1184
|
}
|
|
916
1185
|
|
|
917
1186
|
try {
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
this.
|
|
921
|
-
|
|
922
|
-
this._filesChannel?.detach(),
|
|
923
|
-
].filter(Boolean));
|
|
1187
|
+
logger.debug('[realtime] Detaching session channel');
|
|
1188
|
+
if (this._sessionChannel) {
|
|
1189
|
+
await this._sessionChannel.detach();
|
|
1190
|
+
}
|
|
924
1191
|
} catch (e) {
|
|
925
1192
|
/* ignore */
|
|
926
1193
|
}
|
|
927
1194
|
|
|
928
1195
|
if (this._ably) {
|
|
929
1196
|
try {
|
|
1197
|
+
logger.debug('[realtime] Closing Realtime connection');
|
|
930
1198
|
this._ably.close();
|
|
931
1199
|
} catch (e) {
|
|
932
1200
|
/* ignore */
|
|
@@ -934,11 +1202,8 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
934
1202
|
this._ably = null;
|
|
935
1203
|
}
|
|
936
1204
|
|
|
937
|
-
this.
|
|
938
|
-
this.
|
|
939
|
-
this._ctrlChannel = null;
|
|
940
|
-
this._filesChannel = null;
|
|
941
|
-
this._channelNames = null;
|
|
1205
|
+
this._sessionChannel = null;
|
|
1206
|
+
this._channelName = null;
|
|
942
1207
|
this.apiSocketConnected = false;
|
|
943
1208
|
this.instanceSocketConnected = false;
|
|
944
1209
|
this.authenticated = false;
|
|
@@ -961,11 +1226,51 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
961
1226
|
const region = process.env.AWS_REGION || 'us-east-2';
|
|
962
1227
|
|
|
963
1228
|
// Write SSM parameters to a temp file to avoid shell quoting issues
|
|
1229
|
+
// Log key config details for debugging
|
|
1230
|
+
logger.log('Agent config being provisioned:');
|
|
1231
|
+
logger.log(' sandboxId: ' + agentConfig.sandboxId);
|
|
1232
|
+
logger.log(' apiRoot: ' + agentConfig.apiRoot);
|
|
1233
|
+
logger.log(' channel: ' + (agentConfig.ably?.channel || 'N/A'));
|
|
1234
|
+
logger.log(' token length: ' + (agentConfig.ably?.token ? JSON.stringify(agentConfig.ably.token).length : 0));
|
|
1235
|
+
|
|
964
1236
|
const paramsJson = JSON.stringify({
|
|
965
1237
|
commands: [
|
|
1238
|
+
// Debug: show existing state
|
|
1239
|
+
"Write-Host '=== Checking existing state ==='",
|
|
1240
|
+
"$task = Get-ScheduledTask -TaskName RunTestDriverAgent -ErrorAction SilentlyContinue",
|
|
1241
|
+
"if ($task) { Write-Host \"Task exists, state: $($task.State)\" } else { Write-Host 'Task does NOT exist!' }",
|
|
1242
|
+
"if (Test-Path 'C:\\Windows\\Temp\\testdriver-agent.json') { Write-Host 'Old config:'; Get-Content 'C:\\Windows\\Temp\\testdriver-agent.json' | Write-Host } else { Write-Host 'Config file does NOT exist yet' }",
|
|
1243
|
+
// Stop any running runner
|
|
1244
|
+
"Write-Host '=== Stopping runner ==='",
|
|
1245
|
+
"Stop-Process -Name node -Force -ErrorAction SilentlyContinue",
|
|
1246
|
+
"Stop-ScheduledTask -TaskName RunTestDriverAgent -ErrorAction SilentlyContinue",
|
|
1247
|
+
// Write config
|
|
1248
|
+
"Write-Host '=== Writing config ==='",
|
|
966
1249
|
"$config = '" + configJson.replace(/'/g, "''") + "'",
|
|
967
1250
|
"[System.IO.File]::WriteAllText('C:\\Windows\\Temp\\testdriver-agent.json', $config)",
|
|
968
1251
|
"Write-Host 'Config written for sandbox " + agentConfig.sandboxId + "'",
|
|
1252
|
+
// Show what was written (redact token)
|
|
1253
|
+
"Write-Host '=== New config (token redacted) ==='",
|
|
1254
|
+
"$cfg = Get-Content 'C:\\Windows\\Temp\\testdriver-agent.json' | ConvertFrom-Json",
|
|
1255
|
+
"Write-Host \"sandboxId: $($cfg.sandboxId)\"",
|
|
1256
|
+
"Write-Host \"apiRoot: $($cfg.apiRoot)\"",
|
|
1257
|
+
"Write-Host \"channel: $($cfg.ably.channel)\"",
|
|
1258
|
+
"Write-Host \"token type: $($cfg.ably.token.GetType().Name)\"",
|
|
1259
|
+
// Start the runner
|
|
1260
|
+
"Write-Host '=== Starting runner ==='",
|
|
1261
|
+
"Start-Sleep -Seconds 1",
|
|
1262
|
+
"Start-ScheduledTask -TaskName RunTestDriverAgent -ErrorAction Stop",
|
|
1263
|
+
"$task = Get-ScheduledTask -TaskName RunTestDriverAgent",
|
|
1264
|
+
"Write-Host \"Task state after start: $($task.State)\"",
|
|
1265
|
+
// Check if node process started
|
|
1266
|
+
"Start-Sleep -Seconds 3",
|
|
1267
|
+
"Write-Host '=== Checking runner process ==='",
|
|
1268
|
+
"$procs = Get-Process -Name node -ErrorAction SilentlyContinue",
|
|
1269
|
+
"if ($procs) { Write-Host \"Node processes: $($procs.Count)\"; $procs | ForEach-Object { Write-Host \" PID: $($_.Id), StartTime: $($_.StartTime)\" } } else { Write-Host 'No node process found!' }",
|
|
1270
|
+
// Check runner logs
|
|
1271
|
+
"Write-Host '=== Runner log (last 30 lines) ==='",
|
|
1272
|
+
"if (Test-Path 'C:\\testdriver\\logs\\sandbox-agent.log') { Get-Content 'C:\\testdriver\\logs\\sandbox-agent.log' -Tail 30 | Write-Host } else { Write-Host 'No log file found' }",
|
|
1273
|
+
"Write-Host '=== Done ==='",
|
|
969
1274
|
],
|
|
970
1275
|
});
|
|
971
1276
|
const tmpFile = join(tmpdir(), 'td-provision-' + Date.now() + '.json');
|
|
@@ -987,6 +1292,24 @@ const createSandbox = function (emitter, analytics, sessionInstance) {
|
|
|
987
1292
|
'--command-id "' + cmdId + '" --instance-id "' + instanceId + '"',
|
|
988
1293
|
{ encoding: 'utf-8', timeout: 60000 }
|
|
989
1294
|
);
|
|
1295
|
+
|
|
1296
|
+
// Get the command output for debugging
|
|
1297
|
+
try {
|
|
1298
|
+
const invocationOutput = execSync(
|
|
1299
|
+
'aws ssm get-command-invocation --region "' + region + '" ' +
|
|
1300
|
+
'--command-id "' + cmdId + '" --instance-id "' + instanceId + '" --output json',
|
|
1301
|
+
{ encoding: 'utf-8', timeout: 30000 }
|
|
1302
|
+
);
|
|
1303
|
+
const invocation = JSON.parse(invocationOutput);
|
|
1304
|
+
if (invocation.StandardOutputContent) {
|
|
1305
|
+
logger.log('SSM output:\n' + invocation.StandardOutputContent);
|
|
1306
|
+
}
|
|
1307
|
+
if (invocation.StandardErrorContent) {
|
|
1308
|
+
logger.warn('SSM errors:\n' + invocation.StandardErrorContent);
|
|
1309
|
+
}
|
|
1310
|
+
} catch (e) {
|
|
1311
|
+
logger.warn('Could not retrieve SSM command output: ' + e.message);
|
|
1312
|
+
}
|
|
990
1313
|
} finally {
|
|
991
1314
|
try { unlinkSync(tmpFile); } catch (e) { /* ignore */ }
|
|
992
1315
|
}
|