Skip to content

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

fix: resolve PR 7048 merge conflict and review findings

Steven Enamakel9f5a690cc134
diff --cc app/src/features/conversations/Conversations.tsx
index 8a357b1348,40935633d2..35389aa404
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@@ -508,58 -487,85 +520,106 @@@ const Conversations = (
cancelled = true;
};
}, []);
- const applyComposerReasoningEffort = useCallback((value: ReasoningEffortChoice) => {
- setComposerReasoningEffort(value);
- void openhumanUpdateRuntimeSettings({ reasoning_effort: value === 'default' ? '' : value })
- .then(() => {
- console.debug('[chat][composer-reasoning] persisted reasoning_effort', { effort: value });
+ const applyComposerReasoningEffort = useCallback(
+ (value: ReasoningEffortChoice) => {
+ const model = reasoningModel;
+ if (model) {
+ // `default` on a model drops its own level, falling back to the global one.
+ setReasoningEffortByModel(prev => {
+ const next = { ...prev };
+ if (value === 'default') delete next[model];
+ else next[model] = value;
+ return next;
+ });
+ } else {
+ setGlobalReasoningEffort(value);
+ }
+ void openhumanUpdateRuntimeSettings({
+ reasoning_effort: value === 'default' ? '' : value,
+ ...(model ? { reasoning_effort_model: model } : {}),
})
- .catch((err: unknown) => {
- // The per-send value still applies; only persistence failed.
- console.warn('[chat][composer-reasoning] failed to persist reasoning_effort', {
- message: err instanceof Error ? err.message : String(err),
+ .then(() => {
+ console.debug('[chat][composer-reasoning] persisted reasoning_effort', {
+ effort: value,
+ perModel: Boolean(model),
+ });
+ })
+ .catch((err: unknown) => {
+ // The per-send value still applies; only persistence failed.
+ console.warn('[chat][composer-reasoning] failed to persist reasoning_effort', {
+ message: err instanceof Error ? err.message : String(err),
+ });
});
- });
- }, []);
+ },
+ [reasoningModel]
+ );
- const applyComposerModel = useCallback((value: string | null, contextWindow?: number | null) => {
- setComposerModelOverride(value);
- setPersistedDefaultModel(value);
- setComposerModelContextWindow(contextWindow ?? null);
- void callCoreRpc({
- method: 'openhuman.inference_update_model_settings',
- params: { default_model: value ?? '' },
- })
- .then(() => {
+ const persistComposerModelSettings = useCallback((value: string | null) => {
+ const write = modelSettingsWriteQueueRef.current
+ .catch(() => undefined)
+ .then(() =>
+ callCoreRpc({
+ method: 'openhuman.inference_update_model_settings',
+ params: { default_model: value ?? '' },
+ })
+ );
+ modelSettingsWriteQueueRef.current = write.then(
+ () => undefined,
+ () => undefined
+ );
+ void write.then(
+ () => {
console.debug('[chat][composer-model] persisted default_model', { pinned: value !== null });
- })
- .catch((err: unknown) => {
+ },
+ (err: unknown) => {
// The in-session override still applies; only persistence failed.
console.warn('[chat][composer-model] failed to persist default_model', {
message: err instanceof Error ? err.message : String(err),
});
- });
+ }
+ );
+ return write;
}, []);
+ const startComposerModelClear = useCallback(() => {
+ const promise = persistComposerModelSettings(null).then(
+ () => {
+ barrier.status = 'resolved';
+ },
+ error => {
+ barrier.status = 'rejected';
+ throw error;
+ }
+ );
+ const barrier: ComposerModelClearBarrier = { promise, status: 'pending' };
+ composerModelClearBarrierRef.current = barrier;
+ // Keep a failed clear available for the next explicit send retry while
+ // marking the rejection handled if the user does not submit again.
+ void promise.catch(() => undefined);
+ return promise;
+ }, [persistComposerModelSettings]);
+
+ const waitForComposerModelClear = useCallback(() => {
+ const barrier = composerModelClearBarrierRef.current;
+ if (!barrier) return null;
+ if (barrier.status === 'rejected') return startComposerModelClear();
+ return barrier.promise;
+ }, [startComposerModelClear]);
+
+ const applyComposerModel = useCallback(
+ (value: string | null, contextWindow?: number | null) => {
+ setComposerModelOverride(value);
++ setPersistedDefaultModel(value);
+ setComposerModelContextWindow(contextWindow ?? null);
+ if (value === null) {
+ void startComposerModelClear();
+ } else {
+ composerModelClearBarrierRef.current = null;
+ void persistComposerModelSettings(value);
+ }
+ },
+ [persistComposerModelSettings, startComposerModelClear]
+ );
+
useEffect(() => {
let cancelled = false;
(async () => {
@@@ -842,11 -854,12 +913,13 @@@
window.addEventListener('dictation://insert-text', onDictationInsert as EventListener);
return () =>
window.removeEventListener('dictation://insert-text', onDictationInsert as EventListener);
- }, []);
+ // `setInputValue` is `useThreadDraft`'s stable setter.
+ }, [setInputValue]);
useEffect(() => {
- if (sendErrorRef.current && inputValue.length > 0) {
+ if (preserveSendErrorForRestoredDraftRef.current) {
+ preserveSendErrorForRestoredDraftRef.current = false;
+ } else if (sendErrorRef.current && inputValue.length > 0) {
setSendError(null);
}
// The store-recorded create failure (#5156) dismisses on the same signal:
@@@ -1474,9 -1557,16 +1628,9 @@@
selectedThreadId ?? 'none',
composerEmpty
);
- handleStopGeneration();
+ handleStopGenerationRef.current?.();
if (composerEmpty) {
- // Restore the last *visible* user prompt (hidden system/injected
- // messages are excluded here to match how the transcript is rendered).
- const lastUserMessage = [...messages]
- .reverse()
- .find(m => m.sender === 'user' && !m.extraMetadata?.hidden);
- const restored = lastUserMessage
- ? parseMessageImages(lastUserMessage.content ?? '').text
- : '';
+ const restored = lastVisibleUserPrompt();
if (restored.length > 0) {
debug('[chat] esc interrupt: restored prompt len=%d', restored.length);
setInputValue(restored);
diff --cc app/src/features/conversations/threadList/groupThreads.ts
index d4f64bc6db,0000000000..434afc3a22
mode 100644,000000..100644
--- a/app/src/features/conversations/threadList/groupThreads.ts
+++ b/app/src/features/conversations/threadList/groupThreads.ts
@@@ -1,97 -1,0 +1,96 @@@
+import type { Thread } from '../../../types/thread';
+
+/**
+ * Reserved thread label that marks a conversation as pinned. Persisted by the
+ * core like any other label (`openhuman.threads_update_labels`), so a pin
+ * survives restarts and follows the workspace. It never makes a thread a task
+ * (`isThreadVisibleInTab` keys tasks off other labels), so pinned threads stay
+ * in the General tab.
+ */
+export const PINNED_THREAD_LABEL = 'pinned';
+
+export type ThreadGroupKey =
+ | 'pinned'
+ | 'today'
+ | 'yesterday'
+ | 'previous7Days'
+ | 'previous30Days'
+ | 'older';
+
+export interface ThreadGroup {
+ key: ThreadGroupKey;
+ threads: Thread[];
+}
+
- const DAY_MS = 24 * 60 * 60 * 1000;
-
+export function isThreadPinned(thread: Thread): boolean {
+ return Boolean(thread.labels?.includes(PINNED_THREAD_LABEL));
+}
+
+/** Labels with the pin toggled; every other label is kept in order. */
+export function labelsWithPin(labels: readonly string[] | undefined, pinned: boolean): string[] {
+ const rest = (labels ?? []).filter(label => label !== PINNED_THREAD_LABEL);
+ return pinned ? [...rest, PINNED_THREAD_LABEL] : rest;
+}
+
+/** Case-insensitive title match; a blank query matches everything. */
+export function threadMatchesQuery(title: string, query: string): boolean {
+ const needle = query.trim().toLowerCase();
+ return needle === '' || title.toLowerCase().includes(needle);
+}
+
+function startOfLocalDay(date: Date): number {
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
+}
+
+/** Which recency bucket a timestamp falls into, relative to `now`'s local day. */
+export function recencyGroupFor(timestamp: string, now: Date): Exclude<ThreadGroupKey, 'pinned'> {
+ const time = new Date(timestamp).getTime();
+ // An unparseable timestamp sorts to the bottom rather than claiming "Today".
+ if (Number.isNaN(time)) return 'older';
- const today = startOfLocalDay(now);
- if (time >= today) return 'today';
- if (time >= today - DAY_MS) return 'yesterday';
- if (time >= today - 7 * DAY_MS) return 'previous7Days';
- if (time >= today - 30 * DAY_MS) return 'previous30Days';
++ const dayStart = (offset: number) =>
++ new Date(now.getFullYear(), now.getMonth(), now.getDate() - offset).getTime();
++ if (time >= dayStart(0)) return 'today';
++ if (time >= dayStart(1)) return 'yesterday';
++ if (time >= dayStart(7)) return 'previous7Days';
++ if (time >= dayStart(30)) return 'previous30Days';
+ return 'older';
+}
+
+const GROUP_ORDER: ThreadGroupKey[] = [
+ 'pinned',
+ 'today',
+ 'yesterday',
+ 'previous7Days',
+ 'previous30Days',
+ 'older',
+];
+
+/**
+ * Splits an already-sorted thread list into the sidebar's sections: pinned
+ * first, then recency buckets by `lastMessageAt`. Input order is preserved
+ * inside each section and empty sections are dropped.
+ */
+export function groupThreads(
+ threads: readonly Thread[],
+ now: Date,
+ isPinned: (thread: Thread) => boolean = isThreadPinned
+): ThreadGroup[] {
+ const buckets = new Map<ThreadGroupKey, Thread[]>();
+ for (const thread of threads) {
+ const key = isPinned(thread) ? 'pinned' : recencyGroupFor(thread.lastMessageAt, now);
+ const bucket = buckets.get(key);
+ if (bucket) bucket.push(thread);
+ else buckets.set(key, [thread]);
+ }
+ return GROUP_ORDER.filter(key => buckets.has(key)).map(key => ({
+ key,
+ threads: buckets.get(key) ?? [],
+ }));
+}
+
+/** Last path segment of a folder, for a compact tooltip. */
+export function folderBasename(path: string): string {
+ const trimmed = path.replace(/[\\/]+$/, '');
+ const parts = trimmed.split(/[\\/]/);
+ return parts[parts.length - 1] || trimmed || path;
+}
diff --cc crates/openhuman-core/src/config/ops/model.rs
index 6b0358d934,980a8d2845..9a2bdb0343
--- a/crates/openhuman-core/src/config/ops/model.rs
+++ b/crates/openhuman-core/src/config/ops/model.rs
@@@ -471,26 -467,7 +471,28 @@@ pub async fn apply_runtime_settings
} else {
let parsed = crate::agent::tinyagents::parse_reasoning_effort(effort)
.ok_or_else(|| format!("unknown reasoning_effort '{effort}'"))?;
- config.runtime.reasoning_effort = Some(parsed.as_str().to_string());
+ Some(parsed.as_str().to_string())
+ };
+ let model = update
+ .reasoning_effort_model
+ .as_deref()
- .map(str::trim)
- .filter(|model| !model.is_empty());
++ .map(str::trim);
++ if model == Some("") {
++ return Err("reasoning_effort_model must not be empty".into());
++ }
+ match (model, parsed) {
+ (Some(model), Some(effort)) => {
+ log::debug!("[config][reasoning] model={model} effort={effort}");
+ config
+ .runtime
+ .reasoning_effort_by_model
+ .insert(model.to_string(), effort);
+ }
+ (Some(model), None) => {
+ log::debug!("[config][reasoning] model={model} effort cleared");
+ config.runtime.reasoning_effort_by_model.remove(model);
+ }
+ (None, effort) => config.runtime.reasoning_effort = effort,
}
}
config.save().await.map_err(|e| e.to_string())?;
diff --cc crates/openhuman-core/src/threads/ops/working_dir.rs
index 8a18ef274e,0000000000..e88261efd2
mode 100644,000000..100644
--- a/crates/openhuman-core/src/threads/ops/working_dir.rs
+++ b/crates/openhuman-core/src/threads/ops/working_dir.rs
@@@ -1,122 -1,0 +1,116 @@@
+//! A thread's working folder: the `action_dir` its agent acts in, picked
+//! above the composer when a conversation starts.
+//!
+//! The folder is bound before the first message and is fixed from then on. A
+//! resumed session keeps its first system prompt and tool surface verbatim
+//! (see the Sessions notes in `CLAUDE.md`), so moving a live thread to another
+//! folder would leave the model describing one directory while its tools act
+//! in another.
+
+use super::support::{counts, envelope, thread_to_summary, workspace_dir};
+use crate::core::Outcome;
+use crate::security::SecurityPolicy;
+use crate::threads::store as conversations;
+use crate::threads::ThreadsError;
+use crate::threads::{
+ ApiEnvelope, ConversationThreadSummary, UpdateConversationThreadWorkingDirRequest,
+};
+use std::path::{Path, PathBuf};
+
+/// Validates a requested working folder and returns its canonical form, or
+/// `None` for an empty request (use the global `action_dir`).
+///
+/// The folder must be an existing absolute directory outside the paths the
+/// security policy never opens (credential stores, system roots), the same
+/// floor that holds with the autonomy policy disabled.
+pub(crate) fn validate_working_dir(raw: Option<&str>) -> Result<Option<String>, String> {
+ let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
+ return Ok(None);
+ };
+ if raw.contains('\0') {
+ return Err("working folder must not contain a null byte".to_string());
+ }
+ let path = Path::new(raw);
+ if !path.is_absolute() {
+ return Err("working folder must be an absolute path".to_string());
+ }
+ let canonical = path
+ .canonicalize()
+ .map_err(|err| format!("working folder is not accessible: {err}"))?;
+ if !canonical.is_dir() {
+ return Err("working folder is not a directory".to_string());
+ }
+ if SecurityPolicy::is_always_forbidden(&canonical) {
+ return Err("working folder is in a protected location".to_string());
+ }
+ Ok(Some(canonical.to_string_lossy().into_owned()))
+}
+
+/// The working folder bound to `thread_id`, if the thread exists and has one.
+///
- /// A folder that has since disappeared or become forbidden is ignored (with a
- /// warning) so the turn falls back to the global `action_dir` instead of
- /// failing.
- pub(crate) async fn thread_working_dir(workspace_dir: PathBuf, thread_id: &str) -> Option<PathBuf> {
- let threads = match conversations::blocking::list_threads(workspace_dir).await {
- Ok(threads) => threads,
- Err(err) => {
- tracing::warn!(thread_id, error = %err, "[threads][working_dir] list failed");
- return None;
- }
- };
++/// An unusable bound folder is an error, rather than a reason to run in the
++/// global folder. This preserves the conversation's filesystem boundary.
++pub(crate) async fn thread_working_dir(
++ workspace_dir: PathBuf,
++ thread_id: &str,
++) -> Result<Option<PathBuf>, String> {
++ let threads = conversations::blocking::list_threads(workspace_dir)
++ .await
++ .map_err(|err| format!("failed to load thread working folder: {err}"))?;
+ let bound = threads
+ .into_iter()
- .find(|thread| thread.id == thread_id)?
- .working_dir?;
++ .find(|thread| thread.id == thread_id)
++ .and_then(|thread| thread.working_dir);
++ let Some(bound) = bound else {
++ return Ok(None);
++ };
+ match validate_working_dir(Some(&bound)) {
- Ok(Some(dir)) => Some(PathBuf::from(dir)),
- Ok(None) => None,
- Err(err) => {
- tracing::warn!(
- thread_id,
- error = %err,
- "[threads][working_dir] bound folder unusable; using the global action_dir"
- );
- None
- }
++ Ok(Some(dir)) => Ok(Some(PathBuf::from(dir))),
++ Ok(None) => Ok(None),
++ Err(err) => Err(format!("thread working folder is unusable: {err}")),
+ }
+}
+
+/// Binds or clears the working folder of a thread that has no messages yet.
+pub async fn thread_update_working_dir(
+ request: UpdateConversationThreadWorkingDirRequest,
+) -> Result<Outcome<ApiEnvelope<ConversationThreadSummary>>, ThreadsError> {
+ let dir = workspace_dir().await?;
+ let working_dir = validate_working_dir(Some(&request.action_dir))?;
+ let Some(thread) = conversations::blocking::list_threads(dir.clone())
+ .await?
+ .into_iter()
+ .find(|thread| thread.id == request.thread_id)
+ else {
+ return Err(ThreadsError::not_found(request.thread_id));
+ };
+ if thread.message_count > 0 {
+ return Err(
+ "the working folder can only change before the conversation's first message"
+ .to_string()
+ .into(),
+ );
+ }
+ let updated = conversations::blocking::update_thread_working_dir(
+ dir,
+ request.thread_id.clone(),
+ working_dir,
+ chrono::Utc::now().to_rfc3339(),
+ )
+ .await
+ .map_err(|err| ThreadsError::from_thread_scoped_store_error(&request.thread_id, err))?;
+ tracing::debug!(
+ thread_id = %request.thread_id,
+ bound = updated.working_dir.is_some(),
+ "[threads][working_dir] updated thread working folder"
+ );
+ Ok(envelope(
+ thread_to_summary(updated),
+ Some(counts([("num_threads", 1)])),
+ None,
+ ))
+}
+
+#[cfg(test)]
+#[path = "working_dir_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/web_chat/run_task.rs
index dc2629e2cf,a9e84f99c6..6458db94e7
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@@ -97,17 -97,7 +97,20 @@@ pub(crate) async fn run_chat_task
}
}
- let config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout().await?;
+ // A thread started in a chosen folder acts there, not in the global
+ // `action_dir`. Applied before checkout so the session agent, its security
+ // policy (which grants `action_dir` as a trusted root) and its tools are
+ // all built on the thread's folder.
- if let Some(dir) =
- crate::threads::ops::thread_working_dir(config.workspace_dir.clone(), thread_id).await
++ if let Some(dir) = crate::threads::ops::thread_working_dir(
++ config.workspace_dir.clone(),
++ thread_id,
++ )
++ .await?
+ {
+ log::debug!("[web-channel] thread working folder applied thread_id={thread_id}");
+ config.action_dir = dir;
+ }
let model_override = normalize_model_override(model_override);
// The cached session (or a cold-boot resumed one) is the thread's single
// live history; every turn on the thread checks it out through this path.