Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): always await for sandbox boot in pi cloud (#95053)

Jonathan Mieloo4e55369fb719
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
index 0a73160117b9..022e24d06ccd 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
@@ -895,8 +895,12 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
if (!response.ok) {
const errorText = await response.text().catch(() => "");
let errorMessage = `Command failed with status ${response.status}`;
+ let errorCode: string | undefined;
try {
const errorJson = JSON.parse(errorText);
+ if (typeof errorJson.code === "string") {
+ errorCode = errorJson.code;
+ }
if (errorJson.error?.message) {
errorMessage = errorJson.error.message;
} else if (errorJson.error) {
@@ -915,11 +919,13 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
method: input.method,
status: response.status,
error: errorMessage,
+ code: errorCode,
});
const retryable = [400, 502, 503, 504].includes(response.status);
return {
success: false,
error: errorMessage,
+ code: errorCode,
status: response.status,
retryable,
};
diff --git a/products/desktop/packages/core/src/cloud-task/schemas.ts b/products/desktop/packages/core/src/cloud-task/schemas.ts
index 69e6fdbeae64..ae79c62437c2 100644
--- a/products/desktop/packages/core/src/cloud-task/schemas.ts
+++ b/products/desktop/packages/core/src/cloud-task/schemas.ts
@@ -87,6 +87,7 @@ export const sendCommandOutput = z.object({
success: z.boolean(),
result: z.unknown().optional(),
error: z.string().optional(),
+ code: z.string().optional(),
status: z.number().optional(),
retryable: z.boolean().optional(),
});
diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts
index 577c99451d78..9c04ec3b9f39 100644
--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts
+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts
@@ -360,6 +360,65 @@ describe("CloudPiSessionClient", () => {
expect(cloud.client.sendCommand).toHaveBeenCalledOnce();
});
+ it("retries a sandbox command after a resumed sandbox starts", async () => {
+ const cloud = createCloudTaskClient();
+ let liveRuntimeStarted = false;
+ vi.mocked(cloud.client.sendCommand)
+ .mockResolvedValueOnce({
+ success: false,
+ status: 400,
+ code: "sandbox_not_ready",
+ error: "No active sandbox for this task run",
+ })
+ .mockImplementationOnce(async () => {
+ if (!liveRuntimeStarted) {
+ throw new Error("Sandbox command retried before Pi started");
+ }
+ return {
+ success: true,
+ result: {
+ type: "response",
+ command: "get_state",
+ success: true,
+ data: { isStreaming: false },
+ },
+ };
+ });
+ const session = new CloudPiSessionClient(
+ cloud.client,
+ context("in_progress"),
+ );
+ session.onConversationEvent(vi.fn(), vi.fn());
+
+ const state = session.client.getState();
+ cloud.sendUpdate({
+ taskId: "task-1",
+ runId: "run-1",
+ kind: "snapshot",
+ status: "in_progress",
+ newEntries: [{ type: "pi_run_started" }],
+ totalEntryCount: 1,
+ });
+
+ await vi.waitFor(() =>
+ expect(cloud.client.sendCommand).toHaveBeenCalledOnce(),
+ );
+
+ liveRuntimeStarted = true;
+ cloud.sendUpdate({
+ taskId: "task-1",
+ runId: "run-1",
+ kind: "logs",
+ newEntries: [{ type: "pi_run_started" }],
+ totalEntryCount: 2,
+ });
+
+ await expect(state).resolves.toMatchObject({ isStreaming: false });
+ expect(cloud.client.sendCommand).toHaveBeenCalledTimes(2);
+ const commandCalls = vi.mocked(cloud.client.sendCommand).mock.calls;
+ expect(commandCalls[1][0].id).toBe(commandCalls[0][0].id);
+ });
+
it("does not fail while a sandbox takes longer than 30 seconds to boot", async () => {
vi.useFakeTimers();
try {
diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts
index 7156945c39d2..6ee4f68fad23 100644
--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts
+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts
@@ -30,6 +30,8 @@ import type { CloudTaskClient } from "../cloud-task/cloudTaskClient";
import {
isTerminalStatus,
progressNotificationParams,
+ type SendCommandInput,
+ type SendCommandOutput,
} from "../cloud-task/schemas";
import type {
PiConversationEventContext,
@@ -126,6 +128,15 @@ function isCompletedCompaction(event: AgentConversationEvent): boolean {
);
}
+function isNoActiveSandboxError(result: SendCommandOutput): boolean {
+ return (
+ result.success === false &&
+ result.status === 400 &&
+ (result.code === "sandbox_not_ready" ||
+ result.error === "No active sandbox for this task run")
+ );
+}
+
export interface CloudPiSessionContext {
taskId: string;
runId: string;
@@ -157,6 +168,15 @@ export class CloudPiSessionClient implements PiSession {
this.rejectRuntimeReady = reject;
},
);
+ private liveRuntimeStarted = false;
+ private resolveLiveRuntimeStarted: () => void = () => {};
+ private rejectLiveRuntimeStarted: (error: unknown) => void = () => {};
+ private readonly liveRuntimeStartedReceived = new Promise<void>(
+ (resolve, reject) => {
+ this.resolveLiveRuntimeStarted = resolve;
+ this.rejectLiveRuntimeStarted = reject;
+ },
+ );
private terminalEventSent = false;
private readonly resolvedExtensionRequestIds = new Set<string>();
private resolveTerminalStatus: () => void = () => {};
@@ -174,6 +194,7 @@ export class CloudPiSessionClient implements PiSession {
}
void this.snapshotReceived.catch(() => {});
void this.runtimeReadyReceived.catch(() => {});
+ void this.liveRuntimeStartedReceived.catch(() => {});
this.liveClient = new RemotePiRpcClient({
request: (command) => this.request(command),
});
@@ -441,6 +462,7 @@ export class CloudPiSessionClient implements PiSession {
(update) => this.handleUpdate(update, onEvent, onError, onCloudStatus),
(error) => {
this.rejectRuntimeReady(error);
+ this.rejectLiveRuntimeStarted(error);
if (!this.snapshotReady || isTerminalStatus(this.runStatus)) {
this.rejectSnapshot(error);
}
@@ -460,6 +482,7 @@ export class CloudPiSessionClient implements PiSession {
})
.catch((error) => {
this.rejectRuntimeReady(error);
+ this.rejectLiveRuntimeStarted(error);
if (!this.snapshotReady || isTerminalStatus(this.runStatus)) {
this.rejectSnapshot(error);
}
@@ -492,10 +515,15 @@ export class CloudPiSessionClient implements PiSession {
update.kind === "snapshot" &&
update.status === "in_progress" &&
update.sandboxAlive !== false;
- const hasCurrentReadinessEvent =
- (update.kind === "logs" || snapshotCanProveReadiness) &&
+ const hasRuntimeStartedEvent =
+ (update.kind === "logs" || update.kind === "snapshot") &&
update.newEntries.some((entry) => entry.type === "pi_run_started");
- if (hasCurrentReadinessEvent) {
+ const hasLiveRuntimeStarted =
+ update.kind === "logs" && hasRuntimeStartedEvent;
+ if (hasLiveRuntimeStarted) {
+ this.markLiveRuntimeStarted();
+ this.markRuntimeReady();
+ } else if (snapshotCanProveReadiness && hasRuntimeStartedEvent) {
this.markRuntimeReady();
}
@@ -505,6 +533,7 @@ export class CloudPiSessionClient implements PiSession {
retryable: update.retryable,
});
this.rejectRuntimeReady(error);
+ this.rejectLiveRuntimeStarted(error);
if (!this.snapshotReady || isTerminalStatus(this.runStatus)) {
this.rejectSnapshot(error);
}
@@ -702,7 +731,7 @@ export class CloudPiSessionClient implements PiSession {
if (isTerminalStatus(this.runStatus)) {
return { steering: [], followUp: [] };
}
- const result = await this.cloudTaskClient.sendCommand({
+ const result = await this.sendSandboxCommand({
taskId: this.context.taskId,
runId: this.context.runId,
apiHost: this.context.apiHost,
@@ -743,7 +772,7 @@ export class CloudPiSessionClient implements PiSession {
};
}
- const result = await this.cloudTaskClient.sendCommand({
+ const result = await this.sendSandboxCommand({
taskId: this.context.taskId,
runId: this.context.runId,
apiHost: this.context.apiHost,
@@ -778,6 +807,22 @@ export class CloudPiSessionClient implements PiSession {
return result.result;
}
+ private async sendSandboxCommand(
+ input: SendCommandInput,
+ ): Promise<SendCommandOutput> {
+ const result = await this.cloudTaskClient.sendCommand(input);
+ if (isTerminalStatus(this.runStatus) || !isNoActiveSandboxError(result)) {
+ return result;
+ }
+
+ await this.waitForLiveRuntimeStarted();
+ if (isTerminalStatus(this.runStatus)) {
+ return result;
+ }
+
+ return this.cloudTaskClient.sendCommand(input);
+ }
+
private markSnapshotReady(): void {
if (this.snapshotReady) {
return;
@@ -786,6 +831,14 @@ export class CloudPiSessionClient implements PiSession {
this.resolveSnapshot();
}
+ private markLiveRuntimeStarted(): void {
+ if (this.liveRuntimeStarted) {
+ return;
+ }
+ this.liveRuntimeStarted = true;
+ this.resolveLiveRuntimeStarted();
+ }
+
private markRuntimeReady(): void {
if (this.runtimeReady) {
return;
@@ -794,6 +847,17 @@ export class CloudPiSessionClient implements PiSession {
this.resolveRuntimeReady();
}
+ private async waitForLiveRuntimeStarted(): Promise<void> {
+ if (this.liveRuntimeStarted || isTerminalStatus(this.runStatus)) {
+ return;
+ }
+
+ await Promise.race([
+ this.liveRuntimeStartedReceived,
+ this.terminalStatusReceived,
+ ]);
+ }
+
private async waitForRuntimeReady(): Promise<void> {
if (this.runtimeReady || isTerminalStatus(this.runStatus)) {
return;