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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Cmd+Enter steers queued prompts and native steers preempt the queue (#3740)
Harsh Kumar1b13351483cb
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 4a9b4a4c5..e6e3031ea 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -2754,8 +2754,6 @@ export function StandaloneChat({const turnIntentLedgerRef = useRef<TurnIntentRecord[]>([]);const pendingSteerBatchRef = useRef<PendingSteerBatchItem[]>([]);const pendingSteerFlushInFlightRef = useRef(false);- const steerAbortAtBoundaryRef = useRef(false);- const steerAbortInFlightRef = useRef(false);const streamRenderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// Last error text observed anywhere in the current Pi stream — used to surface// quota / credits_exhausted errors when agent_end arrives with no content and@@ -4109,6 +4107,11 @@ export function StandaloneChat({void Promise.resolve(steerMessage(input.trim())).finally(() => {steerShortcutInFlightRef.current = false;});+ } else if (!input.trim() && pastedImages.length === 0 && pendingDocsRef.current.length === 0 && queuedPrompts.length > 0 && !steerShortcutInFlightRef.current) {+ steerShortcutInFlightRef.current = true;+ void Promise.resolve(steerQueuedPrompt(queuedPrompts[0])).finally(() => {+ steerShortcutInFlightRef.current = false;+ });}return;}@@ -4160,12 +4163,17 @@ export function StandaloneChat({void Promise.resolve(steerMessage(input.trim())).finally(() => {steerShortcutInFlightRef.current = false;});+ } else if (!input.trim() && pastedImages.length === 0 && pendingDocsRef.current.length === 0 && queuedPrompts.length > 0 && !steerShortcutInFlightRef.current) {+ steerShortcutInFlightRef.current = true;+ void Promise.resolve(steerQueuedPrompt(queuedPrompts[0])).finally(() => {+ steerShortcutInFlightRef.current = false;+ });}};window.addEventListener("keydown", handleComposerSteerShortcut, true);return () => window.removeEventListener("keydown", handleComposerSteerShortcut, true);- }, [input, isComposing, isMac, pastedImages, showMentionDropdown]);+ }, [input, isComposing, isMac, pastedImages, showMentionDropdown, queuedPrompts]);useEffect(() => {// Don't resolve preset until settings are loaded from the store —@@ -4749,7 +4757,6 @@ export function StandaloneChat({) {const evt = data.assistantMessageEvent;if (evt.type === "text_delta" && evt.delta) {- void maybeInterruptForPendingSteer("text_delta");// First delta of a queued turn → create the placeholder lazily.if (!ensureAssistantPlaceholder()) return;piStreamingTextRef.current += evt.delta;@@ -4790,7 +4797,6 @@ export function StandaloneChat({}scheduleStreamingMessageRender();} else if (evt.type === "thinking_end") {- void maybeInterruptForPendingSteer("thinking_end");const blocks = piContentBlocksRef.current;const thinkingBlock = blocks[blocks.length - 1];if (thinkingBlock && thinkingBlock.type === "thinking") {@@ -4808,7 +4814,6 @@ export function StandaloneChat({}}} else if (data.type === "tool_execution_start") {- void maybeInterruptForPendingSteer("tool_execution_start");if (!ensureAssistantPlaceholder()) return;if (piMessageIdRef.current) {const msgId = piMessageIdRef.current;@@ -4826,7 +4831,6 @@ export function StandaloneChat({);}} else if (data.type === "tool_execution_end") {- void maybeInterruptForPendingSteer("tool_execution_end");if (piMessageIdRef.current) {const msgId = piMessageIdRef.current;const toolCallId = data.toolCallId;@@ -5262,9 +5266,7 @@ export function StandaloneChat({setIsLoading(false);setIsStreaming(false);emitSessionActivity({ status: "idle" });- if (steerAbortAtBoundaryRef.current) {- finishPendingSteerInterrupt();- } else if (pendingSteerBatchRef.current.some((item) => item.sessionId === piSessionIdRef.current)) {+ if (pendingSteerBatchRef.current.some((item) => item.sessionId === piSessionIdRef.current)) {void flushPendingSteerBatch();}}@@ -5443,8 +5445,6 @@ export function StandaloneChat({piStoppedIntentionallyRef.current = false;return;}- const shouldResumePendingSteer = steerAbortAtBoundaryRef.current &&- pendingSteerBatchRef.current.some((item) => item.sessionId === payload.sessionId);console.log("[Pi] Process terminated, pid:", terminatedPid);try {const info = await commands.piInfo(piSessionIdRef.current);@@ -5454,21 +5454,6 @@ export function StandaloneChat({}} catch {}- if (shouldResumePendingSteer) {- piStreamingTextRef.current = "";- piMessageIdRef.current = null;- piContentBlocksRef.current = [];- piLastErrorRef.current = null;- piActiveStopRequestedRef.current = false;- piThinkingStartRef.current = null;- followUpFiredRef.current = false;- forceQueueModeRef.current = false;- setIsLoading(false);- setIsStreaming(false);- finishPendingSteerInterrupt();- return;- }-// If a message was in flight, append error to the message so the user// knows the agent stopped unexpectedly (not just "completed").if (piMessageIdRef.current) {@@ -6883,20 +6868,75 @@ export function StandaloneChat({}}+ /**+ * Extracts the pending steer batch for the given session, clears it from+ * the ref, computes derived fields (prompt, preview, images), and sets+ * the intent / display / optimistic refs needed by the message_start+ * handler to recognise the steer echo. Returns null when there is no+ * pending batch for the session.+ */+ function prepareSteerBatch(sessionId: string) {+ const batch = pendingSteerBatchRef.current.filter(+ (item) => item.sessionId === sessionId,+ );+ if (batch.length === 0) return null;+ pendingSteerBatchRef.current = pendingSteerBatchRef.current.filter(+ (item) => item.sessionId !== sessionId,+ );++ const latest = batch[batch.length - 1];+ const prompt = buildSteerPrompt(batch);+ const preview = queuedPreviewForText(latest.content);+ const combinedImages = imageDataUrlsToPiImages(+ batch.flatMap((item) => item.images),+ );++ // Remove earlier batch items' turn intents (only latest survives).+ batch.slice(0, -1).forEach((item) => removeTurnIntent(item.turnIntentId));++ // Set intent refs so the message_start handler recognises the+ // steer echo and creates the assistant placeholder.+ pendingNextPiUserIntentRef.current = "steer";+ pendingNextPiUserDisplayRef.current = {+ preview,+ images: [...latest.images],+ ...(latest.attachments?.length+ ? { attachments: [...latest.attachments] }+ : {}),+ ...(latest.displayContent+ ? { displayContent: latest.displayContent }+ : {}),+ optimisticUserId: latest.optimisticUserId,+ turnIntentId: latest.turnIntentId,+ };+ optimisticSteerRef.current = {+ id: latest.optimisticUserId,+ content: prompt,+ turnIntentId: latest.turnIntentId,+ };+ registerTurnIntent({+ id: latest.turnIntentId,+ sessionId,+ kind: "steer",+ content: prompt,+ preview,+ displayedUserId: latest.optimisticUserId,+ createdAt: latest.createdAt,+ });++ return { batch, latest, prompt, preview, combinedImages };+ }+async function flushPendingSteerBatch() {const sessionId = piSessionIdRef.current;if (!sessionId || pendingSteerFlushInFlightRef.current) return;- const batch = pendingSteerBatchRef.current.filter((item) => item.sessionId === sessionId);- if (batch.length === 0) return;- pendingSteerBatchRef.current = pendingSteerBatchRef.current.filter((item) => item.sessionId !== sessionId);+ const prepared = prepareSteerBatch(sessionId);+ if (!prepared) return;pendingSteerFlushInFlightRef.current = true;- const latest = batch[batch.length - 1];+ const { batch, latest, prompt, preview, combinedImages } = prepared;const interruptedAssistantId = batch.find((item) => item.interruptedAssistantId)?.interruptedAssistantId ?? null;- const prompt = buildSteerPrompt(batch);- const preview = queuedPreviewForText(latest.content);- const combinedImages = imageDataUrlsToPiImages(batch.flatMap((item) => item.images));const hasActiveAssistant = Boolean(piMessageIdRef.current);const labelMarkers: Message[] = batch.slice(0, -1).map((item, index) => ({@@ -6930,31 +6970,6 @@ export function StandaloneChat({}}- pendingNextPiUserIntentRef.current = "steer";- pendingNextPiUserDisplayRef.current = {- preview,- images: [...latest.images],- ...(latest.attachments?.length ? { attachments: [...latest.attachments] } : {}),- ...(latest.displayContent ? { displayContent: latest.displayContent } : {}),- optimisticUserId: latest.optimisticUserId,- turnIntentId: latest.turnIntentId,- };- optimisticSteerRef.current = {- id: latest.optimisticUserId,- content: prompt,- turnIntentId: latest.turnIntentId,- };- batch.slice(0, -1).forEach((item) => removeTurnIntent(item.turnIntentId));- registerTurnIntent({- id: latest.turnIntentId,- sessionId,- kind: "steer",- content: prompt,- preview,- displayedUserId: latest.optimisticUserId,- createdAt: latest.createdAt,- });-let precreatedSteerAssistantId: string | null = null;if (hasActiveAssistant) {const steerAssistantId = `${latest.turnIntentId}-assistant`;@@ -7066,39 +7081,6 @@ export function StandaloneChat({}}- function finishPendingSteerInterrupt(options?: { flush?: boolean }) {- steerAbortAtBoundaryRef.current = false;- steerAbortInFlightRef.current = false;- if (options?.flush !== false) {- void flushPendingSteerBatch();- }- }-- async function maybeInterruptForPendingSteer(_reason: string) {- if (!steerAbortAtBoundaryRef.current) return;- if (steerAbortInFlightRef.current) return;- const sid = piSessionIdRef.current;- if (!sid) return;- const hasPending = pendingSteerBatchRef.current.some((item) => item.sessionId === sid);- if (!hasPending) {- finishPendingSteerInterrupt({ flush: false });- return;- }- if (!piMessageIdRef.current || (!isLoading && !isStreaming)) {- finishPendingSteerInterrupt();- return;- }-- steerAbortInFlightRef.current = true;- try {- piActiveStopRequestedRef.current = true;- await commands.piAbortActive(sid);- } catch (e) {- console.warn("[steer] boundary abort failed", e);- steerAbortInFlightRef.current = false;- }- }-async function steerMessage(userMessage: string, displayLabel?: string, imageDataUrls?: string[]) {const hasImages = imageDataUrls ? imageDataUrls.length > 0 : pastedImages.length > 0;const trimmed = userMessage.trim();@@ -7218,9 +7200,49 @@ export function StandaloneChat({},];if (hadActiveReply) {- // Request interruption at the next safe boundary event.- steerAbortAtBoundaryRef.current = true;- void maybeInterruptForPendingSteer("steer_message");+ const sid = piSessionIdRef.current;+ if (sid) {+ const prepared = prepareSteerBatch(sid);+ if (!prepared) return;+ const { batch, latest, prompt, combinedImages } = prepared;++ piActiveStopRequestedRef.current = true;+ const interruptedAssistantId =+ latest.interruptedAssistantId ?? null;++ // Send steer directly — no abort needed.+ // send_immediate sets steer_in_flight in Rust, holding the+ // drain loop until the steer turn's agent_start fires.+ // If piSteer fails at the IPC layer, Pi never received the+ // steer — revert is clean. Mid-stream failures surface as+ // agent_end / response events, not IPC errors.+ void commands+ .piSteer(+ sid,+ prompt,+ combinedImages.length > 0 ? combinedImages : null,+ )+ .then((result) => {+ if (result.status !== "ok") {+ console.warn("[steer] piSteer returned non-ok:", result);+ revertFailedComposerSteer(+ batch,+ latest,+ interruptedAssistantId,+ result.error ?? "steer command rejected",+ );+ }+ })+ .catch((err: unknown) => {+ console.warn("[steer] piSteer failed, reverting", err);+ revertFailedComposerSteer(+ batch,+ latest,+ interruptedAssistantId,+ err instanceof Error ? err.message : String(err),+ );+ });+ }return;}if (!piMessageIdRef.current) {@@ -7228,6 +7250,49 @@ export function StandaloneChat({}}+ /** Undo all side-effects of a failed composer steer. */+ function revertFailedComposerSteer(+ batch: typeof pendingSteerBatchRef.current,+ latest: (typeof pendingSteerBatchRef.current)[number],+ interruptedAssistantId: string | null,+ errorDescription: string,+ ) {+ // Clear intent refs so message_start handler ignores the steer.+ pendingNextPiUserIntentRef.current = null;+ pendingNextPiUserDisplayRef.current = null;+ optimisticSteerRef.current = null;+ piActiveStopRequestedRef.current = false;+ removeTurnIntent(latest.turnIntentId);++ // Un-mark the assistant that was marked interrupted.+ setAssistantInterruptedState(interruptedAssistantId, false);++ // Remove only the optimistic steer user bubble inserted by steerMessage.+ const optimisticId = latest.optimisticUserId;+ setMessages((prev) =>+ prev.filter(+ (m) =>+ !(+ m.id === optimisticId &&+ m.role === "user" &&+ m.intent === "steer"+ ),+ ),+ );++ // Put the batch back so a retry or future steer can use it.+ pendingSteerBatchRef.current = [+ ...batch,+ ...pendingSteerBatchRef.current,+ ];++ toast({+ title: "failed to send steered message",+ description: errorDescription,+ variant: "destructive",+ });+ }+async function steerQueuedPrompt(prompt: PiQueuedPrompt) {setQueuedActionPromptId(prompt.id);const queuedDisplay = takeQueuedDisplayById(currentQueueSessionId, prompt.id);@@ -7249,6 +7314,7 @@ export function StandaloneChat({turnIntentId,timestamp: Date.now(),};+ const interruptedAssistantBeforeSteer = piMessageIdRef.current;try {pendingNextPiUserIntentRef.current = "steer";pendingNextPiUserDisplayRef.current = {@@ -7293,19 +7359,41 @@ export function StandaloneChat({pendingNextPiUserIntentRef.current = null;pendingNextPiUserDisplayRef.current = null;removeTurnIntent(turnIntentId);- setMessages((prev) => prev.filter((message) => message.turnIntentId !== turnIntentId));+ setMessages((prev) =>+ prev.filter(+ (m) =>+ !(+ m.id === optimisticQueuedUser.id &&+ m.role === "user" &&+ m.intent === "steer"+ ),+ ),+ );restoreQueuedDisplay(currentQueueSessionId, prompt.id, queuedDisplay);- clearCurrentAssistantInterrupted();+ setAssistantInterruptedState(interruptedAssistantBeforeSteer, false);toast({ title: "failed to steer queued message", description: result.error, variant: "destructive" });return;}if (!result.data) {+ // Benign race: the queued prompt already left the queue and will+ // render via the normal message_start path. Only remove the+ // steer-specific optimistic user bubble — do not remove or disturb+ // any transcript state that the normal message_start path may need.pendingNextPiUserIntentRef.current = null;pendingNextPiUserDisplayRef.current = null;removeTurnIntent(turnIntentId);- setMessages((prev) => prev.filter((message) => message.turnIntentId !== turnIntentId));+ setMessages((prev) =>+ prev.filter(+ (m) =>+ !(+ m.id === optimisticQueuedUser.id &&+ m.role === "user" &&+ m.intent === "steer"+ ),+ ),+ );restoreQueuedDisplay(currentQueueSessionId, prompt.id, queuedDisplay);- clearCurrentAssistantInterrupted();+ setAssistantInterruptedState(interruptedAssistantBeforeSteer, false);toast({title: "message already started",description: "That follow-up has moved out of the queue.",@@ -7324,9 +7412,18 @@ export function StandaloneChat({pendingNextPiUserIntentRef.current = null;pendingNextPiUserDisplayRef.current = null;removeTurnIntent(turnIntentId);- setMessages((prev) => prev.filter((message) => message.turnIntentId !== turnIntentId));+ setMessages((prev) =>+ prev.filter(+ (m) =>+ !(+ m.id === optimisticQueuedUser.id &&+ m.role === "user" &&+ m.intent === "steer"+ ),+ ),+ );restoreQueuedDisplay(currentQueueSessionId, prompt.id, queuedDisplay);- clearCurrentAssistantInterrupted();+ setAssistantInterruptedState(interruptedAssistantBeforeSteer, false);toast({title: "failed to steer queued message",description: e instanceof Error ? e.message : String(e),diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rsindex 5e7e8c3ac..71a8a983e 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -1902,12 +1902,26 @@ pub async fn pi_start_inner(// mid-stream `response` ACK doesn't unblock the// queue early.qs.mark_agent_active();+ // If a steer was in flight, it has now started its+ // agent turn. The drain loop can rely on agent_active+ // from here on.+ qs.clear_steer_in_flight();}Some("agent_end") => {qs.mark_agent_idle();qs.signal_done();}- Some("message_start") => {}+ Some("message_start") => {+ // Native steer may not emit agent_start — it goes+ // straight from message_start to text deltas. If a+ // steer is in flight, treat message_start as the+ // start of the steered turn so the drain loop+ // stays blocked via agent_active until agent_end.+ if qs.is_steer_in_flight() {+ qs.mark_agent_active();+ qs.clear_steer_in_flight();+ }+ }Some("response") => {// Only meaningful for new_session/abort — those don't// fire agent_start/agent_end. Suppress while a promptdiff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rsindex 555bac074..0f0c2f404 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs@@ -128,6 +128,11 @@ pub struct PiQueueState {/// authoritative done signal; the response-fallback only matters for/// new_session/abort, which never fire agent_start.agent_active: AtomicBool,+ /// True while a steer command has been written to stdin via+ /// `send_immediate` but the new turn's `agent_start` has not yet fired.+ /// Prevents the drain loop from writing the next queued prompt during+ /// the brief `agent_end` → `agent_start` transition.+ steer_in_flight: AtomicBool,}impl PiQueueState {@@ -142,6 +147,7 @@ impl PiQueueState {cancelled: std::sync::Mutex::new(HashSet::new()),queued_payloads: std::sync::Mutex::new(HashMap::new()),agent_active: AtomicBool::new(false),+ steer_in_flight: AtomicBool::new(false),})}@@ -166,6 +172,25 @@ impl PiQueueState {self.agent_active.load(Ordering::SeqCst)}+ /// Mark that a steer command is in flight (written to stdin, awaiting+ /// `agent_start`). The drain loop checks this alongside `agent_active`.+ pub fn set_steer_in_flight(&self) {+ self.steer_in_flight.store(true, Ordering::SeqCst);+ self.done_notify.notify_waiters();+ }++ /// Clear the steer-in-flight guard. Called on `agent_start`, write+ /// failure, process termination, and the bounded 30s timeout.+ pub fn clear_steer_in_flight(&self) {+ self.steer_in_flight.store(false, Ordering::SeqCst);+ self.done_notify.notify_waiters();+ }++ /// Whether a steer command is awaiting its `agent_start`.+ pub fn is_steer_in_flight(&self) -> bool {+ self.steer_in_flight.load(Ordering::SeqCst)+ }+/// Called by the stdout reader when the process terminates (EOF).pub fn signal_terminated(&self) {let _ = self.alive.send(false);@@ -183,6 +208,7 @@ impl PiQueueState {// Clear the agent-active flag so a future restart doesn't start out// in a stuck "active" state if the process died mid-stream.self.agent_active.store(false, Ordering::SeqCst);+ self.clear_steer_in_flight();}/// Subscribe to queue-pending changes. Each receive yields the current@@ -358,6 +384,11 @@ impl PiQueueHandle {.unwrap_or("?").to_string();let cmd_str = serde_json::to_string(&payload).map_err(|e| e.to_string())?;+ // Set the guard *before* writing so the drain loop sees it even if+ // agent_end (old turn) fires before agent_start (steer turn).+ if cmd_type == "steer" {+ self.state.set_steer_in_flight();+ }let mut stdin_guard = stdin.lock().await;info!("pi_command_queue: writing immediate {} ({}), {} bytes",@@ -365,9 +396,14 @@ impl PiQueueHandle {req_id,cmd_str.len());- writeln!(*stdin_guard, "{}", cmd_str)- .and_then(|_| stdin_guard.flush())- .map_err(|e| format!("stdin write failed: {}", e))+ let write_result = writeln!(*stdin_guard, "{}", cmd_str)+ .and_then(|_| stdin_guard.flush());+ if write_result.is_err() {+ if cmd_type == "steer" {+ self.state.clear_steer_in_flight();+ }+ }+ write_result.map_err(|e| format!("stdin write failed: {}", e))}/// Abort only the active Pi turn. Unlike `abort`, this does not drain or@@ -497,12 +533,47 @@ pub fn spawn_queue(.to_string();// Prompt commands must be serialized against the currently- // active agent turn. We cannot rely on response ACK order:- // ACK can arrive before pi-mono actually starts streaming.- if is_prompt && state.is_agent_active() {- let ok =- wait_for_done_or_terminated(&state, &mut alive_rx, &cmd_type).await;- if !ok {+ // active agent turn *and* any in-flight steer command.+ // We cannot rely on response ACK order: ACK can arrive+ // before pi-mono actually starts streaming.+ {+ let mut died_during_wait = false;+ while is_prompt+ && (state.is_agent_active() || state.is_steer_in_flight())+ {+ // When only steer_in_flight holds us (agent finished+ // but steer's agent_start hasn't arrived yet), use a+ // short 30s timeout. If agent_start never fires (Pi+ // rejected the steer silently), force-clear and let+ // the queue proceed.+ if state.is_steer_in_flight() && !state.is_agent_active() {+ tokio::select! {+ _ = state.done_notify.notified() => {}+ _ = state.terminated_notify.notified() => {+ died_during_wait = true;+ break;+ }+ _ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {+ warn!(+ "pi_command_queue: steer_in_flight stuck 30s, force-clearing"+ );+ state.clear_steer_in_flight();+ }+ }+ } else {+ let ok = wait_for_done_or_terminated(+ &state,+ &mut alive_rx,+ &cmd_type,+ )+ .await;+ if !ok {+ died_during_wait = true;+ break;+ }+ }+ }+ if died_during_wait {if let Some(pid) = &prompt_id {state.dequeue_prompt(pid);}@@ -511,19 +582,19 @@ pub fn spawn_queue(.send(Err("Pi process died while processing".to_string()));continue;}+ }- // The first queued prompt can already be popped from- // the mpsc channel and parked here waiting for the- // current turn to finish. If the user deletes it- // during that wait, the original tombstone check above- // is now stale. Re-check before writing so "Delete"- // really prevents the prompt from ever reaching Pi.- if let Some(pid) = &prompt_id {- if state.take_cancelled(pid) {- state.dequeue_prompt(pid);- let _ = cmd.reply.send(Err("cancelled".to_string()));- continue;- }+ // The first queued prompt can already be popped from+ // the mpsc channel and parked here waiting for the+ // current turn to finish. If the user deletes it+ // during that wait, the original tombstone check above+ // is now stale. Re-check before writing so "Delete"+ // really prevents the prompt from ever reaching Pi.+ if let Some(pid) = &prompt_id {+ if state.take_cancelled(pid) {+ state.dequeue_prompt(pid);+ let _ = cmd.reply.send(Err("cancelled".to_string()));+ continue;}}@@ -835,4 +906,97 @@ mod tests {let _ = h2.await;let _ = abort_handle.await;}++ /// The real regression guard for native-steer queue serialization: drive+ /// the actual `spawn_queue` drain loop and prove a queued follow-up stays+ /// blocked while `steer_in_flight` is set, then is written once the guard+ /// clears. This exercises the `while is_prompt && (is_agent_active() ||+ /// is_steer_in_flight())` gate and the steer-only `select!` — not just the+ /// atomic, which is why it would catch a regression in the drain loop+ /// itself (e.g. dropping the `is_steer_in_flight()` term).+ ///+ /// Unix-only because it needs a real writable child stdin; `cat` drains+ /// whatever the loop writes and exits on EOF.+ #[cfg(unix)]+ #[tokio::test]+ async fn test_steer_in_flight_blocks_drain_loop_until_cleared() {+ use std::process::{Command as StdCommand, Stdio};++ let mut child = StdCommand::new("cat")+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn cat as a fake pi stdin");+ let stdin = Arc::new(Mutex::new(child.stdin.take().expect("child stdin")));++ let state = PiQueueState::new();+ let (handle, join) = spawn_queue(stdin, state.clone(), 0);++ // Simulate the agent_end -> agent_start gap: a steer has been written+ // to stdin but its turn hasn't started, and the prior turn already+ // ended (agent NOT active). This is exactly the window the guard+ // exists to cover.+ state.set_steer_in_flight();++ let (_id, mut reply_rx) = handle+ .send_prompt(+ json!({ "type": "prompt", "text": "queued-follow-up" }),+ WaitMode::Prompt,+ "queued-follow-up".to_string(),+ true,+ )+ .await+ .expect("enqueue follow-up");++ // The drain loop must park in the steer wait and never write the+ // follow-up while the steer is in flight.+ let blocked =+ tokio::time::timeout(std::time::Duration::from_millis(300), &mut reply_rx).await;+ assert!(+ blocked.is_err(),+ "follow-up must stay queued while a steer is in flight"+ );+ assert!(state.is_steer_in_flight(), "guard should still be set");++ // The steered turn started (in prod, agent_start/message_start clears+ // the guard). Clearing it must wake the drain loop and release the+ // follow-up — proving the `select!` is wired to `done_notify`.+ state.clear_steer_in_flight();++ let released = tokio::time::timeout(std::time::Duration::from_secs(5), reply_rx)+ .await+ .expect("follow-up must be released once the steer clears")+ .expect("reply channel stayed open");+ assert!(+ released.is_ok(),+ "follow-up should be written after the steer cleared, got {released:?}"+ );++ // Tear down: end the post-write wait the loop entered, close the+ // channel so the loop exits, and reap cat.+ state.signal_terminated();+ drop(handle);+ let _ = tokio::time::timeout(std::time::Duration::from_secs(2), join).await;+ let _ = child.kill();+ let _ = child.wait();+ }++ /// Process death must clear the steer guard. Otherwise a steer that dies+ /// before its `agent_start` arrives would leave `steer_in_flight` set, and+ /// every subsequent queued prompt would eat the full 30s fallback timeout.+ #[tokio::test]+ async fn test_signal_terminated_clears_steer_in_flight() {+ let state = PiQueueState::new();+ assert!(!state.is_steer_in_flight(), "starts clear");++ state.set_steer_in_flight();+ assert!(state.is_steer_in_flight(), "set takes effect");++ state.signal_terminated();+ assert!(+ !state.is_steer_in_flight(),+ "process termination must clear the in-flight steer guard"+ );+ }}