Commit Graph
65 Commits
Author SHA1 Message Date
Yuvraj Singh SisodiyaandGitHub 504d10e98d feat(core): desktop companion domain — session, pipeline, pointing (#1909) (#2025) 2026-05-19 12:17:24 -07:00
Steven EnamakelandGitHub 16b35af570 feat(ai-panel): per-workload temperature + endpoint URL UX for local runtimes (#2165) 2026-05-18 22:04:54 -07:00
Zavian WangandGitHub 8896aa14d6 feat(core): add global tool registry (#2003) 2026-05-17 18:21:55 -07:00
Steven EnamakelandGitHub 95f1f5f063 Refactor inference around external Ollama routing (#1975) 2026-05-17 02:37:42 -07:00
Steven EnamakelandGitHub d92cebdbdf test(rust): expand coverage for state, threads, and channel prompts (#1969) 2026-05-16 16:43:06 -07:00
Steven EnamakelandGitHub 40a384ed65 feat(wallet): add default rpc and EVM execution tools (#1964) 2026-05-16 15:12:09 -07:00
Steven EnamakelandGitHub 30a4a0706f Harden Rust custom provider routing and mock coverage (#1958) 2026-05-16 13:18:10 -07:00
5411f19e47 Add LM Studio as a local model provider (#1750)
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-05-15 11:54:17 -07:00
6d2e722fa8 fix(threads): typed ThreadNotFound error + skip Sentry for stale-thread RPCs (OPENHUMAN-TAURI-4H, -60) (#1570)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-05-12 21:30:34 -07:00
Steven EnamakelandGitHub 065e198cf4 Support reliable self-update for server-side and headless core instances (#1458) 2026-05-09 23:55:25 -07:00
Steven EnamakelandGitHub 97089a68a6 feat(wallet): add execution surface for balances, transfers, swaps, contract calls (#1396) (#1424) 2026-05-09 15:54:09 -07:00
Steven EnamakelandGitHub 6e2d69792d Add seed phrase onboarding and multi-chain wallet setup (#1407) 2026-05-09 13:54:10 -07:00
0f6cc583f3 feat(tools/whatsapp_data): expose local WhatsApp store to agent (#1341) (#1373)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 19:04:15 -07:00
Steven EnamakelandGitHub 0636b0c1a5 feat(meet_agent): live note-taking agent for Google Meet (listen + speak) (#1355) 2026-05-07 20:10:42 -07:00
Steven EnamakelandGitHub 836a6d852c feat(meet): join Google Meet calls with mascot virtual camera (#1350) 2026-05-07 17:56:05 -07:00
obchainandGitHub 3bbf4b5d9f fix(stt): rewrite stale-sidecar voice error + e2e registration guard (#1298) 2026-05-07 12:05:07 -07:00
ba88d8cfc3 fix(webview/meet): gate orchestrator handoff on user opt-in (#1299) (#1310)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 17:43:21 -07:00
a35ba10bb2 feat(channels): expose WhatsApp Web data to agent via structured RPC API (#1308)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 13:11:52 -07:00
obchainandGitHub 1ac3feed3a fix(channels): managed-DM credentials surface as connected to chat (#1209) 2026-05-05 11:24:28 -07:00
Steven EnamakelandGitHub 49a9b835b6 Persist turn state + restore conversation history on cold-boot (#1202) 2026-05-04 22:02:51 -07:00
62516ba418 feat(memory_tree): cloud-default LLM, queue priority, entity filter, Memory tab UI (#1198)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 20:52:56 -07:00
YellowSnnowmannandGitHub 995e5ccccb feat(security): enforce prompt-injection guard before model and tool execution (#1175) 2026-05-04 02:30:22 -07:00
Steven EnamakelandGitHub 2484ea40f2 feat(memory): ingestion pipeline + tree-architecture docs + ops/schemas split (#1142) 2026-05-03 15:22:22 -07:00
Steven EnamakelandGitHub 52eb3a175f feat(memory): singleton ingestion + status RPC + UI pill (#1126) 2026-05-03 12:52:55 -07:00
393852b1d6 Feat: core rpc auth (#881)
Co-authored-by: Steven Enamakel <31011319+senamakel@users.noreply.github.com>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-04-29 18:43:58 -07:00
Steven EnamakelandGitHub 2304d9d58f feat(memory): add Sync and Learn sections to Memory workspace (#1031) 2026-04-29 18:43:11 -07:00
Steven EnamakelandGitHub ac97a96d3a fix(local-ai): cap local models to 1b preset (#1029) 2026-04-29 18:39:03 -07:00
Steven EnamakelandGitHub b11b8f333f [Feature] Thread labels / categories for list organization (#947) 2026-04-28 22:08:45 -07:00
fd0398d5fa feat(memory): MD-on-disk content + participant bucketing + async pipeline foundation (#1008)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-04-28 17:44:20 -07:00
oxoxDevandGitHub 215a776eea feat(ux): lock UI to welcome agent until chat onboarding completes (#883) (#892) 2026-04-24 15:46:31 -07:00
Mega MindandGitHub d2f045769f test(notifications): add Phase 4 RPC and dismiss reducer coverage (#878) 2026-04-24 12:45:26 -07:00
95504d4b09 test: add 196 tests across MCP, services, utils, autocomplete (#855)
Co-authored-by: Jwalin Shah <jshah1331@gmail.com>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-04-24 11:47:26 -07:00
b329e45cdb feat(skills): uninstall for user-scope SKILL.md skills (#781) (#833)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 17:23:40 +05:30
629b4ccb07 test(memory_tree): unit tests for retrieval RPC handlers (#710) (#839)
- Add JSON-RPC handlers for source, global, and topic-based memory retrieval.
- Integrate Ollama embeddings for semantic reranking of chunks and summaries.
- Implement 15 unit tests for RPC handlers covering parameter parsing and PII redaction.
- Redact PII from logs by removing raw source, entity, and node identifiers.
- Fix BFS traversal for drill-down and deduplicate results in topic queries.
- Add configuration for embedding endpoints, models, and strictness modes.

Co-authored-by: sanil-23 <sanil@vezures.xyz>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-04-23 12:31:56 -07:00
3bb714bf96 feat(webview): native OS notifications from embedded webview apps (#714) (#727)
* feat(webview_accounts): native OS notifications from embedded webviews (#714)

Forward CEF notification intercept payloads to tauri-plugin-notification,
prefixing the title with the provider label so the source of each toast is
obvious at a glance. Honour `silent` (skip toast, still record route),
`icon` (passed through to the native builder), and `tag` (used as the
dedup key, with a monotonic timestamp fallback for untagged payloads).

Record a NotificationRoute keyed by `{provider}:{account_id}:{tag_or_uuid}`
so a future click hook (UNUserNotificationCenter / notify-rust on_response)
can route the OS click back to the source account. Entries are cleared on
webview_account_close / _purge to bound map growth.

Expose webview_notification_permission_state / _request commands mapping
tauri::plugin::PermissionState onto the web API triple. Non-cef stubs
return "default" so the frontend can call the same invoke names on both
runtimes. Wire notification:allow-* capabilities so the plugin can be
invoked from the webview.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(accounts): wire notification permission + click bridge (#714)

Round-trip the OS notification permission once per session on first
account open via the new invoke pair. Attach a dormant notification:click
listener that dispatches setActiveAccount and brings the main window to
front when a platform click hook starts emitting the event — contract
matches the Rust NotificationRoute shape so the emit side is a one-liner.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: sync Cargo.lock to 0.52.26 after version bump

Lockfile picked up the pending 0.52.26 version bump from Cargo.toml
while building the notification feature. No dependency graph change.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(notifications): add notification bypass for embedded webview apps (#679)

- Add NotificationBypassPrefs (global DND, per-account mute, bypass-when-focused)
  to WebviewAccountsState with thread-safe AtomicBool window focus tracking
- Evaluate all three bypass conditions inside forward_native_notification before
  showing OS toast; each suppression path logs at debug with [notify-bypass] prefix
- Add four new Tauri commands: webview_notification_set_dnd,
  webview_notification_mute_account, webview_notification_get_bypass_prefs,
  webview_set_focused_account
- Wire window focus tracking in setup hook via on_window_event Focused handler
- Frontend: add setAccountMuted, setGlobalDnd, getBypassPrefs, setFocusedAccount
  helpers in webviewAccountService; sync focused account on open + click
- Add NotificationsPanel settings page with Global DND toggle
- Register NotificationsPanel at /settings/notifications

Closes #679

* feat(notifications): integrate notifications feature into app

- Added Notifications page and routing to AppRoutes.
- Introduced NotificationRoutingPanel in Settings for managing notification settings.
- Updated SettingsHome to include navigation for notification routing.
- Integrated notifications reducer into the store for state management.
- Enhanced Rust backend to support notification handling from embedded webviews.

This commit lays the groundwork for a comprehensive notification system within the application.

* refactor(notifications): clean up code formatting and structure

- Simplified JSX structure in NotificationCard for better readability.
- Consolidated fetchNotifications call in NotificationCenter for cleaner syntax.
- Improved formatting in NotificationRoutingPanel and notificationsSlice for consistency.
- Enhanced Rust code readability by streamlining function signatures and logic.

These changes enhance code maintainability and readability across the notifications feature.

* refactor(webview_accounts): simplify webview_notification_set_dnd function signature

- Removed unnecessary line breaks in the webview_notification_set_dnd function for improved readability.

* feat(notifications): implement provider-level notification settings management

- Added `getNotificationSettings` and `setNotificationSettings` functions to manage notification settings for providers.
- Enhanced `NotificationRoutingPanel` to display and update settings for Gmail, Slack, Discord, and WhatsApp.
- Introduced new RPC endpoints for retrieving and updating notification settings.
- Updated database schema to store notification settings persistently.

This commit establishes a robust system for managing notification preferences, improving user control over notifications.

* refactor(notifications): improve code formatting and readability

- Enhanced formatting in NotificationRoutingPanel for better clarity.
- Streamlined function signatures in notificationService and Rust backend.
- Improved readability of assertions in tests by adjusting line breaks.

These changes contribute to a more maintainable and comprehensible codebase for the notifications feature.

* chore(vendor): bump tauri-cef to fix Slack notification permission banner

Updates the tauri-cef submodule to 55db2d6 which adds a
navigator.permissions.query shim in the CEF render process. Slack checks
this API (not just Notification.permission) to decide whether to show its
"needs your permission" banner — the shim returns "granted" for
notifications queries so the banner no longer appears.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(vendor): bump tauri-cef for cargo fmt fixes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(vendor): bump tauri-cef — native V8 permissions.query shim

Switches from context.eval() to a proper PermissionsQueryV8Handler so
the navigator.permissions.query fix actually runs in on_context_created.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(notifications): patch navigator.permissions.query in ua_spoof.js

The V8 set_value_bykey approach in cef-helper's on_context_created does
not stick on CEF platform objects (Chromium's V8 binding layer silently
ignores property writes on native wrappers like Permissions). The init
script path via frame.execute_java_script runs in the fully-initialised
JS context where navigator.permissions IS writable, matching how
ua_spoof.js already overrides navigator.userAgent successfully.

Slack checks navigator.permissions.query({ name: 'notifications' })
before showing its "needs permission" banner — patching it here to
return "granted" removes the banner.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(notifications): use Object.defineProperty to shim navigator.permissions

Two-layer fix for the Slack "needs permission to enable notifications" banner:

1. cef-helper (submodule update to 99a2686): context.eval() in
   on_context_created installs Object.defineProperty(navigator, 'permissions',
   ...) before any page JS runs.

2. ua_spoof.js: same Object.defineProperty pattern as belt-and-suspenders
   for frames that reload or trigger permission checks after on_load_end.

Simple property assignment on Blink platform objects is silently ignored;
Object.defineProperty on the navigator wrapper itself (the same mechanism
already used for navigator.userAgent) works correctly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(notifications): address CodeRabbit review issues on PR #727

- Move raw_title out of log::info! (PII risk) — log title_chars at info,
  raw_title at debug only
- Fix permissionChecked set before async invoke in ensureNotificationPermission
  so transient failures allow retry on next account open

* fix(cef): enable webview-data-url feature for CEF placeholder URL

The CEF backend uses a data: URL as the initial webview location so CDP
can attach before the real provider URL loads. Tauri's add_child rejects
data: URLs unless the webview-data-url feature is enabled.

* fix(notifications): address remaining CodeRabbit issues on PR #727

- cdp/emulation: bump Chrome UA 124→136 to pass Slack browser check
- cdp/session: inject Page.addScriptToEvaluateOnNewDocument to stub
  Notification.permission as "granted" and silence provider banners
- notifications/mod.rs + core/all.rs: wire notifications domain into
  the controller registry (fixes unknown-method in json_rpc_e2e tests)
- notifications/schemas: add skipped bool output to ingest schema
- notifications/store: add tracing::warn on datetime parse failure
- notificationService: union return type for ingestNotification
- webviewAccountService: narrow union before accessing result.id
- NotificationCenter: drive loading/error from fetch effect; track
  allProviders separately so filter pills don't collapse on selection
- NotificationRoutingPanel: rollback optimistic update on save failure
- useSettingsNavigation: add notifications/notification-routing routes
- scripts/install.sh: remove silent dry-run exit 0 on asset failure
- scripts/setup-dev-codesign.sh: remove unconditional -legacy flag
- docs/SUMMARY.md: remove worktree path, fix macOS capitalisation,
  remove self-referential deletion note

* chore: apply prettier + cargo fmt + fix useEffect dep warning

Auto-apply formatting changes flagged by the pre-push hook:
- prettier reformatted NotificationCenter.tsx and notificationService.ts
- cargo fmt reformatted all.rs, openhuman/mod.rs, notifications/schemas.rs
- NotificationRoutingPanel: move providers array to module scope so
  useEffect dependency array is satisfied without exhaustive-deps warning

* feat(notifications): enhance notification management and permissions

- Added new commands for managing notification preferences, including setting global Do Not Disturb (DND), muting specific accounts, and retrieving current bypass preferences.
- Implemented a notification permission state handler to ensure consistent behavior across different environments.
- Updated the JavaScript shim for notification permissions to handle both Notification and PushManager states, ensuring compatibility with various providers.
- Refactored the WebviewAccountsState to include a new structure for managing notification bypass preferences, improving the overall notification handling logic.

* update agents

* fix(notifications): complete schema + navigation metadata for ingest/settings routes

- app/src/components/settings/hooks/useSettingsNavigation.ts: resolve the
  new `/settings/notifications` and `/settings/notification-routing` URLs
  to their SettingsRoute values and feed them into breadcrumbs so the new
  panels don't silently fall through to `'home'`. Addresses CodeRabbit on
  useSettingsNavigation.ts:34.
- src/openhuman/notifications/schemas.rs: add the optional `reason` output
  on `notification.ingest` (populated alongside `skipped=true` by the
  runtime) and the normalized `settings` output on `notification.settings_set`
  so schema-driven clients see the full response shape. Addresses
  CodeRabbit on schemas.rs:103 and schemas.rs:217.
- src/core/all.rs: add a `notification` namespace_description so CLI help
  covers the new controllers, plus a test assertion. Addresses CodeRabbit
  on src/core/all.rs:149.

* fix(notifications): trace DB entry, surface empty update matches, warn on bad scored_at

- Add `tracing::trace!` checkpoints around the `with_connection` DB open
  and schema migration so notification-delivery issues are reconstructible
  from logs.
- `update_triage` and `mark_read` now inspect `Connection::execute`'s
  affected-row count: log a `warn!` when the update matched zero rows
  (row deleted between ingest and scoring / client passed a stale id),
  `debug!` on the normal path.
- `scored_at` parsing no longer silently drops malformed values — log a
  `warn!` with the raw value and parse error before treating the row as
  unscored, matching the existing behavior for `received_at`.

Addresses CodeRabbit on store.rs (lines 72, 172, 294).

* fix(webview): respect silent notifications, multi-host CDP fallback, shim idempotency

- webview_accounts/mod.rs: honor the Web Notification `silent` flag.
  Previously we only logged it and still called `builder.show()`, so
  pages that marked a notification silent still produced an OS toast.
  Mirror event still fires so the in-app center updates; only the OS
  toast is suppressed. Also picks up a prior cargo-fmt rewrap.
- cdp/target.rs: `browser_ws_url()` now continues the host loop when
  `resp.json()` fails instead of early-returning via `?`. A malformed
  response from the first host (CDP_HOST) no longer prevents the
  `localhost` fallback from being tried.
- webview_accounts/ua_spoof.js: guard the Notification wrapper behind
  `window.__OH_NOTIF_SHIM` so repeated evaluations of the script
  (Page.addScriptToEvaluateOnNewDocument + frame-level re-injections)
  don't stack wrappers onto the same page globals or re-proxy
  `Function.prototype.toString`.

Addresses CodeRabbit on webview_accounts/mod.rs:377, cdp/target.rs:33,
and ua_spoof.js:176.

* update agents

* update

---------

Co-authored-by: oxoxDev <nikhil@tinyhumans.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-04-22 14:13:35 -07:00
5fff5568d3 feat(memory): Phase 2 memory tree - preprocessing, scoring, admission gate (#708) (#733)
* feat(memory): phase 1 memory tree - multi-source ingestion & canonical chunks (#707)

Adds an isolated memory tree layer under src/openhuman/memory/tree/
implementing Phase 1 of the new memory architecture (umbrella #711).
Zero edits to existing memory/*.rs files - the new layer coexists
with the legacy TinyHumans-backed client.

- Source adapters: chat / email / document -> canonical Markdown
- Token-bounded chunker with deterministic SHA-256 chunk IDs
- SQLite persistence at <workspace>/memory_tree/chunks.db with full
  provenance metadata (source_kind, source_id, owner, timestamps,
  tags, time_range) and back-pointer to raw source
- Unified JSON-RPC ingest (dispatches on source_kind + JSON payload):
  openhuman.memory_tree_ingest, _list_chunks, _get_chunk
- DataSource enum covering the 8 providers from m.excalidraw step 1
  (Discord/Telegram/Whatsapp/Gmail/OtherEmail/Notion/MeetingNotes/DriveDocs)
- ~40 unit tests (chunk ID stability, UTF-8-safe splitting,
  canonicalisation idempotence, store round-trip, filter behavior)

Additive only: new tables in a new DB file, new JSON-RPC namespace,
no existing behavior changes. Feeds #708 (scoring), #709 (summary
trees), #710 (query tools).

Closes #707. Parent: #711.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(memory): phase 2 memory tree - preprocessing, scoring, admission gate (#708)

Adds the scoring / admission layer between Phase 1's chunker and store.
Stacked on feat/707-memory-ingestion (PR #732) - depends on Phase 1's
chunk substrate.

- Pluggable EntityExtractor trait + CompositeExtractor chain
- RegexEntityExtractor: mechanical entities (emails, URLs, @handles, #hashtags)
  - Always on, deterministic, zero deps, UTF-8-safe char spans
- Five weighted signals: token count, unique-word ratio, metadata weight,
  source weight (per-DataSource), interaction (reply/sent/mention/dm tags),
  entity density
- Exact-match entity canonicalisation (email lowercased, @ and # stripped)
- Admission gate drops chunks below configurable threshold (default 0.3)
  - Score rationale persists for EVERY chunk (kept or dropped) for debugging
  - Entities indexed for KEPT chunks only
- Two new SQLite tables added to the memory_tree DB:
  - mem_tree_score: per-chunk score rationale with all signal values
  - mem_tree_entity_index: inverted index entity_id -> node_id
- Idempotent ALTER TABLE migration adds embedding BLOB column to
  mem_tree_chunks (used in Phase 3 retrieval, wired but not populated here)
- Ingest pipeline converted to async to accommodate the extractor trait;
  blocking SQLite work isolated on spawn_blocking; JSON-RPC surface
  unchanged (same memory_tree_ingest / list / get methods)
- Phase 2 deliberately ships without GLiNER/semantic NER - per-chunk
  semantic entities land later behind a cargo feature flag; the composite
  extractor interface keeps that drop-in trivial

Additive only: new tables, new columns, new module. Existing Phase 1
behavior unchanged except that low-signal chunks are now dropped before
reaching mem_tree_chunks. Raise score_drop_threshold to 0 to disable
the gate and restore Phase-1-identical behavior.

Closes #708. Parent: #711. Depends on: #707 (#732).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Fix memory tree scoring persistence issues

* Fix memory tree scoring robustness issues from PR review

- ingest: fail fast if scorer returns fewer/more results than chunks
  (silent zip truncation would drop chunks or their score rationale)
- score::persist_score{,_tx}: clear stale entity-index rows before
  re-indexing a re-scored chunk, since INSERT OR REPLACE never deletes
  rows whose entity_id is no longer in the new extraction
- score::store::lookup_entity: clamp limit to i64::MAX before casting
  to prevent a large usize wrapping into a negative LIMIT

Adds clear_entity_index_drops_stale_rows regression test.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-04-21 16:17:27 -07:00
0ce1253fe1 feat(memory): Phase 1 memory tree - multi-source ingestion & canonical chunks (#707) (#732)
* feat(memory): phase 1 memory tree - multi-source ingestion & canonical chunks (#707)

Adds an isolated memory tree layer under src/openhuman/memory/tree/
implementing Phase 1 of the new memory architecture (umbrella #711).
Zero edits to existing memory/*.rs files - the new layer coexists
with the legacy TinyHumans-backed client.

- Source adapters: chat / email / document -> canonical Markdown
- Token-bounded chunker with deterministic SHA-256 chunk IDs
- SQLite persistence at <workspace>/memory_tree/chunks.db with full
  provenance metadata (source_kind, source_id, owner, timestamps,
  tags, time_range) and back-pointer to raw source
- Unified JSON-RPC ingest (dispatches on source_kind + JSON payload):
  openhuman.memory_tree_ingest, _list_chunks, _get_chunk
- DataSource enum covering the 8 providers from m.excalidraw step 1
  (Discord/Telegram/Whatsapp/Gmail/OtherEmail/Notion/MeetingNotes/DriveDocs)
- ~40 unit tests (chunk ID stability, UTF-8-safe splitting,
  canonicalisation idempotence, store round-trip, filter behavior)

Additive only: new tables in a new DB file, new JSON-RPC namespace,
no existing behavior changes. Feeds #708 (scoring), #709 (summary
trees), #710 (query tools).

Closes #707. Parent: #711.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(memory): enhance memory tree functionality and tests

- Added support for "memory_tree" namespace description in `namespace_description`.
- Implemented clamping for zero token budget in `chunk_markdown` to prevent empty leading chunks.
- Introduced detailed logging for document ingestion, including title length.
- Updated output schemas in `schemas.rs` for improved clarity.
- Enhanced chunk listing with clamping limits and ordering by sequence in `list_chunks`.
- Normalized source references in canonicalization functions to drop blank values.
- Added comprehensive tests for new features and edge cases in chunking and canonicalization.

These changes improve the robustness and usability of the memory tree layer, aligning with ongoing development efforts for Phase 1 of the memory architecture.

* fix(memory): address follow-up CodeRabbit comments

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Steven Enamakel <enamakel@tinyhumans.ai>
2026-04-21 14:40:27 -07:00
1836c7691f Feat: smart routing (#569)
* chore: update OpenHuman version to 0.52.9 and add intelligent routing functionality

- Bumped OpenHuman version from 0.52.7 to 0.52.9 in Cargo.lock files.
- Introduced a new routing module that implements intelligent model routing based on task complexity and local model health.
- Added a health checker for the local Ollama model server to improve routing decisions.
- Enhanced the provider to classify tasks and determine the appropriate backend (local or remote) for processing requests.
- Updated related files to support the new routing logic and ensure seamless integration with existing functionalities.

* refactor(routing): streamline provider and enhance routing logic

- Removed the `build_tool_instructions` function from the public API, simplifying the routing module.
- Updated the `IntelligentRoutingProvider` to utilize a more efficient model resolution process, improving routing decisions based on task complexity and local model health.
- Introduced a new `quality` module to assess response quality, enabling better fallback decisions when local responses are deemed low quality.
- Enhanced the `RoutingHints` struct to provide more granular control over routing behavior, including privacy requirements and cost sensitivity.
- Added tests to validate the new routing logic and quality assessment, ensuring robust functionality across various scenarios.

* feat(tests): add live end-to-end routing tests for real backend integration

- Introduced a new test file `live_routing_e2e.rs` containing end-to-end tests for routing against a live backend.
- Tests require a valid backend URL, user session JWT, and real network interactions, hence marked as `#[ignore]`.
- Implemented functionality to set up environment variables, write configuration files, and perform JSON-RPC calls to validate routing behavior.
- Added assertions to ensure correct handling of various routing cases, enhancing test coverage for the routing module.

* refactor(format): ran format command

* feat(routing): add IntelligentRoutingProvider and enhance LocalHealthChecker

- Introduced a new `factory.rs` file containing the `new_provider` function to construct an `IntelligentRoutingProvider` that integrates local AI capabilities with remote backend providers.
- Enhanced the `LocalHealthChecker` in `health.rs` by adding a `reqwest::Client` for improved health probing, including better logging for cache hits and misses, and streamlined cache updates.
- Updated health check logic to utilize the new client, ensuring more reliable health status checks for local AI services.

* refactor(routing): move new_provider function to factory module

- Moved the `new_provider` function from `mod.rs` to a new `factory.rs` module to improve code organization and maintainability.
- Updated public exports to include the new location of `new_provider`, ensuring continued accessibility for constructing `IntelligentRoutingProvider` instances.
- Removed the old implementation from `mod.rs`, streamlining the routing module's structure.

* refactor(routing): simplify local task routing logic

- Removed redundant conditions for routing medium tasks locally, streamlining the decision-making process in the `decide` function.
- Updated comments to reflect the simplified logic, enhancing code clarity and maintainability.

* docs(tests): clarify comments in json_rpc_e2e.rs regarding hint overrides
logic.

* refactor(tests): enhance live routing end-to-end tests with timeout handling

- Introduced a timeout mechanism for reading SSE events to prevent indefinite blocking.
- Updated environment variable management in tests to ensure safe access and cleanup.
- Improved comments for clarity regarding the safety of environment variable mutations during tests.

* refactor(tests): update SSE event reading in live routing tests.

* refactor(routing): enhance medium task routing logic and update comments

- Updated the routing logic for medium tasks to utilize hints for local bias, ensuring more accurate routing decisions.
- Revised comments throughout the code to clarify the behavior of task categories and routing preferences.
- Adjusted test cases to reflect the new routing logic, ensuring they accurately validate the expected behavior for medium tasks.

* refactor(tests): implement timeout handling for dictation event reception

- Added a timeout mechanism to the dictation event test to prevent indefinite blocking while waiting for the "pressed" event.
- Enhanced the test logic to consume events until the expected event type is received, improving reliability and clarity in the test flow.

---------

Co-authored-by: Steven Enamakel <31011319+senamakel@users.noreply.github.com>
2026-04-14 13:06:48 -07:00
7685e877ee feat(agent): welcome->orchestrator routing + per-agent tool scoping (#525, #526) (#544)
* feat(agent): add subagents + delegate_name fields to AgentDefinition (#525, #526)

Introduces the schema change needed to make agent definitions the single source
of truth for both direct tools and delegation targets:

- `subagents: Vec<SubagentEntry>` — declarative list of agents this agent can
  spawn, expanding at build time into synthesised delegate_* tools on the LLM's
  function-calling surface. Supports two TOML shapes via `#[serde(untagged)]`:
    * Bare string (`"researcher"`) → `SubagentEntry::AgentId`
    * Inline table (`{ skills = "*" }`) → `SubagentEntry::Skills(SkillsWildcard)`
  The `Skills` variant expands dynamically to one delegate_{toolkit} tool per
  connected Composio toolkit at runtime.

- `delegate_name: Option<String>` — optional override for the tool name this
  agent is exposed as when another agent lists it in `subagents`. Defaults to
  `delegate_{id}` when absent, lets the researcher agent be exposed as
  `research`, code_executor as `run_code`, etc.

Schema only — no runtime behavior change yet. Follow-up commits wire the field
into `collect_orchestrator_tools`, the dispatch path, and the debug dump.

TOML placement note: `subagents = [...]` must appear before the `[tools]` table
header in agent TOMLs. Once a table section opens, every subsequent top-level
key is consumed by that table, so placing `subagents` after `[tools]` parses it
as `tools.subagents` and fails deserializing ToolScope. The test doc-comment
records this constraint.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(agent): drive orchestrator delegation tools from TOML subagents (#525, #526)

Completes the half-built migration from a hardcoded ARCHETYPE_TOOLS table
+ orphan skill_delegation.rs to a TOML-driven delegation surface where
each agent declares its subagents and the tool list is synthesised from
the registry at agent-build time.

Rewrites `collect_orchestrator_tools` to take the orchestrator's
AgentDefinition, the global AgentDefinitionRegistry, and the slice of
connected Composio integrations, then iterates the definition's
`subagents` field:

  * `SubagentEntry::AgentId` → one ArchetypeDelegationTool. The tool's
    `name()` comes from the target agent's `delegate_name` override (or
    `delegate_{id}` fallback) and its `description()` is the target's
    `when_to_use`. Editing an agent's TOML when_to_use now immediately
    updates the tool schema the orchestrator LLM sees — zero drift, no
    hardcoded description strings to keep in sync.

  * `SubagentEntry::Skills { skills = "*" }` → one SkillDelegationTool
    per connected Composio toolkit. Each routes to the generic
    skills_agent with `skill_filter` pre-populated. Empty integrations
    list (CLI path, or user not yet connected) produces zero tools
    rather than phantom `delegate_*` entries for unconnected toolkits.

Also in this commit:

- Wire the orphan `skill_delegation.rs` into `impl/agent/mod.rs` via
  `mod skill_delegation;` + `pub use SkillDelegationTool;`. The file has
  existed since earlier work but was never declared in the module tree,
  so it compiled as dead code.

- Delete the legacy `MAIN_AGENT_TOOL_ALLOWLIST` constant and the
  `main_agent_tools` filter in `tools/ops.rs`. They were documented as
  "no longer the primary source of truth" since the from_config builder
  switched to `collect_orchestrator_tools`, and grep confirms no
  external callers remain. Clean deletion.

- Delete the hardcoded `ARCHETYPE_TOOLS` const in
  `tools/impl/agent/mod.rs`. The 4-entry table has been replaced by the
  orchestrator TOML's `subagents` list (which covers those 4 plus
  archivist plus the skills wildcard), and the re-export in
  `tools/mod.rs` is removed accordingly.

- Update `agents/orchestrator/agent.toml`: add the `subagents` field
  listing researcher / planner / code_executor / critic / archivist /
  { skills = "*" }. Keep `spawn_subagent` in `[tools] named` as an
  advanced fallback so power users can still spawn custom workspace-
  override agent ids that aren't in the declarative subagents list.

- Add `delegate_name = "..."` to the 5 archetype TOMLs so the
  orchestrator LLM sees natural tool names (`research`, `plan`,
  `run_code`, `review_code`, `archive_session`) rather than the
  `delegate_<agent_id>` fallback.

- Update `agent/harness/session/builder.rs` (line ~461) to call the new
  `collect_orchestrator_tools` signature. Looks up the orchestrator
  definition from the global registry; passes an empty integrations
  slice because the builder is synchronous and cannot await Composio's
  async fetch. The channel-dispatch path will populate integrations in
  a later commit — the CLI/REPL path ships without per-toolkit delegation
  tools, which is acceptable regression since CLI users still reach
  Composio via `composio_execute` and the retained `spawn_subagent`
  fallback.

Tests:

  * 5 new unit tests in `orchestrator_tools.rs` cover the baseline
    AgentId + Skills wildcard expansion, empty-integrations edge case,
    unknown-id graceful skip, non-delegating agent with empty subagents,
    and the slug sanitiser for tool-name-safe Composio toolkit names.
  * Runs clean alongside all existing agent-module tests (323 pass;
    one pre-existing Windows-path failure in `self_healing::tests::
    tool_maker_prompt_includes_command` is unrelated to this PR and
    fails identically on the upstream baseline).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(agent): plumb per-agent tool scoping through bus + tool loop (#525, #526)

Adds the parameter plumbing for agent-aware tool filtering without
changing any runtime behaviour. Every existing call site continues to
pass `None` / empty extras, so the LLM still sees the full unfiltered
registry — the actual routing logic that populates these fields lands
in commit 4b (dispatch.rs onboarding-flag → target_agent_id).

Why two parameters and not one filter:

  Tools in this codebase are `Box<dyn Tool>` — owned trait objects with
  no Clone impl, stored in a shared `Arc<Vec<Box<dyn Tool>>>`. We can't
  cheaply build a per-turn filtered subset of the global registry, and
  we can't mutate the Arc to remove entries. Two new parameters work
  around this without touching the global registry's lifetime model:

  * `visible_tool_names: Option<&HashSet<String>>` — whitelist filter
    applied at the iteration site inside `run_tool_call_loop`. When
    `Some(set)`, only tools whose `name()` is in the set contribute to
    the function-calling schema and are eligible for execution; every
    other tool in the combined registry is hidden from the model and
    rejected if the model emits a call for it. `None` preserves the
    legacy "everything visible" behaviour.

  * `extra_tools: &[Box<dyn Tool>]` — per-turn synthesised tools spliced
    alongside `tools_registry`. The dispatch path will use this to
    surface delegation tools (`research`, `delegate_gmail`, …) that are
    built fresh each turn from the active agent's `subagents` field and
    the current Composio integration list — tools that don't exist in
    the global startup-time registry because they depend on per-user
    runtime state. Empty slice for agents that don't delegate.

  Inside the loop, `tool_specs` is built from
  `tools_registry.iter().chain(extra_tools.iter()).filter(is_visible)`,
  and the tool-execution lookup uses the same chain + filter so the
  function-calling schema and the execution surface stay in sync.

Files touched in this commit:

  src/openhuman/agent/harness/tool_loop.rs
    - Add `visible_tool_names` and `extra_tools` parameters to
      `run_tool_call_loop`. Build `tool_specs` from chained iteration
      with the visibility filter applied. Replace the `find_tool` call
      at the execution site with an inline chain+filter lookup so
      hallucinated calls to filtered-out tools surface as "unknown
      tool" errors. Drop the now-unused `find_tool` import.
    - Update the legacy `agent_turn` wrapper to pass `None, &[]`,
      preserving its existing unfiltered behaviour.
    - Update all 9 in-file test sites to pass `None, &[]`.

  src/openhuman/agent/harness/tests.rs
    - Update all 3 `run_tool_call_loop` test sites to pass `None, &[]`.

  src/openhuman/agent/bus.rs
    - Add `target_agent_id: Option<String>`, `visible_tool_names:
      Option<HashSet<String>>`, and `extra_tools: Vec<Box<dyn Tool>>`
      fields to `AgentTurnRequest`, with rustdoc explaining each.
    - Destructure the new fields in the `agent.run_turn` handler;
      thread `visible_tool_names.as_ref()` and `&extra_tools` through
      to `run_tool_call_loop`. Augment the dispatch trace with
      target_agent / extra_tool_count / visible_tool_count /
      filter_active so production logs show whether scoping is active.
    - Update the in-test `test_request()` helper to populate the new
      fields with safe defaults.

  src/openhuman/agent/triage/evaluator.rs
    - Update the triage `AgentTurnRequest` initializer to set
      `target_agent_id = Some("trigger_triage")` (for tracing) with
      `visible_tool_names: None` + `extra_tools: Vec::new()` because
      the classifier intentionally runs against an empty registry and
      emits a structured JSON decision rather than calling tools.

  src/openhuman/channels/runtime/dispatch.rs
    - Update the channel-message `AgentTurnRequest` initializer to set
      the three new fields to safe defaults (`None` / `None` / empty
      vec). Commit 4b will replace these with the real onboarding-flag
      based routing.

  src/openhuman/tools/impl/agent/mod.rs
    - Bug fix: `dispatch_subagent` previously took `_skill_filter:
      Option<&str>` but discarded the value, hardcoding
      `SubagentRunOptions::skill_filter_override = None`. That meant
      `SkillDelegationTool::execute()` synthesising
      `dispatch_subagent("skills_agent", ..., Some("gmail"))` never
      actually narrowed `skills_agent`'s tool list — so even with the
      orchestrator's view scoped, the spawned `skills_agent` subagent
      would still see the full Composio catalog. Drop the underscore,
      propagate `skill_filter` into `skill_filter_override`, and add a
      tracing log line to make this path observable. This is the
      downstream half of the #526 leak that commit 3's orchestrator-
      side scoping alone wouldn't have caught.

Tests: 8/8 `tool_loop` tests pass, 3/3 harness `tests.rs` cases pass,
323/324 agent module tests pass overall (the one failure is the same
pre-existing Windows-path bug in `self_healing::tool_maker_prompt_
includes_command` that fails identically on the upstream baseline).
No existing test expectations were changed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(dispatch): route channel messages to welcome/orchestrator by onboarding flag (#525)

Wires the per-agent tool scoping plumbing from commit 4a into the
channel-message dispatch path. Each incoming channel message now picks
the active agent — `welcome` pre-onboarding, `orchestrator` post — based
on `Config::onboarding_completed`, loads the matching definition from
the global `AgentDefinitionRegistry`, synthesises any `delegate_*` tools
the agent declares in its `subagents` field, and passes everything
through to `agent.run_turn` on the bus.

This is the half of #525 that makes the welcome agent actually run for
new users — the welcome definition has existed since upstream PR #522
but had no caller; nothing in dispatch consulted the onboarding flag,
so every channel message ran through the same generic tool loop with
the full registry exposed.

Changes:

  src/openhuman/channels/runtime/dispatch.rs
    - New `AgentScoping` struct carrying the three new `AgentTurnRequest`
      fields (`target_agent_id`, `visible_tool_names`, `extra_tools`)
      plus an `unscoped()` constructor for safe-fallback paths.
    - New async `resolve_target_agent(channel)` helper:
      * fresh `Config::load_or_init().await` per turn (no cache — the
        loader reads from disk every call, verified at
        `config/schema/load.rs:409`, so the welcome→orchestrator
        handoff is observed on the next message after
        `complete_onboarding(complete)` flips the flag, with no need
        for an explicit handoff event);
      * picks `"welcome"` or `"orchestrator"` based on the flag and
        emits a structured `[dispatch::routing] selected target agent`
        info trace recording the choice + the flag value, satisfying
        the #525 acceptance criterion `"agent-selection logs clearly
        record why each agent was selected at onboarding boundaries"`;
      * looks up the definition in `AgentDefinitionRegistry::global()`,
        gracefully falling back to `AgentScoping::unscoped()` (= legacy
        behaviour, no filter, no extras) if the registry isn't
        initialised or the definition isn't found, so a routing miss
        never fails the user message;
      * for agents with a non-empty `subagents` field, awaits
        `composio::fetch_connected_integrations(&config)` and runs
        `orchestrator_tools::collect_orchestrator_tools` to materialise
        per-turn delegation tools (`research`, `plan`, `delegate_gmail`,
        …). Agents with empty `subagents` get an empty extras vec.
    - New `build_visible_tool_set(definition, &extra_tools)` helper that
      returns `Some(union)` for `ToolScope::Named` agents (their named
      list ∪ the names of the synthesised delegation tools) and `None`
      for `ToolScope::Wildcard` agents to preserve the unfiltered
      semantics — so agents like `skills_agent` and `morning_briefing`
      that already work via `wildcard + category_filter` keep their
      existing behaviour without this layer interfering.
    - `process_channel_message` calls `resolve_target_agent` once per
      turn, drops the placeholder defaults from commit 4a, and feeds
      the real `target_agent_id`/`visible_tool_names`/`extra_tools`
      into `AgentTurnRequest`.
    - New imports: `AgentDefinition`, `AgentDefinitionRegistry`,
      `ToolScope`, `Config`, `fetch_connected_integrations`,
      `orchestrator_tools`, `Tool`, `HashSet`.

End-to-end behaviour after this commit:

  1. New user, `onboarding_completed=false`: dispatch picks `welcome`,
     loads its 2-tool TOML scope, builds `visible_tool_names =
     {complete_onboarding, memory_recall}`, no extras, hands off to
     the bus. Bus handler applies the filter → welcome's LLM sees
     exactly 2 tools.
  2. Welcome agent guides the user through setup, eventually calls
     `complete_onboarding(action="complete")` → flag persists to disk
     via `config.save()`.
  3. Next user message: dispatch reads the flag fresh, picks
     `orchestrator`, fetches connected Composio integrations, expands
     `subagents = ["researcher", "planner", "code_executor", "critic",
     "archivist", { skills = "*" }]` into delegate_research /
     delegate_plan / delegate_run_code / delegate_review_code /
     delegate_archive_session + one delegate_<toolkit> per connected
     integration. visible_tool_names is the union with the 4 direct
     tools from orchestrator's `[tools] named` list. LLM sees the
     scoped delegation surface, not the full 1000+ Composio catalog.

#526's runtime leak is now fixed end-to-end: the orchestrator's LLM
prompt only contains the tools its TOML allows, and the
SkillDelegationTool path narrows skills_agent to a single toolkit via
the `skill_filter` propagation fix from commit 4a. No agent at any
layer sees more than its definition declares.

Tests: 599/599 channel module tests pass — including
`runtime_dispatch::dispatch_routes_through_agent_run_turn_bus_handler`
and the telegram integration variant, which exercise the full bus
roundtrip with the new fields populated. No existing assertions were
modified.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(debug_dump): apply orchestrator definition filter to main dump (#526)

Replaces the explicit `empty_filter: HashSet::new()` in
`render_main_agent_dump` with a real visibility whitelist derived from
the orchestrator's `AgentDefinition`. The "main" dump path now mirrors
the runtime dispatch path from commits 4a/4b — same definition, same
delegation tool synthesis, same filter — so `openhuman agent dump-prompt
main` shows what the LLM actually sees in production instead of the
unfiltered global registry.

Before this commit, `dump-prompt main` always rendered every tool in
the registry regardless of which agent was supposed to run, which is
exactly the symptom #526 reports: "agent prompt tool scopes leak full
GitHub tool catalog". The runtime fix in commit 4b stops the leak in
production but the dump path was the user's primary observability tool
for inspecting prompts, so leaving it unscoped would mask future
regressions and confuse debug sessions.

Changes in `src/openhuman/context/debug_dump.rs`:

  * `dump_agent_prompt` now loads `AgentDefinitionRegistry` once at the
    top (previously only loaded inside the sub-agent branch). When the
    request is for "main" or "orchestrator_main", it looks up the
    "orchestrator" definition from the registry and passes it into
    `render_main_agent_dump` along with the registry itself. Missing
    orchestrator entry → structured error listing known agents
    instead of silently rendering an unfiltered prompt.

  * `render_main_agent_dump` signature gains `registry:
    &AgentDefinitionRegistry` and `orchestrator_def: &AgentDefinition`.
    Inside, it:
      - calls `collect_orchestrator_tools(orchestrator_def, registry,
        connected_integrations)` to synthesise the same per-turn
        delegation tools (`research`, `plan`, `delegate_<toolkit>`,
        …) that dispatch generates;
      - extends `prompt_tools` with the synthesised extras so they
        contribute to the rendered tool catalogue;
      - builds `visible_filter: HashSet<String>` from
        `orchestrator_def.tools` (the `[tools] named` list) ∪ the
        names of the synthesised extras, falling back to an empty
        HashSet when the orchestrator definition uses
        `ToolScope::Wildcard` (which the prompt builder treats as "no
        filter, every tool visible") so dump consumers that supply a
        wildcard orchestrator (custom workspace overrides, tests)
        retain the legacy unscoped behaviour;
      - replaces `visible_tool_names: &empty_filter` in the
        `PromptContext` with `&visible_filter`;
      - filters the returned `tool_names` and `skill_tool_count` by
        the same predicate so the `DumpedPrompt` summary fields
        match what the prompt text actually contains.

Tests:

  * Replaces the previous `render_main_agent_dump_includes_tool_
    instructions_and_skill_count` test with two more focused cases:

    1. `render_main_agent_dump_wildcard_scope_shows_full_tool_set` —
       regression guard for the legacy wildcard path. Builds a
       wildcard-scoped orchestrator definition, asserts every tool
       from `tools_vec` survives, and checks the standard system-
       prompt skeleton (Tools section, Tool Use Protocol, cache
       boundary) still renders.

    2. `render_main_agent_dump_named_scope_filters_to_whitelist` —
       the #526 regression guard. Builds an orchestrator with
       `ToolScope::Named(["query_memory", "ask_user_clarification"])`
       and a `tools_vec` containing `shell`, `query_memory`, and
       `GMAIL_SEND_EMAIL`. Asserts the dump's `tool_names` is exactly
       `["query_memory"]` — `shell` and `GMAIL_SEND_EMAIL` are in the
       global registry but NOT in the whitelist, so they MUST be
       excluded. If a future change reintroduces the unfiltered
       behaviour this test fails immediately.

  * Adds two test helpers: `wildcard_orchestrator_def()` builds a
    minimal orchestrator definition with all `omit_*` flags set and
    `ToolScope::Wildcard`, and `registry_with_orchestrator(orch)`
    wraps it in an `AgentDefinitionRegistry` so the tests can call
    `render_main_agent_dump` without going through the full TOML
    loader.

11/11 debug_dump tests pass. The two new guards plus the 9 existing
sub-agent / filter / composio-stub tests all run clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test(dispatch): unit tests for build_visible_tool_set + cargo fmt cleanup (#525, #526)

Adds focused unit tests for the per-agent scoping helper landed in
commit 4b and runs `cargo fmt` across the files touched by this PR.

Why scoping unit tests, not full integration tests:

  `resolve_target_agent` is async and reads `Config::load_or_init().await`
  which does a real disk read every call (no cache, verified at
  `config/schema/load.rs:409`). Mocking that requires either spinning up
  a full workspace under a temp dir with a config.toml containing the
  right `onboarding_completed` value, or adding a test-only injection
  point on the public Config API. Both are tractable but invasive
  enough to belong in their own follow-up PR. The end-to-end dispatch
  path is already covered by the existing channel integration tests
  (`dispatch_routes_through_agent_run_turn_bus_handler` etc.) which
  exercise the full bus roundtrip with the new fields populated, and
  which still pass after the new resolver landed (it gracefully falls
  back to `AgentScoping::unscoped()` when no orchestrator definition
  is registered in the test environment).

  Pure-function unit tests for `build_visible_tool_set` cover the
  branching logic that does the actual scoping work: how the named
  whitelist + extras union is built, how Wildcard scope is preserved,
  how duplicates are de-duplicated, etc. That's the part most likely
  to drift in future changes, so it's the part most worth fencing
  with focused tests.

Tests added (all in `src/openhuman/channels/runtime/dispatch.rs` under
the new `scoping_tests` module):

  * `wildcard_scope_yields_none_filter` — `ToolScope::Wildcard` must
    produce `None` regardless of whether extras are present, so
    skills_agent / morning_briefing keep their full skill-category
    catalogue.

  * `named_scope_without_extras_returns_named_only` — the welcome
    agent's path: 2 named tools, no delegation, exactly 2 entries in
    the visibility whitelist.

  * `named_scope_with_extras_returns_union` — the orchestrator's path:
    3 direct named tools + 3 synthesised extras (research,
    delegate_gmail, delegate_github) → 6 entries.

  * `empty_named_with_extras_returns_extras_only` — guards a future
    "delegation-only" agent layout where the agent has no direct tools
    of its own, just spawns subagents.

  * `empty_named_with_no_extras_returns_empty_set` — guards the
    distinction between `None` (no filter, all visible) and
    `Some(empty)` (filter active, nothing matches). Important because
    the prompt loop's `is_visible` check treats them differently.

  * `duplicate_names_across_named_and_extras_are_deduplicated` — the
    HashSet handles collisions automatically, but the test pins that
    behaviour so a future migration to `Vec<String>` (which would
    silently double-count) gets caught.

  * `agent_scoping_unscoped_has_no_filter_or_extras` — pins the
    safe-fallback constructor's contract. Used when the registry is
    uninitialised or the target agent is missing — every field must
    default to "no scoping" so the channel turn falls back to legacy
    unfiltered behaviour rather than crashing.

Plus `cargo fmt` run across the 6 files modified by this PR. No
behavioural changes.

Final test status across all commits 2-6 in this PR:

  * agent::harness::definition: 10/10  (4 new for Subagents schema)
  * agent::harness::tool_loop: 8/8 
  * agent::harness::tests: 3/3 
  * tools::orchestrator_tools: 5/5  (5 new)
  * channels::*: 599/599  (incl. dispatch integration)
  * channels::runtime::dispatch::scoping_tests: 7/7  (7 new)
  * context::debug_dump: 11/11  (1 replaced + 1 new)
  * Total agent module: 323/324 (one pre-existing Windows path
    failure in `self_healing::tool_maker_prompt_includes_command`
    confirmed identical against upstream/main baseline)

Pre-existing Windows-environment test failures NOT caused by this PR
and out of scope (all confirmed identical on upstream baseline; CI on
Linux is unaffected):

  * self_healing::tool_maker_prompt_includes_command (PathBuf separator)
  * cron::scheduler::run_job_command_success / _failure (Unix shell)
  * composio::trigger_history::archives_triggers_in_daily_jsonl... (path)
  * local_ai::paths::target_paths_preserve_absolute_overrides (path)
  * security::policy::checklist_root_path_blocked (POSIX absolute)
  * security::policy::checklist_workspace_only_blocks_all_absolute (POSIX)
  * tools::implementations::browser::screenshot::screenshot_command_
    contains_output_path (browser binary lookup)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(welcome): upgrade bare-install nudge with concrete integration pitches (#525)

Follow-up to #522 that addresses a rough UX edge in the welcome agent
prompt: users who arrive with only an API key configured (no
channels, no Composio integrations, no web search / browser / local
AI) were getting a "gentle suggestion" to connect something without
any concrete picture of what they'd actually unlock. The welcome
agent would finish onboarding, hand off to orchestrator, and leave
the user staring at a functional-but-empty assistant with no
roadmap for how to make it useful.

This commit rewrites the prompt to handle sparse setups explicitly.
No Rust changes — this is prompt.md only, picked up at build time
via the existing `include_str!` loader in `agents/mod.rs`.

Changes to `src/openhuman/agent/agents/welcome/prompt.md`:

  * Step 2's "point out what's missing" sub-point is rewritten from
    a single "gently suggest" line into a four-case decision tree
    keyed off `check_status` state:
      - No API key → critical, block completion.
      - Integrations yes, channels no → note the Tauri-only reach
        limitation, suggest a messaging platform.
      - Channels yes, integrations no → degraded assistant, nudge
        toward Composio.
      - Nothing beyond the API key → the "bare install" case, gets
        the new Step 2.5 treatment.

  * New **Step 2.5: Handling a bare install** section added after
    Step 2. Spells out what the user DOES have (sandboxed reasoning
    + coding assistant with memory), what they're MISSING (any
    external action), and how to structure the message: state the
    current capability honestly, pitch 2-3 specific integrations
    with concrete example prompts, point to Settings → Integrations
    / Channels, and leave room for the user to opt into the
    coding-only experience if that's what they actually want. For
    bare-install users the word budget stretches to 250-400 words
    (up from 200-350) so the concrete pitches and example prompts
    actually fit without cramming.

  * New **Integration capability reference** section giving the LLM
    a menu it can draw from when pitching integrations. Each entry
    is a one-line "connect X → I can Y" with a concrete example
    prompt the user could send next:
      - Gmail: "Summarise the most important emails that came in
        overnight and flag anything that needs a reply today."
      - Google Calendar: "What's on my calendar tomorrow, and do I
        have a 30-minute gap before 2pm?"
      - GitHub: "List open issues on my main project tagged 'bug'
        and summarise which ones look newest or most urgent."
      - Notion: "Pull up my 'Ideas' Notion database and show me
        the three newest entries."
      - Slack / Discord / Linear / Jira / etc. with similar shapes.

    Plus a sub-section for messaging platforms (Telegram / Discord /
    Slack / iMessage / WhatsApp / Signal / web-fallback) that
    clarifies which each is best for, and a sub-section for the
    other capabilities (web search, browser automation, HTTP
    requests, local AI) that explains what breaks without them.

    The LLM is told NOT to list everything — just pick 2-3 most
    likely to matter, defaulting to Gmail + GitHub + one of
    {Calendar, Notion} as the top-3 pitch when no profile context
    is available.

  * Tone guidelines updated to document the stretched word budget
    for bare installs (200-350 for configured users, 250-400 for
    bare installs).

  * "What NOT to do" list updated:
      - Explicitly allows product-tour-style listing ONLY in the
        bare-install case (Step 2.5), forbids it elsewhere.
      - Clarifies that describing what WOULD unlock with integration
        X is fine and encouraged; claiming a capability the user
        doesn't have is still forbidden.
      - Adds a new "Don't gloss over a bare install" entry that
        pins the rule: API-key-only users get concrete pitches and
        example prompts, not vague suggestions.

Scope note: this commit does NOT change the completion logic.
`complete_onboarding(complete)` still accepts API-key-only as the
minimum bar — that's a separate design question for the maintainer
about whether zero-integration users should be gatekept. This
change improves what the welcome agent SAYS to those users, not
whether they're allowed to proceed.

Tests: all 14 `agent::agents::tests` pass (including
`welcome_has_onboarding_and_memory_tools` which validates the
welcome agent's declarative shape is unchanged). The prompt.md
edit is pure content — no schema changes, no tool additions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(web-channel): route Tauri in-app chat to welcome/orchestrator + Windows fsync fix (#525)

Closes the web-channel-side half of the #525 welcome agent routing.
Also bundles a small pre-existing Windows compatibility fix for
`app_state::ops::sync_parent_dir` that was blocking end-to-end testing
of this branch on Windows.

## Web channel routing (primary change)

Commit 4b (274b50ed) wired the welcome-vs-orchestrator routing into
`channels/runtime/dispatch.rs::process_channel_message` — the handler
for inbound messages on external channels (Telegram, Discord, Slack,
iMessage, etc.). That path reads `config.onboarding_completed` and
selects the right agent via the bus.

End-to-end testing on the Tauri desktop app revealed a gap: the
in-app chat window does NOT route through `process_channel_message`.
It uses its own JSON-RPC method (`openhuman.channel_web_chat` →
`start_chat` → `run_chat_task` → `build_session_agent` →
`Agent::from_config`) which was hardcoded to build a generic
main-agent every turn. So a new user typing in the Tauri app saw the
orchestrator immediately, never the welcome agent.

This commit closes that gap without adding a third code path:

### `src/openhuman/agent/harness/session/builder.rs`

* Split the existing `Agent::from_config` into a thin wrapper + a
  new `Agent::from_config_for_agent(config, agent_id)`. The wrapper
  calls the new function with `agent_id = "orchestrator"`, preserving
  the legacy behaviour byte-identically for all existing callers
  (CLI, REPL, tests, every call site that doesn't care which agent
  they get).
* `from_config_for_agent` looks up `agent_id` in
  `AgentDefinitionRegistry::global()` up front; unknown ids fail
  fast with a clear error. Missing orchestrator is tolerated as a
  legacy / pre-startup fallback so existing tests that run without
  a populated registry continue to work.
* When a target definition is resolved:
    - `prompt_builder` uses `SystemPromptBuilder::for_subagent` with
      the agent's `system_prompt` body (read from the registry,
      which already has it inlined via `include_str!` from
      `agents/*/prompt.md` at crate-build time) and the three
      `omit_*` flags from its TOML.
    - `visible_tool_names` is built from the agent's
      `ToolScope::Named` list, unioned with the names of any
      synthesised delegation tools produced by
      `collect_orchestrator_tools` (for agents that declare
      `subagents = [...]`).
    - `ToolScope::Wildcard` yields an empty filter, matching the
      legacy "no filter, all visible" semantics.
    - `temperature` comes from the agent's TOML (e.g. welcome is
      0.7, orchestrator is 0.4) instead of
      `config.default_temperature`.
* Legacy behaviour for plain `from_config(config)` — which passes
  `agent_id = "orchestrator"` — is preserved: the prompt builder
  continues to use `SystemPromptBuilder::with_defaults()`, temperature
  comes from `config.default_temperature`, and the orchestrator's
  `subagents` list drives delegation tool synthesis exactly as
  before. No test expectations changed.

### `src/openhuman/channels/providers/web.rs`

* `build_session_agent` now reads `config.onboarding_completed` and
  picks `"welcome"` or `"orchestrator"` as the target agent id, then
  calls `Agent::from_config_for_agent`. Structured info log records
  the routing decision + the flag state for observability, matching
  the `[dispatch::routing]` trace pattern from Commit 4b.
* `config.onboarding_completed` is read fresh every turn because
  `run_chat_task` loads the config via
  `config_rpc::load_config_with_timeout`, which reads from disk on
  every call (no in-process cache). Welcome → orchestrator handoff
  therefore happens automatically on the next chat message after
  `complete_onboarding(complete)` flips the flag, with no explicit
  event or notification plumbing.
* `set_event_context` call is unchanged — the event context is a
  (session_id, channel_name) pair for telemetry, not the agent id.

## Windows fsync fix (bundled)

### `src/openhuman/app_state/ops.rs`

`sync_parent_dir` was calling `File::open(parent).and_then(|dir|
dir.sync_all())` on the save path for `app_state.json`. On Windows,
opening a directory as a regular file requires
`FILE_FLAG_BACKUP_SEMANTICS` which `std::fs::File::open` does not
set, so the call fails with "Access is denied. (os error 5)".

Mirrored the existing `#[cfg(unix)]` guard already in
`config/schema/load.rs::sync_directory`. On non-Unix the function is
a no-op and returns `Ok(())`. Durability on Windows is provided by
`NamedTempFile::persist`'s atomic `MoveFileEx`, which is sufficient
for config files.

This is a pre-existing upstream bug, not caused by this PR, but it
blocks end-to-end testing of any code path that touches
`app_state::save_stored_app_state_unlocked` on Windows — which
includes the web channel's agent_server_status RPC. Fixing it here
so the #525 routing can actually be tested on the developer's
machine, and the fix is tiny and self-contained. The `File` import
on line 1 is also gated behind `#[cfg(unix)]` to avoid an
unused-import warning on Windows.

## Tests

All 35 `agent::harness::session` tests pass, including the
transcript round-trip + session queue + runtime tests that exercise
the builder path most heavily. No test expectations were modified;
the refactor is a pure delegation chain (`from_config` → new inner
method → existing builder).

CLI dump-prompt testing from the earlier session still validates:
  * `openhuman agent dump-prompt welcome` → 2 tools, Step 2.5
    bare-install prompt embedded
  * `openhuman agent dump-prompt main` → 6 tools, zero skill leakage
  * `openhuman agent dump-prompt main --stub-composio` → still 6
    tools, composio meta-tools correctly filtered out

End-to-end Tauri testing (next step after this commit) will exercise
the new `build_session_agent` branch live — user types `hi`, web
channel routes to welcome, welcome replies with the updated
bare-install prompt from commit 990a7264.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(config): split chat_onboarding_completed from React UI onboarding flag (#525)

End-to-end testing on the Tauri desktop app revealed that the welcome
agent could never run from the in-app chat pane — even with all of
Commits 4b/8 in place — because the React layer's
`OnboardingOverlay.tsx` renders a full-screen wizard whenever
`onboarding_completed = false` and gates the chat pane behind it. By
the time a user can type a chat message the React wizard has already
flipped `onboarding_completed = true` (via `OnboardingOverlay::handleDone`
or the `Onboarding.tsx` wizard's completion handler), so the welcome
agent's routing condition is never satisfied on the Tauri surface.

This commit fixes the architectural conflict by splitting the single
`onboarding_completed` flag into two orthogonal flags:

* **`onboarding_completed`** — unchanged semantics. Tracks whether the
  React UI wizard has been completed/dismissed. Continues to be set
  by `OnboardingOverlay.tsx::handleDone` and `Onboarding.tsx` via the
  existing `config.set_onboarding_completed` JSON-RPC method. Used
  exclusively to gate whether the React layer renders the wizard.

* **`chat_onboarding_completed`** — NEW. Tracks whether the welcome
  agent's chat-based greeting flow has run. Set exclusively by the
  welcome agent itself via `complete_onboarding(action="complete")`.
  Used by both the Tauri web channel
  (`channels::providers::web::build_session_agent`) and the external
  channel dispatch path (`channels::runtime::dispatch::resolve_target_agent`)
  to decide whether to route to welcome or orchestrator.

The two flags are intentionally orthogonal:

  * A Tauri desktop user completes the React wizard → only
    `onboarding_completed` flips → wizard disappears → user types `hi`
    → welcome agent runs (because `chat_onboarding_completed` is still
    false) → welcome calls `complete_onboarding(complete)` →
    `chat_onboarding_completed` flips → next chat turn routes to
    orchestrator.

  * A Telegram/Discord user (no React wizard exists) sends a message
    → external channel dispatch checks `chat_onboarding_completed` →
    routes to welcome → welcome runs → flips the flag → next inbound
    message routes to orchestrator.

Both paths give every user the chat welcome experience, regardless of
which surface they came in through, and without requiring the React
wizard to be removed or restructured.

## Files changed

`src/openhuman/config/schema/types.rs`
* Add `chat_onboarding_completed: bool` field with `#[serde(default)]`
  for backward compat — existing `config.toml` files that don't have
  the field default to `false`, which means existing users will see
  the welcome agent on their next chat turn (correct behaviour, the
  welcome agent is idempotent).
* Default impl initializes the new field to `false`.
* Extensive rustdoc on both flags explaining the orthogonal split,
  why two flags exist, and which code paths gate on which.

`src/openhuman/tools/impl/agent/complete_onboarding.rs`
* `check_status` now reports BOTH flags side-by-side so the welcome
  agent's LLM can see whether the React wizard has run AND whether
  the chat welcome itself has run. Old single "Onboarding completed"
  line replaced with two lines: "UI onboarding wizard completed" and
  "Chat welcome flow completed".
* `complete()` now flips `chat_onboarding_completed`, NOT
  `onboarding_completed`. The React UI's flag is left untouched —
  that's owned by the React layer. Idempotency guard updated to
  check the chat flag.
* Rustdoc on `complete()` explains the orthogonal-flags rationale
  for future readers.

`src/openhuman/channels/providers/web.rs::build_session_agent`
* Reads `effective.chat_onboarding_completed` instead of
  `effective.onboarding_completed` for the welcome-vs-orchestrator
  decision.
* Log line now includes BOTH flags so observability captures the
  full picture (e.g. `chat_onboarding_completed=false,
  ui_onboarding_completed=true` is the expected steady state for a
  Tauri user who completed the React wizard but hasn't typed yet).

`src/openhuman/channels/runtime/dispatch.rs::resolve_target_agent`
* Same flag swap for the external-channel path.
* `[dispatch::routing] selected target agent` info trace also
  reports both flags.
* Function-level rustdoc updated with the new semantics.

## Backward compatibility

* Existing `config.toml` files: `chat_onboarding_completed` defaults
  to `false` via `#[serde(default)]`. Means existing users get a
  welcome message on their next chat turn — this is the desired
  behaviour, not a regression.
* React layer: untouched. The `config.set_onboarding_completed`
  JSON-RPC method continues to write the same field; the new flag is
  not exposed to React at all.
* External callers of `complete_onboarding(complete)`: they now flip
  a different flag. This may matter for callers who were depending
  on the flag flip side effect; a quick grep shows
  `tools/impl/agent/complete_onboarding.rs` is the only caller and
  the rest of the codebase reads `onboarding_completed` for UI
  purposes (snapshots, app state) and `chat_onboarding_completed`
  for routing — the split is clean.

## Tests

399/400 tools tests pass. The single failure
(`tools::impl::browser::screenshot::screenshot_command_contains_output_path`)
is a pre-existing Windows-environment bug that fails identically on
`upstream/main` baseline and is unrelated to this PR. No test
expectations were modified.

## Next step

Restage sidecar, relaunch Tauri, click through the React wizard once
to dismiss it, then type `hi` in the chat pane. This time
`build_session_agent` should read `chat_onboarding_completed=false`
and route to welcome, even though `onboarding_completed=true` was set
by the React layer.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(welcome): force tool-call-first iteration to stop greeting fallback (#525)

End-to-end testing on the Tauri desktop app revealed that the welcome
agent — even with all routing/scoping commits in place and the
correct prompt embedded — was producing 1-line greetings like
"Hey! What's up?" (15 chars, single iteration, zero tool calls)
instead of running its workflow. The user typed `hihi`, the LLM saw
the welcome agent's full ~14KB persona prompt, and chose to ignore
every workflow step in favour of the chatbot fallback behaviour.

Diagnosis: the previous prompt was descriptive ("Call check_status to
get a snapshot...") rather than imperative. Combined with a "Concise"
tone guideline and a low-information user input ("hihi"), the model
under tension between "be warm and concise" and "follow the workflow"
collapsed to "tiny greeting" — which is the chatbot training-data
default for short user messages.

This commit makes the workflow non-negotiable by:

## 1. New "MANDATORY FIRST ACTION" preamble at the top of the prompt

Inserted as a blockquote between the role description and "Your
workflow" so the model encounters it before any workflow steps. The
preamble:

* States explicitly that the **first thing emitted on every turn must
  be a tool call** to `complete_onboarding(check_status)` — before
  any user-facing text, before any greeting, before any thinking out
  loud.
* States the user's input is **irrelevant** to this rule: "hi",
  "hello", emoji, nothing — the first iteration always emits the
  same thing, a check_status tool call.
* Explains *why* the rule exists (without a status snapshot the
  agent has nothing to personalise on, and any blind greeting
  defeats the welcome agent's one job).
* Shows three concrete  wrong examples (generic chitchat reply,
  greeting-then-tool, refusing the tool because the user said hi)
  and one  correct example (first iteration emits ONLY the tool
  call, message comes in iteration 2).
* Closes with a stop-and-correct rule: "If you find yourself about
  to write any text in your first iteration, STOP. Emit the tool
  call instead."

## 2. Strengthened "Your workflow / Step 1" heading

Renamed to "Step 1: Check setup status (ALWAYS — see Mandatory First
Action above)" so the cross-reference is unmissable. Body explicitly
says "In your **first iteration**, ... No text. No greeting. Just
the tool call. ... You will use this report to write the actual
welcome message in your second iteration."

## 3. Length is non-negotiable (rewritten "Concise" tone guideline)

The previous "Concise — but scale with the situation" framing was the
exact phrase the model latched onto when producing 15 chars. Rewritten
to "Length is non-negotiable" and adds:

* "A 1-2 sentence greeting is a failure, not a 'concise' success."
* Explicit "if you ever produce a message under 100 words, stop and
  try again — you've almost certainly skipped a required element."
* A "concise vs. terse" callout distinguishing "no wasted words in a
  message that does its full job" from "skip the job entirely."

## 4. New "What NOT to do" entries

Three new bullets target the exact failure modes observed:

* The existing "Don't skip check_status" entry is upgraded with
  "**This is the single most common failure mode**" and a pointer
  back to the mandatory-first-action preamble.
* New "Don't reply with a 1-line greeting" entry forbids the chatbot
  fallback explicitly and sets a 100-word floor.
* New "Don't treat 'hi' / 'hello' / short greetings as a signal to
  be brief" entry explicitly disconnects user input length from
  agent output length, since "hi" is the most common opening and
  the user typing it needs the FULL welcome experience.

## What this does NOT change

* No Rust code changes. `prompt.md` is `include_str!`'d into the
  binary at crate-build time via `agents/mod.rs`, so the next sidecar
  rebuild picks up the new content automatically.
* No agent definition changes (`agent.toml` untouched). The welcome
  agent still has 2 tools (`complete_onboarding` + `memory_recall`),
  `temperature = 0.7`, `max_iterations = 6`, `omit_*` flags
  unchanged.
* No model hint change. Still `"agentic"`. If the new prompt language
  alone isn't enough to push the model over the workflow-following
  threshold, a follow-up commit can bump to `"reasoning"` for
  stronger instruction-following.
* The integration capability reference, Step 2.5 bare-install
  handling, subscription/referral flow, and handoff sections are
  unchanged from commit 990a7264. Those were never the problem —
  the problem was the model never reaching them because it skipped
  Step 1 entirely.

## Tests

14/14 `agent::agents::tests` pass, including
`welcome_has_onboarding_and_memory_tools` and `every_builtin_has_a_
prompt_body`. The structural shape of the welcome agent definition
is byte-identical; only the embedded prompt body changed.

## Verification plan

After restaging the sidecar and relaunching Tauri, type `hi` in the
chat pane. Expected behaviour:

1. `[web-channel] routing chat turn to 'welcome'` (already validated
   in commit 56d95e2c).
2. `[agent::builder] building session agent id=welcome` (already
   validated).
3. **`[agent_loop] iteration start i=1`** with a `check_status` tool
   call as the first emission — this is the new behaviour we're
   verifying.
4. `[agent_loop] iteration start i=2` after the tool returns, with
   the actual welcome message — should be 100-400 words covering all
   required elements.
5. If everything's in place, `complete_onboarding(complete)` call in
   the same turn or a later iteration → `chat_onboarding_completed`
   flips to `true` → next chat turn routes to orchestrator.

If iteration 1 still produces text instead of a tool call, the next
escalation is bumping the model hint from `"agentic"` to
`"reasoning"` in `agent.toml`.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(complete_onboarding): check session JWT in addition to legacy api_key (#525)

Discovered during end-to-end Tauri testing that the welcome agent
refused to call `complete_onboarding(complete)` for a fully
authenticated user because `check_status` reported "API key:
**missing**" — even though the user had completed the desktop OAuth
flow and a valid encrypted JWT was sitting in `auth-profiles.json`.

## Root cause

`check_status` was reading only `config.api_key` (an `Option<String>`
on the Config struct), which is a **legacy free-form provider key
field**. It is not where the desktop OAuth flow stores its
credentials. The actual openhuman backend session JWT lives in
`<openhuman_dir>/auth-profiles.json` under the `app-session:default`
profile, encrypted via the SecretStore using `<openhuman_dir>/.secret_key`,
and is read at every inference RPC via
`crate::api::jwt::get_session_token(config)` (which delegates to
`AuthService::from_config(config).get_profile(APP_SESSION_PROVIDER, None)`).

So a user who:
1. Completed the desktop deep-link OAuth flow (the only supported
   way to get an account), and
2. Has a fully populated `auth-profiles.json` with a valid encrypted
   `app-session:default` token,

was reported by `check_status` as "API key missing" because their
JWT lives in the auth profile store, not in `config.api_key`. The
welcome agent then dutifully refused to call `complete_onboarding(
complete)` per its own prompt rule ("If critical setup is missing,
do not complete onboarding"), and re-ran on every chat turn forever
even though there was nothing to fix.

This is a **pre-existing upstream bug** dating from PR #522 (the
welcome agent's introduction). It was written before, or in parallel
with, the auth-profile refactor that moved session credentials out of
`config.api_key` into the dedicated profile store. The check was
never updated to reflect the new auth model.

## Fix

`check_status` now checks BOTH sources:

```rust
let has_legacy_api_key = config.api_key.as_ref().map_or(false, |k| !k.is_empty());
let has_session_jwt = crate::api::jwt::get_session_token(&config)
    .ok()
    .flatten()
    .is_some_and(|t| !t.is_empty());
let is_authenticated = has_legacy_api_key || has_session_jwt;
```

The status report now shows:
* `Authentication: configured ✓ (session token from desktop login)` —
  when the user has gone through the OAuth flow (the typical case);
* `Authentication: configured ✓ (legacy api_key)` — when the user
  has set the legacy `config.api_key` field directly (CI / dev
  setups);
* `Authentication: **missing** — log in via the desktop app or set
  `api_key` in config to enable inference` — when neither source has
  a credential.

The line label changed from "API key" to "Authentication" because
"API key" was misleading for both states (it isn't really the user's
API key; it's the openhuman backend session JWT).

## What this unblocks

After this fix, a Tauri user who:
1. Logs in once via the desktop OAuth flow → JWT lands in
   `auth-profiles.json`,
2. Types `hi` in the chat pane → welcome agent runs,
3. Welcome calls `check_status` → reports "Authentication: configured ✓",
4. Welcome calls `complete_onboarding(complete)` → flips
   `chat_onboarding_completed` from false to true,
5. Next chat turn → routes to orchestrator.

Without this fix, step 4 never happens because welcome's prompt
explicitly forbids completing without an API key, so the user gets
the welcome message on every single turn forever.

## Files touched

`src/openhuman/tools/impl/agent/complete_onboarding.rs`
* `check_status` reads both `config.api_key` and
  `crate::api::jwt::get_session_token(&config)`.
* Status line renamed from "API key" to "Authentication" with a
  more informative message.
* Long inline comment documenting the two auth sources, why the
  check needs to consult both, and what bug was being fixed.

## Tests

360/361 tools tests pass. Only failure is the pre-existing Windows
browser-screenshot bug (`tools::impl::browser::screenshot::
screenshot_command_contains_output_path`) which fails identically on
upstream/main and is unrelated to this PR. The
`complete_onboarding::tool_metadata` test still passes — it only
checks the tool schema, not the runtime behaviour.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(welcome): force complete_onboarding(complete) in iteration 2 (#525)

Live Tauri test after Commit 11 (auth-aware check_status) showed the
welcome agent completing iteration 1 with the correct check_status
tool call AND iteration 2 with a beautiful 1586-char welcome message
— but NOT calling complete_onboarding(action="complete") to flip
chat_onboarding_completed. So the user gets the welcome message and
then routes to welcome AGAIN on every subsequent chat turn forever,
because the prompt's Step 3 is descriptive rather than imperative.

Same failure pattern as the iteration-1 chitchat fallback that
Commit 10 fixed — the LLM follows the path of least resistance. If
the prompt says "call X to finalize" without making it mandatory,
the model will write the welcome text, see that it's done its job,
and stop without emitting the second tool call.

Fix: rewrite Step 3 with the same "MANDATORY" preamble pattern that
worked for the iteration-1 fix. Specifically:

* Renamed Step 3 to "Complete onboarding — MANDATORY in iteration 2
  (when authenticated)" so the cross-reference is unmissable.
* Added a blockquoted "MANDATORY SECOND TOOL CALL" preamble at the
  top of Step 3 that:
  - States the rule: when check_status reports "Authentication:
    configured ✓", iteration 2 MUST contain BOTH the welcome message
    text AND a complete_onboarding(action="complete") tool call.
  - Explains the consequence: without the tool call, the user is
    routed to welcome forever, which is a hard failure.
  - Defines the iteration 2 output structure as a 2-element list:
    welcome text + tool call.
  - Shows / examples (welcome message without tool call vs. with
    tool call) so the model has a concrete pattern to match.
  - Documents the single exception: only when authentication is
    missing should complete() be skipped, and explicitly says
    "missing channels, missing Composio integrations, missing local
    AI — none of those block completion." Auth is the only blocker.
* Replaced the descriptive bullet list with a stricter "Decision
  rule for iteration 2" that pairs each check_status outcome with
  exactly what the agent must emit.

## What stays the same

* No code changes — the existing complete_onboarding tool already
  handles the action="complete" call correctly (Commit 11 made it
  flip the right flag and check the right auth source).
* No agent.toml changes — welcome still has 2 tools, max_iterations=6,
  temperature=0.7. Plenty of headroom for the 2-iteration flow.
* The decision logic itself is unchanged — auth → complete, no auth
  → no complete. Just the framing.

## Test plan

Restage sidecar, relaunch Tauri, type `hi`. Expected:

```
i=1: complete_onboarding(check_status) → "Authentication: configured ✓"
i=2: 1500-2000 char welcome message + complete_onboarding(action="complete")
       ↓
     [complete_onboarding] chat welcome flow marked complete, proactive agents seeded
       ↓
     chat_onboarding_completed flips false → true
```

Then type a follow-up message → expect:

```
[web-channel] route → orchestrator (chat_onboarding_completed=true)
```

That's the welcome → orchestrator handoff — the actual goal of #525.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(web-channel): include target_agent_id in THREAD_SESSIONS cache key (#525)

Final bug discovered during E2E testing: after Commit 12 made the
welcome agent successfully call complete_onboarding(complete) and
flip chat_onboarding_completed to true, the user typed a follow-up
message — but the next turn STILL routed through the welcome agent
instead of orchestrator.

## Root cause

`run_chat_task` caches the built `Agent` in a `THREAD_SESSIONS`
HashMap keyed by `(client_id, thread_id)`. The cache hit predicate
checked `model_override` and `temperature` for invalidation but not
the routing target — so when the routing decision flipped
(chat_onboarding_completed: false → true) between turns, the cache
happily returned the stale welcome agent and `build_session_agent`
was never invoked.

This was a real bug introduced by Commit 8 — when I added
agent-aware routing to `build_session_agent`, I should have
extended the cache key (or hit predicate) with the target agent id.
Without that, the routing fix only worked on the FIRST turn of any
thread; every subsequent turn served the cached agent regardless of
flag changes.

Symptoms in the live test:
* Turn 1: routes to welcome ✓, welcome runs 3 iterations, calls
  complete(), flag flips on disk → cached as welcome agent
* Turn 2: cache hits on (client_id, thread_id), returns cached
  welcome agent. NO `[web-channel]` routing trace, NO
  `[agent::builder]` trace. Welcome runs again with history_len=10.
* Result: orchestrator handoff never happens. User stuck in welcome
  forever.

## Fix

Three small changes in `web.rs`:

### 1. `SessionEntry` gains a `target_agent_id` field

```rust
struct SessionEntry {
    agent: Agent,
    model_override: Option<String>,
    temperature: Option<f64>,
    target_agent_id: String,  // NEW
}
```

Documents which agent definition was used to build the cached
`Agent`, so the next turn's cache lookup can compare against the
current routing decision.

### 2. New `pick_target_agent_id(config)` helper

```rust
fn pick_target_agent_id(config: &Config) -> &'static str {
    if config.chat_onboarding_completed {
        "orchestrator"
    } else {
        "welcome"
    }
}
```

Mirrors the routing decision inside `build_session_agent` so
`run_chat_task` can compute it once up front and use it as a cache
key component. Since `Config::load_or_init` reads from disk every
call, the value reflects the freshly persisted state — meaning the
moment the welcome agent flips the flag, the next turn's
`pick_target_agent_id` returns the new value, the cache hit
predicate falls through, and `build_session_agent` is invoked.

### 3. Cache hit predicate extended

```rust
let mut agent = match prior {
    Some(entry)
        if entry.model_override == model_override
            && entry.temperature == temperature
            && entry.target_agent_id == target_agent_id =>
    {
        log::info!("[web-channel] reusing cached session agent id={} ...");
        entry.agent
    }
    Some(prior_entry) => {
        log::info!(
            "[web-channel] cache miss — rebuilding session agent \
             (was id={}, now id={}) ...",
            prior_entry.target_agent_id, target_agent_id
        );
        build_session_agent(...)?
    }
    None => build_session_agent(...)?,
};
```

The `Some(prior_entry)` arm now distinguishes stale-cache hits
(rebuild + log the transition) from cold misses (rebuild silently).
The transition log line gives observability for the welcome →
orchestrator handoff: whenever you see "cache miss — rebuilding
session agent (was id=welcome, now id=orchestrator)", that's the
moment of the handoff in production.

## Tests

Library compiles. The cache-key change is small and the logic is
straightforward; no test changes needed (existing tests don't
exercise the `THREAD_SESSIONS` cache flow, and adding a unit test
would require mocking the global config + memory backend which is
significantly more setup than the change itself warrants).

Live verification: type `hi` (welcome), wait for the "all set"
message + flag flip, type a follow-up. Expected logs:

```
[web-channel] routing chat turn to 'welcome'  (turn 1)
[agent::builder] building session agent id=welcome
... welcome runs, calls complete(), flag flips ...

[web-channel] routing chat turn to 'orchestrator'  (turn 2)
[web-channel] cache miss — rebuilding session agent (was id=welcome, now id=orchestrator)
[agent::builder] building session agent id=orchestrator
```

That's the complete welcome → orchestrator handoff that has been
the goal of #525 since day one.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(complete_onboarding): document tool semantics in schema, terse success result (#525)

Stopping the prompt-bloat cycle on the welcome agent. Previous
commits (10, 12, and a half-applied iteration of 14) progressively
added MANDATORY blockquotes to welcome's prompt.md to fix three
distinct failure modes: chitchat-fallback in iter 1, missing
complete() in iter 2, and prose-leak in iter 3. Each fix worked but
the welcome prompt is now ~250 lines of imperatives encoding what
should be tool semantics, not agent persona.

The right home for tool semantics is the tool's own schema —
specifically `Tool::description()` and `parameters_schema()`. Those
fields are what the LLM sees when deciding when and how to call the
tool, and they apply to every agent that uses the tool, not just
welcome. Encoding the contract there lets the welcome prompt stay
about persona / workflow / tone, not implementation details.

## Changes

### `tools/impl/agent/complete_onboarding.rs`

#### `Tool::description()` — full rewrite

Replaces the previous 5-line description with a structured ~30-line
contract documenting BOTH actions:

* **`check_status`** — explicit list of what the report contains
  (auth, default model, channels, integrations, memory, both
  onboarding flags), explicit "side effects: NONE (read-only)"
  declaration, and explicit framing as "intended for an LLM agent
  to read and use as the basis for a personalized welcome message"
  so consumers know how to use the result.

* **`complete`** — explicit semantics: flips
  `chat_onboarding_completed`, triggers welcome→orchestrator
  handoff, seeds proactive cron jobs, idempotent, writes config.toml,
  has a pre-condition (must be authenticated). And critically:

  > The complete action returns the literal token "ok" on success.
  > **This return value is a machine-readable success marker, not
  > user-facing prose.** Do not paraphrase it, summarize it, or
  > acknowledge it back to the user — the actual user-facing welcome
  > text should have been emitted alongside the tool call in the
  > same iteration. The chat layer extracts the LAST iteration's
  > text as the user-visible reply, so any prose written after this
  > tool returns will overwrite the welcome message in the chat pane.

  This is the contract that prevents the iter-3 paraphrase leak,
  documented at the source of the tool result instead of in every
  consumer's prompt.

#### `parameters_schema()` — extended action description

The `action` enum's description now mirrors the contract:
> "check_status" → read-only inspection ... "complete" → finalize
> the chat welcome flow, flips chat_onboarding_completed to true,
> returns the literal token "ok" (NOT a user-facing message — do
> not paraphrase the result back to the user).

JSON-schema descriptions are seen by the LLM at function-calling
decision time, so the warning lands in the same place the LLM is
deciding whether to call the tool.

#### `complete()` return value

Changed from a 118-char chatty success string ("Chat welcome flow
marked as complete. Morning briefing and proactive agent jobs have
been set up. The user is all set!") to the literal 2-char `"ok"`.

The chatty string was the source of the iter-3 paraphrase leak —
the LLM kept treating it as something to summarize back to the user
in iteration 3, which overwrote the iter-2 welcome message in the
chat pane (because the chat layer extracts the last iteration's
text). With "ok" there's nothing to paraphrase.

The inline comment block on the return statement records the bug
history so a future maintainer who sees `Ok(ToolResult::success("ok"))`
and is tempted to make it more "informative" understands why it's
deliberately terse.

### `agents/welcome/prompt.md`

Reverts the half-applied "Step 6: STOP after iteration 2" blockquote
that I started adding in the previous commit attempt. Replaces it
with a single one-line pointer at the end of Step 5:

> "(See the `complete_onboarding` tool's own description for what
> its `"ok"` return value means and why you should not paraphrase it
> back to the user.)"

That's enough context for the welcome agent to understand the
return-value contract without duplicating the contract text. The
contract lives in the tool, not in the agent that consumes it.

## What this DOESN'T touch

* Commits 10 (mandatory first action) and 12 (mandatory second tool
  call) stay as-is. They're still arguably too forceful, but they
  encode workflow steps specific to the welcome agent's persona,
  not general tool semantics. Trimming them is a separate prompt
  audit follow-up.

* No code changes outside `complete_onboarding.rs`. No agent.toml
  changes, no schema changes, no other tool changes. Pure
  documentation + return-value tweak.

## Tests

`tool_metadata` still passes (it pins name, scope, permission_level,
and schema shape — not description text, which is intentionally
allowed to drift). 1/1 complete_onboarding tests pass. Library
compiles clean.

## Test plan

Restage sidecar, relaunch Tauri, type `hi`. Expected:
* iter 1: check_status → 600-char status report
* iter 2: 1500-char welcome message + complete_onboarding(complete)
* iter 3 (if it fires): no prose, or trivial prose ≪ iter 2 chars
* Chat pane shows the iter-2 welcome message, NOT a confirmation
  paraphrase.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(complete_onboarding): merge check + finalize, return JSON, halve welcome prompt (#525)

End-to-end testing surfaced the cleanest version of this design,
collapsing what had grown into a multi-iteration imperative dance
back into a single tool call with a JSON return value. Three
problems addressed in one pass:

## Problem 1 — two tool calls were a state-machine race condition

Previous design required the welcome agent to call two tools in
order: `complete_onboarding(check_status)` in iteration 1, then
`complete_onboarding(complete)` in iteration 2 alongside the welcome
text. This created a fragile state machine: if the model wrote the
welcome message but forgot the second tool call, the chat_onboarding
flag never flipped and the user got stuck in welcome forever. The
prompt grew a 50-line "MANDATORY SECOND TOOL CALL" blockquote with
multiple / examples to compensate for what was really an API
shape problem.

## Problem 2 — Markdown report fed paraphrase loops

`check_status` returned a 600-char human-readable Markdown report
with section headers, bullet points, and check marks. The LLM kept
treating it as a draft and paraphrasing fragments back into the
welcome message instead of using the field values as ground-truth
facts. Worse, the structured-looking output gave the model
permission to "wrap up" the tool result in iteration 3, producing
the (parenthetical) leak text the user kept seeing.

## Problem 3 — prompt was bloated past the point of usefulness

After three rounds of "the LLM did the wrong thing, add a more
forceful blockquote", the welcome prompt was ~250 lines, with
overlapping MANDATORY blocks, repeated / examples, and
imperatives that contradicted the tone guidelines. A model trying
to serve a coherent welcome persona could not emerge from that.

## Fix — single call, JSON return, auto-finalize as a side effect

`check_status` now does all of:

1. Reads the user's config.
2. Checks JWT via `crate::api::jwt::get_session_token` (the auth
   source the rest of the codebase uses).
3. **If authenticated AND chat_onboarding_completed is false, flips
   the flag + seeds proactive cron jobs as a side effect**. No
   second tool call, no parameter, no opt-in. Authentication is the
   only gate.
4. Returns a structured JSON snapshot:
   ```
   {
     "authenticated": true,
     "auth_source": "session_token",
     "default_model": "reasoning-v1",
     "channels_connected": ["telegram"],
     "active_channel": "web",
     "integrations": {
       "composio": false,
       "browser": false,
       "web_search": true,
       "http_request": false,
       "local_ai": true
     },
     "memory": { "backend": "sqlite", "auto_save": true },
     "delegate_agents": [],
     "ui_onboarding_completed": true,
     "chat_onboarding_completed": true,
     "finalize_action": "flipped"
   }
   ```

The `finalize_action` field discriminates three cases the welcome
agent needs to handle differently:

* `"flipped"` — auth ok, first welcome, flag was just flipped by
  this call. Write the full welcome and hand off.
* `"already_complete"` — auth ok, chat flow already done from a
  prior call. Friendly re-entry; still write a welcome but
  acknowledge they've been here before.
* `"skipped_no_auth"` — not authenticated. Don't write a celebratory
  welcome; explain the auth problem and let them retry on the next
  chat turn.

The `complete` action stays as a legacy manual finalize-only escape
hatch for admin tools / tests. Returns "ok". Welcome agent doesn't
use it.

## Welcome prompt rewrite

Down from ~250 lines to ~140. Specifically removed:

* "MANDATORY FIRST ACTION" blockquote (40 lines) — replaced with
  one tight paragraph in the new "Iteration 1: call
  complete_onboarding" section.
* "MANDATORY SECOND TOOL CALL" blockquote (50 lines) — entirely
  gone. There is no second tool call.
* "STOP after iteration 2" Step 6 from a previous failed iteration
  (never landed in this branch but the structure that motivated it
  is gone too).
* "Decision rule for iteration 2" (5 lines) — replaced with a
  three-bullet list keyed off `finalize_action`.
* Three duplicate "Don't reply with a 1-line greeting" / "Don't
  treat 'hi' as a signal to be brief" rules — collapsed into one
  shorter rule.

Added:

* "You have exactly two iterations. There is no third." — single
  declarative sentence that does the work the previous 90 lines of
  iteration imperatives were doing.
* Explicit framing that JSON is a fact source, not a draft. "Don't
  quote, paraphrase, or summarise the JSON snapshot back to the
  user."
* `finalize_action` decision tree (three bullets) so the agent
  knows what message to write for each case without the prompt
  needing to enumerate side effects.
* Handling for `skipped_no_auth` — short, helpful "you need to log
  in first" message instead of the celebratory welcome.

## Why this works without any iteration-2 imperatives

With a single tool call, the agent loop converges naturally:

* iter 1: tool call (the only thing the prompt allows)
* tool returns: JSON snapshot, flag already flipped server-side
* iter 2: prose response (no remaining tool calls to make)
* iter 3: doesn't fire because there's no incomplete work — the
  loop terminator at `turn.rs:351` returns when `calls.is_empty()`,
  which is iter 2's state.

No race, no forgotten flip, no paraphrased tool result, no
parenthetical leak.

## Files

`src/openhuman/tools/impl/agent/complete_onboarding.rs` — full
rewrite. New `check_status` builds the JSON, performs the auto-
finalize side effect, returns serialised JSON via `ToolResult::
success`. Old Markdown-report code deleted (~150 lines). Tool
description and `parameters_schema` rewritten to document the new
contract; the `finalize` parameter from the previous attempt is
removed entirely (auth presence IS the gate).

`src/openhuman/agent/agents/welcome/prompt.md` — full rewrite.
~250 → ~140 lines. New "two iterations, no third" workflow.
JSON-aware drafting instructions. `finalize_action` decision tree.

## Tests

* `tool_metadata` (1/1): pins schema shape (action enum, required
  fields). Still passes — schema unchanged at the level the test
  asserts.
* `agent::agents::*` (14/14): all welcome-definition shape tests
  pass. The TOML hasn't changed, only the embedded `prompt.md`.

## Verification

Restage sidecar, relaunch Tauri, type `hi`. Expected:

* iter 1: `complete_onboarding(check_status)` → JSON returned with
  `finalize_action: "flipped"`. Side effect: chat_onboarding
  flipped to true on disk.
* iter 2: ~250-word welcome message based on the JSON.
* iter 3: not reached. Loop terminates after iter 2.
* Chat pane shows the iter-2 welcome. No paraphrase leak.

Then type a follow-up:

* `[web-channel] cache miss — rebuilding session agent (was
  id=welcome, now id=orchestrator)` — the welcome → orchestrator
  handoff fires via Commit 13's cache invalidation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(welcome): hide the welcome→orchestrator handoff from the user (#525)

The welcome agent's prompt previously instructed it to close every
welcome message with an explicit handoff line:

> "From here, you're in the hands of the full OpenHuman assistant.
>  Just start a new conversation and ask it anything — it knows how
>  to delegate to specialists, run tools, search the web..."

That line is a UX leak. From the user's perspective they are
talking to "OpenHuman" — one assistant, one conversation. They do
not know there are multiple agents under the hood, and they
shouldn't have to. The welcome → orchestrator transition is a
routing-layer implementation detail. Surfacing it in the chat
makes openhuman feel like a chatbot framework instead of a
product.

## Changes (welcome prompt only — no code)

### Step 5 of the message structure

Renamed from "Hand off" to "Close naturally". New instruction:

> "End the message with something inviting like 'anything you'd
>  like to try first?' or 'what should we dig into?' — a normal
>  conversational close that lets the user pick up the next turn.
>  Do NOT mention handing off, transferring, or any change in who
>  they're talking to. The user does not know there are multiple
>  agents under the hood; from their perspective they're talking
>  to OpenHuman as one entity, and the next message they send
>  will just continue the conversation."

### "What NOT to do" list

Replaced the old "Don't forget the handoff" rule with its inverse:

> "**Don't reveal that the conversation is being routed to a
> different agent.** From the user's perspective they are talking
> to 'OpenHuman' — one assistant, one conversation. Do NOT say
> 'I'll hand you off to the main assistant', 'the orchestrator
> will take over', 'you're now in the hands of the full assistant',
> 'from here on out you'll be talking to a different agent', or
> any variation that exposes the welcome → orchestrator handoff.
> The handoff happens transparently in the routing layer; the user
> just sends another message and the conversation continues.
> Phrases like 'what should we dig into?' or 'anything you'd like
> to try first?' are correct conversational closes — they invite
> the next turn without leaking the architecture."

The rule lists four specific forbidden phrasings the previous
welcome agent runs produced (variations of "you're in the hands
of the full assistant" and "the orchestrator will take over") so
the model has explicit anti-patterns to match against, plus two
acceptable conversational closes.

## Why this matters for #525

The welcome → orchestrator handoff is the central architectural
contribution of this PR. From a developer's perspective it is a
big deal — different agent definition, different tool scope,
different prompt, different temperature, different model hint.
From the user's perspective it should be invisible. They type a
message, OpenHuman replies. They type another, OpenHuman replies.
The fact that one of those replies came from `welcome` and the
next from `orchestrator` is purely an implementation detail they
should never have to think about.

## What does NOT change

* No code changes. Pure prompt edit.
* The handoff still happens — `chat_onboarding_completed` still
  flips to true via the `check_status` auto-finalize, the
  `THREAD_SESSIONS` cache still invalidates between turns (Commit
  13), the next chat turn still routes to orchestrator (Commit 8).
  The mechanism is unchanged; only the user-facing framing of it
  is.
* No test changes. `agent::agents::welcome_has_onboarding_and_
  memory_tools` and `every_builtin_has_a_prompt_body` only
  validate the agent definition shape, not the prompt body text,
  so this commit does not affect them.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor(complete_onboarding): delegate auto-finalize side effect to complete() (#525)

Small refactor on top of Commit 15. The auto-finalize block inside
`check_status` previously inlined the entire flag-flip + cron-seed
sequence:

```rust
config.chat_onboarding_completed = true;
config.save().await?;
let seed_config = config.clone();
tokio::spawn(async move {
    if let Err(e) = crate::openhuman::cron::seed::seed_proactive_agents(&seed_config) {
        tracing::warn!("...");
    }
});
```

But the legacy `complete()` action does literally the same work.
Duplicating it meant two places to update if the finalize semantics
ever changed (e.g. add another side effect, change the cron seed
strategy). Refactor `check_status` to delegate to `complete()`:

```rust
let _ = complete().await?;
config.chat_onboarding_completed = true;  // mirror disk into local
```

The `let _` discards `complete()`'s `ToolResult::success("ok")`
return value — `check_status` is producing its own JSON snapshot,
the caller just wants the side effect.

The `config.chat_onboarding_completed = true` after the call is an
in-memory mirror of the flip that `complete()` just performed on
disk. Without it, the JSON snapshot built later in `check_status`
would still show the pre-flip value, because the local `config` was
loaded BEFORE `complete()` ran and `complete()` operates on its own
fresh disk-loaded copy. The mirror is one line, no extra disk read,
no behavior change.

## Why not extract a `perform_finalize(&mut Config)` helper instead

Considered. Would eliminate the in-memory mirror and the redundant
disk read inside `complete()`. Ruled out because:

* `complete()` is already documented and used as a public legacy
  action; changing its signature would ripple to admin tools and
  tests that call it through the action dispatcher.
* The mirror cost is one line, zero I/O, zero correctness risk.
* The literal "call complete() inside check_status" framing matches
  the request more directly.

If a future maintainer wants to refactor further, the obvious move
is to make `complete()` take `&mut Config`, drop the redundant
`Config::load_or_init` inside `complete()`, and have both
`check_status` and the public action handler load the config once
at their top level. That's a separate refactor.

## Files

`src/openhuman/tools/impl/agent/complete_onboarding.rs` — single
function body change in `check_status`. The "flipped" arm of the
`finalize_action` match now calls `complete()` and mirrors the
flip locally instead of inlining the flip + save + cron seed.
About -10 / +5 lines.

## Tests

Library compiles. The 1 `tool_metadata` test still passes (it
pins the schema shape, not function bodies). No behavior change
for any caller.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* style(builder): cargo fmt cleanup of from_config_for_agent body (#525)

Pure indentation cleanup applied by `cargo fmt` against the
`target_def` resolution block I added in Commit 8 (`feat(web-channel):
route Tauri in-app chat to welcome/orchestrator`). The original
indentation had an awkward type annotation on the `let target_def:
Option<...> = ` line that wrapped before the `match` keyword;
rustfmt prefers the `=` on the same line as the type and the
`match` body indented under it.

Zero behavior change. Same control flow, same logic, same
diagnostics. Detected by the husky pre-push hook running
`yarn rust:check` (which runs `cargo fmt --check`).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test(json_rpc_e2e): set chat_onboarding_completed=true in seed config (#525)

The e2e config seeded by `write_min_config` now sets
`chat_onboarding_completed = true` so `channel_web_chat` routes straight
to the orchestrator. Without this the first chat turn goes through the
new welcome agent whose tool contract is not modelled by the in-process
mock upstream, which tore down the SSE stream mid-response and caused
`json_rpc_protocol_auth_and_agent_hello` to fail with
`sse stream read failed: error decoding response body`.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Steven Enamakel <31011319+senamakel@users.noreply.github.com>
2026-04-13 14:17:11 -07:00
Steven EnamakelandGitHub 8635ac16c5 feat: real-time inference progress events for web channel (#514)
* feat(conversations): implement real-time inference status tracking

- Added new event listeners for inference start, iteration start, subagent spawning, and completion to track the live state of chat interactions.
- Introduced an `InferenceStatus` interface to manage the current phase and active tools/subagents for each thread.
- Updated the UI to display inference status indicators, enhancing user experience during chat interactions.
- Created a new `progress` module in the Rust backend to emit real-time progress events, allowing for better integration with the web channel.
- Refactored the `subscribeChatEvents` function to include new event handlers for managing inference and subagent events, improving clarity and maintainability of the event handling logic.

* style: fix formatting from pre-push hook

* fix(test): read SSE events until chat_done instead of first event

The e2e test expected `chat_done` as the first SSE event, but now
real-time progress events (inference_start, iteration_start) are
emitted before it. Use `read_sse_event_by_type` to skip progress
events and wait for the terminal `chat_done` event.
2026-04-12 11:58:36 -07:00
Steven EnamakelandGitHub 403f239ca5 refactor: remove QuickJS skills runtime (#508)
* refactor: remove quickjs skills runtime

* style: apply repo formatting

* refactor: clean up error reporting and connection handling

- Removed the 'skill' source option from the error report structure to streamline error reporting.
- Refactored the ConnectionsPanel component to simplify connection status badge rendering and improve clarity.
- Updated the CronJobsPanel to enhance logging for cron job loading processes.
- Adjusted SkillCard component to use a more consistent type for icons.
- Deleted outdated end-to-end tests for Gmail and Notion skills, improving test suite maintainability.

* fix: remove unnecessary ESLint disable comment in Conversations component

- Cleaned up the Conversations component by removing the ESLint disable comment for exhaustive dependencies in the useEffect hook, improving code clarity and maintainability.

* fix: remove unnecessary whitespace in Conversations component

- Eliminated an extra line of whitespace in the Conversations component, enhancing code readability and maintainability.

* refactor: streamline SkillCard imports for improved clarity

- Combined import statements in the SkillCard component to enhance code readability and maintainability.
2026-04-11 14:57:35 -07:00
Steven EnamakelandGitHub 73f8d1287a refactor: remove hardware-related components and streamline service management (#502)
* feat(config): introduce pre-login user directory structure

- Added support for a pre-login user directory to encapsulate configuration, memory, and state before any user logs in. This ensures that all initial data is scoped under a dedicated user directory (`users/local`), preventing direct writes to the root `.openhuman` path.
- Implemented the `pre_login_user_dir` function to return the appropriate path for the pre-login user.
- Updated configuration loading logic to defer disk state creation until the first successful login, enhancing user data management and isolation.
- Added tests to verify the correct behavior of the pre-login directory structure.

* refactor: remove hardware-related components and streamline service management

- Deleted hardware configuration and related tools from the codebase, including `HardwareConfig`, `HardwareTransport`, and associated memory management tools.
- Introduced a new `service.ts` module for managing service and daemon commands, consolidating service-related functionalities.
- Updated import paths across the application to reflect the removal of hardware references and the addition of the new service management module.
- Refactored the `build_system_prompt` function to remove hardware access instructions, focusing on action instructions instead.
- Cleaned up the Cargo.toml and Cargo.lock files by removing unused dependencies related to hardware management.

* chore: apply formatting and tauri lockfile sync

* refactor(tests): extract config file writing logic into a reusable function

- Introduced a `write_config_file` function to encapsulate the logic for creating directories and writing configuration files, improving code reuse and readability.
- Updated test cases to utilize the new function for writing configuration files, ensuring consistency and reducing duplication.
- Added handling for pre-login user directory structure to ensure configuration is correctly written to the appropriate paths.
2026-04-10 22:55:47 -07:00
Mega MindandGitHub 9118bfb5d6 Fix/skill start issue (#498)
* chore: update .gitignore and bump openhuman version to 0.52.2

- Added `overlay/src-tauri/target/` to .gitignore to prevent tracking of build artifacts.
- Updated the openhuman package version from 0.52.0 to 0.52.2 in Cargo.lock files for both the main and app/src-tauri directories.
- Enhanced entitlements for macOS Hardened Runtime to allow outbound HTTPS calls and server connections.
- Refactored registry operations to use rustls explicitly, improving network reliability on macOS.

* refactor(logging): improve debug message formatting in fetch_url_bytes function

- Updated the logging statement in the fetch_url_bytes function to enhance readability by formatting the debug message across multiple lines. This change improves clarity in log outputs, making it easier to track the number of bytes fetched from URLs.

* feat(skill-setup): enhance OAuth handling and skill status synchronization

- Introduced a managed OAuth auto-advance mechanism to ensure it runs only once per login attempt, improving user experience during authentication.
- Updated the SkillSetupWizard to handle skill runtime checks more effectively, ensuring that the skill starts correctly and transitions to the setup phase seamlessly.
- Enhanced the useSkillSnapshot hook to provide a synthesized offline snapshot when the skill is not yet running, preventing UI stalls during loading.
- Implemented background synchronization after OAuth completion to ensure users see fresh data immediately without blocking the UI.
- Added tests to validate the new behavior for skills setup completion and status retrieval without requiring the skill to be started first.

* refactor(skills): streamline setup_complete retrieval in handle_skills_status function

- Simplified the retrieval of the `setup_complete` variable by removing unnecessary line breaks, enhancing code readability and maintainability.
- This change improves the clarity of the function's logic without altering its functionality.

* refactor(skills): simplify success message and remove initial sync from OAuth flow

- Updated the success message in the SkillSetupWizard to remove references to background syncing, streamlining user communication.
- Removed the initial sync trigger from the SkillManager after OAuth completion, shifting the responsibility for data synchronization to the user interface or cron jobs.
- Adjusted comments in the desktopDeepLinkListener to reflect the new sync behavior, clarifying that initial data sync is no longer automatic.

* fix(pr-498): address CodeRabbit review and CI failures

- SkillSetupWizard: only show complete after startSetup succeeds; error on failures
- hooks: merge prior snapshot into offline fallback; use const arrow for helper
- E2E: reset skills_set_setup_complete in finally for isolation
- json_rpc_e2e: assert oauth/complete returns start() result; add minimal start()
- Skills page tests: mock screen-intelligence/autocomplete/voice hooks (CoreStateProvider)

Made-with: Cursor

* fix: address follow-up CodeRabbit (readiness poll, shared test mocks)

- SkillSetupWizard: waitForSkillRunning after startSkill before startSetup/auth RPC
- json_rpc_e2e: poll skills_status until running instead of fixed 400ms sleep
- Consolidate Skills page vi.mocks in test/mockDefaultSkillStatusHooks.ts

Made-with: Cursor

* fix: CodeRabbit — legacy OAuth awaits setSetupComplete, const waitForSkillRunning, mock base

- Legacy OAuth: await persistence before complete; error on failure; guard ref + reset on skillId
- waitForSkillRunning: const arrow per TS style
- mockDefaultSkillStatusHooks: offlineStatusBase spread for shared literals

Made-with: Cursor
2026-04-11 04:16:15 +05:30
Steven EnamakelandGitHub acc6246e59 Refactor core-polled app state and screen intelligence status (#464)
* refactor(accessibility): remove device control and predictive input features from accessibility settings

- Updated accessibility-related components and tests to eliminate device control and predictive input features.
- Adjusted AccessibilityPanel and ScreenIntelligencePanel to reflect the removal of these features.
- Modified related tests to ensure consistency with the updated accessibility status structure.
- Cleaned up accessibility session parameters and state management to focus solely on screen monitoring.

* refactor(accessibility): streamline featureOverrides state initialization

- Simplified the initialization of featureOverrides state in AccessibilityPanel and ScreenIntelligencePanel components for better readability.
- Consolidated parameter definitions in startAccessibilitySession to enhance clarity and maintainability.
- Removed unnecessary re-exports in the screen_intelligence engine module to clean up the codebase.

* chore(dependencies): update OpenHuman to version 0.51.19 in Cargo.lock

* chore(dependencies): update OpenHuman version to 0.51.19 in Cargo.lock

* feat(restart): implement core process restart functionality

- Added a new `SystemRestartRequested` event to the `DomainEvent` enum to handle restart requests.
- Introduced a `RestartSubscriber` that listens for restart events and manages the process respawn.
- Created a `service_restart` function to publish restart requests via the event bus.
- Updated service schemas to include a new `restart` controller with parameters for source and reason.
- Enhanced documentation to reflect changes in behavior and added necessary code comments.

* feat(accessibility): add last restart summary to Screen Intelligence Panel

- Introduced `lastRestartSummary` to the accessibility state and updated relevant components to display the last successful core restart information.
- Modified `PermissionsSection` and `ScreenIntelligencePanel` to include the new summary.
- Updated tests to validate the display of the last restart summary and ensure proper state management during core restarts.
- Refactored accessibility slice to handle the new restart summary in state updates.

* feat(core): enhance startup process with restart delay and subscriber registration

- Added a call to apply startup restart delay from environment variables in `run_core_from_args`.
- Updated the `bootstrap_skill_runtime` function to register a `RestartSubscriber` for handling restart requests, ensuring consistent respawn logic across triggers.
- Introduced a new `core_process` field in the `AccessibilityEngine` to track the core process status, including its PID and start time.
- Implemented a helper function to capture the core process start time using `OnceLock` for efficient initialization.

* feat(screen-intelligence): refactor accessibility state management and UI components

- Replaced direct Redux state access with a new `useScreenIntelligenceState` hook across multiple components, including `AccessibilityPanel`, `ScreenIntelligencePanel`, and their respective subcomponents.
- Streamlined permission and session handling by consolidating related functions and removing unnecessary dispatch calls.
- Updated tests to mock the new state management approach, ensuring consistent behavior and validation of UI elements.
- Removed the `SessionAndVisionSection` component to simplify the structure and improve maintainability.
- Introduced a new API file for screen intelligence to encapsulate related functionality and improve code organization.

* refactor(tests): clean up and optimize test files for accessibility and screen intelligence panels

- Removed redundant imports and streamlined the structure of test files for `AccessibilityPanel` and `ScreenIntelligencePanel`.
- Consolidated core process state initialization in test mocks for better readability.
- Updated dependency imports and ensured consistent mocking of state management hooks across tests.
- Enhanced the `ScreenPermissionsStep` component by improving the dependency array in the useEffect hook for better performance.

* refactor(store): remove unused authentication and user management code

- Deleted the `UserProvider`, `authSlice`, `authSelectors`, `userSlice`, `teamSlice`, and related test files to streamline the codebase.
- This cleanup enhances maintainability by removing legacy code that is no longer in use.
- Updated the store configuration to reflect the removal of these slices and ensure proper state management.

* refactor(webhooks): reorganize types and remove legacy state management

- Moved `TunnelRegistration` and `WebhookActivityEntry` types to a new `types.ts` file for better organization.
- Updated imports in `TunnelList` and `WebhookActivity` components to reference the new types location.
- Refactored `useWebhooks` hook to eliminate Redux state management in favor of local state, enhancing performance and reducing complexity.
- Removed unused `aiSlice`, `inviteSlice`, and `webhooksSlice` along with their associated tests to streamline the codebase.

* refactor(daemon): migrate state management from Redux to a custom store

- Introduced a new `store.ts` file to manage daemon state, replacing the previous Redux slice.
- Updated components and hooks to utilize the new state management approach, enhancing performance and reducing complexity.
- Removed the legacy `daemonSlice` and associated Redux logic, streamlining the codebase.
- Adjusted imports in various components and hooks to reference the new store structure.

* refactor(screen-intelligence): integrate core state management and enhance status handling

- Replaced direct state management in `useScreenIntelligenceState` with a new core state approach, utilizing `useCoreState` for improved performance and consistency.
- Updated status fetching and permission handling to leverage the core state snapshot, streamlining the logic and reducing redundant API calls.
- Introduced a new `CoreRuntimeSnapshot` interface to encapsulate runtime statuses, including screen intelligence, local AI, autocomplete, and service states.
- Adjusted related components and hooks to align with the new state management structure, enhancing maintainability and readability.
- Updated tests to validate the new runtime state structure and ensure proper functionality across the application.

* refactor(components): reorganize imports and streamline function formatting

- Moved the import of `Tunnel` and `tunnelsApi` in `TunnelList.tsx` for better organization.
- Reformatted function definitions in `store.ts`, `useDaemonHealth.ts`, `useDaemonLifecycle.ts`, `useWebhooks.ts` for improved readability.
- Cleaned up the structure of test files in `coreRpcClient.test.ts` by consolidating object properties for clarity.
- These changes enhance code maintainability and readability across the application.

* test(screen-intelligence): fix duplicate hook imports

* fix(tests): update ScreenIntelligenceDebugPanel test to use baseState for refresh status and vision calls

* refactor(invites): simplify error message rendering in Invites component

- Consolidated the conditional rendering of the load error message in the Invites component for improved readability.
- This change enhances the clarity of the code without altering functionality.

* refactor(daemon): streamline state management and function definitions

- Removed the `healthTimeoutId` from the `DaemonUserState` interface and related functions to simplify state management.
- Converted several functions in `store.ts` to arrow function syntax for consistency and improved readability.
- Updated the `Invites` component to handle asynchronous loading and error states more effectively, ensuring that in-flight requests are properly managed.
- Refactored the `CoreStateProvider` to enhance the refresh logic and prevent multiple simultaneous refreshes.
- Introduced a new `register_domain_subscribers` function in `jsonrpc.rs` to centralize event bus subscriber registration, improving code organization and maintainability.

* fix: add debug logging, atomic restart guard, and idempotent subscriber registration

- CoreStateProvider: add namespaced debug logger for polling failure diagnostics
- service/bus.rs: add AtomicBool gate to prevent duplicate restart spawns
- service/bus.rs: use OnceLock for idempotent RestartSubscriber registration
- Invites.tsx: add debug log in loadInviteCodes catch block

* style: apply prettier formatting to CoreStateProvider

* fix: sanitize error logging, serialize refresh, and demote restart logs

- CoreStateProvider: sanitize error objects in poll failure logs to avoid
  leaking tokens/headers
- CoreStateProvider: move in-flight guard into refresh() via shared promise
  so all callers (poll, updateLocalState, storeSessionToken) are serialized
- CoreStateProvider: log refreshTeams errors instead of swallowing them
- service/bus.rs: demote duplicate-restart log to debug, omit reason from
  log output to avoid free-form text emission

* style: apply cargo fmt to service/bus.rs
2026-04-09 15:51:27 -07:00
0f578382d1 fix(autocomplete): auto-start engine when config enabled (#412) (#442)
* fix(autocomplete): add start_if_enabled for engine auto-start at boot (#412)

The autocomplete engine was never started automatically when
config had autocomplete.enabled = true. Add start_if_enabled()
that checks config and starts the global engine singleton during
core process startup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(autocomplete): wire engine startup into core server init (#412)

Call start_if_enabled() after config load in the JSON-RPC server
so the autocomplete engine runs automatically when the core process
boots with autocomplete enabled. Remove stale E2E test assertions
that conflicted with the new startup path.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(autocomplete): auto-start engine when enabled via set_style RPC (#412)

When the frontend enables autocomplete through set_style(enabled=true),
automatically start the engine so suggestions begin immediately without
requiring a separate start call or app restart.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 02:56:58 +05:30
Steven EnamakelandGitHub 0609493e1a Add RAM-tiered local AI presets (#425) 2026-04-08 01:35:35 -07:00
200db04fc7 feat: scope user data to per-user directories (#370)
* feat(config): add user ID retrieval and workspace scoping for authenticated users

- Implemented `read_authenticated_user_id` to extract the user's ID from `auth-profiles.json`, avoiding a dependency cycle with the credentials module.
- Introduced `maybe_scope_workspace_to_user` to create user-specific workspace directories based on the authenticated user ID, ensuring isolated workspace data.
- Updated the configuration loading process to call `maybe_scope_workspace_to_user`, enhancing user data management.
- Added unit tests for the new functionality, ensuring correct behavior in various scenarios.

This change improves user experience by providing personalized workspace management based on authentication status.

* feat(config): enhance user management with active user state handling

- Added functions to manage the active user state, including `read_active_user_id`, `write_active_user_id`, and `clear_active_user`, allowing for user-specific configuration and workspace isolation.
- Introduced `default_root_openhuman_dir` to standardize the retrieval of the root directory for user data.
- Updated configuration loading to support user-scoped directories, improving the overall user experience by ensuring personalized settings and workspace management.

This change enhances the OpenHuman platform by enabling better user data management and isolation.

* feat(credentials): enhance user directory management during session storage

- Added logic to create and activate user-scoped directories based on the resolved user ID when storing session data, ensuring credentials are saved in the correct location.
- Implemented error handling for directory creation and active user ID writing, with appropriate logging for failures.
- Updated the configuration loading process to reflect the newly activated user directory, improving user-specific settings management.
- Enhanced the `get_data_dir` function to return user-scoped directories if an active user is set, streamlining data access.

This change improves user experience by ensuring that session data is correctly organized and accessible based on user context.

* refactor(tests): update user ID handling and improve test coverage

- Renamed and refactored tests to better reflect functionality, focusing on active user ID management.
- Removed the `write_auth_profiles` helper function and replaced it with direct calls to `write_active_user_id` for clarity.
- Enhanced tests to cover scenarios for reading and clearing active user IDs, ensuring accurate behavior in user-specific configurations.
- Added a new test for building user directory paths, improving overall test coverage for user management features.

This change streamlines the testing process and enhances the clarity of user ID handling in the configuration schema.

* refactor(paths): streamline model and binary path resolution

- Introduced a new `shared_root_dir` function to centralize the logic for determining the shared root openhuman directory, improving code clarity and reducing duplication.
- Updated `workspace_ollama_dir` and `workspace_local_models_dir` functions to utilize the new shared root directory, ensuring consistent path resolution for user-specific and shared resources.
- Enhanced the `model_artifact_path` function to leverage the new directory structure, improving the organization of model artifacts.

This refactor enhances maintainability and clarity in the path management for local AI resources.

* style: apply cargo fmt formatting

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor(paths): streamline directory management for model artifacts

- Updated the `model_artifact_path` function to utilize a new `shared_root_dir` function, which centralizes the logic for determining the root openhuman directory.
- Enhanced the `config_root_dir` function to improve clarity and maintainability.
- Adjusted the `workspace_ollama_dir` and `workspace_local_models_dir` functions to leverage the new shared directory logic, ensuring consistent path resolution across the application.

These changes improve the organization of directory management and enhance the overall clarity of the codebase.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 13:51:17 -07:00
faa881c5f1 Feat/343 screen intelligence e2e tests (#359)
* test(screen_intelligence): add E2E pipeline proof tests for #343

Add layered test coverage proving the full capture → vision → memory
pipeline: screenshot save/cleanup disk paths, VisionSummary serde
roundtrip, JSON-RPC shape tests for status and vision_recent endpoints.

- tests/screen_intelligence_vision_e2e.rs: save_screenshot_to_disk
  creates a PNG and keep_screenshots=false cleanup removes it;
  VisionSummary struct serializes/persists/is queryable end-to-end;
  platform support table + macOS checklist added to module doc
- tests/json_rpc_e2e.rs: screen_intelligence_status shape test
  (platform_supported, session.active, permissions.screen_recording);
  vision_recent returns empty summaries without an active session
- src/openhuman/screen_intelligence/tests.rs: save_screenshot_to_disk
  unit tests for the write path and the no-image-ref error path

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(screen_intelligence): enhance vision summary persistence and error handling

- Added new fields to track vision persistence count, last persisted key, and last persist error in SessionRuntime and SessionStatus.
- Implemented error handling for vision summary persistence, ensuring errors are logged and state is updated accordingly.
- Introduced a new method  to analyze a frame and persist the summary, improving the vision processing pipeline.
- Updated tests to validate the new functionality and ensure proper behavior with mocked vision outputs.

This commit improves the robustness of the screen intelligence pipeline by enhancing the tracking and handling of vision summary persistence.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 22:04:50 +05:30
YellowSnnowmannandGitHub 1acc916244 feat: extract and load user working memory from skill sync payloads (#357)
* feat: implement user working memory extraction from skill sync payloads

- Added functionality to enable the extraction of user working memory from successful skill syncs, allowing for persistent storage of user preferences, goals, constraints, and entities.
- Introduced a new configuration option in  to toggle working memory extraction.
- Created comprehensive documentation on the working memory extraction process, detailing its implementation and privacy considerations.
- Updated memory loading logic to include working memory entries in the context provided to agents, enhancing personalization capabilities.
- Enhanced logging for memory extraction processes to improve observability and debugging.

This feature enhances the user experience by allowing skills to maintain context across interactions, improving the overall effectiveness of the OpenHuman platform.

* docs: update architecture documentation to include user working memory integration

* refactor: centralize working memory constants and enhance extraction logic

- Moved `WORKING_MEMORY_KEY_PREFIX` and `WORKING_MEMORY_LIMIT` constants to `memory_context.rs` for better organization and accessibility.
- Updated `MemoryLoader` to utilize these constants, improving code clarity.
- Enhanced working memory extraction logic in `MemoryWriteJob` to conditionally persist user working-memory documents based on the job type.
- Improved logging for memory extraction processes to provide clearer insights during execution.
- Adjusted tests to ensure consistent behavior with the new working memory extraction logic.

* chore: update OpenHuman version to 0.51.8 and refactor JSON-RPC test for clarity

- Bumped the OpenHuman version in Cargo.lock from 0.51.6 to 0.51.8.
- Refactored the JSON-RPC end-to-end test to improve readability by encapsulating the result assertion logic within a block, enhancing clarity in the flow of data handling.
2026-04-06 22:04:31 +05:30
YellowSnnowmannandGitHub 0c14aea96a Improve autocomplete observability and runtime controls in settings + JSON-RPC (#308)
* Enhance AutocompletePanel logging and functionality

- Introduced MAX_LOG_ENTRIES constant to limit log entries to 200.
- Updated log formatting to include timestamps with milliseconds for better precision.
- Added UI logging for various actions (e.g., saving settings, starting/stopping autocomplete) to improve traceability.
- Enhanced error handling in refreshStatus, acceptSuggestion, and other functions to log specific failure messages.
- Added unit tests for AutocompletePanel to ensure functionality and logging behavior.

This update improves the overall user experience by providing clearer logs and better error handling in the Autocomplete feature.

* Refactor accessibility and autocomplete components for improved error handling and logging

- Updated  to log role changes as debug information instead of returning an error, allowing for more flexible handling of role fluctuations.
- Increased the timeout for autocomplete refresh operations from 15 seconds to 120 seconds to accommodate longer processing times, enhancing reliability.
- Improved error handling in the autocomplete engine to preserve previous suggestions and provide clearer error messages when operations are aborted.

These changes enhance the user experience by providing better logging and more robust handling of focus and autocomplete functionalities.

* Enhance AutocompletePanel functionality and improve error handling

- Refactored loadHistory to return an empty array when Tauri is not available, improving error handling.
- Introduced waitForAcceptedHistoryEntry to ensure the history is loaded before accepting suggestions, enhancing user experience.
- Updated the accept suggestion logic to use the new waitForAcceptedHistoryEntry function, ensuring the correct suggestion is applied.
- Modified tests to reflect changes in the accept suggestion API, ensuring accurate functionality.

These changes improve the reliability and responsiveness of the autocomplete feature.
2026-04-06 18:14:02 +05:30