Skip to content

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

fix: resolve PR 7268 review findings

Steven Enamakel1da9b39b2753
diff --git a/app/src/store/__tests__/threadSlice.test.ts b/app/src/store/__tests__/threadSlice.test.ts
index 6be60a86c2..384f735075 100644
--- a/app/src/store/__tests__/threadSlice.test.ts
+++ b/app/src/store/__tests__/threadSlice.test.ts
@@ -228,6 +228,28 @@ describe('threadSlice loadThreads thunk', () => {
expect(store.getState().thread.selectedThreadId).toBeNull();
});
+ it('does not restore a cleared stale thread from an older list response', async () => {
+ const store = createStore();
+ mockedThreadApi.getThreads.mockResolvedValueOnce({
+ threads: [makeThread({ id: 't-1' }), makeThread({ id: 't-2' })],
+ count: 2,
+ });
+ await store.dispatch(loadThreads());
+ store.dispatch(setSelectedThread('t-1'));
+
+ let resolveThreads!: (value: { threads: Thread[]; count: number }) => void;
+ mockedThreadApi.getThreads.mockImplementationOnce(
+ () => new Promise(resolve => (resolveThreads = resolve))
+ );
+ const request = store.dispatch(loadThreads());
+ store.dispatch(clearStaleThread('t-1'));
+ resolveThreads({ threads: [makeThread({ id: 't-1' }), makeThread({ id: 't-2' })], count: 2 });
+ await request;
+
+ expect(store.getState().thread.threads.map(thread => thread.id)).toEqual(['t-2']);
+ expect(store.getState().thread.selectedThreadId).toBeNull();
+ });
+
it('sets isLoadingThreads while pending and stores threads on fulfilled', async () => {
const store = createStore();
const payload = { threads: [makeThread({ id: 'a' })], count: 1 };
diff --git a/app/src/store/threadSlice.ts b/app/src/store/threadSlice.ts
index 1869d507d8..990fbfe741 100644
--- a/app/src/store/threadSlice.ts
+++ b/app/src/store/threadSlice.ts
@@ -620,7 +620,7 @@ const threadSlice = createSlice({
const selectionWasSuperseded =
currentIntentVersion !==
(action.payload.selectionIntentVersionAtRequest ?? currentIntentVersion);
- if (selectionWasSuperseded && !state.selectedThreadId && state.threads.length === 0) {
+ if (selectionWasSuperseded && !state.selectedThreadId) {
return;
}
const supersedingThread =
diff --git a/app/test/playwright/helpers/core-rpc.ts b/app/test/playwright/helpers/core-rpc.ts
index b18c84111c..036a48b631 100644
--- a/app/test/playwright/helpers/core-rpc.ts
+++ b/app/test/playwright/helpers/core-rpc.ts
@@ -14,6 +14,16 @@ interface JsonRpcFailure {
error: { message?: string; code?: number; data?: unknown };
}
+class CoreRpcError extends Error {
+ readonly code: number | undefined;
+
+ constructor(method: string, error: JsonRpcFailure['error']) {
+ super(`RPC ${method} failed: ${error.message || 'unknown error'}`);
+ this.name = 'CoreRpcError';
+ this.code = error.code;
+ }
+}
+
function buildBypassJwt(userId: string): string {
const payload = Buffer.from(
JSON.stringify({ sub: userId, userId, exp: Math.floor(Date.now() / 1000) + 3600 })
@@ -37,7 +47,7 @@ export async function callCoreRpc<T>(
const payload = (await response.json()) as JsonRpcSuccess<T> & JsonRpcFailure;
if (payload.error) {
- throw new Error(`RPC ${method} failed: ${payload.error.message || 'unknown error'}`);
+ throw new CoreRpcError(method, payload.error);
}
return payload.result;
}
@@ -261,7 +271,11 @@ export async function waitForAppReady(page: Page): Promise<void> {
return result.snapshot ?? null;
} catch (error) {
// Some slim or older cores do not expose this optional status method.
- if (error instanceof Error && /(?:unknown method|method not found)/i.test(error.message)) {
+ if (
+ error instanceof Error &&
+ ((error as CoreRpcError).code === -32601 ||
+ /(?:unknown method|method not found)/i.test(error.message))
+ ) {
return null;
}
throw error;
@@ -269,6 +283,7 @@ export async function waitForAppReady(page: Page): Promise<void> {
};
const init = await readInitStatus();
if (init?.overall === 'done' || init?.overall === 'idle') return;
+ if (init?.overall && init.overall !== 'running' && init.overall !== 'failed') return;
if (init?.overall === 'running' || init?.overall === 'failed') {
const alreadyDismissed = await page.evaluate(
startedAt =>
@@ -279,18 +294,19 @@ export async function waitForAppReady(page: Page): Promise<void> {
}
const dialog = page.getByTestId('harness-init-dialog');
- const backgroundButton = page.getByTestId('harness-init-background');
- const continueButton = page.getByTestId('harness-init-continue-anyway');
+ const actionButton = dialog
+ .getByTestId(/harness-init-(background|continue-anyway)/)
+ .filter({ visible: true })
+ .first();
const action: { value: 'background' | 'continue' | 'terminal' } = { value: 'terminal' };
await expect
.poll(
async () => {
- if (await continueButton.isVisible().catch(() => false)) {
- action.value = 'continue';
- return true;
- }
- if (await backgroundButton.isVisible().catch(() => false)) {
- action.value = 'background';
+ if (await actionButton.isVisible().catch(() => false)) {
+ action.value =
+ (await actionButton.getAttribute('data-testid')) === 'harness-init-background'
+ ? 'background'
+ : 'continue';
return true;
}
const current = await readInitStatus();
@@ -308,8 +324,7 @@ export async function waitForAppReady(page: Page): Promise<void> {
)
.toBe(true);
if (action.value === 'background' || action.value === 'continue') {
- const button = action.value === 'background' ? backgroundButton : continueButton;
- await button.click();
+ await actionButton.click();
await expect(dialog).toBeHidden({ timeout: 5_000 });
}
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs
index b2bec0c3d2..fe2118c1c2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs
@@ -379,7 +379,6 @@ impl OpenHumanSecurityGate {
#[path = "security_gate_approval.rs"]
mod approval;
-pub(crate) use approval::unanswered_approval_text;
use approval::decision_for_outcome;
#[async_trait]
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate/outcome.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate/outcome.rs
deleted file mode 100644
index 1ce235dff7..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate/outcome.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use tinyagents_harness::host::security_gate::GateDecision;
-
-use crate::security::approval::GateOutcome;
-
-use super::unanswered_approval_text;
-
-/// Convert the approval flow's terminal outcome into the host gate decision.
-///
-/// Expired approval is distinct from an explicit refusal so the model can tell
-/// the user that a new request is needed. Refusals deliberately omit the
-/// policy-denial marker, which would stop the turn before the model can explain
-/// what happened.
-pub(super) fn decision_for_outcome(tool_name: &str, outcome: GateOutcome) -> GateDecision {
- match outcome {
- GateOutcome::Allow => GateDecision::Prompted { approved: true },
- GateOutcome::Deny { reason }
- if crate::security::approval::is_unanswered_approval_reason(&reason) =>
- {
- tracing::warn!(
- target: "tinyagents",
- tool = %tool_name,
- "[tinyagents::host::security] approval prompt expired unanswered"
- );
- GateDecision::deny(unanswered_approval_text(tool_name))
- }
- GateOutcome::Deny { reason } => {
- tracing::warn!(
- target: "tinyagents",
- tool = %tool_name,
- reason = %reason,
- "[tinyagents::host::security] approval flow declined the tool call"
- );
- GateDecision::deny(
- "This action was refused and must not be performed this turn — do not retry this \
- call and do not achieve the same result another way (shell, CLI, another tool). \
- Tell the user it was not done.",
- )
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_approval.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_approval.rs
index 0756f9c199..0fa11c2ab8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_approval.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_approval.rs
@@ -6,7 +6,7 @@ use super::{GateDecision, GateOutcome};
/// unanswered. Like the refusal text it carries no `[policy-denied]` marker
/// (see [`decision_for_outcome`]), so the model keeps the turn to tell the
/// user.
-pub(crate) fn unanswered_approval_text(tool_name: &str) -> String {
+fn unanswered_approval_text(tool_name: &str) -> String {
format!(
"The approval request for '{tool_name}' was not answered in time, so it was not run. \
Tell the user the approval window expired and that they must ask again to retry. \
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
index 1237479f56..955eadc376 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@ -23,6 +23,10 @@ use crate::security::keyring::store::BackendKind;
use tinystoragedrivers::secrets::EncryptedFileSecrets;
use zeroize::Zeroizing;
+#[path = "encrypted_file_backend/key_source.rs"]
+mod key_source;
+use key_source::{env_value, master_key_from_env};
+
const KEYCHAIN_SERVICE: &str = "openhuman";
const KEYCHAIN_MASTER_KEY_USERNAME: &str = "app:master_key";
/// Environment variable carrying the master key inline as `2 * KEY_LEN` hex
@@ -240,68 +244,6 @@ fn try_load_master_key() -> Result<([u8; KEY_LEN], String), MasterKeyError> {
.map_err(MasterKeyError::Keychain)
}
-/// Interprets one `std::env::var` result for a master-key variable.
-///
-/// Only `NotPresent` means unset. A value that is not valid Unicode is a
-/// misconfiguration and must not be treated as unset: that would fall
-/// through to the OS keychain, where [`load_or_mint_master_key`] could mint
-/// a different key and orphan every secret in `secrets.enc`. The rejected
-/// value is never formatted into the error (`VarError`'s `Display` would
-/// include it).
-fn env_value(
- name: &str,
- raw: Result<String, std::env::VarError>,
-) -> Result<Option<String>, String> {
- match raw {
- Ok(value) => Ok(Some(value)),
- Err(std::env::VarError::NotPresent) => Ok(None),
- Err(std::env::VarError::NotUnicode(_)) => {
- Err(format!("{name} is set but is not valid Unicode"))
- }
- }
-}
-
-/// Resolves an operator-supplied master key from the two environment
-/// sources, given their raw values.
-///
-/// `Ok(None)` when neither is set (an empty or whitespace-only value counts
-/// as unset, matching how Compose passes an undefined `${VAR}`), so the
-/// caller falls through to the OS keychain. `Err` when a source is set but
-/// unusable: both set at once, an unreadable file, or a value that is not
-/// exactly `2 * KEY_LEN` hex characters. Error messages and the returned
-/// source label name the variable and the problem but never include its
-/// value — not even the file path, which may be a mistakenly pasted key.
-///
-/// `read_file` is injected so the decision logic is testable without touching
-/// the filesystem; production passes [`read_master_key_file`].
-fn master_key_from_env(
- inline: Option<&str>,
- file: Option<&str>,
- read_file: impl FnOnce(&Path) -> Result<String, String>,
-) -> Result<Option<([u8; KEY_LEN], String)>, String> {
- let inline = inline.map(str::trim).filter(|value| !value.is_empty());
- let file = file.map(str::trim).filter(|value| !value.is_empty());
- match (inline, file) {
- (None, None) => Ok(None),
- (Some(_), Some(_)) => Err(format!(
- "{MASTER_KEY_ENV} and {MASTER_KEY_FILE_ENV} are both set; set exactly one"
- )),
- (Some(hex), None) => parse_master_key_hex(hex)
- .map(|key| Some((key, MASTER_KEY_ENV.to_string())))
- .map_err(|e| format!("{MASTER_KEY_ENV}: {e}")),
- (None, Some(path)) => {
- // Named by the variable, never by its value: an operator who puts
- // the key itself in the `_FILE` variable would otherwise have it
- // copied into the error and the startup log.
- let contents =
- read_file(Path::new(path)).map_err(|e| format!("{MASTER_KEY_FILE_ENV}: {e}"))?;
- parse_master_key_hex(contents.trim())
- .map(|key| Some((key, MASTER_KEY_FILE_ENV.to_string())))
- .map_err(|e| format!("{MASTER_KEY_FILE_ENV}: {e}"))
- }
- }
-}
-
/// Reads the file named by [`MASTER_KEY_FILE_ENV`].
///
/// On Unix a key file must not be writable by other users. Read-only group or
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs
new file mode 100644
index 0000000000..6fe1841647
--- /dev/null
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs
@@ -0,0 +1,46 @@
+//! Resolve operator-supplied master keys from environment variables.
+
+use super::*;
+
+/// Only `NotPresent` means unset. Invalid Unicode must not fall through to the
+/// OS keychain, where a new key could orphan the encrypted secrets.
+pub(super) fn env_value(
+ name: &str,
+ raw: Result<String, std::env::VarError>,
+) -> Result<Option<String>, String> {
+ match raw {
+ Ok(value) => Ok(Some(value)),
+ Err(std::env::VarError::NotPresent) => Ok(None),
+ Err(std::env::VarError::NotUnicode(_)) => {
+ Err(format!("{name} is set but is not valid Unicode"))
+ }
+ }
+}
+
+/// Resolve an operator-supplied master key from either supported environment
+/// source. Empty values fall through to the OS keychain; errors never include
+/// secret values or paths. `read_file` keeps the decision testable.
+pub(super) fn master_key_from_env(
+ inline: Option<&str>,
+ file: Option<&str>,
+ read_file: impl FnOnce(&Path) -> Result<String, String>,
+) -> Result<Option<([u8; KEY_LEN], String)>, String> {
+ let inline = inline.map(str::trim).filter(|value| !value.is_empty());
+ let file = file.map(str::trim).filter(|value| !value.is_empty());
+ match (inline, file) {
+ (None, None) => Ok(None),
+ (Some(_), Some(_)) => Err(format!(
+ "{MASTER_KEY_ENV} and {MASTER_KEY_FILE_ENV} are both set; set exactly one"
+ )),
+ (Some(hex), None) => parse_master_key_hex(hex)
+ .map(|key| Some((key, MASTER_KEY_ENV.to_string())))
+ .map_err(|e| format!("{MASTER_KEY_ENV}: {e}")),
+ (None, Some(path)) => {
+ let contents =
+ read_file(Path::new(path)).map_err(|e| format!("{MASTER_KEY_FILE_ENV}: {e}"))?;
+ parse_master_key_hex(contents.trim())
+ .map(|key| Some((key, MASTER_KEY_FILE_ENV.to_string())))
+ .map_err(|e| format!("{MASTER_KEY_FILE_ENV}: {e}"))
+ }
+ }
+}