Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(chat): recover pre-acceptance prompt failures (#6649)

Ezra Elletteab0d01824086
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/__tests__/pi-preset-switch.test.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/__tests__/pi-preset-switch.test.tsx
index fa2ce44e9..faff28486 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/__tests__/pi-preset-switch.test.tsx
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/__tests__/pi-preset-switch.test.tsx
@@ -37,6 +37,8 @@ import {
awaitPiStartInFlight,
awaitPendingPiPresetSwitch,
checkLivePiSession,
+ dispatchPiPromptWithRecovery,
+ isRecoverablePiPromptDispatchError,
} from "../use-pi-send-transport";
const runningInfo = {
@@ -187,6 +189,61 @@ describe("preset switch serialization", () => {
});
});
+describe("prompt dispatch recovery", () => {
+ it.each([
+ "AI agent did not start responding within its startup grace period",
+ "Pi not initialized",
+ "Pi command queue dropped",
+ "stdin write failed: Broken pipe",
+ "Pi session restarted while preparing prompt",
+ ])("recognizes a pre-acceptance process failure: %s", (error) => {
+ expect(isRecoverablePiPromptDispatchError(error)).toBe(true);
+ });
+
+ it.each([
+ "429 rate limit exceeded",
+ "500 Internal server error",
+ "invalid API key",
+ "model_not_allowed",
+ "context_length_exceeded",
+ "upstream socket reported Broken pipe",
+ ])("does not recover an upstream provider failure: %s", (error) => {
+ expect(isRecoverablePiPromptDispatchError(error)).toBe(false);
+ });
+
+ it("replaces a silent process and redelivers the prompt exactly once", async () => {
+ const dispatch = vi.fn()
+ .mockResolvedValueOnce({
+ status: "error",
+ error: "AI agent did not start responding within its startup grace period",
+ })
+ .mockResolvedValueOnce({ status: "ok", data: "queue-2" });
+ const recover = vi.fn(async () => {});
+
+ await expect(dispatchPiPromptWithRecovery(dispatch, recover)).resolves.toEqual({
+ status: "ok",
+ data: "queue-2",
+ });
+ expect(recover).toHaveBeenCalledOnce();
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it("surfaces provider errors without restarting or redelivering", async () => {
+ const dispatch = vi.fn(async () => ({
+ status: "error" as const,
+ error: "500 Internal server error",
+ }));
+ const recover = vi.fn(async () => {});
+
+ await expect(dispatchPiPromptWithRecovery(dispatch, recover)).resolves.toEqual({
+ status: "error",
+ error: "500 Internal server error",
+ });
+ expect(recover).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledOnce();
+ });
+});
+
describe("send-time preset switch guard", () => {
it("waits for a background agent start instead of rejecting the send", async () => {
const startInFlightRef = { current: true };
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts
index 1a073441e..dc6cdfec0 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts
@@ -59,6 +59,39 @@ export async function awaitPendingPiPresetSwitch(
if (pendingSwitch) await pendingSwitch;
}
+/**
+ * Failures that happen before Pi accepts a prompt and are safe to redeliver
+ * after replacing the process. Provider/model errors are intentionally absent:
+ * retrying those would duplicate billing or hide an upstream failure.
+ */
+export function isRecoverablePiPromptDispatchError(error: string): boolean {
+ const normalized = error.toLowerCase();
+ return (
+ isPiPromptStartTimeout(error) ||
+ normalized.includes("pi not initialized") ||
+ normalized.includes("pi is not running") ||
+ normalized.includes("pi process has died") ||
+ normalized.includes("pi process died during") ||
+ normalized.includes("pi command queue dropped") ||
+ normalized.includes("pi command queue closed") ||
+ normalized.includes("stdin write failed") ||
+ normalized.includes("pi session restarted while preparing prompt")
+ );
+}
+
+export async function dispatchPiPromptWithRecovery<T>(
+ dispatch: () => Promise<Result<T, string>>,
+ recover: (error: string) => Promise<void>,
+): Promise<Result<T, string>> {
+ const first = await dispatch();
+ if (first.status !== "error" || !isRecoverablePiPromptDispatchError(first.error)) {
+ return first;
+ }
+
+ await recover(first.error);
+ return dispatch();
+}
+
/**
* Wait for a background start to finish before dispatching a prompt.
*
@@ -783,48 +816,54 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
return;
}
- // Send prompt — abort/new_session now await completion, so no retry needed
+ // Send prompt. If the process failed before accepting it, replace that
+ // exact session and redeliver once. The native prompt-start watchdog
+ // stops a silent process before returning its timeout, so this cannot
+ // overlap a still-running copy of the turn.
const displayPreview = queuedPreviewForText(displayLabel ?? displayUserMessage);
- let result = await commands.piPrompt(
- turnSessionId,
- promptMessage,
- piImages.length > 0 ? piImages : null,
- displayPreview,
- );
-
- // Race: user hit "+ NEW" before Pi finished registering the new session
- // in the pool. Auto-spawn once and retry before surfacing the error.
- if (result.status === "error" && result.error.includes("Pi not initialized")) {
- console.log("[Pi] session not registered yet — auto-spawning and retrying");
- try {
- const dir = await piProjectDirForSession(turnSessionId);
- const providerConfig = buildProviderConfig(attemptPreset);
- const startRes = await commands.piStart(
- turnSessionId,
- dir,
- settings.user?.token ?? null,
- providerConfig,
+ const dispatchPrompt = () =>
+ commands.piPrompt(
+ turnSessionId,
+ promptMessage,
+ piImages.length > 0 ? piImages : null,
+ displayPreview,
+ );
+ const result = await dispatchPiPromptWithRecovery(dispatchPrompt, async (error) => {
+ console.warn(
+ "[Pi] prompt was not accepted — replacing process and retrying once:",
+ error,
+ );
+ // `piStart` reuses an identical live process. Explicitly stop first so
+ // a queue whose drain task closed while the child stayed alive cannot
+ // be mistaken for a healthy reusable session.
+ const stopRes = await commands.piStop(turnSessionId);
+ if (stopRes.status === "error") {
+ throw new Error(stopRes.error);
+ }
+ const dir = await piProjectDirForSession(turnSessionId);
+ const providerConfig = buildProviderConfig(attemptPreset);
+ const startRes = await commands.piStart(
+ turnSessionId,
+ dir,
+ settings.user?.token ?? null,
+ providerConfig,
+ );
+ if (startRes.status !== "ok" || !startRes.data.running) {
+ throw new Error(
+ startRes.status === "error"
+ ? startRes.error
+ : startRes.data.startupError ?? "AI assistant did not restart",
);
- if (startRes.status === "ok" && startRes.data.running) {
- if (isAttemptForeground()) {
- setPiInfo(startRes.data);
- piSessionSyncedRef.current = false;
- if (providerConfig) {
- setRunningConfigFromProviderConfig(providerConfig);
- }
- }
- syncThinkingLevelAfterStart(turnSessionId);
- result = await commands.piPrompt(
- turnSessionId,
- promptMessage,
- piImages.length > 0 ? piImages : null,
- displayPreview,
- );
+ }
+ if (isAttemptForeground()) {
+ setPiInfo(startRes.data);
+ piSessionSyncedRef.current = false;
+ if (providerConfig) {
+ setRunningConfigFromProviderConfig(providerConfig);
}
- } catch (e) {
- console.error("[Pi] auto-spawn retry failed", e);
}
- }
+ syncThinkingLevelAfterStart(turnSessionId);
+ });
if (result.status === "error") {
if (timeoutId) clearTimeout(timeoutId);