Skip to content

Commit 2cbc69e

Browse files
fix keep active while connected
1 parent f9fe27a commit 2cbc69e

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

src/SandboxClient/index.ts

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { Hosts } from "./hosts";
1212
import { IAgentClient } from "../node/agent-client-interface";
1313
import { setup } from "../pitcher-protocol";
1414
import { Barrier } from "../utils/barrier";
15+
import { clear } from "console";
1516

1617
export * from "./filesystem";
1718
export * from "./ports";
@@ -126,6 +127,30 @@ export class SandboxClient {
126127
this.hosts = new Hosts(this.agentClient.sandboxId, hostToken);
127128
this.interpreters = new Interpreters(this.disposable, this.commands);
128129
this.disposable.onWillDispose(() => this.agentClient.dispose());
130+
131+
this.disposable.onWillDispose(() => {
132+
if (this.keepAliveInterval) {
133+
clearInterval(this.keepAliveInterval);
134+
this.keepAliveInterval = null;
135+
}
136+
});
137+
138+
this.agentClient.onStateChange((state) => {
139+
if (!this.shouldKeepAlive) {
140+
return;
141+
}
142+
143+
// We can not call `keepActiveWhileConnected` here, because it would
144+
// reset the interval, which would turn off the "shouldKeepAlive" flag
145+
if (state === "DISCONNECTED" || state === "HIBERNATED") {
146+
if (this.keepAliveInterval) {
147+
clearInterval(this.keepAliveInterval);
148+
}
149+
this.keepAliveInterval = null;
150+
} else if (state === "CONNECTED") {
151+
this.keepActiveWhileConnected(true);
152+
}
153+
});
129154
}
130155

131156
/**
@@ -219,6 +244,11 @@ export class SandboxClient {
219244
* reconnect to the sandbox.
220245
*/
221246
public disconnect() {
247+
if (this.keepAliveInterval) {
248+
clearInterval(this.keepAliveInterval);
249+
this.keepAliveInterval = null;
250+
}
251+
222252
return this.agentClient.disconnect();
223253
}
224254

@@ -230,22 +260,19 @@ export class SandboxClient {
230260
}
231261

232262
private keepAliveInterval: NodeJS.Timeout | null = null;
263+
private shouldKeepAlive = false;
233264
/**
234265
* If enabled, we will keep the sandbox from hibernating as long as the SDK is connected to it.
235266
*/
236267
public keepActiveWhileConnected(enabled: boolean) {
268+
// Used to manage the interval when disconnects happen
269+
this.shouldKeepAlive = enabled;
270+
237271
if (enabled) {
238272
if (!this.keepAliveInterval) {
239273
this.keepAliveInterval = setInterval(() => {
240274
this.agentClient.system.update();
241275
}, 1000 * 30);
242-
243-
this.disposable.onWillDispose(() => {
244-
if (this.keepAliveInterval) {
245-
clearInterval(this.keepAliveInterval);
246-
this.keepAliveInterval = null;
247-
}
248-
});
249276
}
250277
} else {
251278
if (this.keepAliveInterval) {

0 commit comments

Comments
 (0)