mirror of
https://github.com/tinyhumansai/openhuman.git
synced 2026-07-27 21:08:00 +00:00
2150944cb65ff3a48d696faf226cdafc61cd2feb
1159
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2150944cb6 |
chore(tauri-cef): update submodule pointer to latest commit c64bea69
This commit updates the tauri-cef submodule to the latest commit, ensuring that the project is using the most recent changes and improvements from the upstream repository. This change is part of ongoing maintenance to keep dependencies up to date. |
||
|
|
a5bb3ec32a |
fix(ci): bump tauri-cef submodule to pick up cef-helper build fix
Move the vendored tauri-cef submodule pointer from d278ff5d1 (which sits
on `feat/cef-custom` — the wrong branch; .gitmodules tracks
`feat/cef-notification-intercept`) to 1b58f715f, the current tip of the
tracked branch.
Fixes macOS release builds, which were failing in the `cargo install
--locked --path vendor/tauri-cef/crates/tauri-cli` step with:
error[E0583]: file not found for module `notification`
--> src/main.rs:3:1
|
3 | mod notification;
| ^^^^^^^^^^^^^^^^^
tauri-bundler/build.rs previously copied only cef-helper/Cargo.toml and
src/main.rs into OUT_DIR before invoking a nested cargo build, but
cef-helper's main.rs contains `mod notification;` and the sibling
notification.rs was never copied. The fix on the fork (1b58f715f —
"fix(bundler): copy entire cef-helper/src/ tree, not just main.rs")
copies the whole src/ directory, which resolves the module.
Linux and the CI Docker image are unaffected because the bundler build
script short-circuits on non-apple-darwin targets; this only bites the
macOS release matrix.
|
||
|
|
f88d6572fb |
fix(ci-image): include vendored tauri-cef in CI Docker build context
The root .dockerignore excludes `app/` (it's sized for the openhuman-core Dockerfile), which also excludes `app/src-tauri/vendor/tauri-cef`. The CI image Dockerfile at .github/Dockerfile needs that path to compile the CEF-aware tauri-cli, so the docker-ci-image workflow fails at the `COPY app/src-tauri/vendor/tauri-cef /opt/tauri-cef` step. BuildKit prefers `<dockerfile>.dockerignore` over the root one, so add a dedicated .github/Dockerfile.dockerignore that keeps the vendored submodule while still stripping target/, node_modules/, etc. Verified locally: `docker build -f .github/Dockerfile .` reaches the verify step with `cargo tauri --version` printing 2.10.1. |
||
|
|
93e85c2df3 |
feat(build): make CEF the default webview runtime across builds, tests, and releases (#641)
- Flip `app/src-tauri/Cargo.toml` `default = ["cef"]` (wry is now opt-in via `--no-default-features --features wry`). `cef-dll-sys` auto-downloads the Chromium runtime per-target at compile time. - Update dev scripts: `dev:app` now uses CEF + keychain safe-storage setup; `dev:cef` aliased to it; new `dev:wry` for opt-out; `macos:build:*` and `tauri:build:ui` switched to `cargo tauri` so the CEF-aware bundler runs. - Replace `tauri-apps/tauri-action@v0.6.2` / `yarn tauri build` with `cargo tauri build` in `build.yml`, `build-windows.yml`, and `release.yml`. The upstream `@tauri-apps/cli` binary does not bundle CEF framework files into the produced installer — only the fork at `vendor/tauri-cef` does, so workflows must use the fork's CLI or the shipped apps fail to launch. - Bake the CEF-aware `cargo-tauri` into `ghcr.io/tinyhumansai/openhuman_ci` by compiling it from the submodule during Docker image build, plus CEF runtime libs (libnss3, libgbm1, libxshmfence1, …). Skips the per-run cargo-install in the container-based `build.yml`. - Cache CEF downloads per-OS in matrix jobs (~400MB/platform) and cache the compiled `cargo-tauri` binary on raw GH runners (build-windows, release). - Explicit `gh release upload` step for Linux + Windows installers since the tauri-action upload path was removed; macOS keeps its existing re-sign + notarize + re-upload flow. |
||
|
|
fff24a6c6f |
fix(prompts): v2 prompt pipeline, integrations_agent, and subagent session plumbing (#642)
* refactor(transcript): update session transcript paths and enhance directory structure
- Changed the source of truth path for session transcripts from `sessions/{DDMMYYYY}/{agent}_{index}.jsonl` to `session_raw/{DDMMYYYY}/{agent}_{index}.jsonl` to better reflect the organization of files.
- Updated the logic for creating and resolving transcript paths to accommodate the new directory structure, ensuring compatibility with legacy `.md` files.
- Improved documentation to clarify the changes in file organization and their implications for transcript management.
This refactor enhances the clarity and maintainability of session transcript handling by establishing a more logical file structure.
* refactor(prompts): update tool handling in prompt builders
- Replaced `Vec<String>` with `Vec<ToolSummary<'_>>` for available tools in multiple agent prompt builders, enhancing type safety and clarity.
- Introduced `render_tool_catalog` and `render_connected_integrations` functions to dynamically generate sections in prompts based on available tools and connected integrations.
- Updated the `build` function in various agent prompts to utilize the new rendering functions, ensuring that prompts accurately reflect the current context and available resources.
These changes improve the maintainability and functionality of the prompt generation process across different agents.
* refactor(prompts): streamline prompt builders for agent templates
- Updated the prompt builders for various agents to utilize the sibling `prompt.md` template directly, enhancing clarity and maintainability.
- Replaced `Vec<ToolSummary<'_>>` with `Vec<ToolSummary>` and `Vec<ConnectedIntegration>` for improved type safety in test cases.
- Adjusted the `build` function to ensure consistent formatting and handling of tool catalogs across different agents.
These changes simplify the prompt generation process and prepare the codebase for future enhancements.
* refactor(harness): unify tool filtering and prompt loading for debug consistency
- Exposed `filter_tool_indices` and `load_prompt_source` as `pub(crate)` to ensure that both the live runner and debug dump share the same filtering and loading logic, eliminating discrepancies.
- Enhanced documentation for both functions to clarify their purpose and usage, improving maintainability and understanding of the codebase.
These changes streamline the tool management process and enhance the reliability of debug outputs, ensuring consistency across different contexts.
* refactor(prompts): enhance prompt builders for agent templates
- Updated the prompt builders for various agents to return fully-assembled system prompts, incorporating section helpers from `crate::openhuman::context::prompt`.
- Replaced `Vec<ToolSummary<'_>>` with `Vec<ToolSummary>` and `Vec<ConnectedIntegration>` for improved type safety in test cases.
- Adjusted the `build` function to ensure consistent formatting and handling of user files, tools, and workspace sections across different agents.
These changes streamline the prompt generation process, improve maintainability, and prepare the codebase for future enhancements.
* refactor(prompts): enhance prompt context handling for dynamic sources
- Updated the prompt builders to support fully-assembled prompts from dynamic sources, allowing for more flexible prompt generation.
- Introduced `PromptTool` and `PromptContext` structures to replace `ToolSummary`, improving type safety and clarity in prompt construction.
- Refactored the handling of prompt sources in both the subagent runner and session builder to streamline the integration of dynamic prompts and legacy sources.
These changes improve the maintainability and functionality of the prompt generation process, ensuring accurate representation of available tools and context in agent interactions.
* refactor(prompts): improve prompt context and tool handling
- Enhanced the `PromptContext` structure to include additional fields for better context management, such as `skills`, `dispatcher_instructions`, and `tool_call_format`.
- Replaced `ToolSummary` with `PromptTool` for improved type safety and clarity in prompt generation.
- Updated the handling of dynamic prompt sources in both the subagent runner and debug dump, ensuring consistent integration and rendering of prompts.
- Introduced a mechanism to handle empty visible tool names, enhancing the robustness of prompt generation.
These changes streamline the prompt construction process and improve the overall maintainability of the codebase.
* refactor(prompts): reorganize prompt handling and introduce SystemPromptBuilder
- Moved prompt-related types and builders from `openhuman::context::prompt` to `openhuman::agent::prompts` for better modularity.
- Introduced `SystemPromptBuilder` to streamline the construction of system prompts, allowing for flexible section management.
- Updated module exports to maintain compatibility while enhancing the organization of prompt-related code.
These changes improve the clarity and maintainability of the prompt generation process, aligning it more closely with the agents that utilize these prompts.
* refactor(prompts): unify agent prompt handling and update CLI references
- Removed the "main" alias for the orchestrator in the prompt dumping process, treating it as just another registered agent.
- Updated the `debug-agent-prompts.sh` script to reflect this change, ensuring all agents are included uniformly.
- Revised documentation and error messages in `agent_cli.rs` to replace references to "main" with "orchestrator" for clarity.
- Enhanced the debug dump functionality to maintain consistency across agent prompts, improving overall maintainability and usability.
These changes streamline the prompt handling process and clarify the usage of agent identifiers in the CLI, aligning with the new architecture.
* refactor(prompts): remove CACHE_BOUNDARY references from agent prompts
- Eliminated the CACHE_BOUNDARY marker from various agent prompt files, streamlining the prompt generation process.
- Updated the build functions in multiple agents to ensure consistent handling of workspace rendering without the cache boundary.
- Refactored related prompt handling logic to enhance clarity and maintainability, aligning with the new architecture.
These changes simplify the prompt structure and improve the overall efficiency of prompt generation across agents.
* refactor(prompts): remove cache boundary references from tests and prompts
- Eliminated all instances of cache boundary references from the subagent runner and related tests, simplifying the prompt handling logic.
- Updated test assertions to reflect the removal of cache boundary checks, ensuring consistency across the testing framework.
- Refactored the session manager to streamline the system prompt assembly process without relying on cache boundaries.
These changes enhance the clarity and maintainability of the prompt generation process, aligning with the recent architectural updates.
* refactor(harness): clean up unused imports and streamline code
- Removed unnecessary imports from multiple files, including `RandomState`, `Hasher`, and `SerializeMap`, to enhance code clarity and maintainability.
- Simplified the structure of several modules by eliminating redundant use statements, ensuring a cleaner and more efficient codebase.
These changes contribute to a more organized and readable code structure, aligning with ongoing refactoring efforts.
* refactor(prompts): enhance agent prompt structures and integration handling
- Updated the `orchestrator`, `skills_agent`, and `welcome` prompts to streamline the rendering of connected integrations and delegation guides.
- Introduced dedicated functions for rendering integration information, ensuring clarity in the agent's voice and responsibilities.
- Removed redundant sections from the shared prompt builder, allowing each agent to manage its own prompt content more effectively.
- Improved test coverage for prompt generation, ensuring accurate representation of connected integrations and skills.
These changes enhance the maintainability and clarity of the prompt generation process, aligning with the recent architectural updates.
* refactor(session): update integration handling and clean up prompt parameters
- Revised documentation for `connected_integrations` in the `Agent` struct to clarify its role in the agent's prompt rendering.
- Updated the parameter name in `render_subagent_system_prompt_with_format` to `_connected_integrations` to indicate it is unused, enhancing code clarity.
- Cleaned up import statements in the context module for better organization and maintainability.
These changes improve the clarity of integration handling and streamline the code structure, aligning with ongoing refactoring efforts.
* refactor(agent_cli): simplify command options and improve documentation
- Removed the `--skill` option from the `dump-prompt` command, streamlining the command usage and focusing on essential parameters.
- Updated documentation to clarify the usage of the `dump-prompt` command and its parameters, enhancing user understanding.
- Cleaned up the `DumpFlags` structure by removing unused fields, contributing to a more maintainable codebase.
These changes improve the clarity and usability of the agent CLI, aligning with ongoing refactoring efforts.
* refactor(cli): streamline dotenv loading and clean up prompt rendering
- Introduced `load_dotenv_for_cli` to load environment variables for all CLI entrypoints, ensuring consistent configuration across commands.
- Updated documentation to clarify the purpose of the dotenv loading mechanism.
- Removed unnecessary blank lines in prompt rendering functions across multiple agents, enhancing code readability.
These changes improve the maintainability and clarity of the CLI and prompt handling, aligning with ongoing refactoring efforts.
* refactor(debug-agent-prompts): enhance environment loading and streamline workspace resolution
- Updated the script to load environment variables from a `.env` file, ensuring consistent configuration for prompt generation.
- Simplified workspace resolution by delegating to the binary's internal logic, improving reliability and reducing code duplication.
- Revised documentation to clarify the usage of command options and the impact of environment variables on prompt rendering.
These changes improve the maintainability and clarity of the debug agent prompts script, aligning with ongoing refactoring efforts.
* refactor(agent): remove category filter and simplify agent definitions
- Eliminated the `category_filter` from various agent definitions and related tests, streamlining the agent configuration.
- Updated the `run_list` function in `agent_cli.rs` to reflect the removal of category filtering, enhancing output clarity.
- Revised documentation and comments to remove references to the now-removed category filter, improving overall code maintainability.
These changes contribute to a cleaner and more efficient agent architecture, aligning with ongoing refactoring efforts.
* feat(agents): introduce integrations_agent and tools_agent for enhanced service handling
- Added the `integrations_agent` to manage service integrations via Composio, including a new TOML configuration and prompt structure.
- Introduced the `tools_agent` for general ad-hoc tasks using built-in OpenHuman tools, with its own configuration and prompt.
- Updated the loader to include both agents in the built-in agent list, increasing the total number of agents from 13 to 14.
- Revised orchestrator and welcome prompts to delegate integration tasks to the new `integrations_agent`, ensuring clarity in agent responsibilities.
- Enhanced tests to verify the registration and functionality of the new agents, improving overall test coverage.
These changes expand the capabilities of the agent architecture, allowing for more specialized handling of integrations and tool usage.
* refactor(agents): update references from skills_agent to integrations_agent
- Changed all instances of `skills_agent` to `integrations_agent` across various files, including prompts, CLI commands, and tool registrations.
- Updated documentation and comments to reflect the new agent name, ensuring clarity in agent responsibilities and usage.
- Revised debug scripts to align with the new prompt structure for the integrations agent.
These changes enhance consistency in the codebase and improve the clarity of agent interactions.
* refactor(agents): rename skills_agent to integrations_agent throughout the codebase
- Updated all instances of `skills_agent` to `integrations_agent` in various files, including tests, documentation, and comments.
- Ensured consistency in agent references to improve clarity in agent responsibilities and interactions.
- Revised related code structures to align with the new naming convention, enhancing overall maintainability.
These changes support the transition to the new agent architecture and improve code readability.
* refactor(prompts): implement dynamic prompt rendering for enhanced context handling
- Introduced `DynamicPromptSection` to allow prompts to be built dynamically using a function pointer, enabling real-time access to the `PromptContext`.
- Updated `SystemPromptBuilder` to support dynamic prompts, ensuring that late-arriving state like `connected_integrations` is accurately reflected in the rendered output.
- Revised the prompt handling logic in the agent builder to streamline the integration of dynamic prompts, improving overall flexibility and responsiveness.
These changes enhance the prompt generation process, aligning with the ongoing improvements in agent architecture and context management.
* refactor(prompts): refine delegation guide to display only connected integrations
- Updated the `render_delegation_guide` function to list only the toolkits that are actively connected, omitting unauthorized toolkits to prevent hallucinations during delegation.
- Revised related tests to ensure the prompt correctly reflects the current state of integrations, including scenarios where no integrations are connected.
- Introduced a new utility function to filter out welcome-only tools from non-welcome agents, enhancing the clarity and safety of tool visibility.
These changes improve the accuracy and focus of the delegation guide, aligning with the ongoing enhancements in agent prompt handling.
* refactor(planner): update tool usage and prompt guidelines for read-only operations
- Modified the `agent.toml` configuration to clarify that the planner operates in a read-only mode, specifying that it does not mutate the workspace or memory.
- Revised the prompt guidelines to reflect the read-only nature of the planner, emphasizing the need for explicit nodes for any required writes to be handled by downstream agents.
These changes enhance the clarity of the planner's operational constraints and improve the overall structure of the planning process.
* refactor(config): remove web search enable flag and update related configurations
- Eliminated the `OPENHUMAN_WEB_SEARCH_ENABLED` environment variable and associated logic, as web search is now always enabled by default.
- Updated the configuration schema to reflect the removal of the enable flag from `WebSearchConfig`.
- Adjusted tool registration to ensure web search is always available, simplifying the configuration process.
These changes streamline the web search functionality, ensuring it is consistently available across all sessions.
* refactor(config): update http_request flag to always enabled
- Changed the `http_request` configuration to always be enabled, removing the dependency on the `config.http_request.enabled` flag.
- This adjustment simplifies the configuration process and ensures consistent behavior across the application.
These changes contribute to a more streamlined configuration and enhance the overall reliability of the onboarding process.
* refactor(debug-agent-prompts): transition to dump-all command for agent prompts
- Replaced the previous method of listing agent IDs and dumping prompts with a new `dump-all` command that consolidates the functionality into a single call.
- Updated the script to handle output directory and workspace options more efficiently, leveraging Rust's `dump_all_agent_prompts` for processing.
- Enhanced the handling of the `integrations_agent` to generate separate dumps for each connected toolkit, improving the clarity and organization of output files.
- Revised related logging and summary generation to reflect the new structure, ensuring a more streamlined user experience.
These changes modernize the prompt dumping process, aligning it with the latest architectural improvements and enhancing usability.
* feat(composio): implement dynamic fetching of toolkit actions for integrations
- Added a new `fetch_toolkit_actions` function to retrieve the current action catalogue for a specified Composio toolkit, enhancing the responsiveness of the integrations agent.
- Updated the `subagent_runner` to utilize the fresh action list at spawn time, ensuring that the toolkit's actions reflect the latest backend state.
- Modified the `render_integrations_agent` function to refresh the action catalogue during prompt generation, improving the accuracy of the displayed tools.
These changes enhance the integration experience by providing up-to-date action information, aligning with the ongoing improvements in agent functionality.
* refactor(integrations-agent): update tool visibility and configuration handling
- Modified the `agent.toml` to replace `wildcard` with `named` tools, enhancing control over tool visibility for the integrations agent.
- Updated the `subagent_runner` to ensure that tool visibility aligns with the new TOML configuration, preventing unnecessary stripping of tools.
- Revised the `render_integrations_agent` function to respect the updated tool scope, improving the accuracy of the tool list generated for subagents.
These changes streamline the tool management process, ensuring that only explicitly defined tools are available during agent execution.
* feat(composio): add composio_list_connections tool for dynamic integration detection
- Introduced the `composio_list_connections` tool in the orchestrator's configuration, allowing the agent to detect newly-authorized Composio integrations mid-session.
- Enhanced the `ComposioListConnectionsTool` to filter and return only currently-connected integrations with ACTIVE or CONNECTED status, improving the accuracy of integration management.
- Updated the tool's description to clarify its functionality and usage context.
These changes enhance the agent's ability to manage integrations dynamically, aligning with ongoing improvements in the integration experience.
* fix(prompt): update delegation guide to reference Skills page
- Modified the `render_delegation_guide` function to change the reference from **Settings → Integrations** to the **Skills** page for connecting integrations. This update clarifies the user instructions for integration management.
* feat(session): introduce session key management for sub-agents
- Added `session_key` and `session_parent_prefix` fields to `ParentExecutionContext` to facilitate hierarchical transcript naming for sub-agents.
- Updated `persist_subagent_transcript` to generate transcript filenames based on the parent's session key, ensuring a flat file structure that reflects the parent-child relationship.
- Enhanced `AgentBuilder` and `Agent` to support the new session key management, allowing for better organization of session transcripts.
- Adjusted related functions to ensure proper handling of session keys during agent execution and transcript persistence.
These changes improve the clarity and organization of session transcripts, aligning with the ongoing enhancements in agent functionality.
* refactor(tests): update integrations agent tests for tool scope and transcript handling
- Renamed the `integrations_agent_is_wildcard` test to `integrations_agent_tool_scope_honours_toml` to better reflect its purpose of validating tool scope based on TOML configuration.
- Enhanced the test to assert that the `integrations_agent` correctly recognizes named tools instead of a wildcard.
- Removed the `integrations_agent_has_extra_tools_for_export` test as it is no longer relevant to the current tool management strategy.
- Improved the `latest_in_dir` function to clarify the handling of transcript naming schemes, ensuring proper differentiation between legacy and keyed formats.
These changes streamline the testing process and improve the accuracy of tool scope validation, aligning with recent updates in agent functionality.
* refactor(subagent_runner): improve transcript persistence and streamline inner loop
- Removed the `persist_subagent_transcript` function, transitioning transcript persistence to occur per-iteration within the `run_inner_loop`, enhancing reliability by ensuring transcripts are written immediately after each provider response.
- Updated the handling of session keys to maintain consistent naming for transcripts, reflecting the parent-child relationship in the file structure.
- Simplified the code by eliminating redundant post-loop transcript writes, aligning with recent changes in agent functionality and improving overall clarity in transcript management.
* refactor(agent_cli, subagent_runner, session): improve code readability and formatting
- Enhanced formatting in `agent_cli.rs` for better readability by adjusting the structure of string formatting.
- Streamlined conditional checks in `subagent_runner.rs` to improve clarity and maintainability.
- Simplified the handling of agent IDs in `builder.rs` to reduce line length and improve code flow.
- Updated test cases in `tests.rs` for better alignment and readability of expected values.
- Improved formatting in `debug_dump.rs` to enhance the clarity of toolkit action fetching and logging.
These changes collectively enhance the overall readability and maintainability of the codebase, aligning with ongoing refactoring efforts.
* fix(tests): add missing session_key fields to ParentExecutionContext stub
* fix: address PR review feedback
* fix(prompts-v2): round 2 PR review — dispatcher instructions, workspace-file preservation, cached-tool fallback, transcript persistence
- subagent_runner: populate PromptContext.dispatcher_instructions for Dynamic prompts (was empty string, dropping the ## Tool Use Protocol block in render_tools for PFormat/Json/Native sub-agents)
- subagent_runner: add post-tool persist_transcript after tool results are appended so a mid-round crash doesn't lose tool outputs
- prompts::sync_workspace_file: preserve user-edited workspace files — only overwrite when the file doesn't exist OR its current hash matches the stored builtin hash
- context::debug_dump: mirror runner's cached-tool fallback — keep cached action catalogue on empty/error from fetch_toolkit_actions instead of blanking it
- core::agent_cli: add entry/exit debug logs around dump_all / dump_prompt calls and a trace log around each prompt file write; update module banner to note --toolkit is required when --agent is integrations_agent
|
||
|
|
99d61f93a7 |
feat(webui-messaging): multi-provider webview accounts, scanners, and chat runtime (#629)
* feat(accounts): implement accounts management with webview integration - Added a new Accounts page for managing user accounts, including the ability to add and remove accounts. - Introduced AddAccountModal for selecting account providers and initiating account setup. - Implemented WebviewHost to display third-party web applications (e.g., WhatsApp Web) within the app. - Enhanced routing to include a protected route for the Accounts page. - Updated the BottomTabBar to include an Accounts tab for easy navigation. - Integrated Redux for state management of accounts, messages, and logs, ensuring a seamless user experience. - Updated dependencies in Cargo.lock to version 0.52.9 for compatibility. This commit significantly enhances the application's functionality by allowing users to manage accounts directly within the app, improving overall user engagement and experience. * refactor(accounts): clean up Accounts component layout and improve readability - Removed unnecessary comments and simplified the structure of the Accounts component for better clarity. - Adjusted the rendering logic to enhance the layout of the active account section, improving user experience. - Reformatted text in the no accounts message for better readability. - Streamlined the import statements by consolidating related imports, enhancing code organization. * feat(accounts): enhance account management with new providers and routing updates - Introduced support for additional account providers: Telegram, LinkedIn, Gmail, and Slack, expanding user options for account management. - Updated routing to replace the old /conversations path with /chat, streamlining navigation and improving user experience. - Refactored the App component to include an AppShell for better layout management, ensuring the bottom tab bar visibility aligns with the selected account. - Enhanced the BottomTabBar component to reflect the new routing and account options, improving accessibility and usability. - Implemented fullscreen logic for accounts, allowing for a more immersive experience when interacting with selected accounts. - Added utility functions for managing fullscreen states and account provider icons, enhancing code organization and maintainability. This commit significantly improves the application's account management capabilities, providing users with a more flexible and engaging experience. * feat(cef): integrate Chromium Embedded Framework support and enhance webview functionality - Added support for the Chromium Embedded Framework (CEF) as an alternative runtime, allowing for improved webview capabilities. - Updated Cargo.toml to include new dependencies and features for CEF integration, ensuring compatibility with existing Tauri plugins. - Enhanced the WhatsApp recipe to include ghost-text autocomplete functionality, improving user experience during message composition. - Implemented WebSocket observation in the WhatsApp recipe to capture and forward relevant message frames, enhancing real-time interaction. - Introduced user agent spoofing for specific providers to bypass fingerprinting checks, ensuring better compatibility with services like Slack and LinkedIn. - Refactored various components to accommodate the new runtime and improve overall code organization and maintainability. This commit significantly enhances the application's webview capabilities and user interaction with messaging services, providing a more robust and flexible experience. * feat(cef): add development command for CEF and update configuration - Introduced a new development command `dev:cef` in both package.json files to streamline the development process for the Chromium Embedded Framework (CEF). - Updated Cargo.toml to include the `tauri/devtools` feature alongside `tauri/cef`, enhancing debugging capabilities. - Modified tauri.conf.json to adjust visibility settings for the application window and refined the Content Security Policy (CSP) for improved security. - Enhanced resource paths in tauri.conf.json to support recursive file inclusion for better resource management. - Updated the Rust code to bypass macOS Keychain prompts when using CEF, improving user experience during development. This commit enhances the development workflow for CEF integration, providing better tools and configurations for developers. * fix(cef): update development command for CEF to include signing identity - Modified the `dev:cef` command in package.json to include the `APPLE_SIGNING_IDENTITY` environment variable, enhancing the development process for CEF on macOS. - This change improves the build process by ensuring proper code signing during development, streamlining the workflow for developers working with CEF integration. * feat(cef): enhance development command for CEF with safe storage setup - Updated the `dev:cef` command in package.json to include a call to a new script, `setup-chromium-safe-storage.sh`, which pre-seeds the "Chromium Safe Storage" keychain entry with a permissive ACL. - Added the `setup-chromium-safe-storage.sh` script to ensure that CEF/Chromium can read the keychain entry without prompting, improving the development experience on macOS. - This change streamlines the setup process for developers working with CEF integration, ensuring a smoother workflow. * feat(whatsapp): enhance message ingestion and IndexedDB integration - Introduced a new `IngestMessage` interface to standardize message structure for WhatsApp. - Updated `IngestPayload` to include additional fields for better message handling, including `provider`, `chatId`, and `day`. - Implemented a new function `persistWhatsappChatDay` to handle the ingestion of chat messages by day, improving data organization and retrieval. - Enhanced the WhatsApp recipe to utilize IndexedDB for direct data access, eliminating the need for DOM scraping and improving performance. - Updated the Tauri configuration to enable development tools for easier debugging of webview accounts. This commit significantly improves the application's ability to manage and ingest WhatsApp messages, providing a more robust and efficient user experience. * feat(cdp): integrate IndexedDB scanner for WhatsApp via Chrome DevTools Protocol - Added a new module for scanning IndexedDB using the Chrome DevTools Protocol (CDP), enabling direct access to WhatsApp data without DOM scraping. - Implemented a scanner that communicates with the embedded CEF instance to read and decrypt messages stored in IndexedDB. - Updated the Tauri application to manage the new scanner, ensuring it operates seamlessly with existing webview accounts. - Enhanced the Cargo.toml and Cargo.lock files to include necessary dependencies such as `tokio-tungstenite` and `futures-util` for asynchronous operations. - Refactored the WhatsApp recipe to utilize the new scanning capabilities, improving performance and data handling. This commit significantly enhances the application's ability to interact with WhatsApp's IndexedDB, providing a more efficient and robust user experience. * feat(cdp): enhance message diagnostics in IndexedDB scanner - Updated the ScanSnapshot struct to include new fields for message diagnostics: `messageKeyUnion`, `messageTypeBreakdown`, and `sampleByType`, providing a comprehensive overview of message structures and types. - Modified the scanner logic to capture and log detailed information about message types and their shapes, improving debugging capabilities. - Refactored the JavaScript scanner to aggregate message key signatures and counts, enhancing the analysis of message records. This commit significantly improves the application's ability to analyze and log message data from WhatsApp's IndexedDB, facilitating better debugging and data handling. * feat(cdp): implement fast DOM scraping and crypto key extraction for WhatsApp - Introduced a new fast-tick DOM scraping mechanism to extract rendered WhatsApp message bodies, enabling near real-time message updates without relying on IndexedDB. - Added scripts for capturing and logging CryptoKey operations within WhatsApp's workers, allowing for better analysis of key derivations and decryptions. - Enhanced the CDP scanner to interleave fast DOM scans with full IndexedDB scans, optimizing data retrieval and reducing UI spamming during idle periods. - Updated the ScanSnapshot struct to include new fields for DOM-scraped messages and crypto operation statistics, improving the overall diagnostic capabilities of the application. This commit significantly enhances the application's ability to interact with WhatsApp's messaging system, providing a more efficient and responsive user experience. * feat(whatsapp): replace cdp_indexeddb with whatsapp_scanner for enhanced message handling - Replaced the `cdp_indexeddb` module with `whatsapp_scanner` to streamline the scanning process for WhatsApp messages. - Updated the application to manage the new `ScannerRegistry` for WhatsApp, improving the integration with the Chrome DevTools Protocol. - Introduced new scripts for fast DOM scraping and full IndexedDB scanning, optimizing data retrieval and enhancing real-time message updates. - Added a new `dom_scan.js` for efficient extraction of rendered message bodies directly from the DOM, reducing reliance on IndexedDB. - Enhanced the `ScanSnapshot` struct to accommodate new fields for DOM-scraped messages, improving diagnostic capabilities. This commit significantly improves the application's ability to interact with WhatsApp, providing a more efficient and responsive user experience. * refactor(whatsapp): replace JavaScript DOM scanning with Rust-based DOM snapshot - Removed the `dom_scan.js` script and replaced it with a new Rust module `dom_snapshot.rs` that captures DOM snapshots directly via the Chrome DevTools Protocol, enhancing performance and reliability. - Introduced a new `idb.rs` module for scanning WhatsApp's IndexedDB, streamlining data retrieval and improving integration with the Rust backend. - Updated the `ScanSnapshot` struct to accommodate changes in data handling, ensuring compatibility with the new scanning methods. - Enhanced overall message handling capabilities, providing a more efficient and responsive user experience. This commit significantly improves the application's ability to interact with WhatsApp, leveraging Rust for better performance and reducing reliance on JavaScript for DOM operations. * feat(docs): add webview integration playbook for third-party messaging - Introduced a comprehensive playbook detailing the process for integrating third-party webviews (e.g., Instagram, Messenger) into the application. - Documented architecture, workflow, and best practices for building and debugging new integrations, leveraging Rust and Chrome DevTools Protocol. - Included step-by-step instructions for setting up scanners, monitoring logs, and optimizing message handling, ensuring a streamlined development experience for future integrations. This addition enhances the documentation, providing developers with a clear guide to implement and maintain webview integrations effectively. * docs(webview): improve table formatting for clarity - Enhanced the formatting of tables in the webview integration playbook to improve readability and consistency. - Adjusted column headers and alignment for better presentation of job intervals and costs, ensuring clearer communication of scanning processes and common pitfalls. This update aims to provide a more user-friendly documentation experience for developers integrating third-party webviews. * feat(slack): integrate Slack scanner for message extraction and management - Updated the OpenHuman package version to 0.52.15 in both Cargo.lock files. - Introduced a new Slack scanner module to extract messages, users, and channels from Slack's IndexedDB using the Chrome DevTools Protocol. - Added functionality to manage Slack accounts within the application, allowing for automatic opening of Slack webviews based on environment variables. - Enhanced the existing webview account management to support Slack integration, ensuring seamless interaction with the Slack API. This commit significantly improves the application's ability to interact with Slack, providing a robust framework for message handling and account management. * fix(slack): one-doc-per-channel + omit CDP indexName param CEF 146's IndexedDB.requestData rejects `indexName: ""` with "Could not get index"; the CDP spec says empty string means the primary-key index but this backend only accepts the field unset. Omit it entirely so the Slack Redux-persist dump actually comes back. Also switch memory grouping from (channel, day) → channel. Each Slack channel is now one long-running memory doc keyed by channel name (e.g. `general`, `team-product`, `elvin516`), falling back to channel id for non-slug names. Every transcript line carries its own `YYYY-MM-DD HH:MM` stamp and the header records the full date range. `infer_team_id` updated to Slack's real DB naming pattern `objectStore-<TEAM>-<USER>` (not `ReduxPersistIDB:` as initially assumed). * fix(onboarding): update navigation and test descriptions in OnboardingOverlay tests - Changed the navigation path from '/conversations' to '/chat' in the OnboardingOverlay tests to reflect the updated routing logic. - Updated test descriptions for clarity, ensuring they accurately describe the functionality being tested. These changes enhance the accuracy and readability of the onboarding tests, aligning them with the current application flow. * fix(conversations): add return statement to Conversations component - Introduced a return statement in the Conversations component to ensure proper rendering of the sidebar or page variant. - This change enhances the component's functionality by ensuring it returns the expected JSX structure. These modifications improve the overall structure and behavior of the Conversations component. * feat(accounts): add Discord integration and enhance AddAccountModal - Introduced Discord as a new account provider, including its icon and service details. - Updated the AddAccountModal to filter out already connected providers, improving user experience. - Enhanced the UI to display a message when all providers are connected, ensuring clarity for users. - Implemented context menu functionality for account management, allowing users to log out directly from the accounts list. These changes expand the application's capabilities by integrating Discord and refining account management features. * feat(discord): integrate Discord scanner for HTTP and WebSocket monitoring - Added a new `discord_scanner` module to capture Discord API calls and WebSocket frames using the Chrome DevTools Protocol (CDP). - Updated the `lib.rs` to manage the new Discord scanner alongside existing WhatsApp and Slack scanners. - Enhanced the `webview_accounts` module to support Discord account management, including scanner registration and cleanup. These changes expand the application's capabilities by enabling real-time monitoring of Discord interactions, enhancing user experience and functionality. * feat(google-meet): integrate Google Meet as a new account provider - Added Google Meet as a supported account provider, including its icon and service details. - Updated the account management logic to handle Google Meet interactions, including recipe integration for call monitoring and notifications. - Enhanced the UI to accommodate the new provider, ensuring a seamless user experience when managing accounts. These changes expand the application's capabilities by integrating Google Meet, allowing users to join calls and receive notifications directly within the app. * refactor(runtime): remove notification handling and composer autocomplete - Eliminated the notification interception logic and associated functions, streamlining the runtime code. - Removed composer autocomplete features, transferring responsibility for ghost-text overlays to the UI host. - Updated comments to reflect the changes and clarify the remaining functionality. These modifications simplify the runtime script, focusing on core features while delegating UI responsibilities. * feat(google-meet): enhance Google Meet integration with lifecycle event handling - Implemented lifecycle event handling for Google Meet, including events for call start, captions, and call end. - Introduced in-memory storage for caption snapshots during meetings, allowing for the generation of markdown transcripts upon call completion. - Added interfaces for payload structures related to Google Meet events, improving type safety and clarity in the codebase. - Updated the webview account service to manage active meetings and flush transcripts to memory, ensuring a seamless user experience. These changes significantly enhance the Google Meet integration, enabling real-time caption handling and transcript generation, thereby improving the overall functionality of the application. * feat(cef): integrate CEF-based notification handling and update dependencies - Added support for native OS notifications through the `tauri-runtime-cef` crate, enabling interception of browser notifications in embedded webviews. - Introduced a new submodule for `tauri-cef` to manage CEF dependencies and facilitate notification handling. - Updated the `.gitignore` to exclude CEF-related build artifacts and lock files. - Removed the deprecated `notification_scanner` module, streamlining the codebase and focusing on the new CEF integration. - Enhanced the `webview_accounts` module to register and manage CEF browser notifications, improving user experience with real-time alerts. These changes significantly enhance the application's notification capabilities, leveraging CEF for a more integrated and responsive user experience. * feat(cef): update CEF integration and dependency management - Added `cef` and `tauri-runtime-cef` as dependencies to enhance CEF support. - Updated `Cargo.toml` to reference `tauri-runtime-cef` from a local path, ensuring proper integration with the vendored CEF submodule. - Removed direct Git references for Tauri packages, streamlining dependency management by using local paths. These changes improve the application's CEF capabilities and simplify the dependency structure, facilitating better integration and maintenance. * feat(browserscan): add BrowserScan as a new account provider with associated resources - Introduced BrowserScan as a development-only account provider, including its icon and service details. - Updated the account provider types and management logic to accommodate BrowserScan, enhancing the application's capabilities. - Added a new recipe and manifest for BrowserScan, ensuring it integrates seamlessly into the existing webview account lifecycle. - Enhanced the UI to display BrowserScan, providing users with a bot-detection sandbox for testing purposes. These changes expand the application's functionality by integrating BrowserScan, allowing for improved testing and development workflows. * feat(google-meet): enhance Google Meet integration with new transcript handling and session recovery - Introduced a new service to handle Google Meet transcripts, enabling structured note extraction and proactive follow-up actions. - Implemented session recovery logic to manage in-progress meetings when navigating away from the call. - Updated the webview account service to log call events and captions, improving monitoring and debugging capabilities. - Enhanced the Google Meet recipe to persist meeting state across navigations, ensuring seamless user experience. These changes significantly improve the Google Meet integration, allowing for better management of meeting transcripts and user interactions. * refactor(App): reorganize imports and clean up code structure - Removed unused imports from App.tsx to streamline the code. - Adjusted the import order for better readability and consistency. - Enhanced the BottomTabBar component by simplifying the button rendering logic. - Cleaned up the AddAccountModal component by consolidating prop destructuring. - Improved formatting in various components for better code clarity. These changes enhance code maintainability and readability across the application. * update tauri * feat(google-meet): improve caption handling and speaker identification logic - Enhanced the logic for extracting speaker names from Google Meet rows, adding checks to filter out icon ligatures and irrelevant text. - Updated the caption processing to better identify and score caption regions, ensuring more accurate transcript generation. - Introduced new utility functions to differentiate between real captions and icon names, improving the overall reliability of the captioning feature. These changes significantly enhance the accuracy and usability of the Google Meet integration, providing users with clearer and more relevant caption data. * chore(dependencies): update Cargo.lock with new package versions and remove obsolete entries - Bump OpenHuman version to 0.52.20. - Add new dependencies: cef, futures-util, tauri-plugin-notification, tauri-runtime-cef, tokio-tungstenite, bzip2, clap, console, cookie_store, data-encoding, dioxus-debug-cell, document-features, download-cef, encode_unicode, filetime. - Remove obsolete packages: alloc-no-stdlib, alloc-stdlib, brotli, brotli-decompressor, gdkx11, gdkx11-sys. - Update existing dependencies to their latest versions where applicable. * chore(dependencies): update submodule URLs and pin plugin versions - Changed the tauri-cef submodule URL from SSH to HTTPS for consistency. - Updated Cargo.toml to pin tauri plugins to a specific commit for reproducibility. - Adjusted Cargo.lock to reflect the new plugin source format with pinned revisions. - Modified the builder configuration in lib.rs to conditionally enable devtools in debug builds only, enhancing security in release builds. - Updated webview_accounts to restrict devtools access based on build type, ensuring better control over webview inspection. * feat(ui): enhance BottomTabBar and AddAccountModal interactions - Added focus and blur event handlers to BottomTabBar for improved visibility management. - Implemented keyboard accessibility in AddAccountModal by closing the modal on Escape key press and focusing the close button when opened. - Updated Content Security Policy in tauri.conf.json for enhanced security. - Improved Gmail recipe to use stable message IDs for better message tracking. - Introduced account ID sanitization in webview_accounts to prevent path traversal vulnerabilities. * fix(AddAccountModal): add missing import for improved functionality * chore(dependencies): bump OpenHuman version to 0.52.20 in Cargo.lock |
||
|
|
8d4934e634 |
feat(agent): progressive-disclosure handoff + token-based summarizer threshold (#574) (#586)
* feat(agent): summarizer sub-agent compresses oversized tool results Issue #574. Before this change, tool results larger than a few KB landed verbatim in orchestrator history, burning context budget on raw JSON/HTML/file dumps. The only guardrail was tool_result_budget_bytes which hard-truncated mid-payload, dropping everything past the cut. This PR introduces a dedicated `summarizer` sub-agent (model.hint = "summarization") that the runtime automatically dispatches whenever a tool result exceeds summarizer_payload_threshold_bytes (default 100 KB). The summarizer compresses the payload per an extraction contract that preserves identifiers and key facts, and the compressed summary replaces the raw payload before it enters agent history. Payloads above summarizer_max_payload_bytes (default 5 MB) skip summarization and fall through to the existing truncation path — paying for an LLM call on a 5 MB blob is counterproductive. Scoped to the orchestrator session only. Welcome, skills_agent, researcher, planner, and every other typed sub-agent get None and their tool results are untouched. Gated in build_session_agent_inner by checking agent_id == "orchestrator". Instrumented at both tool-loop paths: - run_tool_call_loop in tool_loop.rs (event-bus/channels path) - Agent::execute_tool_call in session/turn.rs (web channel path via run_single) Both paths call into the same `PayloadSummarizer::maybe_summarize` trait so the threshold check, circuit breaker (3 consecutive failures disables for the session), and sub-agent dispatch policy live in exactly one place (agent/harness/payload_summarizer.rs). The summarizer sub-agent is runtime-dispatched only — it is NOT exposed as a delegation tool to the orchestrator's LLM. It is listed in the orchestrator's `subagents = [...]` for explicit registration, but `collect_orchestrator_tools` filters out the `summarizer` id and never synthesises a `delegate_summarizer` tool. Files: * NEW: src/openhuman/agent/agents/summarizer/{agent.toml,prompt.md} * NEW: src/openhuman/agent/harness/payload_summarizer.rs (trait + SubagentPayloadSummarizer impl + circuit breaker + tests) * src/openhuman/agent/agents/mod.rs — register summarizer in BUILTINS * src/openhuman/agent/agents/orchestrator/agent.toml — list summarizer in subagents (runtime-only, no LLM delegation tool) * src/openhuman/agent/harness/mod.rs — declare module * src/openhuman/agent/harness/builtin_definitions.rs — expect summarizer in `expected_builtin_ids_are_present` * src/openhuman/agent/harness/tool_loop.rs — thread Option<&dyn PayloadSummarizer> into run_tool_call_loop + agent_turn, intercept at the tool-execution success site, plus a new integration test using a MockSummarizer * src/openhuman/agent/harness/tests.rs — thread None through the existing run_tool_call_loop callsites * src/openhuman/agent/harness/session/turn.rs — same interception in Agent::execute_tool_call * src/openhuman/agent/harness/session/types.rs — payload_summarizer field on Agent and AgentBuilder * src/openhuman/agent/harness/session/builder.rs — .payload_summarizer() setter + orchestrator-only construction in build_session_agent_inner * src/openhuman/agent/bus.rs — pass None for the bus path * src/openhuman/config/schema/context.rs — summarizer_payload_threshold_bytes + summarizer_max_payload_bytes on ContextConfig * src/openhuman/tools/orchestrator_tools.rs — filter out the summarizer id from delegation-tool synthesis Tests: unit tests in payload_summarizer pin the pass-through rules (below threshold, above max cap, breaker tripped) and the prompt construction. Integration test in tool_loop::tests uses a MockSummarizer to verify the interception wires through end-to-end. Closes tinyhumansai/openhuman#574. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(tools): csv_export tool + skills_agent oversized output handling When a Composio tool returns a large payload inside skills_agent, the agent now has two prompt-driven paths: Path A — user wants an answer derived from the data: skills_agent extracts the answer in its next iteration and returns a targeted response (no file I/O needed). Path B — user wants the actual raw dataset: skills_agent calls csv_export (tabular data) or file_write (non-tabular) to persist the output to workspace/exports/, then returns a summary + file path. Changes: * NEW: src/openhuman/tools/impl/filesystem/csv_export.rs — CsvExportTool: parses JSON array, formats as CSV, writes to workspace/exports/{filename}. Handles missing keys (empty cells), nested values (JSON-serialised), and optional column ordering. Sandboxed via SecurityPolicy. * src/openhuman/tools/impl/filesystem/mod.rs — wire module * src/openhuman/tools/ops.rs — register CsvExportTool * src/openhuman/agent/harness/definition.rs — new extra_tools field on AgentDefinition, allowing named system tools to bypass category_filter * src/openhuman/agent/harness/subagent_runner.rs — inject extra_tools into allowed_indices after category filtering * src/openhuman/agent/agents/skills_agent/agent.toml — add file_write + csv_export via extra_tools * src/openhuman/agent/agents/skills_agent/prompt.md — new "Handling Oversized Tool Results" section with Path A (extract answer) vs Path B (export file) decision tree, intent-detection heuristics, and examples Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(agent): progressive-disclosure handoff for skills_agent + token-based summarizer threshold (#574) Two layered fixes for #574 plus supporting changes. ## Summarizer thresholds in tokens, not bytes Renamed `ContextConfig::summarizer_payload_threshold_bytes` -> `summarizer_payload_threshold_tokens` (default 500 000, was 100 KB in bytes) and `summarizer_max_payload_bytes` -> `summarizer_max_payload_tokens` (default 2 000 000). Token count is estimated at ~4 chars/token via a local helper that mirrors `tree_summarizer::types::estimate_tokens`. Serde aliases on both fields keep existing config.toml files parsing. `payload_summarizer.rs` now compares token estimates for the threshold and cap, with both `tokens=` and `bytes=` surfaced in log events. ## Progressive-disclosure handoff for skills_agent `skills_agent` typed subagents (when spawned with a Composio toolkit) now receive a per-spawn `ResultHandoffCache` and a new built-in `extract_from_result` tool. When a per-action tool returns more than `HANDOFF_OVERSIZE_THRESHOLD_TOKENS` (20 000 tokens), the raw payload is stashed in the cache and a compact placeholder replaces it in history: [oversized tool output: 187432 bytes - stashed as result_id="res_1"] Preview (first 1500 chars): ... If the preview does not answer your task, call: extract_from_result(result_id="res_1", query="<specific question>") The subagent can answer from the preview, call `extract_from_result` with a targeted query, or re-call the original tool with tighter filters. `extract_from_result` dispatches the `summarizer` subagent against the cached payload with the query as the extraction contract. For payloads over `SUMMARIZER_CHUNK_CHAR_BUDGET` (60 000 chars) the extractor runs a chunked map-reduce: - split at blank-line / newline boundaries - map each chunk to a per-chunk partial via bounded concurrency (`buffer_unordered(3)`) to avoid storming the provider gateway - reduce partials in one more summarizer turn, or fall back to the concatenation if the reduce stage fails Falls back gracefully when the summarizer definition is missing from the registry (placeholder + preview still work; just no extractor). ## Text-mode dispatcher for skills_agent + tighter tool filter Provider-side grammar decoders (Fireworks etc.) cap tool-schema rules at 65 535 (uint16_t). Large Composio toolkits - Gmail, Notion, GitHub, Salesforce, HubSpot, Google Workspace - ship per-action JSON schemas dense enough that even a handful of them exceed the cap. - `subagent_runner::run_inner_loop` now detects `skills_agent` and omits `tools: [...]` from the API request, instead appending an `<tool_call>{...}</tool_call>` XML protocol block (with compact per-tool parameter summaries) into the system prompt. Tool calls are parsed out of the model's free-form response via the shared `parse_tool_calls` helper. Mirrors XmlToolDispatcher behaviour. - `top_k_for_toolkit()` picks 12 for HEAVY_SCHEMA_TOOLKITS (the six listed above plus googledocs, googlesheets, microsoftteams) vs the default 25 for lighter toolkits. ## Skills_agent agent.toml / prompt changes - Dropped `csv_export` from `skills_agent.extra_tools` (kept `file_write`) - the export tool was triggering superfluous file writes after extraction had already answered the query. - `builtin_definitions::skills_agent_has_extra_tools_for_export` test inverted to assert `csv_export` is NOT present. - `prompt.md` re-aligned: Path B now references only `file_write`. ## Wiring - `session/builder.rs`: threshold rename wiring (`_tokens`). - `subagent_runner.rs::run_inner_loop`: new `handoff_cache` parameter (threaded through both call sites; fork-mode passes `None`). ## Tests All green: - `payload_summarizer::tests`: 6/6 (thresholds in tokens) - `tool_loop::tests`: 10/10 (MockSummarizer integration) - `subagent_runner::tests`: 19/19 - `builtin_definitions::tests`: 5/5 (csv_export removal) - `csv_export::tests`: 7/7 (implementation kept, wiring removed) Closes #574. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * perf(agent): drop reduce LLM call and pre-clean tool outputs in chunked extraction Two optimisations to the oversize-handoff / extract_from_result pipeline: 1. Concat chunk summaries in order; drop reduce stage. The reduce-stage summarizer call was the slowest single turn of the pipeline and a single point of failure when the upstream provider hung — a hung reduce burned minutes before timing out. Map summaries are now sorted by original chunk index and concatenated with a plain-separator join. For listing/extraction queries this is equivalent; for top-N / global-ordering queries the caller can post-process. Observed: 8m24s → ~70s on a Notion SEARCH run. 2. Generic cleaner before the oversize check. Strips <script>/<style>/<svg> blocks, HTML comments, data:...;base64,... inline URIs, remaining HTML tags, and collapses whitespace. Applied on every tool output so results that are mostly markup drop below the 20k-token threshold and skip the extract pipeline entirely; the ones that remain oversized get chunked on clean bytes. Debug log emits before/after bytes + saved_pct per call. No changes to the extract_from_result tool surface or placeholder format. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(chat): rearm 2-min silence timer on inference progress events The client-side safety timer in Conversations.tsx was a flat 120s deadline from the send, not a silence window. Long agent turns (chained tool calls, chunked extraction fan-outs, subagent spawns) would trip the timeout even though the backend was actively making progress — showing "No response from the assistant after 2 minutes" while the server was still working. The effect now watches inferenceStatusByThread and rearms the timer on every status change for the sending thread. Any tool_call / tool_result / iteration_start / subagent_{spawned,done} event resets the 120s window. When status is cleared (chat_done / chat_error), the timer is dropped. A truly silent server still fails after 120s as before. Tracks the sending thread id in a ref (sendingThreadIdRef) so switching threads mid-turn doesn't move the timer's reference point. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
2d9f2f7aaa | chore(release): v0.52.20 v0.52.20 | ||
|
|
c7487324cc |
feat(channels): dynamic filler messages during long agent turns (#600) (#636)
* refactor(channels): add extract_message_id helper for varied response shapes
Backend send_channel_message responses use at least three shapes:
{"id":"..."}, {"data":{"id":"..."}}, and {"messageId":1456,"success":true}.
The last one returns the id as a JSON number, so the prior inline
as_str()-only extraction silently dropped it. Consolidate the extraction
into a single helper that handles str/i64/u64 candidates and routes both
streaming-edit and thinking-message send paths through it. Fixes the
silent id loss that left thinking bubbles undeletable (#600).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(channels): latch thinking edits off when first POST yields no id
When the initial thinking POST returned 200 but carried no message id
(either because the response shape was unexpected or the send itself
failed before C1), every subsequent thinking_dirty tick re-entered the
"send new message" branch. The user then saw one standalone italic
bubble per accumulated snippet instead of a single evolving one. Add a
thinking_edit_disabled latch that is set in both failure paths and
guard the edit_timer branch on it so we post at most one thinking
bubble per turn when the id is unrecoverable (#600).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* style(channels): label thinking bubble with explicit "Thinking:" header
A bare italicized snippet under a 💭 emoji reads ambiguously in chat —
it could be a user quote, a system note, or assistant output. Prefix
the italic body with an explicit "Thinking:" line so the ephemeral
bubble is unmistakably the LLM's reasoning stream and visually distinct
from both filler messages and the final reply (#600).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(channels): reply-first finalize with orphan draft recovery
Two problems in the old finalize path. (1) The thinking bubble was
deleted before the reply was sent, leaving the chat momentarily empty
between the two round-trips. (2) When the final edit failed, the half-
streamed draft was left in place and the user never received the
canonical response — a silent data-loss hole during edit-endpoint
flakiness. Wrap the three delivery paths in a 'send: labeled block so
they share a single cleanup tail, delete the orphan draft and send a
fresh atomic reply on edit failure, and move the thinking-bubble
deletion to after the reply is on screen so the chat never blinks
empty (#600).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(channels): ephemeral filler messages every 13s with dynamic snippets
Long agent turns (30–90 s) leave the chat static once the thinking
stream goes quiet and progressive edits stop, which reads as a frozen
bot. Add a third timer branch in the inbound loop that posts a short
"still working" message every FILLER_INTERVAL (13 s, tuned to stay
inside Telegram's ~1 msg/sec chat cap with headroom).
Each filler prefers a tail slice of the live thinking_accumulator
(last MAX_FILLER_CHARS = 200 Unicode scalars, trimmed at a word
boundary so it reads cleanly) so the user sees the agent's actual
reasoning instead of canned text. When the accumulator hasn't advanced
since the last filler we fall through to a rotating STATIC_FILLERS
pool ("💭 Still working on it…", etc.) so the chat still moves. All
filler ids are tracked in StreamingState.filler_message_ids and
deleted in finalize_channel_reply alongside the thinking bubble, so
the user ends each turn seeing only the canonical reply. A
filler_disabled latch stops hammering endpoints that reject filler
sends twice in a row.
Verified end-to-end on Telegram with both long (74 s, 5 fillers) and
short (32 s, 2 fillers) turns — all ephemeral messages cleaned up
cleanly after the final reply landed (#600).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
|
||
|
|
da5fe9260b |
fix(local_ai): hard-override to disabled until explicit opt-in (#573) (#637)
* refactor(local_ai): default to opt-in on all devices (#573) Local AI now defaults to disabled whenever the user has not explicitly picked a tier, regardless of device RAM. The onboarding flow and Settings panel remain the only ways to turn it on. Previously the bootstrap only disabled local AI on <8 GB devices and auto-applied a recommended preset on larger hosts; this flip completes the MVP goal of cloud-first defaults with a single, opt-in local model. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * style(local_ai): apply cargo fmt to bootstrap tests (#573) Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(onboarding): present cloud AI as default on sufficient-RAM path (#573) Flips the LocalAIStep sufficient-RAM screen so the primary button is "Continue with Cloud" and local AI appears as an explicit opt-in ("Use local AI instead"). This aligns onboarding with the new opt-in bootstrap: every device now starts on cloud unless the user chooses local AI. The low-RAM cloud-fallback screen is unchanged. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(onboarding): cover opt-in local AI semantics in LocalAIStep (#573) Updates the sufficient-RAM path tests to match the cloud-primary UI: the default "Continue with Cloud" click advances without triggering local AI bootstrap, and the secondary "Use local AI instead" opt-in still starts the recommended-preset bootstrap and propagates errors. Low-RAM cloud-fallback tests are unchanged. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(local_ai): add opt_in_confirmed marker to local AI config (#573) Bootstrap will hard-override `enabled=false` unless this marker is true, ensuring existing installs with a stale `selected_tier` from the pre-MVP default-on era fall back to cloud until the user explicitly re-opts in. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(local_ai): hard-override local AI to disabled until explicit opt-in (#573) Every bootstrap path now returns `enabled=false` unless `opt_in_confirmed` is true, regardless of device RAM or `selected_tier`. This closes the regression where upgrading users with a persisted `selected_tier` bypassed the onboarding opt-in and started local AI without consent. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(local_ai): set opt_in_confirmed on apply_preset and surface MVP tier only (#573) `apply_preset` is the single source of truth for the opt-in marker: any non-disabled tier flips it true, `disabled` clears it. The preset RPC now returns `mvp_presets()` so the Settings UI exposes only the allowlisted `ram_2_4gb` tier, matching the MVP scope already enforced on the onboarding path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * revert(local_ai): keep full preset catalog in presets RPC (#573) Revert the `mvp_presets()` swap in `handle_local_ai_presets`. PR #588 already renders all 5 tier cards in Settings with non-MVP tiers shown as "Coming soon" / non-selectable, and that roadmap visibility is the intended UX. Returning only the MVP tier from the RPC hid the other 4 cards entirely and broke that signal. The opt-in gate still holds: `apply_preset` remains the single writer of `opt_in_confirmed`, the RPC guard continues to reject non-MVP apply_preset calls, and the bootstrap hard-override still clamps stale configs. This commit only rolls back the UI catalog surface. Fixes failing `json_rpc_local_ai_device_profile_and_presets` integration test which expects 5 presets. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> |
||
|
|
156944478d |
feat(cache): wire-level prompt/response dumps + JSONL into session_raw/ (#640)
* feat(transcript): enhance session transcript persistence with per-turn usage tracking
- Updated the `write_transcript` function to accept an optional `last_assistant_turn_usage` parameter, allowing for the inclusion of per-message token and cost figures in the JSONL output.
- Modified the `persist_session_transcript` method to capture and pass the last turn's usage data to the transcript writer, ensuring accurate tracking of resource usage.
- Improved documentation to clarify the new functionality and its impact on transcript persistence.
This change enhances the fidelity of session transcripts by associating usage metrics with the last assistant message, improving overall transparency in resource consumption.
* refactor(transcript): improve transcript reading logic by routing based on file extension
- Renamed `read_transcript` function to clarify its purpose and updated its logic to first check the file extension.
- Added handling for legacy `.md` files, ensuring they are processed with the appropriate parser.
- Enhanced fallback mechanism to check for the existence of a `.md` sibling file if the primary JSONL file is not found.
This change improves the robustness of transcript reading by accommodating legacy formats while maintaining compatibility with new JSONL files.
* feat(transcript): mirror final assistant reply in session transcript
- Added functionality to capture the final assistant reply in the transcript snapshot, ensuring that both the prompt and response are persisted in the JSONL output.
- This enhancement improves the completeness of session transcripts by including the assistant's final message alongside the user prompts.
This change enhances the fidelity of session transcripts, providing a more comprehensive record of interactions.
* feat(cache): wire-level prompt/response dumps + split JSONL into session_raw/
Two related changes for KV-cache debugging and on-disk clarity:
1. Wire-level dump (`providers/compatible.rs`)
When OPENHUMAN_PROMPT_DUMP_DIR is set, every chat completion writes
the outgoing NativeChatRequest body and the aggregated ApiChatResponse
to paired timestamped JSON files. Covers both the non-streaming and
SSE streaming paths. Unset → zero overhead, no behavior change.
Why: the prompt-level transcript captures what the dispatcher
assembled, but the actual wire bytes (including
prompt_tokens_details.cached_tokens and the openhuman meta block)
only surface at the HTTP layer. Pairing request + response per turn
lets us diff consecutive turns to confirm cache-hit accounting and
diagnose cache-miss causes.
2. JSONL source-of-truth moves to session_raw/ (`agent/harness/session/transcript.rs`)
JSONL transcript files now live under workspace/session_raw/DDMMYYYY/
instead of workspace/sessions/. The human-readable .md companion
stays in workspace/sessions/DDMMYYYY/ so the structured source-of-
truth and the readable debug view are cleanly separated on disk.
- resolve_new_transcript_path returns session_raw/ paths and
advances the index past both session_raw/*.jsonl and legacy
sessions/*.md so indices stay unique across the migration.
- find_latest_transcript prefers session_raw/ and falls back to the
legacy sessions/ dir for pre-migration .md files (one-release compat).
- md_companion_path derives the sessions/ md path from the
session_raw/ jsonl path via path-component rewrite, with a
sibling-file fallback for tests that use flat tempdirs.
* fix(cache,transcript): address PR review findings
- transcript: .md companion write is now best-effort — failures are
logged with log::warn! and Ok(()) is returned. The JSONL above is
the source of truth; a readable-log hiccup must not take down state
persistence.
- compatible: replace peek_dump_seq() (non-atomic) with
reserve_dump_seq() that fetch_adds PROMPT_DUMP_SEQ in one step and
returns the reserved value. dump_prompt_if_enabled now takes seq as
a parameter, so request/response files cannot be misaligned under
concurrent requests.
- turn: explicitly clear last_turn_usage when resp.usage is None so
the final assistant message can't inherit a prior iteration's stale
numbers during a tool-using turn.
- transcript (nit): last-assistant lookup uses rposition; the emit
loop pattern-matches (Option, Option) together so there's no
separate unwrap.
- transcript (nit): JSONL meta parsing is positional — first non-empty
line must be _meta or we error out. Replaces the substring-based
heuristic that could false-positive on message content.
- compatible (nit): lower prompt/response dump success logs from info
to debug — they fire on every turn when the env var is set.
|
||
|
|
c4ef14383d |
fix(ci): unblock release-packages workflow YAML parse (#639)
The `actions/github-script` block for the backlog-issue step used a JS template literal whose markdown body lines sat at column 1, outside the `script: |` literal block. YAML treated those lines as new mapping keys and rejected the whole file — every run of release-packages.yml failed at load time with zero jobs executed, so the brew tap, apt repo, npm publish, linux-arm64 CLI, and smoke tests never ran for recent releases. - Rewrite the issue body as a string array joined with `\n`, so every line lives inside the block scalar at the correct indentation. - Fix stray backslash-escapes around the final `core.info(...)` template literal that were JS-invalid even before YAML choked on the body. Validated locally with PyYAML; file now parses cleanly. |
||
|
|
5082f3e741 |
feat(overlay): activate main window on orb click (#605) (#611)
* feat(tauri): add activate_main_window command for overlay (#605) Exposes the existing show_main_window helper as a Tauri command so the overlay webview can bring the main window to front. The command is whitelisted in allow-core-process.toml so the overlay window capability can invoke it. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(overlay): activate main window on orb click (#605) The overlay orb had no click behavior. Now clicking it in idle mode invokes activate_main_window, bringing the main app window to the front (mirrors the tray icon flow). Since the overlay is an NSPanel NonactivatingPanel on macOS, React's synthesized onClick does not fire. Instead we record the press position on mousedown and emulate click on mouseup when the pointer stayed within a 4px slop. Dragging is deferred to mousemove past the slop so startDragging doesn't swallow the mouseup event. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(window): propagate show_main_window errors instead of swallowing them (#605) `show_main_window` silently logged failures and returned `()`, so the `activate_main_window` Tauri command could report success on a no-op. Thread `Result<(), String>` through so JS `invoke().catch()` sees real failures, and preserve the previous log-on-error behavior at the tray/Reopen call sites where no caller consumes the result. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(overlay): stabilize orb click vs drag vs double-click (#605) Two follow-ups to the deferred-drag pattern: 1. Drop stale pressRef when the primary button is no longer held during mousemove. Window-drag / focus changes can steal the mouseup, leaving the ref populated so the next idle hover would start a spurious drag. 2. Debounce the synthetic click by 250 ms so a follow-up dblclick can cancel it — the double-click-to-reset gesture was firing activate + reset together. Clear the timer on dblclick and on unmount. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
0c04314004 | Refactor: rust modules (#633) | ||
|
|
43d44acc1a | fix: wire proactive welcome into conversations (#635) | ||
|
|
6733720df9 |
fix(channels): delete thinking messages after final response (#600) (#612)
* feat(channels): add send_channel_delete to REST client (#600) Add DELETE method to BackendOAuthClient for removing channel messages. Used to clean up ephemeral thinking indicators after final response delivery. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(channels): show thinking ephemerally and delete on final response (#600) Thinking deltas are accumulated and sent as a temporary "💭" message on the channel. When the final agent response is ready the thinking message is deleted via the new DELETE endpoint so the user only sees the clean reply. This replaces the previous behaviour where thinking messages persisted permanently in the Telegram chat. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style(channels): apply cargo fmt to bus.rs (#600) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
583a4d689c | chore(release): v0.52.19 v0.52.19 | ||
|
|
8ab2c6b540 |
fix(overlay): restore status bubble visibility during voice dictation (#604) (#614)
Reverts to CSS-transition-based visibility so the bubble wrapper
stays mounted in the DOM. The prior conditional mount (`status === 'active' && bubble`)
raced with the async Tauri window resize — the bubble component mounted
before the overlay webview had grown from 50x50 to 224x208, and
`overflow: hidden` on the webview clipped the bubble above the visible
area.
With the wrapper always mounted and toggled via `max-w-0 opacity-0` ↔
`max-w-[184px] opacity-100`, the typewriter status text ("Listening…",
"Transcribing…") reappears reliably when the hotkey is held.
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
|
||
|
|
f098cfda40 |
test(coverage): batches 13–18 — Rust unit tests for 40+ modules (#530) (#618)
* test(coverage): batch 13–14 — core/all registry, proxy_config tool (#530) Add 36 new tests: - core/all: registry integrity (no duplicates, schema-controller parity), rpc_method_name, namespace_description, validate_params, schema lookup - proxy_config: parse_scope, parse_string_list (CSV, array, errors), parse_optional_string_update, env_snapshot, proxy_json, security gates All 4096 tests pass. * test(coverage): batch 15 — memory/store/unified/helpers pure functions (#530) Add 31 new tests for helpers module: - vec_to_bytes/bytes_to_vec roundtrip, cosine_similarity (identical, orthogonal, mismatched, zero), collapse_whitespace, normalize_search_text, tokenize_search_terms, normalize_graph_entity/predicate, json_string_array, merge_unique_string_arrays, json_i64 (int/float/missing/string), recency_score (current/old/future), chunk_document_content All 4127 tests pass. * test(coverage): batch 16 — terminal, supervision, security detect, trigger history (#530) Add 27 new tests across 4 modules: - accessibility/terminal: is_text_role, is_terminal_app, looks_like_terminal_buffer, extract_terminal_input_context, noise line detection - channels/runtime/supervision: compute_max_in_flight_messages clamping - security/detect: all sandbox backend fallback paths (landlock, firejail, bubblewrap, docker on non-linux), disabled-via-enabled-false - composio/trigger_history: list_recent with limit, empty store, field validation All 4154 tests pass. * test(coverage): batch 17 — learning, update, encryption, doctor, service schemas + skills/types (#530) Add 49 new tests across 6 modules: - learning/schemas: catalog, schema validation, unknown fallback - update/schemas: check/apply schemas, optional staging_dir, controller parity - encryption/schemas: encrypt/decrypt schemas, read_required helper - doctor/schemas: report/models schemas, read_optional helper (none/null/value/error) - service/schemas: 8 lifecycle functions, restart optional params, daemon_host - skills/types: ToolResult success/error/json/mixed, serde roundtrip, ToolContent All 4203 tests pass. * test(coverage): batch 18 — accessibility/keys key-state probes (#530) Add tests for is_tab_key_down/is_escape_key_down (platform-safe), macOS-specific constant validation. All 4216 tests pass. * test(coverage): batch 19 — service/restart, memory/store/factories (#530) Add 7 new tests: - service/restart: default source/reason, whitespace trimming, empty-string defaults, RestartStatus serde, startup delay noop - memory/store/factories: effective_memory_backend_name, migration-disabled error All 4223 tests pass. * test(coverage): batch 20 — tree_summarizer schemas, subconscious schemas (#530) Add 38 new tests across 2 modules: - tree_summarizer/schemas: catalog parity, all 5 functions, param helpers (read_required, read_optional, read_optional_timestamp), type_name, namespace_input - subconscious/schemas: catalog parity, all 10 functions, required input validation, field/field_req/field_opt helpers All 4261 tests pass. --------- Co-authored-by: Steven Enamakel <31011319+senamakel@users.noreply.github.com> |
||
|
|
ec309c8f90 |
feat(onboarding): complete conversational onboarding stack and UX audit (#619)
* fix(onboarding): guard complete_onboarding against premature flag flip (#591) - Remove premature `chat_onboarding_completed = true` flip from `set_onboarding_completed` in config/ops.rs. The flag is now exclusively owned by the welcome agent via `complete_onboarding`. - Strip auto-finalize side-effect from `check_status` action. It is now pure read-only and returns `onboarding_status`, `exchange_count`, and `ready_to_complete` in the snapshot instead of `finalize_action`. - Add engagement guard to `complete` action: rejects with a descriptive error unless exchange_count >= 3 OR ≥1 Composio integration connected. Auth check also enforced before any write. - Add process-global `WELCOME_EXCHANGE_COUNT` (AtomicU32) with `increment_welcome_exchange_count()` / `get_welcome_exchange_count()`. Dispatch layer calls `increment_welcome_exchange_count()` each time a user message routes to the welcome agent. - Update `welcome_proactive.rs` snapshot call to new signature and prompt copy to reflect `onboarding_status: "pending"` / no pre-flip. - Add 7 pure-logic unit tests for `engagement_criteria_met`, plus tests for the new exchange counter and updated snapshot shape. Fixes #591 * style: cargo fmt for complete_onboarding.rs * feat(onboarding): inject CONNECTION_STATE block into welcome-agent turns (#593) Add `build_connection_state_block()` to dispatch.rs: fetches current Composio integration status (with a 3s timeout for graceful degradation) and formats it as a `[CONNECTION_STATE]...[/CONNECTION_STATE]` block. After `resolve_target_agent` selects the welcome agent, the block is appended to the last user message in history so the agent always has up-to-date connection state without spending a tool call. This captures OAuth completions that happened mid-conversation (user clicked auth link in chat, authenticated in browser, came back). Scoped strictly to welcome-agent turns (chat_onboarding_completed=false). Orchestrator turns are unaffected. Fixes #593 Part of #599 * style: cargo fmt for dispatch.rs * feat(welcome): parallel template messages with LLM inference for faster perceived welcome (#592) Show two template messages immediately while the LLM runs in the background, cutting the perceived wait from ~15s to ~0s: - Template 1 (t≈0ms): time-of-day greeting that names any connected channels, built from the status snapshot without extra I/O - Template 2 (t=4s): "Getting everything ready for you..." loading indicator, published via tokio::join! alongside the LLM future - LLM response: published when inference completes, opened directly with personalised setup content (no duplicate greeting) `run_proactive_welcome` now fires three `ProactiveMessageRequested` events rather than one. The two template helpers (`time_of_day_greeting`, `build_template_greeting`) are pure functions covered by 6 new unit tests. `prompt.md` gains a proactive-invocation section explaining that greeting templates are pre-delivered and the agent must skip them. * feat(welcome): add composio_authorize tool and inline auth link guidance (#594) Wire `composio_authorize` into the welcome agent's tool allowlist and teach the prompt how to offer OAuth links directly in chat: - agent.toml: add "composio_authorize" to the named tools list so the welcome agent can call it during multi-turn conversations - prompt.md: new "Offering inline auth links" section covering the consent-first flow (offer → user agrees → call tool → markdown link → confirm success via [CONNECTION_STATE] block on next turn) - prompt.md: toolkit slug reference table for the common services - prompt.md: auth link rules (no speculative calls, no bare URLs, one service at a time, await CONNECTION_STATE before confirming) - prompt.md: two new "What NOT to do" bullets for composio_authorize misuse patterns * feat(welcome): conversational onboarding prompt for issue #595 - Rewrite prompt.md: multi-turn flow, Gmail-first, no silent first turn - Align with check_status/complete and ready_to_complete semantics - Update proactive injection copy to match new tool wording Made-with: Cursor * feat(onboarding): add completion readiness reason Made-with: Cursor * docs(ux): add onboarding and welcome audit for #563 Made-with: Cursor * docs(welcome): clarify OAuth link behavior in onboarding prompt Updated the onboarding prompt to explicitly state that clicking the Gmail connection link opens the user's default browser for authentication. Added guidance to return to the chat after completing the authorization process. * fix(onboarding): resolve CI test and proactive greeting review Made-with: Cursor |
||
|
|
dced586a18 | chore(release): v0.52.18 v0.52.18 | ||
|
|
7db71408bd |
feat(local_ai): default to cloud fallback on <8GB RAM devices (#589)
* Enhance draft message handling in streaming edits
- Introduced a new `draft_sent` field in the `StreamingState` struct to track when a draft message has been posted, decoupling the existence of a draft from the ability to edit it.
- Updated the `flush_streaming_edit` function to set `draft_sent` upon posting a draft, ensuring that duplicate messages are not sent if the backend fails to return an ID.
- Modified the `finalize_channel_reply` function to prevent sending a fresh message if a draft was already posted without an ID, improving user experience by avoiding duplicate bubbles.
These changes enhance the robustness of message handling during streaming edits, ensuring a smoother interaction for users.
* feat(onboarding): enhance LocalAIStep for low-RAM device handling
- Added logic to determine if the device is below the RAM threshold, defaulting to a cloud AI fallback if necessary.
- Introduced a new UI for low-RAM devices, informing users about the cloud mode and providing options to continue with cloud AI or force-enable local AI.
- Updated the `ensureRecommendedLocalAiPresetIfNeeded` function to return a `recommend_disabled` flag based on device RAM.
- Enhanced tests to cover new cloud fallback UI and local AI consent handling.
These changes improve the onboarding experience by providing clearer options based on device capabilities.
* style: apply prettier formatting to LocalAIStep
* feat(local_ai): unlock model selection + add Disabled/cloud fallback option
- Remove MVP ceiling that clamped selection to the 2-4 GB tier, in bootstrap
and in the apply_preset RPC — users can now pick any tier.
- Add special "disabled" tier string to apply_preset that toggles
config.local_ai.enabled = false so the app uses the cloud summarizer.
- Presets RPC now returns local_ai_enabled so the UI can render the
currently-active state correctly.
- Rewrite DeviceCapabilitySection: tiers are now clickable buttons that
call apply_preset; adds a "Disabled — Cloud fallback" card at the top
marked "Recommended" on low-RAM devices and "Active" when enabled=false.
- Remove the MVP message copy from the model tier panel.
- Remove unread-count badge from the bottom tab bar.
* refactor(onboarding): streamline LocalAIStep and update local AI preset handling
- Removed the `ensureRecommendedLocalAiPresetIfNeeded` function call from `LocalAIStep`, replacing it with `openhumanLocalAiPresets` to directly fetch preset information.
- Updated the logic in `ensureRecommendedLocalAiPresetIfNeeded` to ensure the recommended tier is applied correctly based on user consent, improving clarity in the local AI setup process.
- Enhanced tests to mock the new `openhumanLocalAiPresets` function, ensuring coverage for low-RAM device scenarios and local AI consent handling.
- Updated documentation in the `schemas.rs` file to reflect changes in the data structure returned by the presets RPC.
These changes improve the onboarding experience by providing a more direct and efficient method for managing local AI presets based on device capabilities.
* test(LocalAIStep): improve mock implementation for local AI presets
- Refactored the mock for `openhumanLocalAiPresets` to enhance readability and maintainability.
- Ensured the mock returns consistent device information and preset details for testing scenarios.
- This change supports better test coverage and clarity in the LocalAIStep component's behavior during onboarding.
* fix(local_ai): preserve hadSelectedTier semantics in bootstrap return
hadSelectedTier / selectedTier represent the incoming state ("was a tier
already selected before this call"), not the post-apply state. Setting
both to the just-applied tier broke the existing localAiBootstrap
contract and the unit test that encodes it.
The Rust-side persistence fix is independent: removing the
recommend_disabled short-circuit ensures openhumanLocalAiApplyPreset
actually writes the selected tier to disk on the opt-in path, so
config_with_recommended_tier_if_unselected() honors the user's choice.
|
||
|
|
923c920ad5 |
fix(tauri): hide main window on close instead of destroying it (#601) (#610)
* fix(tauri): hide main window on close instead of destroying it (#601) On macOS, clicking the close button destroyed the main window. Since a tray icon keeps the process alive, subsequent dock-icon clicks fired RunEvent::Reopen but get_webview_window("main") returned None — the window was gone. Now CloseRequested is intercepted: the close is prevented and the window is hidden instead, so Reopen and tray clicks can show it again. Closes #601 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style(tauri): cargo fmt line wrap Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
2bb20faa55 |
feat(threads): dedicated threads controller with per-thread session scoping (#590)
* feat(conversations): implement thread management features including creation and deletion - Added functionality to create new conversation threads with unique IDs and titles based on the current date and time. - Introduced a deleteThread action to remove existing threads, updating the selected thread accordingly. - Enhanced the UI to display threads in a sidebar, allowing users to select and delete threads easily. - Updated the Conversations component to handle thread loading and selection more efficiently, ensuring a smoother user experience. Also updated the OpenHuman package version to 0.52.15 in Cargo.lock files. * refactor(conversations): rename createThreadLocal to createNewThread and streamline thread creation logic - Updated the function name from `createThreadLocal` to `createNewThread` for clarity and consistency. - Simplified the thread creation process by removing the manual ID and title generation, leveraging the new API method for automatic thread creation. - Adjusted the Conversations component to utilize the new `handleCreateNewThread` function, enhancing readability and maintainability. - Removed unused thread ID and title generation functions to clean up the codebase. This refactor improves the overall structure and clarity of the thread management functionality. * refactor(memory): remove deprecated conversation thread management functions - Eliminated unused functions related to listing, creating, updating, appending, and deleting conversation threads in memory operations. - This cleanup enhances code maintainability and reduces complexity in the memory module. - The refactor focuses on streamlining the conversation management logic, aligning with recent changes in the thread handling API. * refactor(api): update thread API method names and remove deprecated functions - Renamed thread-related API methods to align with the new naming convention, improving clarity and consistency. - Removed deprecated functions related to thread creation, streamlining the API and enhancing maintainability. - Adjusted the implementation of existing methods to reflect the updated API structure, ensuring proper functionality. * refactor(thread): simplify thread state management and remove unused properties - Streamlined the thread state by removing the lastViewedAt property and related logic, enhancing clarity in unread message counting. - Updated the BottomTabBar component to reflect the new unread count logic, which now simply returns the length of threads. - Removed the setLastViewed action from the Conversations component, further simplifying the thread management logic. - Introduced a new deleteThread action to handle thread deletion, ensuring proper state updates and selection handling. - Overall, these changes improve maintainability and reduce complexity in the thread management system. * style(threads): apply cargo fmt * refactor(tabbar): remove conversations unread badge * update(Cargo.lock): bump OpenHuman package version to 0.52.15 * test(threadApi): update RPC method names to threads namespace * refactor(conversations): update model ID for chat functionality - Changed the model ID used in the chatSend function from `agentic-v1` to `reasoning-v1`, clarifying the purpose of each model. - Added comments to explain the distinction between the reasoning model and the agentic model, enhancing code readability and maintainability. |
||
|
|
ead0862d50 |
fix(onboarding): prevent home page flash after onboarding completion (#609)
* fix(onboarding): prevent home page flash after onboarding completion Navigate to /conversations before persisting onboarding_completed so the overlay stays rendered during the route transition. A local isDismissing flag keeps the overlay visible until the flag is persisted and the conversations screen is active, eliminating the brief home page flash. Closes #598 * fix(onboarding): enhance onboarding overlay with location tracking and improved dismissal logic |
||
|
|
ea6895f19d |
test(coverage): batch 5–8 — Rust unit tests toward 80% for 20 modules (#607)
* test(coverage): batch 5–8 — Rust unit tests toward 80% for 20 modules (#530) Add 244 new unit tests across 20 modules to push line coverage from 75.06% → 75.70% overall. Modules improved: - api/socket: 77% → 100% - rpc/dispatch: 75% → 100% - config/schema/channels: 77% → 100% - composio/gmail/sync: 78% → 97% - composio/notion/sync: 77% → 96% - webhooks/router: 78% → 96% - agent/hooks: 78% → 92% - config/schema/proxy: 76% → 90% - local_ai/device: 79% → 89% - text_input/schemas: 73% → 89% - agent/harness/interrupt: 76% → 88% - billing/schemas: 79% → 87% - screen_intelligence/schemas: 78% → 81% - about_app/types, health/schemas, app_state/schemas, core/types, config/schema/identity_cost, cron/scheduler Tests cover: schema catalog integrity, param deserialization, serde roundtrips, helper functions, edge cases, error paths. All 3974 tests pass. * test(coverage): batch 9–10 — browser_open, update_memory_md, credentials profiles, cost tracker (#530) Add 53 new tests across 4 more modules: - browser_open: IPv4/IPv6 private ranges, host matching, normalize_domain edges - update_memory_md: empty file, section creation, unknown action, param validation - credentials/profiles: token expiry, CRUD operations, active profile management - cost/tracker: budget warnings, monthly exceeded, model stats aggregation All 4027 tests pass. * test(coverage): batch 11–12 — channels schemas, conversation store (#530) Add 33 new tests: - channels/controllers/schemas: per-function input validation, param deserialization, helper coverage - memory/conversations/store: thread lifecycle (create, delete, idempotent), multi-thread, empty/nonexistent thread, purge empty store All 4060 tests pass. |
||
|
|
7f686003a0 |
feat(core): gate service lifecycle on user login/logout (#582) (#603)
* refactor(voice): wrap CancellationToken in Mutex for restart support The VoiceServer singleton uses OnceCell so it can't be recreated. CancellationToken is one-shot — once cancelled, stays cancelled. Wrapping it in std::sync::Mutex + adding fresh_cancel() allows stop() then run() to work within the same process (logout → re-login). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor(screen_intelligence): wrap CancellationToken in Mutex for restart support Same pattern as voice server — enables stop() then run() within the same process for logout → re-login cycles. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(credentials): add start/stop helpers for login-gated services Add start_login_gated_services() and stop_login_gated_services() to credentials/ops.rs. Wire start into store_session() (after login) and stop into clear_session() (on logout) so voice, autocomplete, screen intelligence, and local AI are properly managed around auth lifecycle. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(core): defer service startup behind login gate in jsonrpc.rs Replace the unconditional service startup block with a login check. If active_user.toml exists, start services immediately via the new start_login_gated_services() helper. Otherwise defer until the login handler triggers it. Autocomplete shutdown hook remains unconditional. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(screen_intelligence): wait for Stopped state in stop() to prevent restart race stop() now polls until the run-loop sets ServerState::Stopped (5s timeout). Prevents fast logout→login from seeing stale Idle/Running state and skipping the restart. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(dictation): add stop() to prevent listener accumulation across re-logins Store the spawned task JoinHandle and abort it on stop(). Prevents duplicate rdev hotkey listeners from stacking across logout→login cycles. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(credentials): call dictation_listener::stop() on logout Wire the new dictation stop into stop_login_gated_services() so the hotkey forwarder task is aborted when the user logs out. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
cf35f27cd6 | chore(release): v0.52.17 v0.52.17 | ||
|
|
e8639adae0 |
fix: Improve deep link authentication state management and improve logout (#608)
* feat(deepLink): implement deep link authentication state management - Added a new module for managing deep link authentication state, including processing states and error handling. - Integrated deep link authentication state management into the desktop deep link listener, enhancing the handling of authentication flows. - Introduced functions to begin, complete, and fail deep link authentication processing, improving user feedback during the authentication process. * refactor(settings): simplify logout process and enhance error handling - Removed onboarding completion flag from the logout process to streamline functionality. - Improved error handling during logout to provide user feedback if the logout fails. - Updated comments to clarify the behavior of session clearing and routing after logout. - Integrated deep link authentication state management into the settings component for better user experience. * refactor(settings, deepLink): enhance logout and session management - Simplified the logout process by removing unnecessary flags and improving error handling. - Introduced a new function to manage signed-out state in the core state provider. - Streamlined session token application in the deep link listener for better authentication flow. - Updated comments for clarity on session clearing and routing behavior post-logout. * chore(dependencies): update OpenHuman to version 0.52.16 in Cargo.lock files * refactor(format): format the code |
||
|
|
a78506f6a3 |
fix(agent): use canonical assistant history format in subagent_runner (#606)
build_native_assistant_payload in subagent_runner.rs serialised the
assistant tool-call message using {"text": …, "tool_calls": [{
"type":"function","function":{…}}]} — two mismatches vs the format
parse::build_native_assistant_history produces and the backend
jinja template expects:
1. "text" instead of "content" — the downstream convert_messages
parser looks for "content" to detect assistant-with-tool-calls
messages; "text" is not recognised, so the message is treated
as a plain assistant message.
2. Nested {"type":"function","function":{"name":…,"arguments":…}}
wrappers instead of flat {"id":…,"name":…,"arguments":…}.
Result: every sub-agent that made a tool call and entered iteration
1+ hit a 400 from the backend: "jinja template rendering failed.
Message has tool role, but there was no previous assistant message
with a tool call!" — the backend saw a role=tool message without a
recognised assistant-with-tool-calls predecessor.
The fix replaces the broken inline copy with a direct call to
parse::build_native_assistant_history (the same serialiser
tool_loop.rs uses successfully for the orchestrator's tool calls).
The dead build_native_assistant_payload function is removed.
Introduced in PR #474 (
|
||
|
|
fd213d40a2 | chore(release): v0.52.16 v0.52.16 | ||
|
|
c26ca795ca |
fix: keep chat processing alive across tab switches (#587)
* fix(chat): keep in-flight responses alive across tab switches Made-with: Cursor * chore: satisfy lint and format push gates Made-with: Cursor * fix: address CodeRabbit review on chat runtime PR Made-with: Cursor * feat(chat): add explicit inference turn lifecycle in chat runtime slice Made-with: Cursor * feat(chat): implement thinking summary feature in chat responses Added a new mechanism to accumulate and send model reasoning text as a separate message during chat interactions. This includes handling "thinking_delta" events to gather reasoning content, formatting it for clarity, and ensuring it is sent before the main response. Updated the StreamingState struct to include a thinking accumulator for this purpose. This enhancement improves user experience by providing insight into the model's reasoning process. * feat(telegram): update bot username handling for staging and production environments Refactored the Telegram bot username resolution logic to differentiate between staging and production environments. Introduced constants for default usernames based on the application environment and updated the GitHub Actions workflow to set the appropriate environment variables. This change enhances the flexibility and clarity of bot username management in the application. * fix: resolve CodeRabbit review issues on feat/thinking-telegram-summary - bus.rs: fix UTF-8 char boundary panic in format_thinking_summary truncation - threadSlice.ts: remove premature activeThreadId clear from addInferenceResponse.rejected - Conversations.tsx: add composerBlocked global lock, clear tool timeline in safety timeout - ChatRuntimeProvider.tsx: replace stale toolTimelineRef/inferenceStatusRef reads with live store.getState() calls in all event handlers - LocalAIDownloadSnackbar.tsx: reset dismissed/collapsed on not-downloading → downloading transition edge - MemoryGraphMap.tsx: derive activeSelectedNode to guard stale selectedNode after relations refresh; add debug logs to useMemo graph recompute Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: use render-phase update for download dismiss reset in LocalAIDownloadSnackbar Replace effect-based setState with the React render-phase update pattern so the not-downloading → downloading transition resets dismissed/collapsed without triggering the react-hooks/set-state-in-effect lint warning. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: apply prettier and cargo fmt auto-formatting Formatting changes applied by the pre-push hook during the previous commit. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor: replace endInferenceTurn with clearRuntimeForThread in Conversations component Updated the Conversations component to replace the endInferenceTurn dispatch with clearRuntimeForThread. This change simplifies the handling of thread runtime state during error scenarios and timeout conditions, ensuring a cleaner state management approach. --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> |
||
|
|
a8664f066f |
test(coverage): batch 1–4 — Rust unit tests toward 80% for critical modules (#530) (#581)
* test(coverage): phase 1 — webhooks/types, workspace/ops, webhooks/schemas
Lines: webhooks/types 0% → 100%; workspace/ops 0% → 96.98%;
webhooks/schemas 35.40% → 79.18%.
- webhooks/types.rs: serde round-trip tests for WebhookRequest /
WebhookResponseData / TunnelRegistration (including the
default_webhook_target_kind fallback) / WebhookActivityEntry /
WebhookDebugLogEntry / the three debug result wrappers / and
WebhookDebugEvent, exercising every `#[serde(default)]` and
camel-case rename.
- workspace/ops.rs: ensure_workspace_file covers create / leave / force
/ write-error branches; BOOTSTRAP_FILES contract test locks in SOUL
and IDENTITY presence; init_workspace covers fresh-install, idempotent
second-call, and forced-overwrite paths against a temp OPENHUMAN_WORKSPACE
(serialised via the shared TEST_ENV_LOCK).
- webhooks/schemas.rs: catalog integrity (length / namespace /
uniqueness / schema↔handler parity), per-function required-field
assertions for all 11 RPC methods plus the unknown fallback, and
deserialize_params / json_output / to_json coverage.
Also fixes a pre-existing test bug in composio/ops.rs discovered while
running llvm-cov: fetch_connected_integrations_via_mock_aggregates_tools
was not mocking /composio/toolkits, so list_toolkits failed and the
expected aggregation never happened. Adds the missing route so the
test now observes the 2-integration result it asserts.
* test(coverage): phase 2 — webhooks/bus, webhooks/ops
Lines: webhooks/bus 0% → 100%; webhooks/ops 14.34% → 97.96%.
- webhooks/bus.rs: base64_encode / error_body helpers; Default vs new
equivalence; EventHandler name and domain filter; handle() on a
non-webhook variant (early return) and on a WebhookIncomingRequest
without a registered socket manager (graceful fallthrough).
- webhooks/ops.rs: require_token for missing / whitespace / valid
stored sessions; the four stub RPC ops (list_registrations, list_logs
including ignored-limit, clear_logs, register/unregister_echo) lock
in their current payload + log shape; build_echo_response decodes
back to the expected echo body and sets the echo-target header;
trimmed-input validation for create_tunnel (empty/whitespace name)
and the id-bearing ops (get/update/delete); and full mock-backend
round-trips for list_tunnels, create_tunnel (trim + drop-whitespace
description), get_tunnel, update_tunnel, delete_tunnel, and
get_bandwidth, plus a guard asserting authed HTTP calls fail fast
without a session token.
* test(coverage): phase 3 — voice/postprocess, voice/text_input
Lines: voice/postprocess 58.94% → 92.06%; voice/text_input 18.83% → 51.18%.
voice/postprocess.rs
- Convert existing short-circuit tests to #[tokio::test] so the async
function is awaited directly instead of via a freshly-constructed
runtime per case.
- Add `enabled_but_llm_not_ready_returns_raw_text` for the "cleanup is
on but the local LLM hasn't reached ready/degraded yet" branch.
- Add five LLM-ready tests that spin up a mock Ollama behind the
OPENHUMAN_OLLAMA_BASE_URL override: happy-path cleanup + trim,
whitespace-only response fallback, HTTP 500 fallback, conversation
context embedded in the prompt, and whitespace-only context
ignored. Assertions are permissive about "LLM called → cleaned" vs
"LLM short-circuited → raw" because ~30 sibling tests touch the
shared `local_ai::global()` singleton without LOCAL_AI_TEST_MUTEX
and can race our `state = "ready"` setup. Either branch is
documented as acceptable; the function must always return a
deterministic String and never panic. Full end-to-end correctness
of the cleanup output is pinned by the deterministic short-circuit
tests above.
voice/text_input.rs
- Add `\\t` / `\\n`-only input case and verify the OpenWhispr timing
constants (PASTE_DELAY 120ms, CLIPBOARD_RESTORE_DELAY 450ms) so
nobody silently shortens them and breaks paste reliability.
- macOS: escape_applescript_string backslash/quote/idempotence cases
and restore_focus_to_app error path against a bogus app name.
- Ceiling note: the clipboard/enigo body of insert_text is not
testable in a headless environment (Clipboard::new / Enigo::new
fail without a display). Pushing past ~51% here requires
dependency-injecting those traits — a production refactor, not a
test addition.
* test(coverage): batch 4.1 — skills/bus, text_input/{types,ops}
Lines: skills/bus 0% → 100%; text_input/types 0% → 100%;
text_input/ops 0% → 57.67% (accessibility-gated ceiling).
- skills/bus.rs: idempotent no-op for the legacy
register_skill_cleanup_subscriber() hook.
- text_input/types.rs: FieldBounds ↔ accessibility::ElementBounds
round-trip, ReadFieldParams default/omitted-key serde, and
round-trips for every request/result struct (InsertText,
ShowGhostText, DismissGhostText, AcceptGhostText).
- text_input/ops.rs: empty-text guard assertions for insert_text,
show_ghost, and accept_ghost; dismiss_ghost idempotent-success
contract; plus a deterministic-shape check that the accessibility
failure path wraps the error into InsertTextResult rather than
panicking. Anything past the guard reaches `accessibility::*`,
which requires a live focused field on an OS display and is
therefore not reachable in a headless unit-test environment —
lifting the ceiling past ~58% requires dependency-injecting the
accessibility surface, a production refactor.
* test(coverage): batch 4.2 — service/bus, migration/ops, referral/ops
Lines: service/bus 0% → 85.25%; migration/ops 0% → 89.71%;
referral/ops 0% → 94.63%.
- service/bus.rs: RestartSubscriber name and domain metadata, plus
two handle() branches that are safe to exercise — non-restart
event (early return) and duplicate-suppression (gate already set).
Deliberately does NOT cover the success path of a real
SystemRestartRequested — it spawns a tokio task that calls
std::process::exit(0) and would terminate the test runner.
register_restart_subscriber idempotency test confirms the
OnceLock guard skips re-registration.
- migration/ops.rs: dry-run against an empty temp workspace returns
the canonical "migration completed" log; missing source-workspace
path exercises the Err-propagation branch.
- referral/ops.rs: require_token for missing / whitespace / valid
sessions; get_stats + claim_referral guard fast-fail without a
session; claim_referral round-trip against a mock backend
asserting (a) the referral code is trimmed, (b) a whitespace-only
deviceFingerprint is dropped from the outgoing body, and (c) a
non-empty fingerprint is trimmed and forwarded.
* test(coverage): batch 4.3 — security/ops, service/{bus,ops}, update/{ops,scheduler}
Adds unit tests covering:
- security/ops: security_policy_info payload shape + default values
- service/ops: daemon_host_get/set happy path and error branches
- service/bus: fix register_restart_subscriber test to use #[tokio::test]
so it has a runtime under `cargo llvm-cov`
- update/ops: validate_asset_name and validate_download_url edge cases,
update_apply short-circuit guards
- update/scheduler: min-interval invariant, disabled-run short-circuit,
tick resilience when the event bus is uninitialised
All 3583 lib tests pass under `cargo llvm-cov`. Refs #530.
* style: cargo fmt cleanup in coverage test modules
Auto-fixes from `cargo fmt` on test code added in batches 4.1–4.3.
No behavioral changes.
* test(coverage): batch 5.1 — cron/{ops,schemas}
- cron/ops.rs: 74.73% → 91.20% (+add_once_at, pause/resume, async cron_list/update/remove/runs, enabled/disabled and empty-id branches)
- cron/schemas.rs: 29.11% → 77.00% (all schemas() branches, registry helpers, read_required/read_optional_u64/type_name)
30 new deterministic tests. Refs #530.
* test(coverage): batch 5.2 — memory/{rpc_models,schemas}
- memory/rpc_models.rs: 70.91% (targets resolved_limit priority across QueryNamespace/RecallContext/RecallMemories, deny_unknown_fields enforcement, ApiError/ApiMeta/ApiEnvelope round-trips)
- memory/schemas.rs: 45.67% (all 31 controller schemas present, registry parity with handlers, parse_params success + error paths, unknown function placeholder)
19 new deterministic tests. Refs #530.
* test(coverage): batch 5.3 — socket/manager webhook router paths
- socket/manager.rs: 67.54% (adds set_webhook_router populates/overwrites paths and emit-after-disconnect guard)
3 new deterministic tests. Refs #530.
* test(coverage): batch 5.4 — config/{schemas, schema/observability}
- config/schemas.rs: 52.37% (adds required_string / optional_string / optional_bool field builder coverage, exercises deserialize_params across ModelSettings / MemorySettings / WorkspaceOnboarding / SetBrowserAllowAll / OnboardingCompleted params, pins DEFAULT_ONBOARDING_FLAG_NAME constant)
- config/schema/observability.rs: 66.67% (default-values invariant, serde defaults for optional fields, explicit analytics flag, round-trip)
16 new deterministic tests. Refs #530.
* test(coverage): batch 5.5 — local_ai/{core,gif_decision}
- local_ai/core.rs: 33.33% (pins model_artifact_path structure: models/local-ai dir, `.ollama` suffix, colon→dash normalisation for Windows-safe filenames; Arc sharing across global() calls)
- local_ai/gif_decision.rs: 44.04% (trim whitespace in parse, length/word-count boundary cases, tenor_search empty-query guard, local_ai_should_send_gif empty-message early return)
10 new deterministic tests. Refs #530.
* test(coverage): batch 5.6 — local_ai/sentiment, migration/schemas, referral/schemas
- local_ai/sentiment.rs: 68.03% (negative-confidence clamp to zero, unknown valence fallback, all documented emotion/valence labels accepted, neutral() constructor invariants, empty-message early return)
- migration/schemas.rs: 36.73% (controller registry parity, openclaw input shape, MigrateOpenClawParams defaults + round-trip, unknown function placeholder, to_json wrapping)
- referral/schemas.rs: 37.18% (controller registry parity, claim input required/optional mapping, ReferralClaimParams camelCase alias + missing-code rejection, json_output + to_json helpers)
25 new deterministic tests. Refs #530.
* test(coverage): batch 5.7 — tools/traits, local_ai/device
- tools/traits.rs: 76.77% (Tool default-method values for permission/scope/category, PermissionLevel total order + default + Display + serde round-trip, ToolCategory default + Display + snake_case serde, ToolScope variant distinctness)
- local_ai/device.rs: 63.16% (total_ram_gb truncation for sub-GB and partial-GB, detect_gpu branches for Apple-brand / ARM-on-mac / Intel-Mac, DeviceProfile serde round-trip)
17 new deterministic tests. Refs #530.
* test(coverage): address PR review — tighten assertions, fix flaky test, add env-var RAII guard
Inline review fixes:
- migration/ops.rs: migrate_openclaw_returns_error_for_missing_source_workspace now requires Err() (the underlying helper bails when the source dir doesn't exist) and asserts a non-empty error message.
- text_input/ops.rs: replace tautological `!inserted || inserted` in insert_text_surfaces_accessibility_failure_as_inserted_false with the real contract: require Ok(..) and pin `inserted`↔`error` mutual exclusion. Headless runs legitimately see inserted=false, so the assertion still holds while catching regressions in either branch.
- update/scheduler.rs: remove tick_runs_without_panicking_when_event_bus_is_uninitialised — it hit real api.github.com HTTPS and was flaky under offline CI / rate limits. Replace with a comment documenting the decision and the integration-test path for exercising tick().
Nitpick fixes:
- security/ops.rs: extend security_policy_info_matches_default_policy_values with assertions for autonomy and allowed_commands so the full default shape is pinned.
- voice/postprocess.rs: tighten ready_llm_with_whitespace_only_context_never_embeds_header from `assert_eq!(result.trim(), "raw text")` to exact equality (cleanup_transcription trims internally). The pre-existing doc comment on with_ready_llm plus the in-module block comment at lines 255-268 already document the LOCAL_AI_TEST_MUTEX contract and the deliberate non-use in permissive tests — no new docs needed.
- webhooks/ops.rs: list_tunnels_hits_webhooks_core_endpoint_and_returns_payload now asserts the inbound Authorization header equals `Bearer test-session-token`; get_tunnel_encodes_id_in_path uses an id full of reserved URL chars so the test actually verifies percent-encoding rather than just trimming.
- workspace/ops.rs: introduce a WorkspaceEnvGuard RAII helper; replace all six unsafe set_var/remove_var pairs in the init_workspace tests so OPENHUMAN_WORKSPACE is cleared on panic too. Contract is documented inline: guard requires the caller to hold ENV_LOCK.
Refs #530.
* test(coverage): tighten sentry_dsn round-trip assertion to exact value
round_trip_preserves_all_fields previously only checked
`back.sentry_dsn.is_some()`, which would still pass if serde dropped or
corrupted the DSN string. Compare the full decoded value instead so any
regression in the Option<String> path is caught.
Refs #530.
|
||
|
|
19aa50a429 |
fix(agent): thread agent_id into build_session_agent_inner (#584)
build_session_agent_inner took an agent_id: &str parameter but
never threaded it into the Agent::builder() chain — a `let _ =
agent_id;` silenced the unused-variable warning. AgentBuilder::build()
fell back to the legacy "main" default at builder.rs:310-312, so
every session built via Agent::from_config_for_agent carried
agent_definition_name="main" regardless of the id the caller asked
for.
Only two ids reach this path in production: "orchestrator" (legacy
Agent::from_config wrapper, cron, local_ai, escalation) and
"welcome" (channels/providers/web.rs routing after #525/#526, and
welcome_proactive). Orchestrator is benign — "main" was already
an alias for orchestrator everywhere downstream (see debug_dump.rs:249).
Welcome is the visible bug — agent_definition_name feeds three
surfaces that are all silently wrong pre-fix:
1. Transcript filename — welcome sessions land as main_*.md
instead of welcome_*.md.
2. Transcript metadata — the <!-- session_transcript --> block
stamps `agent: main` instead of `agent: welcome`.
3. Transcript resume cross-contamination —
try_load_session_transcript calls
find_latest_transcript(workspace_dir, "main") which scans all
dated session dirs for the latest main_*.md. It finds the
last orchestrator session and resumes from it, loading its
system prompt + user messages + assistant tool-call history
into the welcome agent's `history` as a resume prefix before
run_single runs. The written transcript mixes yesterday's
orchestrator email thread with today's welcome message under
the same main_0.md filename. Reproduced live 2026-04-16: a
welcome_proactive session loaded 5 messages from yesterday's
15042026/main_0.md and wrote 6 messages back that included a
spawn_subagent(skills_agent, toolkit=gmail) tool-call the
welcome agent never made.
Prompt rendering is NOT affected. context/prompt.rs only reads
ctx.agent_id for the is_skill_executor branch at prompt.rs:655, so
welcome/main/orchestrator all fall through the same delegator path.
The welcome persona prompt is rendered by the stamped
SystemPromptBuilder::for_subagent(target_def.system_prompt) built
at session-build time, independent of agent_definition_name. The
pre-fix main_0.md on disk contains `# Welcome Agent\n\nYou are the
Welcome agent...` as its system prompt body — correct content,
wrong filename and metadata.
skills_agent and other typed sub-agents are unaffected — they go
through subagent_runner, which constructs its prompt directly and
writes transcripts under the explicit id it receives. The
pre-existing sessions/15042026/skills_agent_0.md on disk with
`agent: skills_agent` confirms this code path has always been
correct.
Changes:
* src/openhuman/agent/harness/session/builder.rs:
- Add .agent_definition_name(agent_id.to_string()) to the
builder chain in build_session_agent_inner.
- Delete the `let _ = agent_id;` suppression.
- Replace the misleading 8-line comment block at the call site
(which claimed event_channel was for transport identity and
therefore stamping agent_id wasn't needed — conflating two
unrelated fields) with an accurate description of the three
load-bearing surfaces.
- Expand the docstring on AgentBuilder::agent_definition_name
to document the surfaces and the latent prompt-section
foot-gun the fix closes for future code.
- New log::debug! call at the stamping site for grep-friendly
runtime traces ([agent::builder] stamping
agent_definition_name=<id> onto session agent).
* src/openhuman/agent/harness/session/runtime.rs:
- Add pub fn agent_definition_name(&self) -> &str accessor
on Agent so tests and runtime callers can introspect the
stamped id without reaching into the pub(super) field.
* src/openhuman/agent/harness/session/tests.rs:
- Add build_minimal_agent_with_definition_name helper.
- agent_builder_threads_agent_definition_name_when_set —
parameterised over welcome/skills_agent/orchestrator/
trigger_triage, asserts the setter threads the id through.
- agent_builder_falls_back_to_main_when_definition_name_unset
— pins the legacy fallback contract direct builder users rely
on.
Tests: 2 passed; 0 failed; 3477 filtered out; finished in 0.21s.
cargo check --lib clean; cargo fmt clean.
Verified live against G:/projects/vezures/.openhuman on 2026-04-16:
- Pre-fix welcome_proactive run wrote sessions/16042026/main_0.md
with `agent: main` in the metadata header.
- Post-fix welcome_proactive run wrote sessions/16042026/welcome_0.md
with `agent: welcome` in the metadata header.
- Post-fix web-chat dispatch to orchestrator wrote
sessions/16042026/orchestrator_0.md (moved off the historical
main_*.md alias — behaviorally unchanged for orchestrator).
- The new [agent::builder] stamping debug line fires on both
welcome and orchestrator paths.
Does not touch: subagent_runner, spawn_subagent / dispatch_subagent,
any agent/agents/*/agent.toml, any context::prompt code, or the
AgentBuilder::build() fallback itself.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
d4f5b9a357 |
fix(overlay): fullscreen visibility, voice server reliability, and resize (#528) (#585)
* fix(overlay): shrink initial overlay window to match idle orb dimensions (#528) The Tauri overlay window was 248×228 px while the idle orb renders at 50×50. The excess transparent area wasted compositing resources and created an invisible click-absorbing region. Reduce to 60×60 to tightly frame the idle orb with minimal padding. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(overlay): add native drag support with position persistence (#528) - Mouse-down on the orb initiates Tauri startDragging() for native window drag - Dragged position is saved to localStorage and survives mode changes (idle ↔ active) so the orb stays where the user placed it - Double-click resets to the default bottom-right corner - Cursor changes to grab/grabbing for affordance - Skip default repositioning when a saved position exists Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(overlay): reclass NSWindow to NSPanel for fullscreen visibility (#528) macOS fullscreen apps run in separate Spaces where standard NSWindow cannot follow. Use object_setClass() to reclass the Tauri overlay window from NSWindow to NSPanel at runtime, then configure it with NonactivatingPanel style mask and Transient collection behavior — matching the working Swift accessibility helper pattern. Key configuration that makes this work: - object_setClass(NSWindow → NSPanel) — in-place reclass, no reparenting - NSWindowStyleMask::NonactivatingPanel — critical for panel behavior - NSWindowCollectionBehavior::Transient (not Stationary) — follows Spaces - Window level 25 (NSStatusWindowLevel) — floats above fullscreen apps - setFloatingPanel(true), setHidesOnDeactivate(false) Previous approaches that failed: 1. CGShieldingWindowLevel + CanJoinAllSpaces — hidden (NSWindow limitation) 2. Window level i32::MAX-17 + Stationary — hidden (Space membership issue) 3. CGS private API CGSSetWindowTags sticky bit — blocked on Sonoma 4. object_setClass WITHOUT NonactivatingPanel mask — hidden 5. Create new NSPanel + reparent webview — CRASH (Tao delegate panic) Also removes unused objc2-core-graphics and objc2-foundation deps. Ref: https://github.com/tauri-apps/tauri/issues/11488 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(sidecar): make dev signing non-fatal in stage script codesign failures no longer call process.exit(), preventing yarn tauri dev from hanging when the dev signing identity is missing or the keychain rejects the request. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(voice): prevent race condition and fix restart after stop - Atomically transition Stopped → Idle at start of run() to prevent duplicate run() calls during slow globe listener compilation - Wrap CancellationToken in Mutex so run() creates a fresh token on each start — a cancelled token cannot be reused after stop() - Reset state to Stopped if hotkey listener fails to start Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(voice): capture server errors from spawned run() task Store errors from the background server.run() task via set_last_error() so they surface in voice_server_status RPC responses instead of being silently lost. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(overlay): enable programmatic resize and shrink idle dimensions - Change overlay window from 60x60 to 50x50 to match idle orb size - Remove minWidth/minHeight constraints that blocked dynamic resize - Set resizable: true so setSize() calls work for bubble expansion Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(overlay): simplify window resize and bubble rendering - Clear min/max constraints before resizing to avoid clamping - Replace CSS transition-based bubble visibility with conditional mount for more reliable rendering when mode changes Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: fix fmt and remove unused bubbles variable Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(voice): enforce lock ordering to prevent race between run() and stop() Acquire cancel lock before state lock in run() — same order as stop() — so stop() cannot cancel a stale token between setting Idle and swapping. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(overlay): restore saved position on resize and format with prettier Parse and apply saved drag coordinates instead of just using their presence as a sentinel. Also reformats for prettier compliance. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(sidecar): fail-fast on dev signing failure in CI environments Add CI detection so signing failures abort the build in CI but remain non-fatal for local development. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: fix cargo fmt on Tauri shell import Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
f014058417 |
feat(local_ai): MVP model lockdown — lock selection to 2-4 GB tier (#573) (#588)
* feat(local_ai): add MVP tier ceiling and cap model recommendation (#573) Introduce MVP_MAX_TIER constant (Ram2To4Gb), is_mvp_allowed() gate, mvp_presets() filter, and cap recommend_tier() so auto-provisioning never selects a model above the MVP ceiling regardless of device RAM. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(local_ai): enforce MVP model allowlists on resolved IDs (#573) Add per-category allowlists (chat, vision, embedding) so that effective_*_model_id() silently redirects any non-MVP model to the default. Prevents config-file edits from bypassing the 2-4 GB tier restriction. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(local_ai): reject non-MVP tiers in RPC and clamp at bootstrap (#573) apply_preset handler now returns an error for tiers above the MVP ceiling. Bootstrap clamps any existing out-of-range tier selection down to the recommended (capped) preset on startup. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(ui): lock model tier selection and show full roadmap (#573) Replace clickable tier buttons with static cards. Active tier shows "Active" badge; locked tiers show "Coming soon" with reduced opacity. Add MVP info banner. Fix download size to 1 decimal place. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(local_ai): resolve CI failures — fmt, unused props, dead code (#573) Apply cargo fmt to single-element array constants. Remove unused isApplyingPreset/onApplyPreset props and applyPreset function from the settings panel since tier switching is disabled for MVP. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: apply Prettier formatting to settings panels (#573) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
098206cea7 | chore(release): v0.52.15 v0.52.15 | ||
|
|
a2aee3a1f1 | chore(release): v0.52.14 | ||
|
|
cca6c08ab0 |
Fix: discord (#580)
* feat(discord): implement managed link functionality and enhance DiscordConfig component - Added support for managed Discord linking, including new API methods for initiating and checking link status. - Enhanced the DiscordConfig component to manage link tokens and implement polling for link completion. - Introduced new state management for link tokens and improved error handling during connection processes. - Updated the definitions to include a new auth action for managed links, streamlining the onboarding experience for users. - Added tests for the new Discord link functionality to ensure robust integration and error handling. This commit significantly improves the user experience for connecting Discord accounts, providing clearer feedback and handling for managed links. * feat(discord): implement managed link functionality and enhance DiscordConfig component - Added support for managed Discord linking, including new API methods for initiating and checking link status. - Enhanced the DiscordConfig component to manage link tokens and implement polling for link status, improving user experience during the linking process. - Introduced new state management for link tokens and error handling, ensuring robust interaction with the Discord API. - Updated the channel definitions to include a new auth action for managed links, streamlining the integration process. - Added tests for the new API methods and updated existing tests to cover the new functionality. This commit significantly improves the integration with Discord, allowing users to link their accounts more effectively and providing better feedback during the linking process. * chore(release): update OpenHuman version to 0.52.9 in Cargo.lock - Bumped the version of the OpenHuman package from 0.52.7 to 0.52.9 in both Cargo.lock files for the main application and the Tauri app. - This update ensures that the latest features and fixes from the OpenHuman package are included in the project. * fix(tests): update DiscordConfig test to reflect new Connect button count - Adjusted the test for the DiscordConfig component to expect three Connect buttons instead of two, aligning with recent changes in the component's authentication modes. - This update ensures that the test accurately reflects the current functionality and improves test reliability. * refactor(discord): modularize channel permission checks and enhance logging - Extracted the `check_channel_permissions_at_base` function to modularize the permission checking logic for better readability and maintainability. - Updated the API calls to use a dynamic base URL instead of a hardcoded one, improving flexibility. - Enhanced logging for non-success responses from Discord API calls, providing more context for debugging. - Minor adjustment in the hallucination check logic to improve clarity in variable usage. * fix(logging): enhance error handling in DiscordConfig and SocketProvider - Updated error handling in DiscordConfig to log specific errors when link checks fail, improving debugging capabilities. - Enhanced SocketProvider to log non-fatal RPC connection failures, providing clearer context for potential issues with the sidecar or backend connectivity. * feat(discord): add validation functions for Discord link start and complete responses - Introduced `expectDiscordLinkStart` and `expectDiscordLinkComplete` functions to validate the structure of responses from Discord link API calls. - Updated `channelConnectionsApi` methods to utilize these new validation functions, improving error handling and response consistency. - Added tests to ensure proper unwrapping and validation of Discord link responses, enhancing overall reliability of the API integration. * fix(channelConnections): improve handling of lastError and capabilities in touchConnection function - Updated the touchConnection function to conditionally assign lastError and capabilities based on their presence in the patch object, ensuring more accurate state management. - This change enhances the reliability of connection updates by preventing unintended overwrites of existing values. * test(channelConnections): add test to clear lastError when explicitly set to undefined - Introduced a new test case to verify that the lastError state is cleared when an explicit patch sets it to undefined. This enhances the reliability of the state management in the channelConnectionsSlice reducer. * test(tests): add tests for upstream_unhealthy detection and failure reason precedence - Introduced multiple test cases to verify the detection of upstream unavailability and service unavailability errors. - Ensured that the `failure_reason` function correctly prioritizes upstream_unhealthy over other error states, enhancing the reliability of error handling in the system. * feat(discord): add OAuth success handling in DiscordConfig component - Implemented a new useEffect to handle successful OAuth events for Discord, updating the channel connection status and capabilities accordingly. - This enhancement improves the integration with Discord by ensuring that the application responds correctly to OAuth success events, providing a better user experience. * feat(deepLink): enhance OAuth deep link handling to include skillId - Updated the deep link handling logic to also retrieve the skillId from the URL parameters, improving flexibility in OAuth success scenarios. - Added a new simulation example for skillId in the setupDesktopDeepLinkListener function to aid in testing and development. * refactor(format): ran format * fix(discord): update permissions mock and improve message dispatch test - Revised the permissions mock to include additional endpoints for better accuracy in testing Discord API interactions. - Adjusted the message dispatch test to utilize a deterministic stub for the agent's response, ensuring consistent timing and behavior during tests. - Reduced the delay in the SlowProvider to enhance test performance while maintaining robustness. * chore(dependencies): update OpenHuman package version to 0.52.13 in Cargo.lock |
||
|
|
d545c193b9 |
feat(agent): fuzzy-filter skills_agent toolkit actions by task prompt (#579)
* feat(agent): fuzzy-filter skills_agent toolkit actions by task prompt Narrow large Composio toolkits (e.g. github ~500 actions) down to the handful relevant to a given delegation prompt before registering them as native tools on a spawned skills_agent. Falls back to the full catalogue when the filter yields fewer than MIN_CONFIDENT_HITS hits to avoid starving the sub-agent on under-specified prompts. Filter is only invoked when both `definition.id == "skills_agent"` and a `toolkit=` argument is present, so orchestrator and other sub-agents are unaffected. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(composio): mock toolkits route in ops integration test --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
d575cf2cca | chore(release): v0.52.13 | ||
|
|
70a2a6fcc3 | chore(release): v0.52.12 v0.52.12 | ||
|
|
f179d2d3f9 | chore(release): v0.52.11 | ||
|
|
fc103bf89f | chore(release): v0.52.10 | ||
|
|
ea088d9f15 |
feat(prompt): unified delegation guide + dynamic per-toolkit tool registration (#447) (#570)
* feat(prompt): unified delegation guide + dynamic per-toolkit tool registration (#447) Cuts main agent prompt token cost ~98% on accounts with connected integrations and replaces the generic Composio dispatcher with native per-action tool calling inside skills_agent. ## Why Issue #447: prompt payloads were ballooning because main/orchestrator re-shipped a full prose enumeration of every connected toolkit's actions on every turn (~13.7k tokens for one gmail integration alone), and skills_agent had no way to scope tools to a single toolkit so it inherited a flat dispatcher (composio_execute) that the LLM couldn't reliably call without first round-tripping composio_list_tools. ## What ### main / orchestrator prompt - Replace `ConnectedIntegrationsSection`'s per-action prose dump with a unified Delegation Guide: one bullet per integration (toolkit + one-line description + spawn snippet). Tokens added per integration: ~30. Savings vs old per-action listing: ~5k+ tokens per connected toolkit. - Drop every "Composio" reference from delegating-agent prose so the surface stays provider-neutral. ### skills_agent - Add a `toolkit` argument to `spawn_subagent` with three pre-flight validation modes resolved against the parent's connected integrations list before any LLM call: * missing toolkit -> ToolResult::error (model retries) * unknown toolkit -> ToolResult::error (model retries) * in allowlist, not connected -> ToolResult::success (model surfaces "authorize in Settings -> Integrations" to user; not flagged as a tool failure in the agent loop or web channel) - New `ComposioActionTool` (`src/openhuman/composio/action_tool.rs`) implements the `Tool` trait per Composio action. The sub-agent runner constructs ~N of these at spawn time from the cached integration overview and injects them via a new `extra_tools` parameter through `run_typed_mode` -> `run_inner_loop`. - `filter_tool_indices` drops every skill-category parent tool when `is_skills_agent_with_toolkit` is true so the only skill-category entries the sub-agent sees are the freshly-built per-action tools. This eliminates apify_*, composio_list_*, composio_authorize, and composio_execute from the toolkit-scoped surface. - Sub-agent renderer takes the parent's actual `tool_call_format` instead of hardcoding PFormat. Native dispatchers no longer carry a prose `## Tools` section at all (schemas already travel through the request body's `tools` field) — eliminates a ~30k-token duplication that was blowing past the model's context window. ### integration overview fetch - `fetch_connected_integrations_uncached` now merges Composio's toolkit allowlist with the user's active connections and returns one `ConnectedIntegration` per allowlisted toolkit with a `connected: bool` flag. Unconnected entries carry no schemas, just the toolkit name + description, so the orchestrator can mention them without trying to invoke them. - `ConnectedIntegrationTool` preserves the action's full JSON parameter schema so `ComposioActionTool` can advertise it through native function-calling. ### plumbing - `ParentExecutionContext` carries a `ComposioClient` and the parent's resolved `tool_call_format`, populated alongside `connected_integrations` in `Session::fetch_connected_integrations`. Triage and test paths pass `None` / `PFormat` defaults. - `dispatch_subagent` (the `SkillDelegationTool` path) plumbs its pre-bound skill_id through `toolkit_override` instead of the broken `skill_filter_override` (which used `{skill}__` prefix matching that never matched Composio's `TOOLKIT_*` naming). - `web::run_chat_task` failures now log the underlying error at WARN so debugging an in-flight failure no longer requires turning on TRACE for socket events. - `scripts/stage-core-sidecar.mjs` queries `cargo metadata` for the real target directory instead of assuming `<repo>/target` so the staging step works under workspace-level `target-dir` overrides (the vezures-workspace shared `.cargo-target` setup). ## Verified end-to-end Two RPC tests against a freshly-rebuilt sidecar (gmail connected, notion / slack / etc. allowlisted but not connected): | Test | Behavior | Tokens | Iterations | |---|---|---|---| | Connected (gmail, "fetch 5 unread emails") | spawn_subagent -> 62 dynamic gmail tools registered -> 1 GMAIL_FETCH_EMAILS call with smart args -> markdown table response | 42,911 input | 1 | | Not-connected (notion, "create a page") | main answers directly without spawning, tells user to authorize in Settings -> Integrations | 3,319 input | 1 | Both flows complete cleanly. The connected path proves dynamic per-action tool registration is working with full schema validation; the unconnected path proves the unified delegation guide + ToolResult::success return for not-connected toolkits keeps the model on a graceful path without polluting the chat with error styling. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(prompt): update test callers + assertions for new renderer signature Follow-up to #447. The main patch changed three signatures that test callers hadn't been updated for, and flipped one assertion that was validating the now-removed prose schema duplication. - `SubagentRunOptions` test constructors in subagent_runner.rs (2 sites) now pass `toolkit_override: None`. - `ConnectedIntegration` test constructor in orchestrator_tools.rs now passes `connected: true` (the default for test integrations — they're treated as authorized so delegation logic still runs). - 12 `render_subagent_system_prompt` test callers in prompt.rs now pass `&[]` for the new `extra_tools` slice and `ToolCallFormat::PFormat` for the new `tool_call_format` argument. - `render_subagent_system_prompt_honors_identity_safety_and_skills_flags` used to assert `rendered.contains("Parameters:")` on the Json dispatcher branch — that was valid in the old world where the prose `## Tools` section dumped full JSON schemas for Json/Native formats. The main patch deliberately removes that dump (it was the ~30k-token duplication of the native `tools` field), so the test now asserts the opposite: no `## Tools` header and no `Parameters:` line are emitted for Native/Json dispatchers. The schemas still travel through the provider request's `tools` field. Also picks up `rustfmt` rewraps in action_tool.rs and ops.rs from a background linter run — pure whitespace, no semantic change. Verified green against the full `cargo test --lib` suite for every test touched by this PR: - openhuman::context::prompt::tests (26 passed) - openhuman::agent::harness::subagent_runner::tests (19 passed) - openhuman::composio::ops::tests (2 passed) - openhuman::tools::impl::agent::tests (0 scoped) The 7 remaining failures in `cargo test --lib` are pre-existing Windows-path/filesystem flakes in subsystems this PR doesn't touch (self_healing polyfill path separator, cron scheduler shell spawning, local_ai::paths absolute-path detection, security::policy sandbox path handling, composio::trigger_history jsonl archive, and a real pre-existing `Option::unwrap()` panic in browser::screenshot). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(harness): add composio_client + tool_call_format to integration test stub Follow-up to #447. The `tests/agent_harness_public.rs` integration test constructs a `ParentExecutionContext` in `stub_parent_context` that was missing the two fields added in the main patch (`composio_client` and `tool_call_format`). `cargo test --lib` doesn't compile integration tests, which is why this slipped past local verification — it only surfaced on Linux CI. - `composio_client: None` — the stub parent has no composio client because these tests don't exercise the integration-overview path. - `tool_call_format: ToolCallFormat::PFormat` — default legacy format; none of the tests in this file exercise the sub-agent renderer's format branching, so PFormat is the safe pick. Verified locally that `cargo test --no-run` compiles all integration test targets including `agent_harness_public`. (The `agent_memory_loader_public` link error in the local run is a pre-existing Windows `libucrt`/`fgets` C-runtime issue unrelated to this PR — won't reproduce on Linux CI.) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(prompt,composio): address CodeRabbit review on #570 (#447) Four fixes from the CodeRabbit review of PR #570, ranked by impact: ## `context/prompt.rs` — Json dispatcher needs prose tool catalog The initial patch gated the prose `## Tools` section behind `matches!(tool_call_format, ToolCallFormat::PFormat)`, which conflated Json with Native. Only `ToolCallFormat::Native` uses the provider's native function-calling channel where schemas travel via the request body's `tools` field. `ToolCallFormat::Json` is a prompt-driven format (the model wraps JSON tool calls in `<tool_call>` tags) and relies on the prose catalog the same way PFormat does — without it the model sees protocol instructions but no visible tool names or schemas. Inverted the guard to `!matches!(tool_call_format, Native)` so PFormat and Json both render the `## Tools` section with their respective per-entry shapes (compact `Call as:` signature for PFormat, inline `Parameters:` JSON schema for Json). Updated the `render_subagent_system_prompt_honors_identity_safety_and_skills_flags` test: the Json assertion now expects `Parameters:` to be present again (reverting commit 2's flip), and a new Native-branch assertion guards against the ~54k-token schema duplication the original PR fixed. ## `composio/ops.rs` — don't cache degraded snapshots All three backend calls in `fetch_connected_integrations_uncached` (`list_toolkits`, `list_connections`, `list_tools`) previously returned `Some(Vec::new())` or fell through to an empty inner vec on transient errors. The outer `fetch_connected_integrations` caches whatever the uncached path returns, so a single transient 5xx would silently hide every integration, mark connected toolkits as disconnected, or register dynamic Composio tools with zero callable actions — until the cache is invalidated or the process restarts. Changed all three branches to return `None`, which signals the caller to NOT cache the result and retry on the next call. ## `composio/ops.rs` — prefix match needs a delimiter `starts_with(&slug.to_uppercase())` false-matches when two toolkit slugs share a text prefix (e.g. `git` vs `github`). The current allowlist doesn't trigger this, but adding a new toolkit could silently leak actions between integrations. Anchored the prefix with an underscore so `GMAIL_SEND_EMAIL` matches `gmail_`, not just `gmail`. ## `scripts/stage-core-sidecar.mjs` — resolve CARGO_TARGET_DIR vs repo root `resolve(process.env.CARGO_TARGET_DIR)` uses the process's current working directory, but the `cargo build` spawn below runs with `cwd: root`. For an absolute env var this is identical, but a relative `CARGO_TARGET_DIR` and a cwd outside the repo would make the two paths disagree and the binary lookup would miss. Defensive fix: `resolve(root, process.env.CARGO_TARGET_DIR)` so both paths anchor to the same base. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
b2c74458d3 |
fix(voice): enable GPU detection and Metal acceleration for whisper (#558) (#571)
* fix(device): expand GPU detection with Intel Mac and NVIDIA probes (#558) Add Intel Mac detection (no Metal GPU for whisper), nvidia-smi probe for Windows/Linux NVIDIA GPUs, and diagnostic tracing at each decision point in detect_gpu(). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * build(cargo): enable whisper-rs Metal feature on macOS (#558) Add target-specific dependency for macOS that enables the `metal` feature on whisper-rs, compiling whisper.cpp with Metal GPU support. Cargo merges features from both declarations so non-macOS builds are unaffected. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(whisper): configure GPU params from device profile (#558) Accept has_gpu and gpu_description in load_engine() and explicitly set use_gpu and flash_attn on WhisperContextParameters instead of relying on the compile-time default. Log the selected acceleration backend at startup. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(local_ai): pass GPU info to whisper engine load paths (#558) Thread DeviceProfile has_gpu and gpu_description through both the bootstrap (startup) and speech (lazy) whisper engine load calls so the engine can configure Metal or CUDA acceleration at runtime. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
13ce2cdcbf |
test(coverage): raise Rust unit test coverage to ≥80% on 10 critical modules (issue #530) (#567)
* test(coverage): raise 9 critical modules to ≥80% line coverage Pushes unit test coverage to meet issue #530's 80% target on 9 modules: socket (17% → 80%), credentials (46% → 81%), composio (55% → 81%), memory (75% → 80%), tools (73% → 83%), plus previously-passing cron, context, learning, embeddings. Additions span ~400+ new tests across 44 files: - Pure-function tests for types, schemas, parsers, URL builders, and error-classification helpers. - Mock-backend integration tests using axum for HTTP-dependent code (composio client + ops, socket ws_loop against a local WebSocket server). - End-to-end RPC handler tests using tempdir + OPENHUMAN_WORKSPACE env override (credentials, memory, config, cron). Also fixes 4 pre-existing flaky tests on macOS dev machines by pinning absolute paths (/bin/ls, /bin/sleep, /bin/sh, /usr/bin/touch) in cron scheduler tests so sh -lc does not pick up homebrew-shadowed binaries that macOS SIP refuses to execute, and relaxing a screen_intelligence capture-permission hang assertion. Remaining work: voice, config, screen_intelligence, channels, local_ai still below 80% (62%, 61%, 54%, 68%, 35% respectively). * test(coverage): add config module tests (62% → ~71%) Adds tests for: - config/ops.rs: env_flag_enabled, core_rpc_url_from_env, snapshot_config_json, workspace_onboarding_flag_exists/_set, set_browser_allow_all, agent_server_status - config/schemas.rs: catalog parity, all 21 registered schema keys, helpers - config/schema/proxy.rs: normalize_*, parse_proxy_scope, parse_proxy_enabled, validate_proxy_url, service_selector_matches, ProxyConfig defaults - config/schema/load.rs: apply_env_overrides for api_key, model, temperature, reasoning_enabled, web_search.*, storage.*; resolve_config_dir_for_workspace - config/settings_cli.rs: settings_section_json all sections (model/memory/runtime/browser/unknown) * test(coverage): config reaches 80.49%, socket back to 80.10% - config/ops.rs: apply_model/memory/runtime/browser/analytics/screen_intelligence_settings roundtrips via in-memory Config; load_and_apply_dictation/voice_server_settings activation-mode validation; get_dictation/voice_server/onboarding readers; workspace_onboarding_flag_set/resolve error and happy paths. - config/schema/load.rs: apply_env_overrides coverage for OPENHUMAN_MODEL, OPENHUMAN_TEMPERATURE (range clamp), OPENHUMAN_REASONING_ENABLED, OPENHUMAN_WEB_SEARCH_*, OPENHUMAN_STORAGE_* env branches. - config/schema/proxy.rs: normalize_* helpers, parse_proxy_scope/enabled, ProxyConfig defaults, validate_proxy_url schemes + hosts, service_selector_matches wildcards. - config/schemas.rs: every registered controller key, namespace parity. - config/settings_cli.rs: all section projections (model/memory/runtime/browser/unknown). - Shared `TEST_ENV_LOCK` at config::mod level so config::ops and config::schema::load test modules serialize OPENHUMAN_WORKSPACE mutations. - socket: a couple more schema assertions to keep module at 80%+. * test(coverage): channels partial push (68.12% → 68.91%) - channels/controllers/schemas.rs: every registered key resolves, required input coverage for describe/send_message/telegram_login_check. - channels/providers/web.rs: catalog parity, chat/cancel schema required inputs, unknown fallback, key_for, event_session_id_for stability, normalize_model_override trimming/empty, broadcast channel subscribe, field-builder helpers. - channels/providers/discord/api.rs: auth_header prefix, BotPermissionCheck serde with empty/full missing_permissions lists, permission bit flags are single-bit and distinct. Channels remains below the 80% issue target — the bulk of remaining uncovered code lives in telegram/channel.rs (574 lines), ops.rs (462), lark.rs (433) and runtime/startup.rs (350), which depend on live HTTP / socket / runtime bootstrap state that would require extensive mock infrastructure to exercise from unit tests. * test(coverage): partial push on local_ai (34→45%), screen_intelligence (54→62%), voice (62→63%) - local_ai/schemas.rs: catalog parity, every registered key resolves, field-builder helpers, deserialize_params happy/error, download_force optional. - local_ai/ops.rs: local-ai-disabled error paths for prompt/vision_prompt/ embed/summarize/transcribe/tts/chat; empty-messages rejection; suggestions return empty when disabled (graceful degradation). - local_ai/install.rs: find_system_ollama_binary env-override happy/missing/ empty cases; PATH-based lookup stub. - screen_intelligence/schemas.rs: catalog parity, all 15 registered keys resolve to non-unknown, unknown fallback. - screen_intelligence/ops.rs: accessibility_status/doctor_cli_json/ capture_image_ref/stop_session/vision_recent error-free behaviour. - voice/server.rs: truncate_for_log ellipsis + multibyte; try_global_server after init; additional hallucination-pattern coverage. Remaining gap on these modules lives almost entirely in: - local_ai/service/ollama_admin.rs (625 lines) — real HTTP + Ollama subprocess - local_ai/service/{assets,public_infer,vision_embed}.rs — same - voice/{server,audio_capture}.rs deep paths — audio hardware - screen_intelligence/{engine,processing_worker}.rs — active capture session * test(coverage): channels providers (+0.9%) — qq ensure_https, lark parsers - qq: ensure_https accept/reject, QQ_API_BASE/AUTH_URL constants, constructor. - lark: parse_post_content zh_cn/en_us fallback + links/mentions; invalid JSON returns None; strip_at_placeholders for @_user_N tokens; group should_respond_in_group mention gating. * test(coverage): push all 4 remaining modules - discord/api.rs: list_bot_guilds_at_base/list_guild_channels_at_base test seams with mock axum server; parse happy-path, error status, channel filter+sort, empty list. - channels/controllers/ops.rs: parse_allowed_users for string CSV/array/ newline/@-prefix/case-insensitive dedup/non-string; credential_provider; list_channels/describe_channel; connect_channel unknown-channel and non-object credentials. - local_ai/ollama_api.rs: `ollama_base_url()` honours OPENHUMAN_OLLAMA_BASE_URL env var so tests can point at mock servers; DEFAULT_OLLAMA_BASE_URL preserved. - local_ai/service/public_infer.rs: mock-backend tests for inference/prompt happy path, non-success status, suggest_questions parsing, disabled- local-ai short-circuits for summarize/prompt/suggest_questions/ inline_complete. - voice/schemas.rs: overlay_notify cancelled→released, unknown state errors, missing state errors, server_start handler, TranscribeParams + TtsParams deserialize happy/error paths, server_start all-optional invariant, description completeness. * test(coverage): local_ai HTTP mock tests (49→53%) - ollama_api: ollama_base_url() helper now used by ollama_admin/has_model + ollama_healthy (in addition to public_infer + vision_embed). - public_infer: inference against mock /api/generate happy/error/empty; suggest_questions parses line-separated output; disabled short-circuits for summarize/prompt/suggest/inline_complete. - vision_embed: mock /api/embed with /api/tags preflight; empty-input rejection; disabled short-circuits for embed and vision_prompt. - ollama_admin: has_model matches exact + prefixed tags; errors on 5xx /api/tags; ollama_healthy true on 200 and false on unreachable URL. * test(coverage): more local_ai + voice gains - local_ai/ollama_admin: diagnostics against mock Ollama (unreachable + missing models + all models present), list_models happy/error paths. - voice/dictation_listener: start_if_enabled early-returns for disabled/ empty-hotkey/unparseable-hotkey; normalize_hotkey_for_rdev coverage for Shift+Alt, lowercase, function keys, whitespace trimming. * test(coverage): local_ai schemas handlers + voice flakiness fix - local_ai/schemas: handle_device_profile; handle_presets tier+device shape; handle_apply_preset invalid/custom/valid paths; handle_set_ollama_path nonexistent/empty-to-clear paths. - voice/schemas: relax server_status/stop assertion to tolerate other tests in the same binary having initialised the global voice server (it's a OnceLock, so state is shared across the whole test process). * test(coverage): channels incremental push (71→73%) - presentation.rs: split_sentences, group_sentences, merge_short, segment_delay monotonic/bounded, is_structured_content detection, segment_for_delivery edge cases. - runtime/dispatch.rs: contains_any, starts_with_any, full coverage of select_acknowledgment_reaction across all 7 categories + deterministic + empty/single-char inputs. - commands.rs: doctor_channels with telegram/discord/slack/imessage/ multiple-config branches. - discord/api: check_channel_permissions mock-server tests — admin bypass, all-missing, everyone-allow, channel overwrite deny, member lookup failure. Added check_channel_permissions_at_base seam. - lark: should_refresh_last_recv, LarkChannel::new, is_user_allowed wildcard/empty allowlist, parse_event_payload edge cases (unsupported type / empty sender / missing event / post type). - email_channel: is_sender_allowed full matrix (empty/wildcard/exact/ @-prefix/bare-domain/subdomain-confusion), strip_html empty/tags-only/ unclosed/whitespace collapse. - voice/schemas: tolerate event interleaving in broadcast-channel test (schema bus is process-global). * test(coverage): address review findings — assertions, determinism, observability Tighten assertions so regressions surface: - credentials/ops: assert decrypt migrate path returns Ok - credentials/session_support: assert trimmed profile name directly - computer/mouse: check Err branch in single-axis scroll tests - filesystem/git_operations: assert exact error substrings and verify `git init` success before each test - channels/controllers/ops: exact credential_provider key + concrete parse_allowed_users expectation with accurate normalisation note; merged the three duplicate list/describe tests into existing coverage - tools/impl/browser/screenshot: cfg-branched support-matrix assertions - tools/impl/agent: replace misleading stub test with one that actually exercises dispatch_subagent's graceful-failure paths - local_ai/install: cfg-branched build_install_command expectations - local_ai/service/public_infer: exercise empty-response reject path via inference() (allow_empty=false) and assert the error - screen_intelligence: only take the macOS slow-path skip on macOS Test determinism: - local_ai/install: serialise env mutations via a module Mutex and RAII EnvGuard that restores prior values on drop - composio/ops: poll TCP readiness with backoff before returning the mock-backend URL - memory/global: bind TempDir at test scope so its workspace outlives any lazy-init reference Consistency: - local_ai/service/ollama_admin: route every Ollama HTTP call and the diagnostics URL through ollama_base_url(); drop the stale OLLAMA_BASE_URL import so /api/pull, /api/tags (runner check), /api/show, and the health message all honour the env override Observability: - local_ai/service/vision_embed: tracing::debug at entry/response and tracing::error on send/non-success - local_ai/service/ollama_admin::list_models: entry/response/parse logging including raw body on parse failure - channels/providers/discord/api: tracing::debug with endpoint, status, body, and context before every non-success bail! New coverage: - channels/providers/lark: anchor href-only fallback in parse_post_content - local_ai/ollama_api: five-case env-override suite for ollama_base_url (unset / normal / trimmed / trailing slashes / empty|whitespace) Miscellaneous: - voice/server: OnceCell-backed comment (was OnceLock); drop duplicate initial-status test; supply the HallucinationMode argument to two stale hallucination tests so the crate type-checks |
||
|
|
7ae2bf83b2 |
feat: disable permission auto-prompts + typing indicator on webhook channels (#552)
* feat(config): default screen intelligence, dictation, and vision model off Flip defaults so no macOS TCC permission prompt fires on first run: - `dictation.enabled`: `true` → `false` (was auto-starting rdev::listen, which requests Accessibility/Input Monitoring on macOS) - `screen_intelligence.use_vision_model`: `true` → `false` (fewer surprise vision-model calls; Pass 1 Apple Vision OCR still runs) Aligns all permission-gated auto-starts on a consistent opt-in posture: `screen_intelligence.enabled`, `autocomplete.enabled`, and `voice_server.auto_start` already default to `false`. Users must now explicitly flip each toggle (config or JSON-RPC) before the core triggers any OS permission dialog. * feat(channels): fire typing indicator on webhook-inbound path Two inbound flows exist today and only one fires typing: - Local bot (`channels_config.telegram.bot_token` set) → dispatch.rs already calls `channel.start_typing` + `spawn_scoped_typing_task` - Backend webhook (Telegram → backend → socket.io → core) → `ChannelInboundSubscriber` had **no typing call** — replies route via backend REST, so the local `Channel` trait isn't reachable. Close the gap by going through the backend: - `api/rest.rs`: add `send_channel_typing(channel, jwt, body)` hitting the new `POST /channels/:id/typing` backend route. - `channels/bus.rs`: extract the agent-wait loop into `run_agent_loop` and wrap it with a typing task that fires immediately on `start_chat` success, refreshes every 4s (beats Telegram's ~5s and Discord's ~10s typing TTLs), and cancels on every exit path (done / error / empty / bus-closed / lagged / timeout). Backend failures log at debug — a flaky typing call must never block the reply flow. Generalises to every channel with a backend adapter; adapters without a native typing API no-op gracefully. * Enhance test stability by introducing a Mutex guard for TRIAGE_DISABLED_ENV in tests - Added a static Mutex guard to ensure safe concurrent access to the `TRIAGE_DISABLED_ENV` variable during tests, preventing interleaved set_var/remove_var calls that could lead to spurious failures. - Updated relevant test cases to acquire the Mutex lock when accessing the environment variable, ensuring consistent behavior across concurrent test executions. |
||
|
|
933c233704 |
fix(voice): add hallucination filter to chat voice path (#553) (#556)
* fix(voice): add hallucination filter to chat voice path and improve detector (#553) The chat voice transcription pipeline (ops.rs voice_transcribe_bytes) had no hallucination filtering, unlike the desktop dictation server which has had it since inception. This caused Whisper to inject repetitive garbage text ("it... it... it...", "Thank you. Thank you. Thank you.") into chat voice input, especially on short/silent recordings. Changes: - Extract hallucination detection into shared voice/hallucination.rs module - Add hallucination filter to voice_transcribe_bytes (chat voice path) - Improve detector: strip punctuation before word comparison, add dominant-word ratio check (>40%), catch "it... it... it..." patterns - Add 14 unit tests covering exact match, repetition, ratio, and legitimate speech cases Closes #553 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor(voice): introduce HallucinationMode enum with split pattern lists Split monolithic HALLUCINATION_PATTERNS into ALWAYS_HALLUCINATION (blank-audio, YouTube phrases — filtered in all modes) and DICTATION_ONLY_PATTERNS (single-word noise like "yes", "okay" — filtered only in desktop dictation). Add repeating n-gram detection for looping phrases ("Thank you. Thank you. Thank you.") and raise dominant-word ratio from >40%/3 to >60%/5 to prevent false positives on emphatic speech like "no no no don't do that". Addresses CodeRabbit review on PR #556. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(voice): use Conversation mode for chat, Dictation mode for desktop Wire HallucinationMode into both voice paths: - ops.rs (chat voice): HallucinationMode::Conversation — conservative filtering allows short replies like "yes", "okay", "thank you" - server.rs (desktop dictation): HallucinationMode::Dictation — aggressive filtering drops single-word noise artifacts - Update server.rs hallucination_detection test for new signature Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(voice): redact user transcript content from debug logs Remove raw text interpolation (normalized, first, word, pattern) from hallucination detection debug logs to prevent leaking sensitive speech content. Retain non-PII metadata (repeat counts, ratios, n-gram length) for diagnostics. Addresses CodeRabbit review on PR #556. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |