Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix: recover web chat after failed turn

Steven Enamakeld7db5e1358d6
diff --git a/app/test/playwright/specs/chat-harness-subagent.spec.ts b/app/test/playwright/specs/chat-harness-subagent.spec.ts
index d9a2f7b84f..e6f0b548d8 100644
--- a/app/test/playwright/specs/chat-harness-subagent.spec.ts
+++ b/app/test/playwright/specs/chat-harness-subagent.spec.ts
@@ -16,7 +16,6 @@ const RESEARCHER_REPLY = 'The researcher answer is 42.';
const PARENT_THINKING = 'Parent trace: delegate the factual lookup before synthesizing.';
const PARENT_NARRATION = 'I am delegating the factual lookup now.';
const CHILD_THINKING = 'Child trace: isolate the requested marker before replying.';
-const FINAL_THINKING = 'Parent trace: verify the delegated finding and answer.';
const KEYWORD_RESPONSES = [
{ keyword: "Search the user's memory tree", content: 'No relevant memory.' },
{
@@ -47,7 +46,7 @@ const KEYWORD_RESPONSES = [
// exactly how the result body is quoted inside it.
keyword: 'background sub-agent finished while you were busy',
streamScript: [
- { thinking: FINAL_THINKING },
+ { thinking: 'Parent trace: verify the delegated finding and answer.' },
{ text: `Done. The result is: ${CANARY_FINAL}` },
{ finish: 'stop' },
],
@@ -358,15 +357,11 @@ test.describe('Chat Harness - Subagent', () => {
// legacy timeline surface.
const finalMessage = page.getByTestId('agent-message').filter({ hasText: CANARY_FINAL }).last();
await expect(finalMessage).toBeVisible({ timeout: 15_000 });
- const finalReasoning = finalMessage.getByRole('button', { name: /Reasoning/ });
// The final assistant part may contain only the synthesized answer; the
- // delegated reasoning belongs to its preceding trace parts. Expand and
- // verify final-part reasoning only when that optional disclosure exists.
- if (await finalReasoning.count()) {
- if ((await finalReasoning.getAttribute('aria-expanded')) !== 'true')
- await finalReasoning.click();
- await expect(finalMessage.getByText(FINAL_THINKING, { exact: true })).toBeVisible();
- }
+ // delegated reasoning belongs to its preceding trace parts. The durable
+ // parent and child trails are asserted below after a reload, which is the
+ // stable contract regardless of whether the provider emits final-round
+ // reasoning as a separate disclosure.
// Reloading removes the live socket and Redux stream. The same visual
// trace must rehydrate from persisted transcript/turn-state data.
diff --git a/app/test/playwright/specs/chat-pre-stream-failure.spec.ts b/app/test/playwright/specs/chat-pre-stream-failure.spec.ts
index 4fefd9a257..1e24a34fc7 100644
--- a/app/test/playwright/specs/chat-pre-stream-failure.spec.ts
+++ b/app/test/playwright/specs/chat-pre-stream-failure.spec.ts
@@ -140,6 +140,11 @@ test.describe('Chat — a turn that fails before streaming (#5729)', () => {
test.afterEach(async () => {
await resetMock();
+ // A reset fault exercises the harness retry path. Let its bounded
+ // backoff (200 + 400 + 800ms) finish against the restored mock before the
+ // next browser spec mutates shared mock behaviour; otherwise a retry from
+ // this deliberately failed turn can consume the next spec's script.
+ await new Promise(resolve => setTimeout(resolve, 2_000));
});
/**
@@ -179,7 +184,10 @@ test.describe('Chat — a turn that fails before streaming (#5729)', () => {
await openChat(page);
await setMockBehavior(
'httpFaultRules',
- JSON.stringify([{ contains: '/chat/completions', mode: 'reset' }])
+ // A reset is retryable by design. Use a terminal request error here so
+ // the failed first turn cannot wake up later and consume this test's
+ // scripted recovery response.
+ JSON.stringify([{ contains: '/chat/completions', mode: 'status', status: 400 }])
);
await sendMessage(page, 'this turn dies before it streams');
@@ -251,7 +259,10 @@ test.describe('Chat — a turn that fails before streaming (#5729)', () => {
// Clear the fault and prove the surface recovered rather than latching.
await setMockBehavior('httpFaultRules', JSON.stringify([]));
- await setMockBehavior('llmForcedResponses', JSON.stringify([{ content: RECOVERY_CANARY }]));
+ await setMockBehavior(
+ 'llmStreamScript',
+ JSON.stringify([{ text: RECOVERY_CANARY }, { finish: 'stop' }])
+ );
// Asserting only "the composer is editable" would be vacuous — it is
// editable on a healthy run too. The recovery has to be demonstrated by a
diff --git a/app/test/playwright/specs/chat-tool-error-recovery.spec.ts b/app/test/playwright/specs/chat-tool-error-recovery.spec.ts
index 0d7afc8982..45f60de124 100644
--- a/app/test/playwright/specs/chat-tool-error-recovery.spec.ts
+++ b/app/test/playwright/specs/chat-tool-error-recovery.spec.ts
@@ -110,23 +110,27 @@ test.describe('Chat Tool Error Recovery', () => {
page,
}) => {
await resetMock();
+ // Route both turns up front. Changing the global stream script between
+ // an error and its retry leaves a shared mock-server race when this spec
+ // follows another fault-injection case in the same browser session.
await setMockBehavior(
- 'llmStreamScript',
- JSON.stringify([{ text: 'Starting to answer', delayMs: 30 }, { error: 'upstream LLM error' }])
+ 'llmKeywordRules',
+ JSON.stringify([
+ {
+ keyword: 'Tell me something important.',
+ streamScript: [{ text: 'Starting to answer', delayMs: 30 }, { error: 'invalid API key' }],
+ },
+ {
+ keyword: 'Please try again with a fresh answer.',
+ streamScript: [{ text: `Recovery successful: ${RECOVERY_CANARY}` }, { finish: 'stop' }],
+ },
+ ])
);
await openChat(page);
const threadId = await createNewThread(page);
await sendMessage(page, 'Tell me something important.');
- // Two elements briefly carry the streamed text: the live-streaming
- // preview block (`font-mono` console-style render in Conversations.tsx)
- // and the persisted message bubble that takes over once the segment
- // commits. Playwright strict-mode trips when both are simultaneously
- // visible during the transition. `.first()` keeps the assertion robust
- // — we just care that the streamed substring rendered somewhere.
- await expect(page.getByText('Starting to answer').first()).toBeVisible({ timeout: 20_000 });
-
await expect
.poll(async () => {
const lifecycle = await page.evaluate(currentThreadId => {
@@ -151,13 +155,6 @@ test.describe('Chat Tool Error Recovery', () => {
const composer = page.getByTestId('chat-message-input');
await expect(composer).toBeEnabled();
- await setMockBehavior('llmStreamScript', '');
- await setMockBehavior(
- 'llmForcedResponses',
- JSON.stringify([{ content: `Recovery successful: ${RECOVERY_CANARY}` }])
- );
- await setMockBehavior('llmStreamChunkDelayMs', '10');
-
await sendMessage(page, 'Please try again with a fresh answer.');
await expect(page.getByText(RECOVERY_CANARY)).toBeVisible({ timeout: 30_000 });
});
diff --git a/app/test/playwright/specs/conversations-web-channel-flow.spec.ts b/app/test/playwright/specs/conversations-web-channel-flow.spec.ts
index 0b5ba217d1..5b3a8bf3eb 100644
--- a/app/test/playwright/specs/conversations-web-channel-flow.spec.ts
+++ b/app/test/playwright/specs/conversations-web-channel-flow.spec.ts
@@ -128,10 +128,13 @@ test.describe('Conversations web channel flow', () => {
await createNewThread(page);
await sendMessage(page, PROMPT);
- await expect(page.locator('p').filter({ hasText: PROMPT }).first()).toBeVisible({
- timeout: 20_000,
- });
- await expect(page.locator('p').filter({ hasText: REPLY }).first()).toBeVisible({
+ // assistant-ui renders user text in its message root rather than a
+ // paragraph. Keep this scoped to the user bubble so a matching string in
+ // a transcript/tool card cannot satisfy the assertion.
+ await expect(
+ page.locator('[data-slot="aui_user-message-root"]').filter({ hasText: PROMPT }).first()
+ ).toBeVisible({ timeout: 20_000 });
+ await expect(page.getByTestId('agent-message').filter({ hasText: REPLY }).first()).toBeVisible({
timeout: 30_000,
});
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_attribution_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_attribution_tests.rs
index 4093a7832a..3166d6c858 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_attribution_tests.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_attribution_tests.rs
@@ -613,6 +613,7 @@ fn subagent_span_records_prompt_and_final_output_when_capture_on() {
elapsed_ms: 100,
iterations: 2,
output_chars: 12,
+ usage: None,
output: "final answer".to_string(),
worktree_path: None,
changed_files: vec![],
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs
index 4fcb63753c..c217269579 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs
@@ -13,6 +13,7 @@ fn subagent_content_is_withheld_when_capture_off() {
elapsed_ms: 100,
iterations: 2,
output_chars: 12,
+ usage: None,
output: "final answer".to_string(),
worktree_path: None,
changed_files: vec![],
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
index 8a8827ea56..6e5e7e0123 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
@@ -229,6 +229,7 @@ fn subagent_lifecycle_nests_under_the_turn() {
elapsed_ms: 500,
iterations: 3,
output_chars: 1024,
+ usage: None,
output: String::new(),
worktree_path: Some("/private/should/not/leak".to_string()),
changed_files: vec!["secret_file.rs".to_string()],
@@ -318,6 +319,7 @@ fn unknown_subagent_task_ids_are_ignored() {
elapsed_ms: 1,
iterations: 1,
output_chars: 1,
+ usage: None,
output: String::new(),
worktree_path: None,
changed_files: vec![],
diff --git a/crates/openhuman-core/src/threads/ops/usage_tests.rs b/crates/openhuman-core/src/threads/ops/usage_tests.rs
index 5b9de670bd..3da5c9cc05 100644
--- a/crates/openhuman-core/src/threads/ops/usage_tests.rs
+++ b/crates/openhuman-core/src/threads/ops/usage_tests.rs
@@ -32,6 +32,8 @@ fn meta(agent: &str, agent_type: &str, thread_id: Option<&str>) -> TranscriptMet
charged_amount_usd: 0.0,
thread_id: thread_id.map(str::to_owned),
task_id: None,
+ session_id: None,
+ parent_session_id: None,
}
}
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs b/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs
index 41883bef49..d8d2547d52 100644
--- a/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs
+++ b/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs
@@ -509,6 +509,7 @@ fn subagent_lifecycle_records_and_clears_active() {
elapsed_ms: 1234,
iterations: 2,
output_chars: 80,
+ usage: None,
output: String::new(),
worktree_path: None,
changed_files: Vec::new(),
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index 4fb36b2d7a..6b8db06143 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -401,7 +401,12 @@ pub async fn start_chat(
}
};
- match result {
+ // A terminal socket event is also the UI's permission to submit a
+ // replacement turn. Defer `chat_error` until after the in-flight
+ // slot below has been removed: publishing it while the failed slot
+ // is still present lets an immediate retry interrupt the dead run
+ // and inherit its failed model state.
+ let deferred_error = match result {
Ok(chat_result) => {
crate::web_chat::presentation::deliver_response(
&client_id_task,
@@ -416,6 +421,7 @@ pub async fn start_chat(
Some(chat_result.workspace_dir.as_path()),
)
.await;
+ None
}
Err(err) => {
log::warn!(
@@ -461,7 +467,7 @@ pub async fn start_chat(
],
);
}
- publish_web_channel_event(WebChannelEvent {
+ Some(WebChannelEvent {
event: "chat_error".to_string(),
client_id: client_id_task.clone(),
thread_id: thread_id_task.clone(),
@@ -474,9 +480,9 @@ pub async fn start_chat(
error_provider: classified.provider,
error_fallback_available: classified.fallback_available,
..Default::default()
- });
+ })
}
- }
+ };
// Drain followup messages queued during this turn.
let followups = {
@@ -508,6 +514,9 @@ pub async fn start_chat(
);
dispatch_followups(followups);
}
+ if let Some(event) = deferred_error {
+ publish_web_channel_event(event);
+ }
},
));
diff --git a/crates/openhuman-core/src/web_chat/ops/system_turn.rs b/crates/openhuman-core/src/web_chat/ops/system_turn.rs
index edaaf5d0b4..1c05221f47 100644
--- a/crates/openhuman-core/src/web_chat/ops/system_turn.rs
+++ b/crates/openhuman-core/src/web_chat/ops/system_turn.rs
@@ -20,7 +20,7 @@ use tinyagents_harness::run_queue::RunQueue;
use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
use crate::config::rpc as config_rpc;
-use super::super::run_task::turn_error_poisons_session;
+use super::super::run_task::turn_error_discards_session;
use super::super::session::{
checkin_session_agent_if_vacant, checkout_session_agent, CheckedOutSession, CheckoutPolicy,
};
@@ -91,12 +91,12 @@ pub async fn run_system_turn_on_thread(
agent.set_on_progress(None);
progress_drain.abort();
- // Same de-poison rule as a user turn: a provider request rejection means
- // this agent's history replays the rejection forever, so let it drop and
- // the next turn cold-boots from the durable transcript.
- if matches!(&result, Err(err) if turn_error_poisons_session(err)) {
+ // Same rule as a user turn: a failed harness turn can leave the session
+ // partially advanced, so let it drop and cold-boot from the durable
+ // transcript on the next request.
+ if matches!(&result, Err(err) if turn_error_discards_session(err)) {
log::warn!(
- "[web-channel] dropping session agent after provider_request_rejected on a system \
+ "[web-channel] dropping session agent after failed system \
turn thread={} run_id={}",
thread_id,
run_id
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 0d0bf91031..a8ce3507c9 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -18,8 +18,8 @@ use super::session::{
};
use super::types::{ChatRequestMetadata, WebChatTaskResult};
use super::web_errors::{
- classify_inference_error, inference_budget_exceeded_user_message,
- is_empty_provider_response_text, is_inference_budget_exceeded_error,
+ inference_budget_exceeded_user_message, is_empty_provider_response_text,
+ is_inference_budget_exceeded_error,
};
#[cfg(any(test, debug_assertions))]
@@ -263,25 +263,16 @@ pub(crate) async fn run_chat_task(
// Only the primary (non-fork) turn writes its agent back to the shared
// cache; a fork is fully isolated and lets its agent drop here.
if !fork {
- // De-poison guard. A `provider_request_rejected` outcome means the
- // provider could not parse THIS turn's request — an orphaned
- // `tool_calls` round-trip, an empty `tool_call_id`, or a reasoning
- // echo it rejects. For the managed backend that rejection arrives as an
- // in-stream `event: error` SSE frame carrying `errorCode:"BAD_REQUEST"`
- // (the response already flushed HTTP 200), NOT an HTTP 400 — so we key
- // off the classified type, not a status code. Re-caching this agent
- // would replay the identical malformed history on every later turn,
- // dead-ending the thread. Drop it instead (the entry was already
- // removed from the map at the top of this fn): the next turn cold-boots
- // and reseeds from the plain-text conversation log, which is
- // structurally incapable of carrying tool malformation
- // (`seed_resume_from_messages` rebuilds only system/user/assistant
- // text). Transient failures (rate-limit / timeout / 5xx) keep the warm
- // session so the user can retry this turn with context intact.
+ // A harness error can leave its session prefix committed even when the
+ // turn itself did not complete (for example an in-stream credential
+ // failure after partial text). Re-caching that host makes the next
+ // request fail with "cannot change a session prefix after a committed
+ // turn". The durable transcript remains authoritative, so discard an
+ // agent after every failed turn and cold-boot it on the next request.
if turn_result_poisoned_session(&result) {
log::warn!(
- "[web-channel] dropping session agent after provider_request_rejected — \
- next turn cold-boots from the conversation log (de-poison) \
+ "[web-channel] dropping session agent after failed turn — \
+ next turn cold-boots from the durable transcript \
client={} thread={} request_id={}",
client_id,
thread_id,
@@ -295,29 +286,18 @@ pub(crate) async fn run_chat_task(
result
}
-/// Whether a completed turn's session agent must be **dropped** rather than
-/// cached back, because its in-memory history would replay a provider request
-/// rejection on every subsequent turn.
-///
-/// True only for a *retryable* `provider_request_rejected` — i.e. the
-/// poisoned-history case. The copy-split in `web_errors.rs` marks a tool-ordering
-/// rejection (orphaned / mismatched `tool_call_id` — for the managed backend an
-/// in-stream SSE `event: error` frame stamped `errorCode:"BAD_REQUEST"`)
-/// `retryable: true` because the de-poison makes "send it again" true, while a
-/// genuine model/parameter 400 stays `retryable: false`. Gating on `&& retryable`
-/// therefore evicts ONLY the poisoned session: a non-retryable param 400 keeps
-/// its warm session (no needless reseed), exactly like successes and transient
-/// failures (rate-limit, timeout, 5xx, session-expiry).
+/// Whether a completed turn's checked-out agent must be dropped instead of
+/// returned to the warm-session cache. Any `Err` can leave the underlying host
+/// session partially advanced, so only completed task results are reusable.
fn turn_result_poisoned_session(result: &Result<WebChatTaskResult, String>) -> bool {
- matches!(result, Err(err) if turn_error_poisons_session(err))
+ result.is_err()
}
/// The error-string half of [`turn_result_poisoned_session`], shared with the
/// host-authored turn path (`ops/system_turn.rs`) whose result carries no
/// `WebChatTaskResult`.
-pub(super) fn turn_error_poisons_session(err: &str) -> bool {
- let classified = classify_inference_error(err);
- classified.error_type == "provider_request_rejected" && classified.retryable
+pub(super) fn turn_error_discards_session(_err: &str) -> bool {
+ true
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/web_chat/run_task_tests.rs b/crates/openhuman-core/src/web_chat/run_task_tests.rs
index 685767aa6c..e4098ee691 100644
--- a/crates/openhuman-core/src/web_chat/run_task_tests.rs
+++ b/crates/openhuman-core/src/web_chat/run_task_tests.rs
@@ -43,23 +43,22 @@ fn poisoned_on_byo_provider_tool_ordering_400() {
}
#[test]
-fn genuine_param_400_keeps_warm_session() {
- // A non-poisoning model/parameter 400 is a *non-retryable*
- // provider_request_rejected — narrowing on `&& retryable` must keep its
- // warm session (resending the same params won't help; no reseed needed).
+fn genuine_param_400_discards_session() {
+ // Even a non-retryable model/parameter error can have committed a prefix
+ // in the host session. It must never be checked back in.
let err: Result<WebChatTaskResult, String> = Err(
"custom_openai API error (400 Bad Request): {\"error\":{\"message\":\
\"Unsupported value: 'temperature' must be 1 for this model\"}}"
.to_string(),
);
assert!(
- !turn_result_poisoned_session(&err),
- "non-retryable param 400 is not poisoned history — keep warm session"
+ turn_result_poisoned_session(&err),
+ "a failed turn must not return its host session to the cache"
);
}
#[test]
-fn transient_failures_keep_warm_session() {
+fn transient_failures_discard_session() {
for raw in [
// rate limit / 429 — history is fine, user should retry warm
"OpenAI API error (429 Too Many Requests): slow down",
@@ -72,8 +71,8 @@ fn transient_failures_keep_warm_session() {
] {
let err: Result<WebChatTaskResult, String> = Err(raw.to_string());
assert!(
- !turn_result_poisoned_session(&err),
- "transient/non-payload error must keep warm session: {raw}"
+ turn_result_poisoned_session(&err),
+ "a failed turn must not return its host session to the cache: {raw}"
);
}
}
diff --git a/scripts/mock-api/routes/llm.mjs b/scripts/mock-api/routes/llm.mjs
index bab97c750d..768c659d1d 100644
--- a/scripts/mock-api/routes/llm.mjs
+++ b/scripts/mock-api/routes/llm.mjs
@@ -405,7 +405,15 @@ async function streamScriptToResponse({ res, model, script, defaultDelayMs }) {
if (delay > 0) await sleepDelay(delay);
if (entry.error) {
- writeSseEvent(res, { error: { message: String(entry.error) } });
+ // Keep string shorthand for existing scripts, while allowing tests to
+ // model a provider's structured error code. The latter is important for
+ // a non-retryable fault: a bare unknown message is intentionally
+ // classified as retryable by the inference client.
+ const error =
+ entry.error && typeof entry.error === "object"
+ ? entry.error
+ : { message: String(entry.error) };
+ writeSseEvent(res, { error });
res.end();
return;
}
diff --git a/vendor/tinyjuice b/vendor/tinyjuice
index 2f02042029..36e9657a71 160000
--- a/vendor/tinyjuice
+++ b/vendor/tinyjuice
@@ -1 +1 @@
-Subproject commit 2f020420298f728949540a5801297b0400b86093
+Subproject commit 36e9657a71ce93ca2bd1e35c05dba8e41b5de746