Compare commits

...

450 Commits

Author SHA1 Message Date
3bd9657041 Improve documentation on dependency validation and environment variables 2026-06-23 13:38:49 +02:00
db8c92a96c Enhance native dependency checks by adding detailed preflight reports and supporting strict system dependency failure. 2026-06-23 13:37:35 +02:00
8a95a4238c Improve SteamOS package installation robustness by adding keyring initialization, retry logic, and devmode bootstrap fallback. 2026-06-23 13:26:33 +02:00
6d1c3f48d6 Adjust error handling when determining SteamOS readonly status in run.sh 2026-06-22 21:02:43 +02:00
5a81190f76 Require sudo password verification and provide specific instructions for SteamOS users 2026-06-22 20:58:41 +02:00
dd333d106b Improve read-only status check and disable logic for SteamOS 2026-06-22 20:58:41 +02:00
ccfd9992c6 Improve README and run.sh by detailing the full dependency bootstrap process and adding a dedicated bootstrap-only execution mode. 2026-06-22 20:54:51 +02:00
4225150bca Enhance runtime dependency management: Added automated checks and local installations for Python 3.13 and the stable Rust toolchain (Cargo/rustc). 2026-06-22 20:54:23 +02:00
62ae20e811 feat(run): Add robust native build dependency detection and installation for Linux/macOS 2026-06-22 20:53:56 +02:00
a3c9d37b18 Improve dependency management in run.sh by adding automatic download, verification, and path setting for required Node.js versions (v18+). 2026-06-22 20:25:05 +02:00
fa0c98eb8d Fix return value in _migrate_entry_to_global when entry is duplicated 2026-06-16 23:40:02 +02:00
e6b9a2db64 Update chat readiness status message from Database to Knowledge 2026-06-16 23:40:02 +02:00
124581744c Deprecate explicit chat database selection components and hooks, standardizing workflow confirmation dialogs to reference 'Knowledge' instead of specific libraries. 2026-06-16 23:38:47 +02:00
adb7ba7f8e Refactor: Rename all database references to Knowledge across backend and frontend services, updating endpoints, workflows, and UI terminology. 2026-06-16 23:38:29 +02:00
65277acd5e auto-git:
[change] src/App.jsx
2026-06-16 23:37:32 +02:00
20c1e34136 Refactor: Simplify sidebar UI by updating database listing and restricting new chat button visibility based on active mode 2026-06-16 23:35:31 +02:00
396f644f33 Removed chat library session management logic from workflow 2026-06-16 23:35:31 +02:00
0492231194 auto-git:
[change] src/App.jsx
2026-06-16 23:33:29 +02:00
d2323e4e88 auto-git:
[change] src/App.jsx
2026-06-16 23:33:29 +02:00
2f4c2e9e40 Remove local library context enrichment from chat generation workflow 2026-06-16 23:32:33 +02:00
77ba8aa771 Refactor local knowledge context API endpoint and update agent reason string 2026-06-16 23:32:33 +02:00
14923a26e6 Standardize saving tools descriptions to reference 'local Knowledge store' 2026-06-16 23:31:59 +02:00
124e8793bb Update knowledge search tool description to use 'local Knowledge store' 2026-06-16 23:31:59 +02:00
f45a4d1a42 Refine global knowledge handling and standardize workflow descriptions 2026-06-16 23:31:59 +02:00
3a79004bdd Enhance local knowledge retrieval (RAG) by initializing global knowledge store and using effective library slugs for workflow runs. 2026-06-16 23:31:24 +02:00
96840911ce Feature: Add API endpoint to save chat messages to global knowledge store 2026-06-16 23:30:45 +02:00
e423bcee1b Refactor: Centralize library management using a global knowledge store, adding dedicated API endpoints for various content types (texts, websites, files) under /knowledge. 2026-06-16 23:30:33 +02:00
0c158a8ed6 Implement logic to migrate local libraries into the centralized knowledge store 2026-06-16 23:30:19 +02:00
887c74b5cb Initialize global library constants and utility functions 2026-06-16 23:30:19 +02:00
48cf1e9844 Refactor chat memory tests to support recent mode and structured searching; adds test for async search handler tool 2026-06-16 19:53:48 +02:00
c9b8c5d0f5 Add dedicated workflows for searching and answering from past chat memories 2026-06-16 19:53:16 +02:00
05e8b0296f Implement chat memory tool and integrate it into agent capabilities 2026-06-16 19:53:16 +02:00
be7e1c7c49 Refactor workflow run logic by removing explicit dependency on chat memory context blocks during execution 2026-06-16 19:52:18 +02:00
872c94351d Refactor: Simplify message construction in chat and regenerate functions by using direct request inputs for enriched messages and sources 2026-06-16 19:51:49 +02:00
1803345957 Refactor: Remove internal helper functions for context processing, source deduplication, and chat memory retrieval 2026-06-16 19:50:09 +02:00
07af68eb11 Refactor chat memory context generation: Simplify deduplication logic, remove minimum score filtering, and introduce explicit context loading modes. 2026-06-16 19:49:57 +02:00
78de35b2cb Refactor chat memory utilities: Update token limits, simplify score calculation, and remove deprecated expansion logic. 2026-06-16 19:49:35 +02:00
57a73d4597 Remove unused stopwords, conversation regex, and query expansions from chat memory module 2026-06-16 19:49:13 +02:00
c18117fb87 Add async tests for chat handler and context fallback handling 2026-06-16 19:14:07 +02:00
abed82924b Add _model_error_summary and _fallback_content_from_context functions 2026-06-16 19:14:01 +02:00
ce21613905 Add _is_probably_html_url utility function 2026-06-16 19:07:53 +02:00
c46854a7b2 Add tests for rerank tool fallback when embedding model is unavailable and rerank tool uses fallback when rerank errors 2026-06-16 19:06:29 +02:00
f0ff7c894b Add fallback rerank logic for web search 2026-06-16 19:06:01 +02:00
da0c694c91 Add RANK_STOPWORDS and fallback rerank logic for missing embeddings 2026-06-16 19:05:57 +02:00
d174d28928 auto-git:
[change] AGENTS.md
2026-06-16 13:21:43 +02:00
6622b4cce7 auto-git:
[change] AGENTS.md
2026-06-16 13:21:43 +02:00
64089af5c3 Refactor chat memory loading to use idiomatic SQLAlchemy ORM queries 2026-06-15 22:58:50 +02:00
9ea61d5e4f Refactor chat memory retrieval to load context from multiple recent sessions using ORM queries; adds option to skip memory-only turns. 2026-06-15 22:58:28 +02:00
964b75d4b7 Refactor chat memory logic to use sources_json for source validation and candidate loading 2026-06-15 22:57:37 +02:00
2aebadb774 Enhance chat memory tests with helper function for sources and verify exclusion of internal memory contexts. 2026-06-15 22:56:55 +02:00
b5f90331e7 Enhance chat turn processing to correctly handle memory-only responses 2026-06-15 22:56:28 +02:00
9ec66c3196 Add comprehensive unit tests to chat memory context building, validating recency and domain-specific scenarios 2026-06-15 22:55:54 +02:00
5da8b3ba6d Refactor RAG and web search logic for improved compatibility checks in runtime 2026-06-15 22:55:54 +02:00
60b32513cf Update workflow runtime logic to correctly prepend compatibility context blocks when RAG or Web features are enabled 2026-06-15 22:55:28 +02:00
854ee51861 Enhance agent API by adding compatibility checks for RAG/Web capabilities and safely parsing required workflow capabilities 2026-06-15 22:55:28 +02:00
ebfa50bf03 Refactor chat memory context loading and implement previous session history retrieval 2026-06-15 22:55:07 +02:00
a5ad7ab261 Improve hit deduplication by enforcing a minimum score threshold 2026-06-15 22:55:07 +02:00
4b0ed88176 Enhance chat memory scoring and token handling by adding expanded query tokens and refining ranking weights. 2026-06-15 22:54:25 +02:00
ebbc19c01d Enhance chat memory NLP by updating stopwords, improving last conversation detection regex, and adding query expansions. 2026-06-15 22:54:10 +02:00
c9a9253c8d Update type hints in backend/main.py by adding Dict import 2026-06-15 22:38:43 +02:00
1097ca46d8 Ensure chat memory schema exists before running core sync functions 2026-06-15 22:37:19 +02:00
a0a103dacd Update chat memory test scenarios with new details 2026-06-15 22:37:19 +02:00
5c578a7b84 Add unit tests for chat memory context building and synchronization 2026-06-15 22:37:19 +02:00
76d066773a Improve source key extraction robustness in chat tools 2026-06-15 22:37:19 +02:00
17e22ec4ef Enhance context handling by ensuring external context is appended to the last user message if not automatically applied during row processing. 2026-06-15 22:35:57 +02:00
a111624c36 Improve context block merging logic in WorkflowRuntime and synchronize session memory after execution 2026-06-15 22:35:25 +02:00
767b45d334 Pass dynamic memory blocks to workflow run payload and sync chat memory upon regeneration 2026-06-15 22:35:25 +02:00
c0904d78f6 Integrate explicit chat memory context into workflow run selection 2026-06-15 22:34:45 +02:00
3294de9471 Sync and clean up chat memory across session management functions 2026-06-15 22:34:45 +02:00
d0c69a4f96 Feat: Integrate persistent chat memory and enhance context management
Adds helper functions to retrieve historical chat memory context (`_chat_memory_context`) and merge enriched messages. Updates both the main chat endpoint and regeneration logic to utilize this context, ensuring conversation continuity and reliable source deduplication.
2026-06-15 22:34:05 +02:00
031588198d feat: Integrate chat memory schema setup and backfill on startup 2026-06-15 22:33:41 +02:00
d9e963ef74 auto-git:
[change] backend/chat_memory.py
2026-06-15 22:33:41 +02:00
d3e7ec56ee auto-git:
[add] backend/chat_memory.py
2026-06-15 22:33:41 +02:00
8616c077cc Improve line sampling deduplication and add robust tests for message digest and prompt construction in router logic 2026-06-15 22:05:23 +02:00
13cfd7518b Implement structured message digestion and attachment summarizing for improved long-context routing. 2026-06-15 22:05:03 +02:00
ec28cc9bff Update get_workflow_events call with specific parameters in tests 2026-06-15 21:54:25 +02:00
63d0937754 Add unit test for interrupted workflow event stream API endpoint 2026-06-15 21:52:57 +02:00
1f482810fb Handle run interruption state and errors across components 2026-06-15 21:52:57 +02:00
117a16aca5 Add explicit 'run_interrupted' event when streaming workflow events 2026-06-15 21:52:29 +02:00
d415dd7ead Test: Validate research evaluator follow-up query constraints 2026-06-15 21:49:59 +02:00
00fe48f04d Enhance evidence evaluation node with stricter guidelines and richer context 2026-06-15 21:48:44 +02:00
7916fbf242 Add test case to ensure limit node preserves sources from merged context 2026-06-15 21:48:25 +02:00
fafd358890 Clean up workflow runtime result by removing 'items' field 2026-06-15 21:48:25 +02:00
58cdc17341 Update tests to reflect refined built-in workflow routing logic 2026-06-15 21:39:32 +02:00
1609e39840 Refine routing descriptions for web-answer and research workflows 2026-06-15 21:39:32 +02:00
a66db9fe71 Refine agent routing instructions to distinguish between web-answer and research workflows 2026-06-15 21:39:02 +02:00
8d53590e95 Add unit tests for chat history cleanup logic 2026-06-15 21:39:02 +02:00
0e65dd3bd6 Update workflow router built-in test assertions for improved coverage of routing logic 2026-06-15 21:37:44 +02:00
c8930fdb70 Refine title generation prompt to enforce stricter constraints and extract concrete subject 2026-06-15 21:37:44 +02:00
bb08eb4a93 Refactor chat handler to drop superseded trailing user messages from history 2026-06-15 21:37:10 +02:00
e2d86ff96a Enhance workflow name detection by checking multiple event payload fields 2026-06-15 21:36:52 +02:00
564623fa91 Refine agent workflow definitions by updating routing descriptions for clarity and better differentiation between core capabilities (chat, RAG, web, research). 2026-06-15 21:36:41 +02:00
3ed74e7e8a Refactor router prompts and update workflow choice display format 2026-06-15 21:36:24 +02:00
36cd49d956 Refine usage guidelines and descriptions for core agent workflows 2026-06-15 21:35:39 +02:00
57ce5a4d1e Refactor router inputs: Remove complex keyword detection for 'fresh info' and simplify forced web manifest selection. 2026-06-15 21:35:27 +02:00
fb944223e9 Enhance router intelligence to detect requests for fresh information (weather, news) and improve web search forcing logic. 2026-06-15 21:34:50 +02:00
e35a29baef Enhance tests for workflow router builtins by validating specific instructional text in the generated prompt and removing cost assertions. 2026-06-15 21:28:38 +02:00
d8c6dc06c6 Update built-in workflow descriptions to clarify usage boundaries (Input->Output, Web Answer, Research) 2026-06-15 21:26:50 +02:00
631d632911 Refine router prompt rules and remove cost display from workflow choices 2026-06-15 21:26:50 +02:00
7e53c27115 Refactor workflow selection logic and abstract prompt generation; adds comprehensive test for follow-up context. 2026-06-15 21:23:34 +02:00
8d70f37d16 Enhance workflow routing logic by improving prompt structure and adding helpers for formatting conversation history and available workflows. 2026-06-15 21:23:22 +02:00
2c5f4f71a3 Feature: Force web answer selection if web search is enabled and primary workflow choice is weak 2026-06-15 21:06:44 +02:00
b3e1130f97 Update workflow run test case to pass None for session ID 2026-06-15 21:06:28 +02:00
8ced33552e Use direct workflow ID when testing workflow runs 2026-06-15 21:05:01 +02:00
32e9e4478e Update test URL in web tool tests 2026-06-15 21:05:01 +02:00
077bf71aa8 Refine query cleaning logic for web tools 2026-06-15 21:05:01 +02:00
d9d696c22c Add web search queries to reference fields 2026-06-15 21:05:01 +02:00
93387e6cec Test: Ensure automatic workflow runs persist router-supplied web search inputs 2026-06-15 21:04:11 +02:00
b3a33a9fb1 Improve assertions and mock checks in workflow router tests 2026-06-15 21:03:55 +02:00
3e0b285764 Refactor web tool unit tests to update query generation and search assertions 2026-06-15 21:03:28 +02:00
d6b8ee71f6 Refactor built-in workflows to use direct web search inputs instead of dedicated query generation nodes 2026-06-15 21:03:05 +02:00
8787c2cf65 Enhance workflow run input handling by merging router results and supporting web search parameters 2026-06-15 21:03:05 +02:00
4da9b7faef Add utilities to clean and resolve multiple web search queries from input samples 2026-06-15 21:02:25 +02:00
5857c0f60c Refine fast path logic in router by enabling early exit for web search and cleaning up text processing 2026-06-15 21:02:25 +02:00
0270a65ab3 Refactor input processing: Normalize web search queries and simplify fast path logic in router. 2026-06-15 21:01:58 +02:00
5dd5514fc4 Refactor web tools: Simplify query processing, remove complex topic matching, and standardize noise result filtering. 2026-06-15 21:01:36 +02:00
505085fb87 Test: Improve coverage for web tool queries, ensuring accurate transformation and searching for specific topics. 2026-06-15 20:58:16 +02:00
c5b8e5a087 Enhance web tool queries by adding temporal terms and refactoring fallback query generation logic 2026-06-15 20:58:05 +02:00
9c368b97c5 Improve agent reliability by implementing evidence-first chat grounding, expanding search vocabulary, refining research question formulation, and adding comprehensive query generation tests. 2026-06-15 20:56:06 +02:00
ba51bb9a1b Enhance query terms and add specialized aliases for better lookup coverage 2026-06-15 20:55:47 +02:00
bb80610a3c Test: Add comprehensive unit tests for web tools, ensuring robust filtering of noise, generic terms, and irrelevant content during query generation, searching, fetching, and re-ranking. 2026-06-15 20:48:14 +02:00
7b07b344e9 Enhance web toolchain robustness with advanced filtering, topic matching, and refined query generation. 2026-06-15 20:46:44 +02:00
a3abc68d70 Update workflow test cases and refine web search toggle labels 2026-06-15 20:41:43 +02:00
9aac9ccb2b Refactor: Update and improve unit tests for workflow router builtins 2026-06-15 20:40:34 +02:00
fb33c291ea Refactor workflow selection logic: Improves manifest prioritization for combined web/knowledge answers and updates the 'web' capability check to be unconditional. Also enhances context logging to differentiate between forced and automatic web search modes. 2026-06-15 20:40:05 +02:00
f45f9dbfe5 Add unit tests for web fetching tools 2026-06-15 20:35:18 +02:00
8f74205db6 Increase URL limit, enforce text truncation limit, and use full content for hashing in web fetch tool 2026-06-15 20:35:18 +02:00
6e951f6ec8 Update chat workflow mode display using workflowSelectionMode 2026-06-15 20:31:00 +02:00
79c6cee413 Refine regex patterns for extracting content from remember/save commands 2026-06-15 20:29:49 +02:00
ebf90ecd8e Improve target message handling for "remember-this" workflows 2026-06-15 20:29:49 +02:00
c904831bd6 auto-git:
[change] backend/tests/test_workflow_router_builtins.py
2026-06-15 20:29:48 +02:00
8b37a8ef58 Enhance workflow router tests to cover web search scenarios and validate fast path permissions 2026-06-15 20:28:49 +02:00
83cde1011a Feat: Implement workflow selection mode handling in client settings 2026-06-15 20:28:38 +02:00
71d61931cd Feature: Add workflow selection mode settings and normalization 2026-06-15 20:28:38 +02:00
26eaac5d59 Normalize chat workflow selections to reset invalid or outdated explicit choices to 'direct' 2026-06-15 20:28:24 +02:00
3e37697d12 Restrict workflow selection modes to direct or explicit workflows, removing automatic mode support 2026-06-15 20:28:24 +02:00
33e829f6d8 Implement effective workflow selection logic in chat generation handlers 2026-06-15 20:27:49 +02:00
3206613cc0 Pass workflow selection mode change handler when creating a new chat 2026-06-15 20:27:49 +02:00
443b546ad5 Add handler for workflow selection mode changes to SettingsPanel 2026-06-15 20:27:49 +02:00
8519b2feca Conditionally render WorkflowSelector when in manual mode 2026-06-15 20:27:11 +02:00
c3b572be0d Introduce workflow selection mode state management 2026-06-15 20:27:11 +02:00
c420f018f4 Feat: Add workflow selection mode setting (Auto/Manual) 2026-06-15 20:26:58 +02:00
983081eccd Improve prompt generation by handling long messages and dynamic history context 2026-06-15 20:26:48 +02:00
bd2c003965 Pass edited message content when saving to knowledge 2026-06-15 20:26:48 +02:00
3fd2cf4910 auto-git:
[change] backend/agent/validation.py
2026-06-15 20:26:48 +02:00
236d2d8962 auto-git:
[change] backend/agent/api.py
 [change] backend/agent/schemas.py
2026-06-15 20:26:48 +02:00
f2644ce3cd Enhance workflow run context by passing target message content and improving 'remember-this' logic 2026-06-15 20:26:02 +02:00
3f23d22e6b Implement content extraction for 'remember' and 'save' messages 2026-06-15 20:25:44 +02:00
0e7f54dbb6 Pass web search status when selecting a workflow 2026-06-15 20:25:44 +02:00
043e40b0aa Add web search enablement flag to workflow selection parameters 2026-06-15 20:25:44 +02:00
024bffecd1 Enhance workflow selection logic by implementing fast-path detection and improving manifest filtering based on capabilities, attachments, and keywords. 2026-06-15 20:25:21 +02:00
43e329e599 Style workflow list items (ellipsis, min-width fix) 2026-06-15 16:55:01 +02:00
7fbfe215af Improve workflow list and sidebar styling
Updates include restructuring the main workflows container, enhancing the visual appearance of individual workflow items in the sidebar (adding borders, background colors, and spacing), and adjusting responsive layout rules.
2026-06-15 16:54:53 +02:00
35b0c633c3 Refactor WorkflowsArea component to manage state externally via props, simplifying local logic and API interactions. 2026-06-15 16:54:36 +02:00
ae7b78e12b Feature: Implement WorkflowList component and update WorkflowsArea props in App.jsx 2026-06-15 16:54:26 +02:00
65204cda5e Implement workflow selection, creation, duplication, and deletion logic in App component 2026-06-15 16:54:03 +02:00
2c219b3e0c Refactor data fetching: Load workflows and tools concurrently in App component 2026-06-15 16:53:56 +02:00
2c2543b0d1 Feature: Implement core workflow management features (create, delete, duplicate) and define default workflow graph schema in App component 2026-06-15 16:53:46 +02:00
fd1f31ee76 Refactor knowledge search handler to use multiprocessing for isolated context retrieval and improved stability. 2026-06-15 15:50:55 +02:00
604a16d73c Refresh libraries and jobs upon successful Heimgeist save event 2026-06-15 15:49:48 +02:00
7cc9c07612 Remove file count check for disabling chat database picker option 2026-06-15 15:49:13 +02:00
6257cf0912 Update json module usage in workflow API tests 2026-06-15 15:48:00 +02:00
6ebd8b869e Test: Validate workflow run targets source URLs and previous assistant messages 2026-06-15 15:46:53 +02:00
c7eed48fce Improve context handling for workflow runs by auto-detecting target URLs and setting the previous assistant message as the default target ID. 2026-06-15 15:46:38 +02:00
f0edcbccd5 Update session state when a new client run begins 2026-06-15 15:45:36 +02:00
e274c09ae5 Refactor built-in workflows to use conditional branching for message and website saving success/failure states 2026-06-15 15:39:36 +02:00
3a9eb10886 config: Use default environment variable for desktop backend API URL 2026-06-15 15:33:46 +02:00
291f5fe5d0 test(workflow): Use UUIDs for generating unique workflow slugs in tests 2026-06-15 15:33:46 +02:00
0a42dc8a2d feat(tests): Add comprehensive tests for workflow API and runtime execution 2026-06-15 15:33:46 +02:00
6450614c5b Enhance workflow state tracking by passing and utilizing selection mode in agent runtimes 2026-06-15 15:32:14 +02:00
b1eed9f1b6 Refactor chat generation handlers to use a centralized executeWorkflowRun utility for managing complex workflow execution, state updates, and event streaming. 2026-06-15 15:31:35 +02:00
dae2ce0f9d Implement message regeneration feature for workflow runs 2026-06-15 15:30:52 +02:00
f562fd5c01 Fix runtime session check and standardize workflow edge handles in editor 2026-06-15 15:30:51 +02:00
8a0d825274 fix(agent/registry): Improve tool execution timeout and cancellation handling 2026-06-15 15:24:58 +02:00
d3ddefdc27 feat(tests): Add comprehensive unit tests for agent components (registry, router, runtime, validation) 2026-06-15 15:24:58 +02:00
c1f3935cf5 Integrate workflow router model into chat generation handlers and App component 2026-06-15 15:23:26 +02:00
2b29952835 feat(styles): Add comprehensive CSS styling for workflow visualization and components 2026-06-15 15:21:21 +02:00
b04c3a8ac3 Enhance source chip generation to robustly handle object sources, utilizing title and snippet fields. 2026-06-15 15:20:23 +02:00
2271022378 Feature: Implement Workflow Router Model setting across UI and API 2026-06-15 15:20:06 +02:00
31027a4c9c Feature: Integrate comprehensive workflow support into the chat editor, including sidebar navigation, execution panels, and confirmation dialogs. 2026-06-15 15:19:28 +02:00
20e5ae68bd Implement workflow run event handling and update chat state accordingly 2026-06-15 15:19:08 +02:00
2c5a5048dc Enhance request management by adding functionality to track and cancel associated backend workflows. 2026-06-15 15:18:59 +02:00
52b9daba19 Load available workflows from backend API 2026-06-15 15:18:51 +02:00
7fbd3ed3c7 Add local state for managing workflows 2026-06-15 15:18:51 +02:00
9122f82161 Implement chat workflow selection context 2026-06-15 15:18:51 +02:00
4e33a6961d Feat: Implement workflow selection and execution panel 2026-06-15 15:18:07 +02:00
a76803df8c feat(chat): Integrate workflow execution into chat generation flow 2026-06-15 15:17:45 +02:00
2c2e712ba8 feat(workflows): Implement core workflow editor components (canvas, inspector, palette) 2026-06-15 15:17:45 +02:00
920888b336 Feature: Implement comprehensive workflow management system (selection, execution panel, and API wrappers) 2026-06-15 15:15:59 +02:00
8207b1d2e1 Add xyflow react dependency 2026-06-15 15:14:08 +02:00
84a845948b Pass maximum tool calls limit to workflow runtime 2026-06-15 15:14:08 +02:00
e783885503 feat(integration): Integrate agent workflows into main backend and enhance message history tracking 2026-06-15 15:12:58 +02:00
c62152353c feat(agent): Implement core API endpoints for workflow management and execution 2026-06-15 15:12:58 +02:00
97729f4ce8 feat(agent): Implement core workflow runtime logic and event logging 2026-06-15 15:11:41 +02:00
efe4cc0875 Implement intelligent router to select the appropriate agent workflow based on user intent 2026-06-15 15:08:18 +02:00
0376ab8eed Introduce core built-in workflows (Web, Knowledge, Vision, Research) and workflow seeding logic 2026-06-15 15:08:18 +02:00
48cf63d535 Add tools for knowledge persistence (saving messages/websites) and visual attachment analysis. 2026-06-15 15:05:51 +02:00
b2f1aeba42 Implement comprehensive web tools for searching, fetching content, and context reranking. 2026-06-15 15:05:51 +02:00
97366bb8e0 Implement core agent tooling infrastructure (chat, knowledge search) and update tool registration 2026-06-15 15:04:04 +02:00
0c04d5bf7d Add asyncio import to ollama_client 2026-06-15 15:04:04 +02:00
3593117736 Update Ollama client to support typed results, structured tool calling, and detailed usage tracking. 2026-06-15 15:02:39 +02:00
f8325e5458 Introduce core agent framework components: workflow persistence models, tool registry system, and reference binding logic. 2026-06-15 15:02:39 +02:00
f43976f167 Feature: Integrate workflow tracking and agent metadata to chat messages 2026-06-15 14:58:37 +02:00
a6ba0db6ff Refactor video download logic to use httpx instead of requests 2026-06-15 06:20:00 +02:00
a15e068f42 Add styles for video sources/thumbnails in library view, and update chat message card borders 2026-06-15 06:18:09 +02:00
e9e7df7e20 Feat: Enhance library management features
- Adds strict HTTP/HTTPS validation when creating library websites.
- Improves summary cleanup in video ingestion by removing thinking tags and prefixes.
- Updates LibraryManager UI to display comprehensive metadata (ID, provider, upload date, character count, etc.) and improves video source handling.
2026-06-15 06:18:01 +02:00
5df2871c6f Update build process to collect Whisper modules and add styling for video content in the library view 2026-06-15 06:15:19 +02:00
a07870c82c Feat: Add robust support for video content in LibraryManager
Updates the library manager to handle videos alongside websites and text. This includes updating input fields, adding dedicated video summary metadata display (transcription details), expanding searchable content types, and providing specific action buttons for opening or reprocessing video items.
2026-06-15 06:15:07 +02:00
0fa4be73da Feature: Add support for video handling and refreshing in LibraryManager 2026-06-15 06:14:50 +02:00
14986260f0 Feature: Add full video support to library management
Integrates video processing into the local RAG system, allowing users to ingest videos via URL.

This includes:
- Updating content type handling for 'video' across item signatures and content extraction.
- Implementing video ingestion logic within the website creation endpoint.
- Adding a dedicated endpoint to refresh and update metadata for existing video items.
2026-06-15 06:13:46 +02:00
bb2e0c08e2 Feat(video): Implement full video ingestion pipeline using yt-dlp, Whisper transcription, and LLM summarization; updates Ollama client to support options. 2026-06-15 06:13:06 +02:00
912c63468b Refactor: Clean up formatting for autoDeepEnrichment variable assignment 2026-06-15 04:42:51 +02:00
88c4a5b0d4 Feat: Add automatic deep enrichment feature
Implements logic and UI for automatically queuing deep enrichment (Q&A generation) after content indexing, updating settings across backend, frontend, and desktop layers.
2026-06-15 04:41:31 +02:00
36b6b84129 Fix KMP duplicate lib error on macOS for dependencies (PyTorch/FAISS) 2026-06-15 04:07:37 +02:00
4db6fde9be Feature: Implement knowledge base saving for chat messages
Adds functionality to save selected chat messages into an external knowledge database, including new dialog components, state management in App.jsx, updated history syncing, and necessary UI/UX improvements.
2026-06-15 03:53:44 +02:00
d0e5c9300c Feature: Add full support for handling, indexing, and saving chat message content to the knowledge base. 2026-06-15 03:51:56 +02:00
937cd3c6f4 Refactor: Simplify formatting for model setting definitions across default, migration, and normalization functions 2026-06-15 02:43:34 +02:00
c4956fa69e Introduce metadata versioning and upgrade logic for local library reading 2026-06-15 02:43:17 +02:00
d3c4f45501 Feature: Implement Knowledge Metadata Model and enhance library item display with rich metadata (Q&A, model details) 2026-06-15 02:42:47 +02:00
bfb7f870c6 Feat: Add and integrate enrichment model support across backend and frontend 2026-06-15 02:42:18 +02:00
26ef19f4c6 Clear query locks during library purge and deletion 2026-06-15 02:18:13 +02:00
730c6be2cb Implement query locking for local RAG context retrieval 2026-06-15 02:16:07 +02:00
7b42e25135 Enhance RAG corpus enrichment: Update prompt version, improve response validation, increase token limits, and refactor data normalization logic. 2026-06-15 02:11:20 +02:00
90a994f72e Display metadata generation error when status is 'failed' 2026-06-15 02:09:55 +02:00
74958a5336 Improve metadata status tracking and failure handling in local RAG pipeline 2026-06-15 02:08:36 +02:00
32112ddbb6 Only mark text as short if QA enrichment is disabled 2026-06-15 02:08:36 +02:00
55a4e7ce28 Enhance metadata display and refine item readiness status in LibraryManager 2026-06-15 02:05:35 +02:00
d7cf6f3fc4 Feat(Library): Enhance metadata handling and display
Improves search filtering to include summary, headline, keywords, and entities from item metadata.
Adds comprehensive metadata display (summary, chips, entities) on content cards.
Introduces deep enrichment status indicators and adds functionality to trigger metadata generation.
2026-06-15 02:05:22 +02:00
d98bd71a5d Refactor RAG payload generation to use explicit metadata tracking and initialize metadata status in library functions 2026-06-15 02:04:03 +02:00
973e8ba219 Enhance RAG pipeline by implementing robust metadata persistence, extracting detailed information (summary, keywords, entities) into the enhanced corpus record. 2026-06-15 02:03:48 +02:00
1758a27a31 Improve RAG prompt instructions for Q&A and refine processing levels in cache 2026-06-15 02:03:07 +02:00
1c7e5f0691 Feat(RAG): Make QA generation optional and support 'deep' source paths for enrichment 2026-06-15 02:02:53 +02:00
e1f3aaeec1 Manage content preview state by clearing selected/edited item from previews and collapsing expansion view. 2026-06-15 01:26:59 +02:00
7edccc90a3 Reset expanded item and content preview state when library details change 2026-06-15 01:26:46 +02:00
4a624d2d30 Feat: Implement detailed content previews for library items
Adds functionality to display rich content previews (including truncated or extracted RAG text) when viewing a library item, updating backend indexing and frontend rendering accordingly.
2026-06-15 01:25:34 +02:00
9c84076a85 Update prepare job condition to check for indexed status in payload 2026-06-15 01:24:04 +02:00
b05562a2de Simplify job state checks for marking files ready and triggering preparation steps 2026-06-15 01:22:53 +02:00
b45117c52d Improve source URI handling in local RAG context by deduplicating sources 2026-06-15 01:22:53 +02:00
fd84748450 Improve RAG index building and local rag processing
- Implement robust chunking for oversized text in index_builder.
- Prevent job preparation in local_rag if source data contains failed sync items.
2026-06-15 01:21:19 +02:00
cbe30c6ccb Refactor list_libraries to async and ensure background preparation jobs are running before listing libraries 2026-06-15 01:19:17 +02:00
a5142e6dd0 Refactor local_rag to conditionally include item metadata (item_id, kind, title, url) only for managed or text/website content types 2026-06-15 01:17:03 +02:00
ec08af4640 Improve change detection and enhance content extraction logic 2026-06-15 01:15:42 +02:00
9a4f4c7c2b Feat: Overhaul LibraryManager to support diverse content types (text, websites) and implement a unified search/display grid. 2026-06-15 01:14:47 +02:00
3e35ea96ec Add httpx dependency to backend/local_rag.py 2026-06-15 01:14:09 +02:00
c7f904ed01 Implement API endpoints and utilities for managing text and website content within the local RAG system, including web snapshot fetching and metadata updates. 2026-06-15 01:13:00 +02:00
2254a2b7d6 Update Tauri migration documentation for packaged builds, detailing macOS sidecar setup and production readiness steps. 2026-05-06 07:06:00 +02:00
b9d59f531d Refine backend architecture for packaged builds and sidecar deployment 2026-05-06 07:05:47 +02:00
e4fb6a38eb Update README with detailed local macOS packaging guide and adjust file structure for sidecar and scripts 2026-05-06 07:05:17 +02:00
ce3a216242 Implement graceful shutdown for backend sidecar on exit 2026-05-06 07:03:35 +02:00
45ea3f64ab Implement robust cleanup and process tree termination for backend sidecar 2026-05-06 07:03:26 +02:00
c918e61946 Make ffmpeg and ffprobe bundling mandatory and robust 2026-05-06 06:57:53 +02:00
161d0c12aa Improve cross-platform path resolution for bundled executables 2026-05-06 06:52:08 +02:00
0ab5011c22 Add heimgeist-ffprobe to external binaries list 2026-05-06 06:52:08 +02:00
b65f82b48d Format logging message for backend sidecar check 2026-05-06 06:50:09 +02:00
20fd5ddc4b Implement backend sidecar management and health checks 2026-05-06 06:47:19 +02:00
caaf7e6c79 Integrate backend sidecar process and external binaries into the Tauri build 2026-05-06 06:46:27 +02:00
dc8df4a8ab Docs: Centralize and document data path management for packaged builds 2026-05-06 06:14:23 +02:00
ef1ecd463b Refactor path management and configuration utilities 2026-05-06 06:13:56 +02:00
0f0a82b798 Improve exit handling when already shutting down 2026-05-06 06:04:16 +02:00
17ab1fc236 Update diagnostic setting description in InterfaceSettings 2026-05-06 06:02:18 +02:00
cb228ae7aa Format update status functions in main.rs 2026-05-06 06:01:00 +02:00
0f5aec3d1c Update documentation and code strings to reflect production release phase 2026-05-06 06:01:00 +02:00
8946f26813 auto-git:
[change] AGENTS.md
 [change] README.md
 [change] docs/tauri-migration.md
2026-05-06 06:00:20 +02:00
514fde9cad Refactor settings import to use legacy/Heimgeist settings instead of Electron settings 2026-05-06 05:59:08 +02:00
f2abb9121d Refactor desktop API to use Tauri commands exclusively 2026-05-06 05:59:00 +02:00
b085239fe5 auto-git:
[change] package.json
 [change] run.sh
 [change] src-tauri/tauri.conf.json
 [unlink] electron/main.cjs
 [unlink] electron/preload.cjs
 [unlink] scripts/run-electron-dev.cjs
2026-05-06 05:58:48 +02:00
e61c91b69e Enhance process termination logic for child processes 2026-05-06 05:44:28 +02:00
0ab2c39d9b Refactor: Simplify product name retrieval and improve logging readability in main.rs 2026-05-06 05:41:19 +02:00
cbc1c34ced auto-git:
[change] AGENTS.md
 [change] docs/tauri-migration.md
2026-05-06 05:41:07 +02:00
7142cf6395 Update process exit logic when handling termination signals 2026-05-06 05:40:48 +02:00
2e7b438b66 Feature: Implement and apply UI scale settings across the application 2026-05-06 05:39:25 +02:00
7e5238a3c8 Improve settings file detection and loading logic to support explicit environment variables and Electron compatibility. Initializes the application menu. 2026-05-06 05:39:12 +02:00
fe25e6184d Refactor and update Tauri development scripts and configuration 2026-05-06 05:38:55 +02:00
07c74af3a2 Update documentation regarding Tauri migration parity gaps 2026-05-06 05:28:54 +02:00
25bb5b2be9 Refactor settings loading to correctly handle missing files and simplify write condition 2026-05-06 05:25:15 +02:00
4767101595 Update Tauri migration documentation and scaffold 2026-05-06 05:22:24 +02:00
76825289d7 Style: Improve code formatting and readability across settings initialization and logic 2026-05-06 05:21:43 +02:00
570cc67725 auto-git:
[change] src-tauri/Cargo.toml
 [change] src-tauri/capabilities/default.json
 [change] src-tauri/src/main.rs
 [change] src/desktop/desktopApi.js
2026-05-06 05:21:04 +02:00
3c4a49b38c Update documentation on running the Tauri spike environment 2026-05-06 05:04:48 +02:00
2760380430 Update placeholder icon image 2026-05-06 04:59:46 +02:00
fb3e498574 auto-git:
[change] docs/tauri-migration.md
2026-05-06 04:59:08 +02:00
b454810c85 auto-git:
[add] src-tauri/icons/
2026-05-06 04:59:01 +02:00
456bb8de97 auto-git:
[change] src-tauri/tauri.conf.json
2026-05-06 04:58:32 +02:00
ad552dc1ac Add Tauri development and build scripts 2026-05-06 04:57:50 +02:00
8c5dfb3eac auto-git:
[change] package.json
2026-05-06 04:56:36 +02:00
81daab141c auto-git:
[add] docs/
 [add] src-tauri/
 [change] src/desktop/desktopApi.js
2026-05-06 04:56:36 +02:00
08a7c78af6 Add comprehensive project documentation (AGENTS.md) 2026-05-06 04:46:50 +02:00
906f731557 Refactor: Remove optional chaining when calling desktopApi methods 2026-05-06 04:42:44 +02:00
672b51a28d Integrate desktop API module across multiple components and hooks 2026-05-06 04:41:11 +02:00
bb2b929d27 auto-git:
[change] src/App.jsx
 [change] src/AssistantMessageContent.jsx
 [change] src/GeneralSettings.jsx
 [change] src/InterfaceSettings.jsx
 [change] src/LibraryManager.jsx
 [change] src/WebsearchSettings.jsx
 [change] src/main.jsx
 [change] src/useChatScroll.js
2026-05-06 04:40:01 +02:00
cfbae8378f Update App component to use desktopApi for all Electron interactions 2026-05-06 04:39:39 +02:00
15eba38375 auto-git:
[change] src/App.jsx
2026-05-06 04:39:03 +02:00
e2065b3231 auto-git:
[change] src/App.jsx
2026-05-06 04:38:57 +02:00
4773f01a76 auto-git:
[add] src/desktop/
2026-05-06 04:38:34 +02:00
01b0763478 Extract chat generation handlers logic 2026-05-06 03:52:53 +02:00
a0989b5b3e auto-git:
[change] src/App.jsx
2026-05-06 03:52:36 +02:00
789ef97404 Refactor: Remove message sending logic and add web search toggle 2026-05-06 03:52:29 +02:00
46c1a85710 Remove chat message regeneration logic 2026-05-06 03:52:15 +02:00
a89dd5e13d auto-git:
[change] src/App.jsx
2026-05-06 03:51:43 +02:00
54048acdcd auto-git:
[add] src/chatGeneration.js
 [change] src/App.jsx
2026-05-06 03:51:17 +02:00
3440b48c8c Refactor API calls to use dedicated helper functions for web search context, chat messaging, and title generation 2026-05-06 03:49:12 +02:00
34da4bd6c5 Refactor API calls for web search context and message regeneration 2026-05-06 03:48:50 +02:00
4408a01126 Pass backendApiUrl to various API fetching functions for consistent endpoint usage 2026-05-06 03:48:26 +02:00
5e616dd302 auto-git:
[change] src/App.jsx
2026-05-06 03:48:15 +02:00
6f1a7383e9 Add chat API service functions 2026-05-06 03:48:02 +02:00
ace78e205a Refactor: Simplify pending scroll handling when creating a new chat session 2026-05-06 03:47:02 +02:00
4cab0caa83 Remove chat drag enter event handler 2026-05-06 03:46:46 +02:00
c40bdb1223 auto-git:
[change] src/App.jsx
2026-05-06 03:46:05 +02:00
f8d215679a Refactor: Clean up chat state management by removing obsolete scroll and session tracking logic 2026-05-06 03:46:05 +02:00
cf591c91d1 Integrates and utilizes the new scroll management hook across the component, enabling persistent and accurate chat scrolling behavior. 2026-05-06 03:45:56 +02:00
2af1fee98a auto-git:
[change] src/App.jsx
2026-05-06 03:45:27 +02:00
86bb1d0cf2 auto-git:
[add] src/useChatScroll.js
 [change] src/App.jsx
2026-05-06 03:45:14 +02:00
f724bf764d Remove redundant audio recording lifecycle hooks in App.jsx 2026-05-06 03:43:37 +02:00
3b3b613ed6 Remove microphone recording and audio transcription functionality 2026-05-06 03:43:18 +02:00
ccfc67503b Remove audio input runtime status synchronization function 2026-05-06 03:42:37 +02:00
eaf2831cd7 Refactor audio input state management using a dedicated hook 2026-05-06 03:42:28 +02:00
0b4f5b4066 Refactors audio handling by introducing a custom useAudio hook to manage the state and lifecycle of audio recording and playback, improving component modularity and reusability. 2026-05-06 03:42:19 +02:00
39f885a1a9 Refactor: Extract database picker UI into ChatDatabasePicker component and update state management logic 2026-05-06 03:40:47 +02:00
d53ec76560 Refactor: Remove complex state management and derived logic for chat libraries and database picker components. 2026-05-06 03:40:20 +02:00
826b4254bf Integrate chat library selection logic into App component 2026-05-06 03:39:55 +02:00
39e0f3e899 Refactor: Remove redundant local storage state and refs for database picker 2026-05-06 03:39:49 +02:00
bd316e6805 auto-git:
[add] src/ChatDatabasePicker.jsx
 [add] src/useChatLibrarySelection.js
 [change] src/App.jsx
2026-05-06 03:39:28 +02:00
82d7faabf3 Refactor settings view in App.jsx using SettingsPanel and SettingsSidebar components 2026-05-06 03:38:54 +02:00
e27c95c32b auto-git:
[add] src/SettingsPanels.jsx
 [change] src/App.jsx
2026-05-06 03:38:04 +02:00
672cd12a92 Remove generated dist/index.html file 2026-05-06 03:32:26 +02:00
e67f856143 auto-git:
[change] src/App.jsx
2026-05-06 03:32:06 +02:00
c4c256f7c4 Extract backend API utilities into src/backendApi.js 2026-05-06 03:31:03 +02:00
b142e58723 auto-git:
[change] dist/index.html
 [change] src/App.jsx
2026-05-06 03:30:39 +02:00
5e2b6eb57a auto-git:
[change] dist/index.html
2026-05-06 03:28:54 +02:00
8ac85274dc auto-git:
[change] src/App.jsx
2026-05-06 03:25:39 +02:00
5268ec4607 auto-git:
[add] src/AssistantMessageContent.jsx
 [add] src/appConfig.js
 [add] src/attachments.jsx
 [add] src/chatText.js
 [add] src/modelPicker.js
2026-05-06 03:25:28 +02:00
4f6771e787 Update backend and frontend assets for chat session handling 2026-04-17 14:52:51 +02:00
b5e1bc9a68 Rename variable for clarity in image attachment check 2026-04-17 13:08:09 +02:00
43c6f6360b Add image attachment check before sending message 2026-04-17 13:08:09 +02:00
0ea3bfc14b Add function to normalize chat attachments and raise exceptions for invalid types 2026-04-17 13:06:35 +02:00
7d82ef1acf Handle client-side errors in message sending and update UI accordingly 2026-04-17 13:06:06 +02:00
47eaded702 Add attachment menu styles 2026-04-17 13:05:24 +02:00
a9d75cc4b7 Rename image-attach-toggle to attachment-toggle in styles.css 2026-04-17 13:05:16 +02:00
b97108ed25 Update attachment styles and add file attachment card 2026-04-17 13:05:11 +02:00
b11953ef1e Simplify chat drag logic 2026-04-17 13:05:11 +02:00
aac254ec23 Show error alert in sendMessage function 2026-04-17 13:05:11 +02:00
cecbc24f26 Enhance attachment menu and toggle button in App.jsx 2026-04-17 13:03:56 +02:00
ab2424dbd8 Replace ImageAttachmentStrip with AttachmentStrip in App.jsx 2026-04-17 13:03:56 +02:00
f34aa9b150 Update message sending logic to handle attachments and errors 2026-04-17 13:03:14 +02:00
8f018ce17e Include vision and transcription models in API requests 2026-04-17 13:03:09 +02:00
ab93e921d4 Update attachment handling in sendMessage function 2026-04-17 13:03:09 +02:00
4de740ca62 Update model handling in regenerateFromIndex function 2026-04-17 13:02:44 +02:00
599e0156df Update drag and drop logic for chat files 2026-04-17 13:02:31 +02:00
9ba5380705 Add event listeners for attachment menu in App.jsx 2026-04-17 13:01:55 +02:00
d7cbc57563 Add logic to fetch and set chat model capabilities 2026-04-17 13:01:50 +02:00
7c3c746fac Enhance attachment handling with file picker and drag-and-drop support 2026-04-17 13:01:45 +02:00
40945a1a5e Add state for attachment menu and update model support logic 2026-04-17 13:01:44 +02:00
cb8c364b6f Enhance attachment handling in App.jsx 2026-04-17 13:01:07 +02:00
b627c51f7d Enhance pick-paths functionality with options for filters and title 2026-04-17 12:59:37 +02:00
d5a4ab8417 Add functions to build Ollama messages and update chat handling logic 2026-04-17 12:59:31 +02:00
4b3d510bcf Refactor attachment handling and add support for file attachments 2026-04-17 12:54:55 +02:00
67195af4c1 Rename ImageAttachment to ChatAttachment and add new fields 2026-04-17 12:51:50 +02:00
1c80ca4a06 Update index.html and remove unused CSS file 2026-04-17 10:53:21 +02:00
8459ab1837 Add model reference and update vision model check 2026-04-17 10:51:18 +02:00
473ea4ac85 Add styles for chat header and model picker 2026-04-17 10:49:14 +02:00
729fa419d7 Update GeneralSettings.jsx to handle vision model changes 2026-04-17 10:48:51 +02:00
82f89c9211 Refactor chat header to include model picker in App.jsx 2026-04-17 10:48:46 +02:00
604025efb5 Add activeChatSession and chatModelPickerOptions useMemo hooks in App.jsx 2026-04-17 10:48:45 +02:00
791af40503 Add click outside functionality to chat model picker and close on session change 2026-04-17 10:48:16 +02:00
e368d21128 Add model catalog loading effect in App.jsx 2026-04-17 10:48:10 +02:00
0b71e9eb3a Add functions to sync vision model from chat model and handle chat model selection 2026-04-17 10:48:06 +02:00
4ea55457a5 Add model picker options and state management in App.jsx 2026-04-17 10:48:01 +02:00
ccd930f11d auto-git:
[change] dist/index.html
 [unlink] dist/assets/index-CY4Ajh2W.js
2026-04-17 10:33:45 +02:00
50827fd8cf Refactor chat title sanitization logic in backend and frontend 2026-04-17 10:33:44 +02:00
3f3377118c auto-git:
[add] dist/assets/index-CY4Ajh2W.js
 [add] dist/assets/index-DI47K8n5.css
 [change] dist/index.html
 [unlink] dist/assets/index-BFOWWhCS.css
 [unlink] dist/assets/index-MTrbilRB.js
2026-04-17 10:24:48 +02:00
9849ba54ed Update GeneralSettings.jsx to adjust error and loading conditions 2026-04-17 10:24:45 +02:00
5c00010b0a Add styles for changelog panel and list 2026-04-17 10:22:55 +02:00
cb872e0227 Implement changelog functionality in GeneralSettings.jsx 2026-04-17 10:22:50 +02:00
4857eee154 Add getChangelogPage to preload.cjs 2026-04-17 10:22:50 +02:00
6e9ae778f1 Add changelog retrieval functionality in electron/main.cjs 2026-04-17 10:21:58 +02:00
363fb2aba1 auto-git:
[add] dist/assets/index-MTrbilRB.js
 [change] dist/index.html
 [unlink] dist/assets/index-D_Wipza2.js
2026-04-17 09:07:25 +02:00
d85a68ed3c Update GeneralSettings.jsx to handle 'General' panel changes 2026-04-17 09:07:25 +02:00
2cbb4544b0 auto-git:
[add] dist/assets/index-D_Wipza2.js
 [change] dist/index.html
 [change] src/App.jsx
 [unlink] dist/assets/index-CeOPmacy.js
2026-04-17 09:06:15 +02:00
89976f656d Refactor GeneralSettings.jsx to organize settings by panel and improve UI structure 2026-04-17 09:02:37 +02:00
89a85a561f Remove unused backend URL and stream toggle handlers in GeneralSettings.jsx 2026-04-17 09:00:58 +02:00
8091b054c1 Update GeneralSettings.jsx to conditionally load model catalog and handle panel changes 2026-04-17 09:00:50 +02:00
8c5b8c404c Simplify GeneralSettings component by removing unused variables and props 2026-04-17 09:00:25 +02:00
f06864c72b Add backend and Ollama API URL settings in WebsearchSettings.jsx 2026-04-17 09:00:04 +02:00
b7f62ce884 Add stream output toggle in InterfaceSettings 2026-04-17 08:59:47 +02:00
088be29a8d Update settings submenu and audio input default state 2026-04-17 08:59:43 +02:00
ac427bc99f auto-git:
[add] dist/assets/index-CeOPmacy.js
 [change] dist/index.html
 [unlink] dist/assets/index-Bt01BsHn.js
2026-04-17 08:48:28 +02:00
e332515585 Update model catalog fetching and loading state handling 2026-04-17 08:48:27 +02:00
e9b96812f2 Refactor model details caching and vision support checks in ollama_client.py 2026-04-17 08:46:43 +02:00
d8a8e9be20 auto-git:
[add] dist/assets/index-Bt01BsHn.js
 [change] dist/index.html
 [unlink] dist/assets/index-g7N0HjkK.js
2026-04-17 08:41:27 +02:00
20e5527a22 Ensure settings hydration only occurs if not cancelled 2026-04-17 08:41:26 +02:00
b24d29c694 Add settings hydration state to GeneralSettings.jsx 2026-04-17 08:40:22 +02:00
826fd29278 Add handlers for vision and transcription model changes in App.jsx 2026-04-17 08:40:22 +02:00
7aa433b182 Update conditional rendering based on selectedVisionModelSupportsVision 2026-04-17 08:40:22 +02:00
6d1a8788fa Update variable names in App.jsx 2026-04-17 08:40:22 +02:00
950a00d84e Update model checks in App.jsx 2026-04-17 08:38:50 +02:00
549ea2d02e Enhance conversation handling with vision model support 2026-04-17 08:38:31 +02:00
a44240f02e Add model parameter to audio transcription payload 2026-04-17 08:38:31 +02:00
e7ee53ddb0 Add vision and transcription model support in App.jsx 2026-04-17 08:38:17 +02:00
c6a13687ee Update GeneralSettings.jsx to include model selection dropdowns and descriptions 2026-04-17 08:37:38 +02:00
ae0ec60400 auto-git:
[change] src/GeneralSettings.jsx
2026-04-17 08:37:28 +02:00
c03a8d1bd7 Add support for vision and transcription models in GeneralSettings.jsx 2026-04-17 08:37:23 +02:00
ecec4d09ea Add support for new models and settings in Electron app 2026-04-17 08:35:42 +02:00
9607f2192a Update rerank function to use new model preference 2026-04-17 08:35:42 +02:00
84f0bc7a4d Update ollama_admin.py to include new model preferences and checks 2026-04-17 08:34:56 +02:00
2e3855cfa3 Update model listing to include Whisper models 2026-04-17 08:34:29 +02:00
3dbe3fa790 Add model catalog functionality to backend/ollama_client.py 2026-04-17 08:34:22 +02:00
9ee177d47c Add function to list available Whisper models 2026-04-17 08:33:53 +02:00
22d45c4537 auto-git:
[add] dist/assets/index-g7N0HjkK.js
 [change] backend/app_settings.py
 [change] dist/index.html
 [unlink] dist/assets/index-BOZc6wlT.js
2026-04-17 08:33:39 +02:00
d20508649c Enhance error detection in App.jsx 2026-04-17 08:20:07 +02:00
b51e0ab891 Enhance error handling and message enrichment in App.jsx 2026-04-17 08:19:55 +02:00
218834982e auto-git:
[add] dist/assets/index-BOZc6wlT.js
 [change] dist/index.html
 [unlink] dist/assets/index-D9OFbkEX.js
2026-04-17 08:11:58 +02:00
246348e28b Add function to explain Ollama 502 errors in App.jsx 2026-04-17 08:11:58 +02:00
9e94b3a7df auto-git:
[add] dist/assets/index-D9OFbkEX.js
 [change] dist/index.html
 [unlink] dist/assets/index-BvwmOKz6.js
2026-04-17 08:01:47 +02:00
0d1541d64c Enhance App.jsx with activeSidebarModeRef and cleanup listeners 2026-04-17 08:01:46 +02:00
a83486107c Add offWindowFocus method to electronAPI 2026-04-17 08:01:46 +02:00
3f4f0c9475 auto-git:
[add] dist/assets/index-BvwmOKz6.js
 [change] dist/index.html
 [change] src/App.jsx
 [unlink] dist/assets/index-Ctu3w7qr.js
2026-04-17 04:48:56 +02:00
896d3be27f Add function to sync audio input runtime from startup status 2026-04-17 04:48:55 +02:00
2cb4fe4b41 auto-git:
[add] dist/assets/index-Ctu3w7qr.js
 [change] dist/index.html
 [change] src/App.jsx
 [unlink] dist/assets/index-DifKT69O.js
2026-04-17 04:48:17 +02:00
48c35698cb auto-git:
[add] dist/assets/index-DifKT69O.js
 [change] backend/main.py
 [change] backend/schemas.py
 [change] backend/whisper_admin.py
 [change] dist/index.html
 [change] electron/main.cjs
 [change] src/App.jsx
 [change] src/GeneralSettings.jsx
 [change] src/audioInput.js
 [unlink] dist/assets/index-Dm7DZNSo.js
2026-04-17 04:43:29 +02:00
67d9f41f17 auto-git:
[add] dist/assets/index-BFOWWhCS.css
 [add] dist/assets/index-Dm7DZNSo.js
 [change] dist/index.html
 [change] electron/main.cjs
 [change] src/App.jsx
 [unlink] dist/assets/index-CQjkNPEp.js
 [unlink] dist/assets/index-CzQQplJ5.css
2026-04-17 04:22:37 +02:00
a0c2b28591 Add audio transcription route to backend/main.py 2026-04-16 22:07:50 +02:00
7225980fb9 Import asyncio in backend/main.py 2026-04-16 22:07:50 +02:00
4447749439 Add audio transcription request and response schemas 2026-04-16 22:07:08 +02:00
86936dcb96 Extend whisper_admin.py with audio processing and transcription features 2026-04-16 22:07:05 +02:00
d5cdb85629 Add audio input settings to Electron main process 2026-04-16 22:06:10 +02:00
9301c65a93 Update styles for audio input and status display 2026-04-16 22:05:44 +02:00
7d744cf7b0 Add audio input controls to App.jsx 2026-04-16 22:05:44 +02:00
91cfac9fcf Add audio recording and transcription features to App.jsx 2026-04-16 22:05:13 +02:00
00b2d5875a Add audio input settings and effects in App.jsx 2026-04-16 22:04:50 +02:00
aaa3a1c02d Add audio recording and transcription functionality in App.jsx 2026-04-16 22:04:28 +02:00
c3af5ccc72 Add audio input and recording functionality to App.jsx 2026-04-16 22:03:48 +02:00
0d0b52b5d0 Add audio input support and related utility functions 2026-04-16 22:03:44 +02:00
5585f9d2f2 Add audio input settings to GeneralSettings component 2026-04-16 22:03:39 +02:00
1a250c8c2d Add audio input support utilities 2026-04-16 22:03:08 +02:00
88c5e5c5dd auto-git:
[add] dist/assets/index-CQjkNPEp.js
 [add] dist/assets/index-CzQQplJ5.css
 [change] dist/index.html
 [unlink] dist/assets/index-CUHp6hE9.js
 [unlink] dist/assets/index-D21amC2P.css
2026-04-16 21:34:50 +02:00
20a8af0e0e Add drag active background to main content 2026-04-16 21:34:49 +02:00
2f73fabda2 Add styles for message attachment and footer improvements 2026-04-16 21:33:21 +02:00
477c6f275a Add image attachment functionality in App.jsx 2026-04-16 21:32:27 +02:00
553b742d40 Enhance message editing UI in App.jsx 2026-04-16 21:32:06 +02:00
fcfc34d382 Add drag-and-drop functionality to chat content 2026-04-16 21:31:40 +02:00
603db28967 Ensure prompt text presence before processing 2026-04-16 21:31:40 +02:00
2e116b8701 Add drag-and-drop functionality for chat attachments and update message sending logic 2026-04-16 21:31:13 +02:00
972263d523 Add model capabilities check and update UI based on support for vision 2026-04-16 21:30:36 +02:00
c2c5385f66 Add image attachment functionality to App component 2026-04-16 21:29:55 +02:00
4f9799f6fd Add image attachment functionality to App.jsx 2026-04-16 21:29:39 +02:00
bc28b56d0b Add backend API URL input and update handling in GeneralSettings 2026-04-16 21:28:20 +02:00
e88ac88840 Add support for image attachments in chat messages and update model capabilities endpoint 2026-04-16 21:28:16 +02:00
d8784463b5 auto-git:
[add] dist/assets/index-CUHp6hE9.js
 [change] dist/index.html
 [unlink] dist/assets/index-BRSJQ8EZ.js
2026-03-31 01:08:35 +02:00
d58ed8bead Add option to open DevTools on startup in InterfaceSettings 2026-03-20 16:35:09 +01:00
c5b2c17370 Add openDevToolsOnStartup setting and related functionality 2026-03-20 16:35:04 +01:00
102 changed files with 18578 additions and 2764 deletions

120
AGENTS.md Normal file
View File

@@ -0,0 +1,120 @@
# AGENTS.md
## Project Overview
Heimgeist is a local desktop chat app for Ollama. It uses a React/Vite renderer, a Tauri desktop shell, a FastAPI backend, SQLite chat storage, Whisper transcription, optional SearXNG web search, and local RAG libraries under the backend.
## Important Directories and Entry Points
- `src/` - React renderer code.
- `src/main.jsx` mounts the app.
- `src/App.jsx` owns most chat UI state, session flow, model startup checks, and library/sidebar orchestration.
- `src/chatApi.js`, `src/chatGeneration.js`, and `src/backendApi.js` contain backend request and streaming helpers.
- `src/desktop/desktopApi.js` is the renderer platform abstraction for desktop APIs.
- `src/styles.css` contains the main UI styling.
- `src-tauri/` - Tauri desktop shell.
- `src-tauri/src/main.rs` owns Tauri commands for the renderer `desktopApi` surface, settings persistence, dialogs, path opening, external links, focus events, and update placeholders.
- `src-tauri/tauri.conf.json` points Tauri at the existing Vite renderer.
- `src-tauri/capabilities/` contains Tauri permission grants for enabled plugins.
- `backend/` - FastAPI backend and local processing.
- `backend/main.py` defines chat, session, model, audio, Ollama, and web search routes.
- `backend/sidecar_main.py` is the PyInstaller entrypoint used by packaged Tauri builds to start `backend.main:app`.
- `backend/local_rag.py` defines library, file registration, job, and local context routes.
- `backend/paths.py` centralizes backend runtime data paths for SQLite and local RAG libraries.
- `backend/schemas.py` and `backend/models.py` define API and database data shapes.
- `backend/rag/` contains corpus, enrichment, embedding, indexing, and retrieval helpers.
- `backend/database.py` gets the SQLite path from `backend/paths.py`.
- `scripts/` - development wrappers used by npm scripts.
- `scripts/run-backend.cjs` starts Uvicorn from `backend/.venv`.
- `scripts/run-tauri-dev.cjs` starts or reuses FastAPI, then launches the Tauri dev shell.
- `scripts/build-backend-sidecar.cjs` builds the PyInstaller backend sidecar and helper binaries for Tauri packaging.
- `run.sh` - bootstrap script for local development dependencies and dev startup.
- `vite.config.js` - Vite dev/build configuration. Tauri dev uses the strict Vite port `127.0.0.1:5174`.
## Run and Build Commands
- `./run.sh` - bootstrap/update Python and npm dependencies, then start the full dev stack.
- `npm run dev` - start or reuse FastAPI on `127.0.0.1:8000`, start the Vite renderer on `127.0.0.1:5174`, then launch Tauri.
- `npm run dev:tauri` - alias for the primary Tauri development workflow.
- `npm run dev:backend` - start FastAPI on `127.0.0.1:8000` with reload. Requires `backend/.venv`.
- `npm run dev:renderer` - start Vite on `127.0.0.1:5174` for Tauri.
- `npm run dev:tauri:shell` - launch the raw Tauri shell when backend lifecycle is managed separately.
- `npm run build` - build the renderer into `dist/`.
- `npm run build:sidecar` - build the PyInstaller backend sidecar and helper binaries into `src-tauri/binaries/`.
- `npm run package:mac` - build the sidecar and produce `src-tauri/target/release/bundle/macos/Heimgeist.app`.
- `npm run build:app` - alias for `npm run package:mac`.
- `npm start` - alias for `npm run dev`.
There are currently no npm `test` or `lint` scripts in `package.json`.
## Architectural Boundaries
- Renderer code should remain platform-neutral where practical. It may call backend HTTP APIs and may call `desktopApi`, but it should not import or call Tauri APIs directly.
- `src/desktop/desktopApi.js` is the renderer's platform abstraction. Add desktop capabilities there first, then back them with Tauri commands/events.
- `src-tauri/src/main.rs` owns desktop concerns: windows, menus, dialogs, shell opening, settings persistence, update placeholders, focus events, and Tauri command implementations.
- `src-tauri/src/main.rs` also starts the packaged backend sidecar in release builds, waits for `/health`, passes app-managed data-path environment, and shuts the sidecar down when the app exits.
- `backend/paths.py` owns backend runtime path resolution. Default development paths must remain `backend/app.db` and `backend/libraries`; packaged launchers pass app-managed paths through internal environment hooks.
- Backend code owns chat/session persistence, Ollama integration, Whisper transcription, web search enrichment, and RAG library processing.
- Backend API contracts should stay stable unless intentionally coordinated with renderer changes. If a response/request shape changes in `backend/schemas.py` or route handlers, update the renderer callers in the same change.
- Keep local RAG job orchestration and generated library state in the backend. Renderer code should use backend endpoints rather than reading library files directly.
## Generated and Runtime Data
Do not edit or commit generated/runtime data unless the task explicitly requires it:
- `backend/app.db` and any `*.db` files - local SQLite runtime data.
- `backend/libraries/` - local RAG library metadata, corpora, enrichment outputs, embeddings, indexes, and job state.
- `backend/.venv/` and `.venv/` - Python virtual environments.
- `node_modules/` - npm dependencies.
- `dist/` - Vite build output.
- `__pycache__/`, `*.pyc`, `.DS_Store`, and similar machine-generated files.
- Local app settings files under the Tauri app config directory or `HEIMGEIST_SETTINGS_FILE`.
- Packaged-build backend data directories supplied through internal deployment hooks such as `HEIMGEIST_DATA_DIR`, `HEIMGEIST_DB_PATH`, or `HEIMGEIST_LIB_ROOT`.
- Tauri-generated `src-tauri/target/`, `src-tauri/gen/`, and local `src-tauri/Cargo.lock` if generated by local verification.
- Generated sidecar binaries in `src-tauri/binaries/` except `src-tauri/binaries/.gitignore`.
Avoid broad file operations that traverse these directories. Use ignore patterns with search tools when inspecting the repo.
## Verification Expectations
- Frontend changes: run `npm run build` at minimum. For UI or interaction changes, also run the dev stack and exercise the affected flow in Tauri.
- Backend changes: run a targeted syntax/import check such as `backend/.venv/bin/python -m py_compile backend/main.py backend/local_rag.py` for touched modules, then start `npm run dev:backend` or the full dev stack and check `GET /health`.
- Desktop bridge/Tauri changes: run `cargo check --manifest-path src-tauri/Cargo.toml` with a temp `CARGO_TARGET_DIR` when useful, run `npm run build`, and if practical run `npm run dev`. Use a temporary `HEIMGEIST_SETTINGS_FILE` when testing ordinary shared settings behavior; use a temporary `HOME` with a fake legacy settings file when testing first-run import, because `HEIMGEIST_SETTINGS_FILE` intentionally bypasses import.
- Tauri packaging changes: run `npm run build:sidecar`, then `npm run package:mac` on macOS. Verify `src-tauri/target/release/bundle/macos/Heimgeist.app` exists, launches, starts or reuses a compatible backend on `127.0.0.1:8000`, uses app-managed data outside the app bundle, and stops its sidecar processes on quit.
- API contract changes: verify both sides together. Update backend schemas/routes and renderer callers in the same change, then exercise the affected request path.
- RAG, Whisper, Ollama, or SearXNG changes: note any external services or local models required for verification, and test graceful failure paths when those services are unavailable.
## Tauri Guidance
- Keep renderer desktop calls behind `src/desktop/desktopApi.js`; do not import Tauri APIs directly in React components.
- When adding desktop capabilities, prefer method names and payloads that stay stable for renderer callers.
- Preserve `HEIMGEIST_SETTINGS_FILE` as an explicit shared settings override.
- Keep first-run legacy settings import available when Tauri settings do not already exist.
- Do not move or rewrite `backend/app.db` or `backend/libraries`; the development backend must keep using the existing backend working directory.
- Treat `HEIMGEIST_DATA_DIR`, `HEIMGEIST_DB_PATH`, and `HEIMGEIST_LIB_ROOT` as internal app/sidecar deployment hooks only. Do not expose them in the UI or document them as normal user configuration.
- Packaged Tauri builds use `backend/sidecar_main.py` and `scripts/build-backend-sidecar.cjs` to bundle the FastAPI backend. Do not move or migrate development data into the packaged app data directory as part of packaging.
- Production-release work still needs signed updater/changelog parity, final bundle metadata, signing/notarization, full Windows/Linux packaging scripts, and installer behavior.
- Avoid refactors that mix migration prep with unrelated feature work. Migration work should be explicit and reviewable.
## Coding and Refactor Guidelines
- Keep changes scoped to the request. Do not refactor large files such as `src/App.jsx`, `src/styles.css`, `backend/main.py`, or `backend/local_rag.py` unless the task needs it.
- Prefer existing helper modules and patterns over new abstractions.
- Preserve stable backend contracts and persisted data compatibility. Add small migration helpers when changing database-backed fields.
- Keep settings keys backward compatible where possible. Existing settings migrations live in Tauri and backend settings helpers.
- Use structured JSON/schema changes rather than ad hoc string parsing for API payloads.
- Add comments only where they explain non-obvious control flow, concurrency, migration, or integration behavior.
- Do not silently swallow errors in user-facing flows; surface useful messages while preserving graceful degradation for optional services.
- Do not mix formatting churn with behavior changes.
## Known Fragile Areas
- The Tauri bridge is intentionally narrow. Direct `window.__TAURI__` use outside `src/desktop/desktopApi.js` makes desktop behavior harder to reason about.
- `src/App.jsx`, `src/chatGeneration.js`, and backend chat routes share assumptions about streaming, regeneration, attachments, source metadata, and session state.
- `backend/main.py` creates/migrates SQLite tables at import/startup. Schema changes need care because they run against local user data.
- `backend/paths.py` controls where chat and local RAG data are stored. Preserve development defaults unless the task explicitly concerns packaged app data paths.
- `backend/local_rag.py` coordinates asynchronous jobs, file registration, generated artifacts, and per-library locks. Avoid changes that can start duplicate jobs or corrupt `backend/libraries/`.
- RAG builders under `backend/rag/` run heavier file processing and subprocess/threaded work. Test with small inputs before broader runs.
- Whisper depends on ffmpeg/ffprobe paths supplied by the Node backend runner when available.
- Web search depends on an optional SearXNG instance, usually `http://127.0.0.1:8888`; features should fail gracefully when it is absent.
- Ollama availability, model names, embedding model choices, and vision capability checks are runtime-dependent. Keep related UI and backend paths tolerant of missing models.

View File

@@ -1,10 +1,10 @@
# Heimgeist # Heimgeist
Heimgeist is a local desktop chat client for Ollama. It combines an Electron + React renderer with a FastAPI backend, stores chat history in SQLite, supports optional SearXNG-backed web search, and can enrich prompts with context from local library indexes. Heimgeist is a local desktop chat client for Ollama. It combines a Tauri + React renderer with a FastAPI backend, stores chat history in SQLite, supports optional SearXNG-backed web search, and can enrich prompts with context from local library indexes.
## Features ## Features
- Local desktop chat UI with Electron - Local desktop chat UI with Tauri
- Ollama-backed chat with streaming and non-streaming replies - Ollama-backed chat with streaming and non-streaming replies
- Persistent chat sessions and automatic title generation - Persistent chat sessions and automatic title generation
- Edit-and-regenerate flow for earlier user messages - Edit-and-regenerate flow for earlier user messages
@@ -23,9 +23,15 @@ The `DBs` tab is no longer a placeholder. You can:
When files are added or removed, Heimgeist automatically rebuilds the local RAG pipeline for that database: corpus, enrichment, embeddings, and indexes. In the chat composer, you can select which database the current chat should use. For each chat turn, Heimgeist queries the selected database, turns the top results into a local context block, appends that block to the user prompt, and sends the enriched prompt to Ollama. When files are added or removed, Heimgeist automatically rebuilds the local RAG pipeline for that database: corpus, enrichment, embeddings, and indexes. In the chat composer, you can select which database the current chat should use. For each chat turn, Heimgeist queries the selected database, turns the top results into a local context block, appends that block to the user prompt, and sends the enriched prompt to Ollama.
## Local Data
Heimgeist stores chat history and local library indexes on the local machine. During development, the backend keeps using `backend/app.db` and `backend/libraries` so existing local data remains available.
Packaged Tauri builds launch the bundled backend with app-managed data paths so chats and local libraries live under the operating system's normal application data location, such as Application Support on macOS, LocalAppData on Windows, or the XDG data directory on Linux. These paths are managed by the app and are not exposed as normal user settings.
## Stack ## Stack
- Frontend: Electron, React, Vite - Frontend: Tauri, React, Vite
- Backend: FastAPI, SQLAlchemy, SQLite - Backend: FastAPI, SQLAlchemy, SQLite
- Search enrichment: SearXNG + page fetching/reranking - Search enrichment: SearXNG + page fetching/reranking
- Local RAG pipeline: corpus build, enrichment, embedding, and retrieval helpers under `backend/rag/` - Local RAG pipeline: corpus build, enrichment, embedding, and retrieval helpers under `backend/rag/`
@@ -34,8 +40,6 @@ When files are added or removed, Heimgeist automatically rebuilds the local RAG
Requirements: Requirements:
- Node.js 18+
- Python 3.13
- Ollama running locally - Ollama running locally
- Optional: SearXNG on `http://127.0.0.1:8888` - Optional: SearXNG on `http://127.0.0.1:8888`
@@ -45,7 +49,17 @@ Quick start:
./run.sh ./run.sh
``` ```
This creates or refreshes `backend/.venv`, installs Python dependencies, installs npm dependencies, and starts the dev stack. This bootstraps the development environment and starts the dev stack. On a fresh machine it installs:
- the native Tauri prerequisites through `pacman` on Arch/SteamOS or `apt-get` on Debian/Ubuntu
- stable Rust and Cargo through `rustup`
- Python 3.13 through `uv`
- Node.js 22 LTS and npm from the official Node.js binaries
- the project's Python and npm dependencies
SteamOS temporarily requires a writable root filesystem while native packages are installed. `run.sh` disables the read-only mode only around `pacman`, restores it afterward, and may ask for the user's sudo password. It also initializes and populates the SteamOS pacman keyring before installing packages, because a fresh or updated Steam Deck can otherwise reject valid packages with "unknown trust" / PGP signature errors. If that keyring repair is still insufficient and SteamOS provides `steamos-devmode`, `run.sh` uses it as a final SteamOS bootstrap fallback. Set `HEIMGEIST_STEAMOS_DEVMODE=0` to skip that fallback. SteamOS system updates can remove manually installed system packages; rerunning `./run.sh` restores any missing prerequisites.
Downloads and package installation are skipped when usable dependencies already exist. Node.js archives are verified with their published SHA-256 checksum. Use `HEIMGEIST_BOOTSTRAP_ONLY=1 ./run.sh` to install/check dependencies without launching Heimgeist, or `HEIMGEIST_SKIP_SYSTEM_DEPS=1 ./run.sh` when native Tauri dependencies are managed externally. If the package manager succeeds but the native dependency preflight still cannot verify a `pkg-config` module, `run.sh` prints a preflight report and continues so the real Tauri build can produce the authoritative compiler/linker error. Set `HEIMGEIST_STRICT_SYSTEM_DEPS=1` to make that preflight warning fatal. `HEIMGEIST_NODE_MAJOR`, `HEIMGEIST_NODE_DIR`, `HEIMGEIST_TOOL_BIN_DIR`, `CARGO_HOME`, `RUSTUP_HOME`, `PYTHON_BIN`, `HEIMGEIST_STEAMOS_DEVMODE`, and `HEIMGEIST_STRICT_SYSTEM_DEPS` provide explicit runtime overrides.
On Linux `x86_64`, `run.sh` now selects a PyTorch flavor before installing `openai-whisper`: On Linux `x86_64`, `run.sh` now selects a PyTorch flavor before installing `openai-whisper`:
@@ -66,23 +80,52 @@ npm install
npm run dev npm run dev
``` ```
## Local macOS Packaging
Requirements:
- `backend/.venv` with backend dependencies installed
- Rust/Tauri build prerequisites
- Ollama installed and running separately
- Optional: SearXNG on `http://127.0.0.1:8888`
Build a local macOS app bundle:
```bash
npm run package:mac
```
This builds the React renderer, creates a PyInstaller backend sidecar from `backend/.venv`, bundles ffmpeg/ffprobe helpers when available from npm dependencies, and runs `tauri build --bundles app`.
The `.app` is written to:
```text
src-tauri/target/release/bundle/macos/Heimgeist.app
```
The packaged app starts its own FastAPI backend sidecar on `127.0.0.1:8000`. Ollama remains an external requirement, and SearXNG remains optional.
## File Tree ## File Tree
```text ```text
. .
├── backend/ ├── backend/
│ ├── main.py │ ├── main.py
│ ├── sidecar_main.py
│ ├── local_rag.py │ ├── local_rag.py
│ ├── rag/ │ ├── rag/
│ ├── websearch.py │ ├── websearch.py
│ ├── ollama_client.py │ ├── ollama_client.py
│ ├── models.py │ ├── models.py
│ ├── database.py │ ├── database.py
│ ├── paths.py
│ ├── schemas.py │ ├── schemas.py
│ └── requirements.txt │ └── requirements.txt
├── electron/ ├── src-tauri/
│ ├── main.cjs │ ├── src/main.rs
│ └── preload.cjs │ ├── tauri.conf.json
│ ├── binaries/
│ └── capabilities/
├── src/ ├── src/
│ ├── App.jsx │ ├── App.jsx
│ ├── LibraryManager.jsx │ ├── LibraryManager.jsx
@@ -94,5 +137,6 @@ npm run dev
│ └── styles.css │ └── styles.css
├── package.json ├── package.json
├── run.sh ├── run.sh
├── scripts/
└── vite.config.js └── vite.config.js
``` ```

View File

@@ -0,0 +1,8 @@
import os
import sys
# The macOS wheels for PyTorch (used by Whisper) and FAISS bundle different
# libomp copies. FAISS aborts the process when its copy initializes second.
if sys.platform == "darwin":
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")

View File

@@ -0,0 +1,5 @@
"""Native Heimgeist tools and validated workflow execution."""
from .registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
__all__ = ["NativeToolProvider", "ToolDefinition", "ToolExecutionContext"]

642
backend/agent/api.py Normal file
View File

@@ -0,0 +1,642 @@
from __future__ import annotations
import asyncio
from datetime import datetime
import hashlib
import json
import re
import uuid
from typing import Any, Dict, Optional
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from .. import models as chat_models
from ..chat_memory import safe_sync_chat_memory_for_session
from ..database import Base, SessionLocal, engine
from ..local_rag import ensure_global_knowledge_store, global_library_slug
from .events import EventWriter
from .models import (
WorkflowConfirmation,
WorkflowDefinition,
WorkflowEvent,
WorkflowNodeRun,
WorkflowRevision,
WorkflowRun,
)
from .registry import NativeToolProvider
from .router import select_workflow
from .runtime import WorkflowRuntime
from .schemas import (
ConfirmationResponseRequest,
RouterSelectRequest,
WorkflowCreateRequest,
WorkflowRevisionRequest,
WorkflowRunRequest,
WorkflowUpdateRequest,
WorkflowValidateRequest,
)
from .tools import register_native_tools
from .validation import validate_workflow_graph
from .workflows import seed_builtin_workflows
router = APIRouter(tags=["agent-workflows"])
registry = NativeToolProvider()
register_native_tools(registry)
runtime = WorkflowRuntime(registry, SessionLocal)
def _json(value: Optional[str], fallback: Any) -> Any:
try:
return json.loads(value) if value else fallback
except Exception:
return fallback
def _checksum(graph: Dict[str, Any]) -> str:
canonical = json.dumps(graph, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _slugify(value: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", str(value or "").strip().lower()).strip("-")
return slug[:90] or f"workflow-{uuid.uuid4().hex[:8]}"
_REMEMBER_CONTENT_PATTERNS = [
re.compile(r"^\s*(?:please\s+)?remember\s+this\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
re.compile(r"^\s*(?:please\s+)?remember\s+that\s+(.+)$", re.IGNORECASE | re.DOTALL),
re.compile(r"^\s*(?:please\s+)?save\s+this\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
re.compile(r"^\s*(?:please\s+)?save\s+that\s+(.+)$", re.IGNORECASE | re.DOTALL),
re.compile(r"^\s*(?:bitte\s+)?merk\s+dir\s+das\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
re.compile(r"^\s*(?:bitte\s+)?merk\s+dir\s+(.+)$", re.IGNORECASE | re.DOTALL),
re.compile(r"^\s*(?:bitte\s+)?speicher(?:e)?\s+(?:das|dies|diese|diesen)\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
]
def _extract_remember_content(message: str) -> Optional[str]:
text = str(message or "").strip()
for pattern in _REMEMBER_CONTENT_PATTERNS:
match = pattern.match(text)
if match:
content = match.group(1).strip()
return content or None
return None
def _clean_search_queries(raw: Any, fallback: str) -> list[str]:
values = raw if isinstance(raw, list) else [raw]
cleaned: list[str] = []
seen = set()
for item in values:
text = " ".join(str(item or "").split()).strip()
if not text:
continue
key = text.casefold()
if key in seen:
continue
seen.add(key)
cleaned.append(text[:300])
if len(cleaned) >= 5:
break
fallback_text = " ".join(str(fallback or "").split()).strip()
if fallback_text and not cleaned:
cleaned.append(fallback_text[:300])
return cleaned
def _resolve_web_search_inputs(sample_inputs: Dict[str, Any], message: str) -> tuple[str, list[str]]:
raw_queries = sample_inputs.get("web_search_queries")
if raw_queries is None:
raw_queries = sample_inputs.get("search_queries")
raw_query = sample_inputs.get("web_search_query") or sample_inputs.get("search_query")
queries = _clean_search_queries(raw_queries if raw_queries is not None else raw_query, message)
if raw_query:
raw_query_text = " ".join(str(raw_query).split()).strip()
if raw_query_text and raw_query_text.casefold() not in {item.casefold() for item in queries}:
queries.insert(0, raw_query_text[:300])
queries = queries[:5]
query = queries[0] if queries else str(message or "")[:300]
return query, queries or [query]
def initialize_agent_system() -> None:
Base.metadata.create_all(bind=engine)
db = SessionLocal()
try:
db.query(WorkflowRun).filter(WorkflowRun.status.in_(["queued", "running", "waiting_confirmation"])).update(
{
WorkflowRun.status: "interrupted",
WorkflowRun.error_json: json.dumps({"message": "Backend restarted before the workflow completed."}),
WorkflowRun.finished_at: datetime.utcnow(),
},
synchronize_session=False,
)
db.commit()
seed_builtin_workflows(db)
finally:
db.close()
def _workflow_payload(workflow: WorkflowDefinition, db: Session, *, include_graph: bool = False) -> Dict[str, Any]:
revision = None
if workflow.current_revision_id:
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == workflow.current_revision_id).first()
payload = {
"id": workflow.id,
"slug": workflow.slug,
"name": workflow.name,
"description": workflow.description,
"current_revision_id": workflow.current_revision_id,
"current_version": revision.version if revision else None,
"built_in": workflow.built_in,
"enabled": workflow.enabled,
"routing_description": workflow.routing_description,
"routing_examples": _json(workflow.routing_examples_json, []),
"estimated_cost_class": workflow.estimated_cost_class,
"required_capabilities": _json(workflow.required_capabilities_json, []),
"created_at": workflow.created_at.isoformat() if workflow.created_at else None,
"updated_at": workflow.updated_at.isoformat() if workflow.updated_at else None,
}
if include_graph:
payload["graph"] = _json(revision.graph_json if revision else None, {})
payload["revisions"] = [
{
"id": item.id, "version": item.version, "created_at": item.created_at.isoformat(),
"created_by": item.created_by, "trusted": item.trusted, "checksum": item.checksum,
}
for item in db.query(WorkflowRevision).filter(WorkflowRevision.workflow_id == workflow.id).order_by(WorkflowRevision.version.desc()).all()
]
return payload
def _find_workflow(db: Session, workflow_id: str) -> WorkflowDefinition:
workflow = db.query(WorkflowDefinition).filter(
(WorkflowDefinition.id == workflow_id) | (WorkflowDefinition.slug == workflow_id)
).first()
if workflow is None:
raise HTTPException(status_code=404, detail="Workflow not found.")
return workflow
def _run_payload(run: WorkflowRun, db: Session) -> Dict[str, Any]:
node_runs = db.query(WorkflowNodeRun).filter(WorkflowNodeRun.workflow_run_id == run.id).order_by(WorkflowNodeRun.started_at.asc()).all()
confirmations = db.query(WorkflowConfirmation).filter(WorkflowConfirmation.workflow_run_id == run.id).order_by(WorkflowConfirmation.created_at.asc()).all()
return {
"id": run.id, "workflow_id": run.workflow_id, "workflow_revision_id": run.workflow_revision_id,
"session_id": run.session_id, "user_message_id": run.user_message_id, "status": run.status,
"selection_mode": run.selection_mode, "inputs": _json(run.inputs_json, {}), "outputs": _json(run.outputs_json, None),
"error": _json(run.error_json, None), "metrics": _json(run.metrics_json, {}),
"started_at": run.started_at.isoformat() if run.started_at else None,
"finished_at": run.finished_at.isoformat() if run.finished_at else None,
"cancellation_requested": run.cancellation_requested,
"node_runs": [{
"id": item.id, "node_id": item.node_id, "attempt": item.attempt, "status": item.status,
"resolved_inputs": _json(item.resolved_inputs_json, None), "outputs": _json(item.outputs_json, None),
"error": _json(item.error_json, None), "metrics": _json(item.metrics_json, {}),
"started_at": item.started_at.isoformat() if item.started_at else None,
"finished_at": item.finished_at.isoformat() if item.finished_at else None,
} for item in node_runs],
"confirmations": [{
"id": item.id, "node_id": item.node_id, "tool_name": item.tool_name, "status": item.status,
"request": _json(item.request_json, {}), "response": _json(item.response_json, None),
"created_at": item.created_at.isoformat() if item.created_at else None,
"resolved_at": item.resolved_at.isoformat() if item.resolved_at else None,
} for item in confirmations],
}
@router.get("/tools")
def list_tools():
return {"tools": list(registry.list_tools())}
@router.get("/workflows")
def list_workflows():
db = SessionLocal()
try:
workflows = db.query(WorkflowDefinition).order_by(WorkflowDefinition.built_in.desc(), WorkflowDefinition.name.asc()).all()
return {"workflows": [_workflow_payload(item, db) for item in workflows]}
finally:
db.close()
@router.post("/workflows")
def create_workflow(request: WorkflowCreateRequest):
validation = validate_workflow_graph(request.graph, registry)
if not validation.valid:
raise HTTPException(status_code=422, detail={"message": "Invalid workflow graph.", "errors": [item.model_dump() for item in validation.errors]})
db = SessionLocal()
try:
slug = _slugify(request.slug or request.name)
if db.query(WorkflowDefinition).filter(WorkflowDefinition.slug == slug).first():
slug = f"{slug}-{uuid.uuid4().hex[:6]}"
workflow = WorkflowDefinition(
slug=slug, name=request.name.strip() or "Untitled Workflow", description=request.description,
built_in=False, enabled=request.enabled, routing_description=request.routing_description,
routing_examples_json=json.dumps(request.routing_examples),
)
db.add(workflow)
db.flush()
revision = WorkflowRevision(
workflow_id=workflow.id, version=1, graph_json=json.dumps(request.graph, ensure_ascii=False),
created_by="user", trusted=False, checksum=_checksum(request.graph),
)
db.add(revision)
db.flush()
workflow.current_revision_id = revision.id
db.commit()
db.refresh(workflow)
return _workflow_payload(workflow, db, include_graph=True)
finally:
db.close()
@router.get("/workflows/{workflow_id}")
def get_workflow(workflow_id: str):
db = SessionLocal()
try:
return _workflow_payload(_find_workflow(db, workflow_id), db, include_graph=True)
finally:
db.close()
@router.post("/workflows/{workflow_id}/duplicate")
def duplicate_workflow(workflow_id: str):
db = SessionLocal()
try:
source = _find_workflow(db, workflow_id)
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == source.current_revision_id).first()
workflow = WorkflowDefinition(
slug=f"{_slugify(source.slug)}-copy-{uuid.uuid4().hex[:6]}", name=f"{source.name} Copy",
description=source.description, built_in=False, enabled=True,
routing_description=source.routing_description, routing_examples_json=source.routing_examples_json,
estimated_cost_class=source.estimated_cost_class, required_capabilities_json=source.required_capabilities_json,
)
db.add(workflow)
db.flush()
copy_revision = WorkflowRevision(
workflow_id=workflow.id, version=1, graph_json=revision.graph_json, created_by="user",
trusted=False, checksum=revision.checksum,
)
db.add(copy_revision)
db.flush()
workflow.current_revision_id = copy_revision.id
db.commit()
return _workflow_payload(workflow, db, include_graph=True)
finally:
db.close()
@router.put("/workflows/{workflow_id}")
def update_workflow(workflow_id: str, request: WorkflowUpdateRequest):
db = SessionLocal()
try:
workflow = _find_workflow(db, workflow_id)
updates = request.model_dump(exclude_unset=True)
if "name" in updates:
workflow.name = updates["name"].strip() or workflow.name
if "description" in updates: workflow.description = updates["description"]
if "routing_description" in updates: workflow.routing_description = updates["routing_description"]
if "routing_examples" in updates: workflow.routing_examples_json = json.dumps(updates["routing_examples"])
if "enabled" in updates: workflow.enabled = bool(updates["enabled"])
workflow.updated_at = datetime.utcnow()
db.commit()
return _workflow_payload(workflow, db, include_graph=True)
finally:
db.close()
@router.post("/workflows/{workflow_id}/revisions")
def create_revision(workflow_id: str, request: WorkflowRevisionRequest):
validation = validate_workflow_graph(request.graph, registry)
if not validation.valid:
raise HTTPException(status_code=422, detail={"message": "Invalid workflow graph.", "errors": [item.model_dump() for item in validation.errors]})
db = SessionLocal()
try:
workflow = _find_workflow(db, workflow_id)
if workflow.built_in:
raise HTTPException(status_code=409, detail="Built-in workflows are read-only. Duplicate the workflow first.")
latest = db.query(WorkflowRevision).filter(WorkflowRevision.workflow_id == workflow.id).order_by(WorkflowRevision.version.desc()).first()
revision = WorkflowRevision(
workflow_id=workflow.id, version=(latest.version + 1) if latest else 1,
graph_json=json.dumps(request.graph, ensure_ascii=False), created_by=request.created_by,
trusted=False, checksum=_checksum(request.graph),
)
db.add(revision)
db.flush()
workflow.current_revision_id = revision.id
workflow.updated_at = datetime.utcnow()
db.commit()
return _workflow_payload(workflow, db, include_graph=True)
finally:
db.close()
@router.post("/workflows/validate")
def validate_workflow(request: WorkflowValidateRequest):
return validate_workflow_graph(request.graph, registry).model_dump()
@router.delete("/workflows/{workflow_id}")
def delete_workflow(workflow_id: str):
db = SessionLocal()
try:
workflow = _find_workflow(db, workflow_id)
if workflow.built_in:
raise HTTPException(status_code=409, detail="Built-in workflows cannot be deleted.")
db.delete(workflow)
db.commit()
return {"ok": True}
finally:
db.close()
async def _select_for_run(
db: Session,
request: WorkflowRunRequest,
) -> tuple[WorkflowDefinition, Optional[Dict[str, Any]]]:
router_result = None
if request.selection_mode == "automatic":
ensure_global_knowledge_store()
router_library_slug = request.library_slug or global_library_slug()
recent_messages = []
if request.session_id:
session = db.query(chat_models.ChatSession).filter(chat_models.ChatSession.session_id == request.session_id).first()
if session:
rows = db.query(chat_models.ChatMessage).filter(chat_models.ChatMessage.session_pk == session.id).order_by(chat_models.ChatMessage.id.desc()).limit(4).all()
recent_messages = [{"role": row.role, "content": row.content} for row in reversed(rows)]
router_result = await select_workflow(
db, message=request.message, recent_messages=recent_messages, attachments=request.attachments,
library_slug=router_library_slug, router_model=request.router_model, chat_model=request.model,
web_search_enabled=request.web_search_enabled,
)
workflow = _find_workflow(db, router_result["workflow_id"])
elif request.selection_mode == "explicit":
if not request.workflow_id:
raise HTTPException(status_code=422, detail="Explicit workflow mode requires workflow_id.")
workflow = _find_workflow(db, request.workflow_id)
if not workflow.enabled:
raise HTTPException(status_code=409, detail="The selected workflow is disabled.")
else:
workflow = _find_workflow(db, "input-output")
return workflow, router_result
@router.post("/workflow-runs")
async def create_workflow_run(request: WorkflowRunRequest):
db = SessionLocal()
try:
workflow, router_result = await _select_for_run(db, request)
revision_id = request.workflow_revision_id or workflow.current_revision_id
if (
request.workflow_revision_id
and request.workflow_revision_id != workflow.current_revision_id
and request.regenerate_index is None
):
raise HTTPException(status_code=409, detail="The requested workflow revision is stale.")
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == revision_id).first()
if revision is None or revision.workflow_id != workflow.id:
raise HTTPException(status_code=409, detail="The selected workflow has no current revision.")
graph = _json(revision.graph_json, {})
validation = validate_workflow_graph(graph, registry)
if not validation.valid:
raise HTTPException(status_code=422, detail={"message": "Invalid workflow graph.", "errors": [item.model_dump() for item in validation.errors]})
session = None
user_message = None
run_attachments = request.attachments
sample_inputs = dict(request.sample_inputs)
router_inputs = router_result.get("inputs") if isinstance(router_result, dict) else None
if isinstance(router_inputs, dict):
merged_inputs = dict(router_inputs)
merged_inputs.update(sample_inputs)
sample_inputs = merged_inputs
target_message_id = sample_inputs.get("target_message_id") or sample_inputs.get("message_id")
target_message_content = sample_inputs.get("target_message_content") or sample_inputs.get("edited_content")
target_url = sample_inputs.get("target_url") or sample_inputs.get("url")
if not target_url:
url_match = re.search(r"https?://[^\s<>'\"]+", request.message or "")
target_url = url_match.group(0).rstrip(".,);]") if url_match else None
if request.session_id:
session = db.query(chat_models.ChatSession).filter(chat_models.ChatSession.session_id == request.session_id).first()
if session is None and request.regenerate_index is not None:
raise HTTPException(status_code=404, detail="Chat session not found.")
if session is None:
session = chat_models.ChatSession(session_id=request.session_id)
db.add(session)
db.flush()
previous_assistant_message_id = None
if not target_message_id:
previous_assistant = db.query(chat_models.ChatMessage).filter(
chat_models.ChatMessage.session_pk == session.id,
chat_models.ChatMessage.role == "assistant",
).order_by(chat_models.ChatMessage.created_at.desc(), chat_models.ChatMessage.id.desc()).first()
if previous_assistant:
previous_assistant_message_id = previous_assistant.message_id
from .. import main as main_module
if request.regenerate_index is not None:
rows = db.query(chat_models.ChatMessage).filter(
chat_models.ChatMessage.session_pk == session.id
).order_by(chat_models.ChatMessage.created_at.asc(), chat_models.ChatMessage.id.asc()).all()
if request.regenerate_index >= len(rows):
raise HTTPException(status_code=400, detail="Invalid regeneration message index.")
user_index = request.regenerate_index
while user_index >= 0 and rows[user_index].role != "user":
user_index -= 1
if user_index < 0:
raise HTTPException(status_code=400, detail="No user message is available for regeneration.")
user_message = rows[user_index]
user_message.content = request.message
for stale_message in rows[user_index + 1:]:
db.delete(stale_message)
stored_attachments = _json(user_message.attachments_json, [])
run_attachments = request.attachments or stored_attachments
db.flush()
if not target_message_id and workflow.slug == "remember-this":
target_message_id = user_message.message_id
target_message_content = target_message_content or _extract_remember_content(request.message)
else:
attachments = [main_module._normalize_chat_attachment_or_raise(item, include_text=True) for item in request.attachments]
run_attachments = attachments
user_message = chat_models.ChatMessage(
session_pk=session.id, role="user", content=request.message,
attachments_json=json.dumps(attachments, ensure_ascii=False),
)
db.add(user_message)
db.flush()
if not target_message_id:
if workflow.slug == "remember-this":
target_message_id = user_message.message_id
target_message_content = target_message_content or _extract_remember_content(request.message)
elif previous_assistant_message_id:
target_message_id = previous_assistant_message_id
messages = []
if session:
rows = db.query(chat_models.ChatMessage).filter(chat_models.ChatMessage.session_pk == session.id).order_by(chat_models.ChatMessage.id.asc()).all()[-20:]
messages = [{"role": row.role, "content": row.content} for row in rows]
else:
messages = [{"role": "user", "content": request.message}]
sample_inputs.setdefault("prompt", request.message)
sample_inputs.setdefault("session_id", request.session_id)
web_search_query, web_search_queries = _resolve_web_search_inputs(sample_inputs, request.message)
try:
required_capabilities = set(json.loads(workflow.required_capabilities_json or "[]"))
except Exception:
required_capabilities = set()
knowledge_required = bool({"rag", "knowledge_write"} & required_capabilities)
effective_library_slug = request.library_slug
if knowledge_required:
ensure_global_knowledge_store()
effective_library_slug = effective_library_slug or global_library_slug()
run_values = {
"session_id": request.session_id,
"chat_model": request.model,
"router_model": request.router_model or request.model,
"vision_model": request.vision_model,
"transcription_model": request.transcription_model,
"library_slug": effective_library_slug,
"searx_url": request.searx_url,
"searx_engines": request.searx_engines,
"messages": messages,
"attachments": run_attachments,
"generation_options": request.generation_options,
"context_blocks": [],
"manual_library_enabled": bool(request.library_slug),
"web_search_enabled": request.web_search_enabled,
"compatibility_rag_enabled": bool(request.library_slug and "rag" not in required_capabilities),
"compatibility_web_enabled": bool(request.web_search_enabled and "web" not in required_capabilities),
"web_search_query": web_search_query,
"web_search_queries": web_search_queries,
"show_thinking": request.show_thinking,
"target_message_id": target_message_id,
"target_message_content": target_message_content,
"target_url": target_url,
}
run = WorkflowRun(
workflow_id=workflow.id, workflow_revision_id=revision.id, session_id=request.session_id,
user_message_id=user_message.message_id if user_message else None, selection_mode=request.selection_mode,
inputs_json=json.dumps({"input": sample_inputs, "run": run_values, "explicit_user_action": request.explicit_user_action}, ensure_ascii=False),
)
db.add(run)
db.commit()
db.refresh(run)
if request.regenerate_index is not None and request.session_id:
safe_sync_chat_memory_for_session(db, request.session_id)
run_id = run.id
workflow_payload = {"id": workflow.id, "slug": workflow.slug, "name": workflow.name, "revision_id": revision.id}
finally:
db.close()
writer = EventWriter(run_id, workflow_payload["id"], SessionLocal)
if router_result:
await writer.emit("router_completed", router_result)
await writer.emit("workflow_selected", workflow_payload)
runtime.start(run_id)
return {"run_id": run_id, "status": "queued", "workflow": workflow_payload, "router": router_result}
@router.get("/workflow-runs/{run_id}")
def get_workflow_run(run_id: str):
db = SessionLocal()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
if not run:
raise HTTPException(status_code=404, detail="Workflow run not found.")
return _run_payload(run, db)
finally:
db.close()
@router.get("/workflow-runs/{run_id}/events")
def get_workflow_events(run_id: str, after_sequence: int = Query(0, ge=0), follow: bool = True):
async def stream():
sequence = after_sequence
idle_after_terminal = 0
emitted_interrupted = False
while True:
db = SessionLocal()
try:
events = db.query(WorkflowEvent).filter(
WorkflowEvent.workflow_run_id == run_id,
WorkflowEvent.sequence > sequence,
).order_by(WorkflowEvent.sequence.asc()).all()
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
if run is None:
yield json.dumps({"type": "error", "payload": {"message": "Workflow run not found."}}) + "\n"
return
for item in events:
sequence = item.sequence
yield json.dumps({
"run_id": item.workflow_run_id, "workflow_id": item.workflow_id, "node_id": item.node_id,
"sequence": item.sequence, "timestamp": item.timestamp.isoformat(), "type": item.event_type,
"payload": _json(item.payload_json, {}),
}, ensure_ascii=False) + "\n"
terminal = run.status in {"completed", "failed", "cancelled", "interrupted"}
if run.status == "interrupted" and not emitted_interrupted:
emitted_interrupted = True
yield json.dumps({
"run_id": run.id,
"workflow_id": run.workflow_id,
"node_id": None,
"sequence": sequence + 1,
"timestamp": (run.finished_at or datetime.utcnow()).isoformat(),
"type": "run_interrupted",
"payload": _json(run.error_json, {"message": "Workflow run was interrupted."}),
}, ensure_ascii=False) + "\n"
finally:
db.close()
if not follow:
return
if terminal:
idle_after_terminal += 1
if idle_after_terminal >= 2:
return
else:
idle_after_terminal = 0
await asyncio.sleep(0.15)
return StreamingResponse(stream(), media_type="application/x-ndjson")
@router.post("/workflow-runs/{run_id}/cancel")
def cancel_workflow_run(run_id: str):
if not runtime.cancel(run_id):
raise HTTPException(status_code=404, detail="Workflow run not found.")
return {"ok": True}
@router.post("/workflow-runs/{run_id}/confirmations/{confirmation_id}")
def respond_to_confirmation(run_id: str, confirmation_id: str, request: ConfirmationResponseRequest):
db = SessionLocal()
try:
confirmation = db.query(WorkflowConfirmation).filter(
WorkflowConfirmation.id == confirmation_id,
WorkflowConfirmation.workflow_run_id == run_id,
).first()
if not confirmation:
raise HTTPException(status_code=404, detail="Confirmation request not found.")
if confirmation.status != "pending":
raise HTTPException(status_code=409, detail="Confirmation has already been resolved.")
finally:
db.close()
if not runtime.resolve_confirmation(confirmation_id, request.approved):
raise HTTPException(status_code=409, detail="The workflow is no longer waiting for this confirmation.")
return {"ok": True, "approved": request.approved}
@router.post("/workflow-router/select")
async def route_workflow(request: RouterSelectRequest):
db = SessionLocal()
try:
ensure_global_knowledge_store()
return await select_workflow(
db, message=request.message, recent_messages=request.recent_messages[-4:], attachments=request.attachments,
library_slug=request.library_slug or global_library_slug(), router_model=request.model, chat_model=request.chat_model,
web_search_enabled=request.web_search_enabled,
confidence_threshold=request.confidence_threshold,
)
finally:
db.close()

67
backend/agent/bindings.py Normal file
View File

@@ -0,0 +1,67 @@
from __future__ import annotations
import re
from typing import Any, Dict, Iterable, List, Tuple
REFERENCE_RE = re.compile(r"\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}")
class BindingError(ValueError):
pass
def lookup_reference(reference: str, values: Dict[str, Any]) -> Any:
parts = [part for part in str(reference or "").split(".") if part]
if not parts or parts[0] not in {"input", "run", "nodes"}:
raise BindingError(f"Invalid reference root: {reference}")
current: Any = values
traversed: List[str] = []
for part in parts:
traversed.append(part)
if isinstance(current, dict) and part in current:
current = current[part]
continue
if isinstance(current, list) and part.isdigit() and int(part) < len(current):
current = current[int(part)]
continue
raise BindingError(f"Missing reference: {'.'.join(traversed)}")
return current
def resolve_bindings(value: Any, values: Dict[str, Any]) -> Any:
if isinstance(value, dict):
if set(value) == {"$ref"}:
return lookup_reference(str(value["$ref"]), values)
return {key: resolve_bindings(item, values) for key, item in value.items()}
if isinstance(value, list):
return [resolve_bindings(item, values) for item in value]
if not isinstance(value, str) or "{{" not in value:
return value
matches = list(REFERENCE_RE.finditer(value))
if len(matches) == 1 and matches[0].span() == (0, len(value)):
return lookup_reference(matches[0].group(1), values)
output = value
for match in reversed(matches):
resolved = lookup_reference(match.group(1), values)
replacement = "" if resolved is None else str(resolved)
output = output[:match.start()] + replacement + output[match.end():]
if "{{" in output or "}}" in output:
raise BindingError("Malformed template expression")
return output
def iter_references(value: Any, path: str = "") -> Iterable[Tuple[str, str]]:
if isinstance(value, dict):
if set(value) == {"$ref"}:
yield path or "$", str(value["$ref"])
return
for key, item in value.items():
child = f"{path}.{key}" if path else key
yield from iter_references(item, child)
elif isinstance(value, list):
for index, item in enumerate(value):
yield from iter_references(item, f"{path}[{index}]")
elif isinstance(value, str):
for match in REFERENCE_RE.finditer(value):
yield path or "$", match.group(1)

52
backend/agent/events.py Normal file
View File

@@ -0,0 +1,52 @@
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
import json
from typing import Any, Dict, Optional
from sqlalchemy import func
from .models import WorkflowEvent
class EventWriter:
def __init__(self, run_id: str, workflow_id: str, db_factory) -> None:
self.run_id = run_id
self.workflow_id = workflow_id
self.db_factory = db_factory
self._lock = asyncio.Lock()
db = db_factory()
try:
self._sequence = int(db.query(func.max(WorkflowEvent.sequence)).filter(WorkflowEvent.workflow_run_id == run_id).scalar() or 0)
finally:
db.close()
async def emit(self, event_type: str, payload: Dict[str, Any], node_id: Optional[str] = None) -> Dict[str, Any]:
async with self._lock:
self._sequence += 1
timestamp = datetime.now(timezone.utc)
event = {
"run_id": self.run_id,
"workflow_id": self.workflow_id,
"node_id": node_id,
"sequence": self._sequence,
"timestamp": timestamp.isoformat(),
"type": event_type,
"payload": payload,
}
db = self.db_factory()
try:
db.add(WorkflowEvent(
workflow_run_id=self.run_id,
workflow_id=self.workflow_id,
node_id=node_id,
sequence=self._sequence,
event_type=event_type,
timestamp=timestamp.replace(tzinfo=None),
payload_json=json.dumps(payload, ensure_ascii=False, default=str),
))
db.commit()
finally:
db.close()
return event

116
backend/agent/models.py Normal file
View File

@@ -0,0 +1,116 @@
from datetime import datetime
import uuid
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import relationship
from ..database import Base
def _uuid() -> str:
return str(uuid.uuid4())
class WorkflowDefinition(Base):
__tablename__ = "workflow_definitions"
id = Column(String(36), primary_key=True, default=_uuid)
slug = Column(String(100), unique=True, nullable=False, index=True)
name = Column(String(160), nullable=False)
description = Column(Text, nullable=False, default="")
current_revision_id = Column(String(36), nullable=True)
built_in = Column(Boolean, nullable=False, default=False)
enabled = Column(Boolean, nullable=False, default=True)
routing_description = Column(Text, nullable=False, default="")
routing_examples_json = Column(Text, nullable=False, default="[]")
estimated_cost_class = Column(String(32), nullable=False, default="low")
required_capabilities_json = Column(Text, nullable=False, default="[]")
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
revisions = relationship(
"WorkflowRevision",
back_populates="workflow",
foreign_keys="WorkflowRevision.workflow_id",
cascade="all, delete-orphan",
)
class WorkflowRevision(Base):
__tablename__ = "workflow_revisions"
__table_args__ = (UniqueConstraint("workflow_id", "version", name="uq_workflow_revision_version"),)
id = Column(String(36), primary_key=True, default=_uuid)
workflow_id = Column(String(36), ForeignKey("workflow_definitions.id"), nullable=False, index=True)
version = Column(Integer, nullable=False)
graph_json = Column(Text, nullable=False)
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
created_by = Column(String(64), nullable=False, default="user")
trusted = Column(Boolean, nullable=False, default=False)
checksum = Column(String(64), nullable=False, index=True)
workflow = relationship("WorkflowDefinition", back_populates="revisions", foreign_keys=[workflow_id])
class WorkflowRun(Base):
__tablename__ = "workflow_runs"
id = Column(String(36), primary_key=True, default=_uuid)
workflow_id = Column(String(36), ForeignKey("workflow_definitions.id"), nullable=False, index=True)
workflow_revision_id = Column(String(36), ForeignKey("workflow_revisions.id"), nullable=False)
session_id = Column(String(64), nullable=True, index=True)
user_message_id = Column(String(36), nullable=True)
status = Column(String(32), nullable=False, default="queued", index=True)
selection_mode = Column(String(24), nullable=False, default="direct")
inputs_json = Column(Text, nullable=False, default="{}")
outputs_json = Column(Text, nullable=True)
error_json = Column(Text, nullable=True)
metrics_json = Column(Text, nullable=False, default="{}")
started_at = Column(DateTime, nullable=True)
finished_at = Column(DateTime, nullable=True)
cancellation_requested = Column(Boolean, nullable=False, default=False)
class WorkflowNodeRun(Base):
__tablename__ = "workflow_node_runs"
__table_args__ = (UniqueConstraint("workflow_run_id", "node_id", "attempt", name="uq_node_run_attempt"),)
id = Column(String(36), primary_key=True, default=_uuid)
workflow_run_id = Column(String(36), ForeignKey("workflow_runs.id"), nullable=False, index=True)
node_id = Column(String(120), nullable=False)
attempt = Column(Integer, nullable=False, default=1)
status = Column(String(32), nullable=False, default="queued")
resolved_inputs_json = Column(Text, nullable=True)
outputs_json = Column(Text, nullable=True)
error_json = Column(Text, nullable=True)
started_at = Column(DateTime, nullable=True)
finished_at = Column(DateTime, nullable=True)
metrics_json = Column(Text, nullable=False, default="{}")
class WorkflowEvent(Base):
__tablename__ = "workflow_events"
__table_args__ = (UniqueConstraint("workflow_run_id", "sequence", name="uq_workflow_event_sequence"),)
id = Column(String(36), primary_key=True, default=_uuid)
workflow_run_id = Column(String(36), ForeignKey("workflow_runs.id"), nullable=False, index=True)
workflow_id = Column(String(36), nullable=False)
node_id = Column(String(120), nullable=True)
sequence = Column(Integer, nullable=False)
event_type = Column(String(64), nullable=False)
timestamp = Column(DateTime, nullable=False, default=datetime.utcnow)
payload_json = Column(Text, nullable=False, default="{}")
class WorkflowConfirmation(Base):
__tablename__ = "workflow_confirmations"
id = Column(String(36), primary_key=True, default=_uuid)
workflow_run_id = Column(String(36), ForeignKey("workflow_runs.id"), nullable=False, index=True)
node_id = Column(String(120), nullable=False)
tool_name = Column(String(160), nullable=False)
status = Column(String(24), nullable=False, default="pending")
request_json = Column(Text, nullable=False, default="{}")
response_json = Column(Text, nullable=True)
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
resolved_at = Column(DateTime, nullable=True)

View File

@@ -0,0 +1,101 @@
from __future__ import annotations
import json
from typing import Any, Dict, List
from ..ollama_client import chat_typed
from .registry import NativeToolProvider, ToolExecutionContext
def _usage_dict(usage: Any) -> Dict[str, int]:
return {
"prompt_eval_count": usage.prompt_eval_count,
"eval_count": usage.eval_count,
"total_duration": usage.total_duration,
"load_duration": usage.load_duration,
"prompt_eval_duration": usage.prompt_eval_duration,
"eval_duration": usage.eval_duration,
}
async def run_agent_loop(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
registry = context.registry
if registry is None:
raise RuntimeError("Agent tool registry is unavailable.")
allowed_names = []
for name in arguments.get("allowed_tool_names") or []:
if name == "heimgeist.agent":
continue
registry.get_tool(name)
allowed_names.append(name)
tools = [registry.get_tool(name).ollama_manifest() for name in allowed_names]
messages: List[Dict[str, Any]] = [dict(item) for item in arguments.get("messages") or []]
maximum_rounds = max(1, min(int(arguments.get("maximum_rounds") or 4), 8))
maximum_output_chars = max(1000, min(int(arguments.get("maximum_output_chars") or 60_000), 120_000))
tool_summary: List[Dict[str, Any]] = []
usage_totals: Dict[str, int] = {}
for round_index in range(maximum_rounds):
if context.cancellation_event.is_set():
raise RuntimeError("Agent execution was cancelled.")
if context.consume_llm_call:
context.consume_llm_call()
result = await chat_typed(
arguments["model"],
messages,
options=arguments.get("generation_options") or {},
tools=tools or None,
think=bool(arguments.get("reasoning")),
cancellation_event=context.cancellation_event,
)
for key, value in _usage_dict(result.usage).items():
usage_totals[key] = usage_totals.get(key, 0) + int(value or 0)
if result.thinking and context.show_thinking:
await context.emit("model_thinking", {"text": result.thinking, "round": round_index + 1})
if not result.tool_calls:
content = result.content[:maximum_output_chars]
return {
"content": content,
"tool_summary": tool_summary,
"usage": usage_totals,
"rounds": round_index + 1,
}
assistant_message: Dict[str, Any] = {
"role": "assistant",
"content": result.content or "",
"tool_calls": [call.raw for call in result.tool_calls],
}
messages.append(assistant_message)
for call in result.tool_calls:
if call.name not in allowed_names:
tool_result = {"error": f"Tool is not allowed: {call.name}"}
else:
definition = registry.get_tool(call.name)
approved = True
if definition.requires_confirmation and context.request_confirmation:
approved = await context.request_confirmation(definition, call.arguments)
if approved:
await context.emit("tool_started", {"tool": call.name, "arguments": call.arguments, "agent_round": round_index + 1})
try:
tool_result = await registry.call_tool(call.name, call.arguments, context)
except Exception as exc:
tool_result = {"error": f"{type(exc).__name__}: {exc}"}
await context.emit("tool_result", {"tool": call.name, "result": tool_result, "agent_round": round_index + 1})
else:
tool_result = {"status": "rejected", "confirmed": False}
tool_summary.append({"tool": call.name, "arguments": call.arguments, "result": tool_result})
messages.append({
"role": "tool",
"tool_name": call.name,
"content": json.dumps(tool_result, ensure_ascii=False, default=str),
})
return {
"content": "I could not complete the task within the configured agent round limit.",
"tool_summary": tool_summary,
"usage": usage_totals,
"rounds": maximum_rounds,
}

241
backend/agent/registry.py Normal file
View File

@@ -0,0 +1,241 @@
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
import json
from typing import Any, Awaitable, Callable, Dict, Iterable, Optional, Protocol
class SchemaValidationError(ValueError):
pass
def _type_matches(value: Any, expected: str) -> bool:
if expected == "null":
return value is None
if expected == "object":
return isinstance(value, dict)
if expected == "array":
return isinstance(value, list)
if expected == "string":
return isinstance(value, str)
if expected == "boolean":
return isinstance(value, bool)
if expected == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if expected == "number":
return isinstance(value, (int, float)) and not isinstance(value, bool)
return True
def validate_json_schema(value: Any, schema: Dict[str, Any], path: str = "$", *, partial: bool = False) -> None:
if not isinstance(schema, dict):
raise SchemaValidationError(f"{path}: schema must be an object")
if "const" in schema and value != schema["const"]:
raise SchemaValidationError(f"{path}: must equal {schema['const']!r}")
if "enum" in schema and value not in schema["enum"]:
raise SchemaValidationError(f"{path}: must be one of {schema['enum']!r}")
for union_key in ("oneOf", "anyOf"):
if union_key in schema:
matches = 0
errors = []
for candidate in schema[union_key]:
try:
validate_json_schema(value, candidate, path, partial=partial)
matches += 1
except SchemaValidationError as exc:
errors.append(str(exc))
if (union_key == "oneOf" and matches != 1) or (union_key == "anyOf" and matches == 0):
raise SchemaValidationError(f"{path}: does not match {union_key}: {'; '.join(errors[:3])}")
return
expected = schema.get("type")
if isinstance(expected, list):
if not any(_type_matches(value, item) for item in expected):
raise SchemaValidationError(f"{path}: expected one of {expected}, got {type(value).__name__}")
elif expected and not _type_matches(value, expected):
raise SchemaValidationError(f"{path}: expected {expected}, got {type(value).__name__}")
if isinstance(value, dict):
properties = schema.get("properties") or {}
if not partial:
for required in schema.get("required") or []:
if required not in value:
raise SchemaValidationError(f"{path}.{required}: required value is missing")
if schema.get("additionalProperties") is False:
unknown = [key for key in value if key not in properties]
if unknown:
raise SchemaValidationError(f"{path}: unknown properties: {', '.join(unknown)}")
for key, item in value.items():
if key in properties:
validate_json_schema(item, properties[key], f"{path}.{key}", partial=partial)
minimum = schema.get("minProperties")
if minimum is not None and len(value) < minimum:
raise SchemaValidationError(f"{path}: expected at least {minimum} properties")
elif isinstance(value, list):
if "minItems" in schema and len(value) < int(schema["minItems"]):
raise SchemaValidationError(f"{path}: expected at least {schema['minItems']} items")
if "maxItems" in schema and len(value) > int(schema["maxItems"]):
raise SchemaValidationError(f"{path}: expected at most {schema['maxItems']} items")
item_schema = schema.get("items")
if item_schema:
for index, item in enumerate(value):
validate_json_schema(item, item_schema, f"{path}[{index}]", partial=partial)
elif isinstance(value, str):
if "minLength" in schema and len(value) < int(schema["minLength"]):
raise SchemaValidationError(f"{path}: string is too short")
if "maxLength" in schema and len(value) > int(schema["maxLength"]):
raise SchemaValidationError(f"{path}: string is too long")
elif isinstance(value, (int, float)) and not isinstance(value, bool):
if "minimum" in schema and value < schema["minimum"]:
raise SchemaValidationError(f"{path}: must be at least {schema['minimum']}")
if "maximum" in schema and value > schema["maximum"]:
raise SchemaValidationError(f"{path}: must be at most {schema['maximum']}")
def validate_schema_definition(schema: Dict[str, Any], path: str = "$schema") -> None:
if not isinstance(schema, dict):
raise SchemaValidationError(f"{path}: schema must be an object")
expected = schema.get("type")
allowed = {"object", "array", "string", "boolean", "integer", "number", "null"}
if isinstance(expected, str) and expected not in allowed:
raise SchemaValidationError(f"{path}.type: unsupported type {expected!r}")
if isinstance(expected, list) and any(item not in allowed for item in expected):
raise SchemaValidationError(f"{path}.type: contains an unsupported type")
if expected == "object":
properties = schema.get("properties", {})
if not isinstance(properties, dict):
raise SchemaValidationError(f"{path}.properties: must be an object")
for key, child in properties.items():
validate_schema_definition(child, f"{path}.properties.{key}")
required = schema.get("required", [])
if not isinstance(required, list) or any(not isinstance(item, str) for item in required):
raise SchemaValidationError(f"{path}.required: must be a string array")
missing = [item for item in required if item not in properties]
if missing:
raise SchemaValidationError(f"{path}.required: unknown properties: {', '.join(missing)}")
if expected == "array" and "items" in schema:
validate_schema_definition(schema["items"], f"{path}.items")
for key in ("oneOf", "anyOf"):
if key in schema:
if not isinstance(schema[key], list) or not schema[key]:
raise SchemaValidationError(f"{path}.{key}: must be a non-empty array")
for index, child in enumerate(schema[key]):
validate_schema_definition(child, f"{path}.{key}[{index}]")
ToolHandler = Callable[[Dict[str, Any], "ToolExecutionContext"], Awaitable[Dict[str, Any]]]
@dataclass(frozen=True)
class ToolDefinition:
name: str
description: str
input_schema: Dict[str, Any]
output_schema: Dict[str, Any]
handler: ToolHandler
risk_level: str = "low"
timeout_seconds: float = 120.0
result_size_limit: int = 120_000
requires_confirmation: bool = False
llm_call: bool = False
def manifest(self) -> Dict[str, Any]:
return {
"name": self.name,
"description": self.description,
"inputSchema": self.input_schema,
"outputSchema": self.output_schema,
"riskLevel": self.risk_level,
"timeoutSeconds": self.timeout_seconds,
"resultSizeLimit": self.result_size_limit,
"requiresConfirmation": self.requires_confirmation,
}
def ollama_manifest(self) -> Dict[str, Any]:
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.input_schema,
},
}
@dataclass
class ToolExecutionContext:
run_id: str
workflow_id: str
node_id: str
session_id: Optional[str]
selection_mode: str
explicit_user_action: bool
emit: Callable[[str, Dict[str, Any]], Awaitable[None]]
cancellation_event: asyncio.Event
db_factory: Callable[[], Any]
registry: Optional["NativeToolProvider"] = None
run_values: Dict[str, Any] = field(default_factory=dict)
request_confirmation: Optional[Callable[[ToolDefinition, Dict[str, Any]], Awaitable[bool]]] = None
consume_llm_call: Optional[Callable[[], None]] = None
show_thinking: bool = False
class ToolProvider(Protocol):
def list_tools(self) -> Iterable[Dict[str, Any]]: ...
def get_tool(self, name: str) -> ToolDefinition: ...
async def call_tool(self, name: str, arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]: ...
class NativeToolProvider:
def __init__(self) -> None:
self._tools: Dict[str, ToolDefinition] = {}
def register(self, definition: ToolDefinition) -> None:
if definition.name in self._tools:
raise ValueError(f"Duplicate tool name: {definition.name}")
validate_schema_definition(definition.input_schema, f"{definition.name}.inputSchema")
validate_schema_definition(definition.output_schema, f"{definition.name}.outputSchema")
self._tools[definition.name] = definition
def list_tools(self) -> Iterable[Dict[str, Any]]:
return [tool.manifest() for tool in sorted(self._tools.values(), key=lambda item: item.name)]
def get_tool(self, name: str) -> ToolDefinition:
try:
return self._tools[name]
except KeyError as exc:
raise KeyError(f"Unknown tool: {name}") from exc
async def call_tool(self, name: str, arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
definition = self.get_tool(name)
validate_json_schema(arguments, definition.input_schema)
if context.cancellation_event.is_set():
raise asyncio.CancelledError()
if definition.llm_call and context.consume_llm_call:
context.consume_llm_call()
handler_task = asyncio.create_task(definition.handler(arguments, context))
cancellation_task = asyncio.create_task(context.cancellation_event.wait())
try:
done, _pending = await asyncio.wait(
{handler_task, cancellation_task},
timeout=definition.timeout_seconds,
return_when=asyncio.FIRST_COMPLETED,
)
if cancellation_task in done and cancellation_task.result():
handler_task.cancel()
await asyncio.gather(handler_task, return_exceptions=True)
raise asyncio.CancelledError()
if handler_task not in done:
handler_task.cancel()
await asyncio.gather(handler_task, return_exceptions=True)
raise TimeoutError(f"Tool {name} exceeded {definition.timeout_seconds:g}s")
result = handler_task.result()
finally:
cancellation_task.cancel()
await asyncio.gather(cancellation_task, return_exceptions=True)
validate_json_schema(result, definition.output_schema)
size = len(json.dumps(result, ensure_ascii=False, default=str))
if size > definition.result_size_limit:
raise ValueError(f"Tool {name} result exceeded {definition.result_size_limit} characters")
return result

477
backend/agent/router.py Normal file
View File

@@ -0,0 +1,477 @@
from __future__ import annotations
import json
import re
from typing import Any, Dict, List, Optional
from sqlalchemy.orm import Session
from ..app_settings import get_workflow_router_model_preference
from ..ollama_client import chat_typed, list_model_catalog
from .models import WorkflowDefinition
ROUTER_FORMAT = {
"type": "object",
"properties": {
"workflow_id": {"type": "string"},
"confidence": {"type": "number"},
"reason": {"type": "string"},
"inputs": {"type": "object"},
},
"required": ["workflow_id", "confidence", "reason", "inputs"],
"additionalProperties": False,
}
MESSAGE_DIGEST_THRESHOLD = 2600
MESSAGE_DIGEST_HEAD_CHARS = 900
MESSAGE_DIGEST_MIDDLE_CHARS = 500
MESSAGE_DIGEST_TAIL_CHARS = 900
MESSAGE_DIGEST_MAX_SAMPLE_LINES = 6
MESSAGE_DIGEST_SAMPLE_LINE_CHARS = 180
ATTACHMENT_SUMMARY_LIMIT = 8
def workflow_manifests(db: Session) -> List[Dict[str, Any]]:
workflows = db.query(WorkflowDefinition).filter(WorkflowDefinition.enabled.is_(True)).order_by(WorkflowDefinition.name.asc()).all()
manifests = []
for item in workflows:
manifests.append({
"workflow_id": item.id,
"slug": item.slug,
"name": item.name,
"routing_description": item.routing_description,
"examples": json.loads(item.routing_examples_json or "[]"),
"estimated_cost_class": item.estimated_cost_class,
"required_capabilities": json.loads(item.required_capabilities_json or "[]"),
})
return manifests
def _fallback_result(fallback: WorkflowDefinition, reason: str = "Router fallback to direct chat.") -> Dict[str, Any]:
return {
"workflow_id": fallback.id,
"workflow_slug": fallback.slug,
"confidence": 0.0,
"reason": reason,
"inputs": {},
"fallback": True,
}
def _manifest_by_slug(manifests: List[Dict[str, Any]], slug: str) -> Optional[Dict[str, Any]]:
return next((item for item in manifests if item["slug"] == slug), None)
def _workflow_result(item: Dict[str, Any], *, confidence: float, reason: str, inputs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return {
"workflow_id": item["workflow_id"],
"workflow_slug": item["slug"],
"confidence": max(0.0, min(float(confidence), 1.0)),
"reason": reason,
"inputs": inputs or {},
"fallback": False,
}
def _capability_enabled(capability: str, *, library_slug: Optional[str], web_search_enabled: bool, has_attachments: bool) -> bool:
if capability in {"chat", "chat_memory"}:
return True
if capability == "web":
return True
if capability in {"rag", "knowledge_write"}:
return bool(library_slug)
if capability == "vision":
return has_attachments
return False
def _allowed_manifests(
manifests: List[Dict[str, Any]],
*,
library_slug: Optional[str],
web_search_enabled: bool,
has_attachments: bool,
) -> List[Dict[str, Any]]:
allowed = []
for item in manifests:
capabilities = item.get("required_capabilities") or []
if all(_capability_enabled(str(capability), library_slug=library_slug, web_search_enabled=web_search_enabled, has_attachments=has_attachments) for capability in capabilities):
allowed.append(item)
return allowed
def _filter_for_interface_settings(
manifests: List[Dict[str, Any]],
*,
web_search_enabled: bool,
) -> List[Dict[str, Any]]:
if not web_search_enabled:
return manifests
web_capable = [item for item in manifests if "web" in (item.get("required_capabilities") or [])]
return web_capable or manifests
_REMEMBER_RE = re.compile(
r"\b(remember\s+(this|that)|save\s+(this|that)|merk\s+dir\s+(das|:)?|speicher(e)?\s+(das|dies|diese|diesen)?)\b",
re.IGNORECASE,
)
_KNOWLEDGE_RE = re.compile(
r"\b(my\s+(notes|documents|files|database|knowledge)|meine[nr]?\s+(notizen|dokumente|dateien|datenbank|daten)|rag|knowledge\s+base|datenbank)\b",
re.IGNORECASE,
)
_GREETING_RE = re.compile(r"^\s*(hi|hello|hey|hallo|moin|servus|danke|thanks|thank\s+you)[!.?\s]*$", re.IGNORECASE)
def _fast_path(
manifests: List[Dict[str, Any]],
*,
message: str,
library_slug: Optional[str],
web_search_enabled: bool,
has_attachments: bool,
) -> Optional[Dict[str, Any]]:
text = str(message or "").strip()
if not text and not has_attachments:
return None
if has_attachments:
vision = _manifest_by_slug(manifests, "vision-answer")
if vision:
return _workflow_result(vision, confidence=1.0, reason="The request includes attachments.")
mentions_knowledge = bool(_KNOWLEDGE_RE.search(text))
if _REMEMBER_RE.search(text):
remember = _manifest_by_slug(manifests, "remember-this")
if remember:
return _workflow_result(remember, confidence=1.0, reason="The user explicitly asked Heimgeist to remember or save this.")
if web_search_enabled:
return None
if library_slug and mentions_knowledge:
knowledge = _manifest_by_slug(manifests, "knowledge-answer")
if knowledge:
return _workflow_result(knowledge, confidence=0.95, reason="The request explicitly refers to local knowledge.")
if _GREETING_RE.match(text):
direct = _manifest_by_slug(manifests, "input-output")
if direct:
return _workflow_result(direct, confidence=1.0, reason="Simple conversational prompt.")
return None
def _clean_router_queries(raw: Any, fallback: str) -> List[str]:
values = raw if isinstance(raw, list) else [raw]
cleaned: List[str] = []
seen = set()
for item in values:
text = " ".join(str(item or "").split()).strip()
if not text:
continue
key = text.casefold()
if key in seen:
continue
seen.add(key)
cleaned.append(text[:300])
if len(cleaned) >= 5:
break
fallback_text = " ".join(str(fallback or "").split()).strip()
if fallback_text and not cleaned:
cleaned.append(fallback_text[:300])
return cleaned
def _normalize_router_inputs(selected: Dict[str, Any], inputs: Any, message: str) -> Dict[str, Any]:
normalized = dict(inputs) if isinstance(inputs, dict) else {}
if "web" not in (selected.get("required_capabilities") or []):
return normalized
raw_queries = normalized.get("web_search_queries")
if raw_queries is None:
raw_queries = normalized.get("search_queries")
raw_query = normalized.get("web_search_query") or normalized.get("search_query")
queries = _clean_router_queries(raw_queries if raw_queries is not None else raw_query, message)
if raw_query:
raw_query_text = " ".join(str(raw_query).split()).strip()
if raw_query_text and raw_query_text.casefold() not in {item.casefold() for item in queries}:
queries.insert(0, raw_query_text[:300])
queries = queries[:5]
normalized["web_search_query"] = queries[0] if queries else str(message or "")[:300]
normalized["web_search_queries"] = queries or [normalized["web_search_query"]]
return normalized
def _forced_web_manifest(manifests: List[Dict[str, Any]], *, library_slug: Optional[str]) -> Optional[Dict[str, Any]]:
if library_slug:
combined = _manifest_by_slug(manifests, "knowledge-web-answer")
if combined:
return combined
return _manifest_by_slug(manifests, "web-answer")
def _format_recent_messages(recent_messages: List[Dict[str, Any]], *, char_limit: int) -> str:
rows: List[str] = []
for index, item in enumerate(recent_messages[-4:], 1):
role = str(item.get("role") or "message").strip().title()
content = " ".join(str(item.get("content") or "").split())
if len(content) > char_limit:
content = content[:char_limit].rstrip() + "..."
rows.append(f"{index}. {role}: {content}")
return "\n".join(rows) if rows else "(none)"
def _normalize_message_text(message: str) -> str:
return str(message or "").replace("\r\n", "\n").replace("\r", "\n").replace("\x00", "")
def _short_line(line: str, limit: int = MESSAGE_DIGEST_SAMPLE_LINE_CHARS) -> str:
text = " ".join(str(line or "").split()).strip()
if len(text) > limit:
text = text[:limit].rstrip() + "..."
return text
def _sample_representative_lines(text: str, *, max_lines: int = MESSAGE_DIGEST_MAX_SAMPLE_LINES) -> List[str]:
candidates = []
seen = set()
for line_number, line in enumerate(text.splitlines(), 1):
compact = _short_line(line)
if not compact:
continue
if compact in seen:
continue
seen.add(compact)
candidates.append((line_number, compact))
if len(candidates) <= max_lines:
return [f"L{line_number}: {compact}" for line_number, compact in candidates]
if max_lines <= 1:
line_number, compact = candidates[0]
return [f"L{line_number}: {compact}"]
selected = []
last_index = len(candidates) - 1
for index in range(max_lines):
selected_index = round(index * last_index / (max_lines - 1))
line_number, compact = candidates[selected_index]
selected.append(f"L{line_number}: {compact}")
return selected
def _count_substrings(text: str, values: List[str]) -> int:
lowered = text.casefold()
return sum(lowered.count(value.casefold()) for value in values)
def _format_message_for_router(message: str) -> str:
text = _normalize_message_text(message)
if len(text) <= MESSAGE_DIGEST_THRESHOLD:
return text
lines = text.splitlines()
middle_start = max(0, (len(text) - MESSAGE_DIGEST_MIDDLE_CHARS) // 2)
middle_end = min(len(text), middle_start + MESSAGE_DIGEST_MIDDLE_CHARS)
samples = _sample_representative_lines(text)
sections = [
"<long_user_message_digest>",
f"Original length: {len(text)} characters, {len(lines)} lines.",
f"Detected structure: {_count_substrings(text, ['http://', 'https://'])} URL marker(s), {text.count('```')} code-fence marker(s).",
"This is a routing digest, not the full message. Use the visible beginning/end and structural summary to route; do not infer omitted content.",
"",
"<beginning_excerpt>",
text[:MESSAGE_DIGEST_HEAD_CHARS].rstrip(),
"</beginning_excerpt>",
"",
"<middle_excerpt>",
text[middle_start:middle_end].strip(),
"</middle_excerpt>",
"",
"<ending_excerpt>",
text[-MESSAGE_DIGEST_TAIL_CHARS:].lstrip(),
"</ending_excerpt>",
]
if samples:
sections.extend([
"",
"<representative_short_lines>",
*samples,
"</representative_short_lines>",
])
sections.append("</long_user_message_digest>")
return "\n".join(sections)
def _format_attachment_summary(attachments: List[Dict[str, Any]]) -> str:
if not attachments:
return "No attachments."
rows = [f"{len(attachments)} attachment(s) are present."]
for index, attachment in enumerate(attachments[:ATTACHMENT_SUMMARY_LIMIT], 1):
if not isinstance(attachment, dict):
rows.append(f"{index}. Attachment")
continue
kind = str(attachment.get("kind") or ("image" if attachment.get("data_url") else "file") or "attachment")
name = str(attachment.get("name") or attachment.get("source_path") or f"attachment-{index}")
mime_type = str(attachment.get("mime_type") or "").strip()
size = attachment.get("size")
text_length = len(str(attachment.get("text") or ""))
parts = [f"{index}. {kind}: {name}"]
if mime_type:
parts.append(f"mime={mime_type}")
if size is not None:
parts.append(f"size={size}")
if text_length:
parts.append(f"text_chars={text_length}")
rows.append("; ".join(parts))
if len(attachments) > ATTACHMENT_SUMMARY_LIMIT:
rows.append(f"... {len(attachments) - ATTACHMENT_SUMMARY_LIMIT} more attachment(s) omitted from routing summary.")
return "\n".join(rows)
def _format_workflow_choices(manifests: List[Dict[str, Any]]) -> str:
rows: List[str] = []
for item in manifests:
examples = "; ".join(str(value) for value in (item.get("examples") or [])[:2])
capabilities = ", ".join(str(value) for value in (item.get("required_capabilities") or []))
suffix = f" Examples: {examples}." if examples else ""
rows.append(
f"- {item['name']} ({item['slug']}, id: {item['workflow_id']}): "
f"Capabilities: {capabilities or 'none'}. "
f"Routing contract: {item.get('routing_description') or 'No description.'}{suffix}"
)
return "\n".join(rows)
def _router_prompt(
*,
message: str,
recent_messages: List[Dict[str, Any]],
attachments: List[Dict[str, Any]],
manifests: List[Dict[str, Any]],
) -> str:
message_excerpt = _format_message_for_router(message)
history_chars = 250 if len(message_excerpt) > MESSAGE_DIGEST_THRESHOLD else 500
attachment_line = _format_attachment_summary(attachments)
return (
"You are Heimgeist's workflow router. Choose exactly one allowed workflow for the current user message.\n\n"
"Decision method:\n"
"1. Resolve the current message into a standalone request using recent conversation. Do this before choosing a workflow.\n"
"2. Identify which capabilities are required to answer faithfully: ordinary chat, local knowledge retrieval, web evidence, attachment analysis, or saving knowledge.\n"
"3. Choose the lowest-complexity allowed workflow whose capabilities cover the required work. If two workflows can answer faithfully, choose the simpler one. Do not choose a workflow because an example sounds similar; use the routing contract and capabilities.\n"
"4. Choose a direct chat workflow only when the answer can be produced from the conversation, stable model knowledge, writing/reasoning ability, or already-supplied context. If the request needs information from outside those sources, choose a workflow with the needed capability.\n"
"5. Choose a web-answer workflow when the missing capability is external facts or source grounding and one search-and-answer pass should be enough. Needing web evidence by itself is not a reason to choose Research.\n"
"6. Choose the research workflow only when the standalone request asks for or truly requires investigation, comparison, dispute resolution, claim validation, broad synthesis, or a second search pass. If unsure between Web Answer and Research, choose Web Answer.\n\n"
"Context resolution rules:\n"
"- Short follow-ups usually inherit the previous subject, place, entity, file, source, or task unless the user clearly changes topic.\n"
"- Resolve pronouns and fragments such as 'that', 'it', 'there', 'also', 'and', 'politically', or 'what about' into the standalone request.\n"
"- For web workflows, write search queries for the standalone factual request, not the literal fragment the user typed.\n\n"
"Long-message routing rule:\n"
"- If the current user message is shown as a digest, route from the user's explicit request and the required capabilities. A long pasted payload alone does not require web search or research.\n\n"
f"Recent conversation:\n{_format_recent_messages(recent_messages, char_limit=history_chars)}\n\n"
f"Current user message or routing digest:\n{message_excerpt}\n\n"
f"Attachments:\n{attachment_line}\n\n"
"Allowed workflows. This list is already filtered by interface settings and available capabilities; choose only from this list:\n"
f"{_format_workflow_choices(manifests)}\n\n"
"Return JSON only with this shape:\n"
"{\n"
' "workflow_id": "<id or slug from allowed workflows>",\n'
' "confidence": 0.0,\n'
' "reason": "<brief reason>",\n'
' "inputs": {\n'
' "resolved_request": "<standalone interpretation of the current request>",\n'
' "web_search_query": "<required for web workflows>",\n'
' "web_search_queries": ["<required for web workflows, 1-5 concise queries>"]\n'
" }\n"
"}\n"
"For non-web workflows, inputs may be empty unless useful. For web workflows, web_search_query and web_search_queries are required."
)
async def select_workflow(
db: Session,
*,
message: str,
recent_messages: List[Dict[str, Any]],
attachments: List[Dict[str, Any]],
library_slug: Optional[str],
router_model: Optional[str],
chat_model: Optional[str],
web_search_enabled: bool = False,
confidence_threshold: float = 0.55,
) -> Dict[str, Any]:
fallback = db.query(WorkflowDefinition).filter(WorkflowDefinition.slug == "input-output").first()
if fallback is None:
raise RuntimeError("The built-in input-output workflow is missing.")
fallback_result = _fallback_result(fallback)
has_attachments = bool(attachments)
manifests = _allowed_manifests(
workflow_manifests(db),
library_slug=library_slug,
web_search_enabled=web_search_enabled,
has_attachments=has_attachments,
)
fast = _fast_path(
manifests,
message=message,
library_slug=library_slug,
web_search_enabled=web_search_enabled,
has_attachments=has_attachments,
)
if fast:
return fast
manifests = _filter_for_interface_settings(manifests, web_search_enabled=web_search_enabled)
if not manifests:
return fallback_result
preferred = str(router_model or get_workflow_router_model_preference() or "").strip()
model = preferred or str(chat_model or "").strip()
if not model:
return fallback_result
if preferred:
try:
catalog = await list_model_catalog()
if preferred not in (catalog.get("chat_models") or []):
model = str(chat_model or "").strip()
except Exception:
model = str(chat_model or "").strip() or preferred
if not model:
return fallback_result
prompt = _router_prompt(message=message, recent_messages=recent_messages, attachments=attachments, manifests=manifests)
try:
result = await chat_typed(
model,
[{"role": "user", "content": prompt}],
format=ROUTER_FORMAT,
options={"temperature": 0, "num_ctx": 4096},
)
parsed = json.loads(result.content)
workflow_id = str(parsed.get("workflow_id") or "")
selected = next((item for item in manifests if item["workflow_id"] == workflow_id or item["slug"] == workflow_id), None)
confidence = float(parsed.get("confidence") or 0)
forced_web = _forced_web_manifest(manifests, library_slug=library_slug) if web_search_enabled else None
forced = False
if selected is None and forced_web:
selected = forced_web
confidence = max(confidence, 0.95)
forced = True
elif selected is not None and forced_web and "web" not in (selected.get("required_capabilities") or []):
selected = forced_web
confidence = max(confidence, 0.95)
forced = True
if selected is None or (confidence < confidence_threshold and not forced):
return fallback_result
if "rag" in selected["required_capabilities"] and not library_slug:
return fallback_result
inputs = _normalize_router_inputs(selected, parsed.get("inputs"), message)
return {
"workflow_id": selected["workflow_id"],
"workflow_slug": selected["slug"],
"confidence": max(0.0, min(confidence, 1.0)),
"reason": (str(parsed.get("reason") or "") + (" Forced web search is enabled." if forced else "")).strip(),
"inputs": inputs,
"fallback": False,
"model": model,
}
except Exception as exc:
return {**fallback_result, "reason": f"Router failed: {type(exc).__name__}: {exc}"}

644
backend/agent/runtime.py Normal file
View File

@@ -0,0 +1,644 @@
from __future__ import annotations
import asyncio
from collections import defaultdict
from datetime import datetime
import json
import time
import uuid
from typing import Any, Dict, List, Optional, Set
from sqlalchemy.orm import Session
from .. import models as chat_models
from ..chat_memory import safe_sync_chat_memory_for_session
from ..ollama_client import chat_typed
from .bindings import BindingError, resolve_bindings
from .events import EventWriter
from .models import WorkflowConfirmation, WorkflowNodeRun, WorkflowRevision, WorkflowRun
from .registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
from .schemas import WorkflowGraph, WorkflowNode
from .validation import validate_workflow_graph
TERMINAL_NODE_STATUSES = {"completed", "failed", "skipped", "cancelled"}
def json_size(value: Any) -> int:
return len(json.dumps(value, ensure_ascii=False, default=str))
def collect_sources(value: Any) -> List[Any]:
output: List[Any] = []
seen = set()
def visit(item: Any) -> None:
if isinstance(item, dict):
if isinstance(item.get("sources"), list):
for source in item["sources"]:
key = json.dumps(source, sort_keys=True, ensure_ascii=False, default=str)
if key not in seen:
seen.add(key)
output.append(source)
for child in item.values():
visit(child)
elif isinstance(item, list):
for child in item:
visit(child)
visit(value)
return output
def _merge_values(values: List[Any], deduplicate_by: Optional[str]) -> Dict[str, Any]:
context_parts: List[str] = []
sources: List[Any] = []
items: List[Any] = []
seen = set()
for value in values:
if value is None:
continue
if isinstance(value, dict):
text = str(value.get("context_block") or value.get("content") or "").strip()
if text:
context_parts.append(text)
candidates = value.get("sources") if isinstance(value.get("sources"), list) else []
items.append(value)
elif isinstance(value, list):
candidates = value
items.extend(value)
else:
candidates = []
context_parts.append(str(value))
for source in candidates:
if deduplicate_by and isinstance(source, dict):
key = str(source.get(deduplicate_by) or json.dumps(source, sort_keys=True, default=str))
else:
key = json.dumps(source, sort_keys=True, ensure_ascii=False, default=str)
if key not in seen:
seen.add(key)
sources.append(source)
return {"context_block": "\n\n".join(context_parts), "sources": sources, "items": items}
class WorkflowRuntime:
def __init__(self, registry: NativeToolProvider, db_factory) -> None:
self.registry = registry
self.db_factory = db_factory
self.active_runs: Dict[str, asyncio.Task] = {}
self.cancellation_events: Dict[str, asyncio.Event] = {}
self.confirmation_futures: Dict[str, asyncio.Future] = {}
def start(self, run_id: str) -> None:
if run_id in self.active_runs and not self.active_runs[run_id].done():
return
task = asyncio.create_task(self.execute(run_id))
self.active_runs[run_id] = task
task.add_done_callback(lambda _task: self.active_runs.pop(run_id, None))
def cancel(self, run_id: str) -> bool:
event = self.cancellation_events.get(run_id)
if event:
event.set()
db = self.db_factory()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
if not run:
return False
run.cancellation_requested = True
db.commit()
return True
finally:
db.close()
def resolve_confirmation(self, confirmation_id: str, approved: bool) -> bool:
future = self.confirmation_futures.get(confirmation_id)
if future and not future.done():
future.set_result(bool(approved))
return True
return False
async def execute(self, run_id: str) -> None:
db = self.db_factory()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
if run is None:
return
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == run.workflow_revision_id).first()
if revision is None:
run.status = "failed"
run.error_json = json.dumps({"message": "Workflow revision not found."})
run.finished_at = datetime.utcnow()
db.commit()
return
graph_raw = json.loads(revision.graph_json)
inputs = json.loads(run.inputs_json or "{}")
workflow_id = run.workflow_id
selection_mode = run.selection_mode
session_id = run.session_id
finally:
db.close()
writer = EventWriter(run_id, workflow_id, self.db_factory)
cancellation_event = asyncio.Event()
self.cancellation_events[run_id] = cancellation_event
graph = WorkflowGraph.model_validate(graph_raw)
validation = validate_workflow_graph(graph_raw, self.registry)
if not validation.valid:
await self._fail_run(run_id, writer, "Workflow validation failed.", {"errors": [item.model_dump() for item in validation.errors]})
return
db = self.db_factory()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
run.status = "running"
run.started_at = datetime.utcnow()
db.commit()
finally:
db.close()
await writer.emit("run_started", {"inputs": inputs})
started = time.monotonic()
counters = {"tool_calls": 0, "llm_calls": 0, "nodes": 0}
counter_lock = asyncio.Lock()
node_outputs: Dict[str, Any] = {}
run_values = dict(inputs.get("run") or {})
run_values["maximum_tool_calls_override"] = graph.limits.maximum_tool_calls
workflow_inputs = dict(inputs.get("input") or {})
values = {"input": workflow_inputs, "run": run_values, "nodes": {}}
def consume_llm_call() -> None:
counters["llm_calls"] += 1
if counters["llm_calls"] > graph.limits.maximum_llm_calls:
raise RuntimeError("Workflow exceeded maximum_llm_calls.")
try:
if (
selection_mode == "direct"
or run_values.get("compatibility_rag_enabled")
or run_values.get("compatibility_web_enabled")
):
existing_context_blocks = list(run_values.get("context_blocks") or [])
compatibility_context_blocks = await self._prepare_compatibility_context(
run_id, workflow_id, run_values, workflow_inputs, writer, cancellation_event, counters, consume_llm_call
)
run_values["context_blocks"] = [*compatibility_context_blocks, *existing_context_blocks]
await asyncio.wait_for(
self._execute_graph(
run_id, workflow_id, session_id, selection_mode, graph, values, node_outputs,
writer, cancellation_event, counters, counter_lock, consume_llm_call,
explicit_user_action=bool(inputs.get("explicit_user_action")),
),
timeout=graph.limits.maximum_runtime_seconds,
)
if cancellation_event.is_set():
raise asyncio.CancelledError()
output_nodes = [node for node in graph.nodes if node.type == "output" and node.id in node_outputs]
if not output_nodes:
raise RuntimeError("Workflow completed without an output node result.")
final_output = node_outputs[output_nodes[-1].id]
if json_size(final_output) > graph.limits.maximum_result_chars:
raise RuntimeError("Workflow final output exceeded maximum_result_chars.")
await self._persist_assistant_message(run_id, final_output, counters, time.monotonic() - started)
db = self.db_factory()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
run.status = "completed"
run.outputs_json = json.dumps(final_output, ensure_ascii=False, default=str)
run.metrics_json = json.dumps({**counters, "duration_seconds": time.monotonic() - started})
run.finished_at = datetime.utcnow()
db.commit()
finally:
db.close()
await writer.emit("run_completed", {"output": final_output, "metrics": {**counters, "duration_seconds": time.monotonic() - started}})
except asyncio.CancelledError:
db = self.db_factory()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
run.status = "cancelled"
run.finished_at = datetime.utcnow()
run.metrics_json = json.dumps({**counters, "duration_seconds": time.monotonic() - started})
db.commit()
finally:
db.close()
await writer.emit("run_cancelled", {"metrics": counters})
except Exception as exc:
await self._fail_run(run_id, writer, f"{type(exc).__name__}: {exc}", {"metrics": counters})
finally:
self.cancellation_events.pop(run_id, None)
async def _prepare_compatibility_context(
self, run_id: str, workflow_id: str, run_values: Dict[str, Any], workflow_inputs: Dict[str, Any],
writer: EventWriter, cancellation_event: asyncio.Event, counters: Dict[str, int], consume_llm_call,
) -> List[Any]:
blocks: List[Any] = []
context = ToolExecutionContext(
run_id=run_id, workflow_id=workflow_id, node_id="compatibility", session_id=run_values.get("session_id"),
selection_mode="direct", explicit_user_action=True,
emit=lambda event_type, payload: writer.emit(event_type, payload, "compatibility"),
cancellation_event=cancellation_event, db_factory=self.db_factory, registry=self.registry,
run_values=run_values, consume_llm_call=consume_llm_call,
)
prompt = str(workflow_inputs.get("prompt") or "")
rag_enabled = bool(run_values.get("compatibility_rag_enabled", run_values.get("manual_library_enabled")))
web_enabled = bool(run_values.get("compatibility_web_enabled", run_values.get("web_search_enabled")))
if run_values.get("library_slug") and rag_enabled and prompt:
try:
counters["tool_calls"] += 1
await writer.emit("tool_started", {"tool": "heimgeist.knowledge_search"}, "compatibility")
result = await self.registry.call_tool("heimgeist.knowledge_search", {
"prompt": prompt, "library_slug": run_values["library_slug"], "top_k": 5,
"context_character_budget": 12000, "embedding_model": None,
}, context)
blocks.append(result)
await writer.emit("tool_result", {"tool": "heimgeist.knowledge_search", "result": result}, "compatibility")
except Exception as exc:
await writer.emit("tool_result", {"tool": "heimgeist.knowledge_search", "error": str(exc)}, "compatibility")
if web_enabled and prompt:
try:
query_args = {"prompt": prompt, "model": run_values["chat_model"], "messages": run_values.get("messages") or []}
counters["tool_calls"] += 1
queries = await self.registry.call_tool("heimgeist.web_generate_queries", query_args, context)
counters["tool_calls"] += 1
search = await self.registry.call_tool("heimgeist.web_search", {
"query": None, "queries": queries["queries"], "engines": run_values.get("searx_engines") or [],
"maximum_results": 14, "searx_url": run_values.get("searx_url"),
}, context)
counters["tool_calls"] += 1
fetched = await self.registry.call_tool("heimgeist.web_fetch", {"url": None, "urls": search["results"], "maximum_pages": 6}, context)
counters["tool_calls"] += 1
ranked = await self.registry.call_tool("heimgeist.web_rerank", {
"prompt": prompt, "pages": fetched["pages"], "model": run_values["chat_model"], "rerank_model": None,
"context_excerpt": "", "maximum_results": 6, "minimum_score": 55,
}, context)
blocks.append(ranked)
await writer.emit("tool_result", {"tool": "compatibility_web", "result": ranked}, "compatibility")
except Exception as exc:
await writer.emit("tool_result", {"tool": "compatibility_web", "error": str(exc)}, "compatibility")
return blocks
async def _execute_graph(
self, run_id: str, workflow_id: str, session_id: Optional[str], selection_mode: str,
graph: WorkflowGraph, values: Dict[str, Any], node_outputs: Dict[str, Any], writer: EventWriter,
cancellation_event: asyncio.Event, counters: Dict[str, int], counter_lock: asyncio.Lock, consume_llm_call,
explicit_user_action: bool,
) -> None:
nodes = {node.id: node for node in graph.nodes}
incoming = defaultdict(list)
outgoing = defaultdict(list)
for edge in graph.edges:
incoming[edge.target].append(edge)
outgoing[edge.source].append(edge)
statuses = {node_id: "pending" for node_id in nodes}
semaphore = asyncio.Semaphore(graph.limits.maximum_concurrency)
def edge_active(edge) -> bool:
source_node = nodes[edge.source]
if statuses[edge.source] != "completed":
return False
if source_node.type != "condition":
return True
result = bool((node_outputs.get(edge.source) or {}).get("result"))
return edge.source_handle in {"output", "true" if result else "false"}
async def execute_one(node: WorkflowNode) -> None:
async with semaphore:
if cancellation_event.is_set():
raise asyncio.CancelledError()
statuses[node.id] = "running"
counters["nodes"] += 1
await self._create_node_run(run_id, node.id, "running")
await writer.emit("node_started", {"type": node.type}, node.id)
started = time.monotonic()
try:
output, resolved_inputs = await self._execute_node(
run_id, workflow_id, session_id, selection_mode, node, values, writer,
cancellation_event, counters, counter_lock, consume_llm_call, explicit_user_action,
)
if json_size(output) > graph.limits.maximum_result_chars:
raise RuntimeError(f"Node {node.id} output exceeded maximum_result_chars.")
statuses[node.id] = "completed"
node_outputs[node.id] = output
values["nodes"][node.id] = {"output": output}
await self._finish_node_run(run_id, node.id, "completed", resolved_inputs, output, None, time.monotonic() - started)
for source in collect_sources(output):
await writer.emit("source_found", {"source": source}, node.id)
await writer.emit("node_completed", {"output": output, "duration_seconds": time.monotonic() - started}, node.id)
except Exception as exc:
statuses[node.id] = "failed"
error = {"type": type(exc).__name__, "message": str(exc), "node_id": node.id}
await self._finish_node_run(run_id, node.id, "failed", None, None, error, time.monotonic() - started)
await writer.emit("node_failed", error, node.id)
raise
while True:
if cancellation_event.is_set():
raise asyncio.CancelledError()
pending = [node_id for node_id, status in statuses.items() if status == "pending"]
if not pending:
break
progressed = False
ready: List[WorkflowNode] = []
for node_id in pending:
dependencies = incoming[node_id]
if any(statuses[edge.source] not in TERMINAL_NODE_STATUSES for edge in dependencies):
continue
if dependencies and not any(edge_active(edge) for edge in dependencies):
statuses[node_id] = "skipped"
await self._create_node_run(run_id, node_id, "skipped")
await writer.emit("node_completed", {"skipped": True}, node_id)
progressed = True
continue
ready.append(nodes[node_id])
if ready:
progressed = True
for node in ready:
statuses[node.id] = "queued"
await writer.emit("node_queued", {"type": node.type}, node.id)
await asyncio.gather(*(execute_one(node) for node in ready))
if not progressed:
raise RuntimeError("Workflow scheduler could not resolve remaining nodes.")
async def _execute_node(
self, run_id: str, workflow_id: str, session_id: Optional[str], selection_mode: str,
node: WorkflowNode, values: Dict[str, Any], writer: EventWriter, cancellation_event: asyncio.Event,
counters: Dict[str, int], counter_lock: asyncio.Lock, consume_llm_call, explicit_user_action: bool,
) -> tuple[Any, Any]:
if node.type == "input":
return dict(values["input"]), dict(values["input"])
if node.type == "output":
resolved = resolve_bindings(node.config.get("value", {}), values)
return resolved, resolved
if node.type == "template":
template = str(node.config.get("template") or "")
resolved = resolve_bindings(template, values)
return resolved, {"template": resolved}
if node.type == "select":
resolved = resolve_bindings(node.config.get("value"), values)
return resolved, {"value": resolved}
if node.type == "merge":
resolved_values = []
for item in node.config.get("values") or []:
try:
resolved_values.append(resolve_bindings(item, values))
except BindingError:
if not node.config.get("allow_missing"):
raise
output = _merge_values(resolved_values, node.config.get("deduplicate_by"))
return output, {"values": resolved_values}
if node.type == "limit":
resolved = resolve_bindings(node.config.get("value"), values)
maximum = max(1, int(node.config.get("maximum_chars") or 12000))
output = self._limit_value(resolved, maximum)
return output, {"value": resolved, "maximum_chars": maximum}
if node.type == "condition":
left = resolve_bindings(node.config.get("value"), values)
right = resolve_bindings(node.config.get("compare_to"), values)
result = self._condition(node.config.get("operation"), left, right)
return {"result": result, "value": left}, {"value": left, "compare_to": right}
if node.type == "prompt":
return await self._execute_prompt(node, values, writer, consume_llm_call, cancellation_event)
if node.type in {"tool", "agent"}:
tool_name = "heimgeist.agent" if node.type == "agent" else str(node.config.get("tool") or "")
arguments_config = node.config.get("arguments") or node.config
arguments = resolve_bindings(arguments_config, values)
if tool_name == "heimgeist.chat":
run_context_blocks = values["run"].get("context_blocks") or []
node_context_blocks = arguments.get("context_blocks") or []
if run_context_blocks:
arguments["context_blocks"] = [*node_context_blocks, *run_context_blocks]
async with counter_lock:
counters["tool_calls"] += 1
maximum = int(values.get("run", {}).get("maximum_tool_calls_override") or 0)
if maximum and counters["tool_calls"] > maximum:
raise RuntimeError("Workflow exceeded maximum tool calls.")
definition = self.registry.get_tool(tool_name)
async def request_confirmation(tool: ToolDefinition, tool_arguments: Dict[str, Any]) -> bool:
if explicit_user_action or selection_mode != "automatic":
return True
return await self._request_confirmation(run_id, workflow_id, node.id, tool, tool_arguments, writer)
context = ToolExecutionContext(
run_id=run_id, workflow_id=workflow_id, node_id=node.id, session_id=session_id,
selection_mode=selection_mode, explicit_user_action=explicit_user_action,
emit=lambda event_type, payload: writer.emit(event_type, payload, node.id),
cancellation_event=cancellation_event, db_factory=self.db_factory, registry=self.registry,
run_values=values["run"], request_confirmation=request_confirmation,
consume_llm_call=consume_llm_call, show_thinking=bool(values["run"].get("show_thinking")),
)
if definition.requires_confirmation:
approved = await request_confirmation(definition, arguments)
if not approved:
return {"status": "rejected", "confirmed": False, "result": {}}, arguments
await writer.emit("tool_started", {"tool": tool_name, "arguments": arguments}, node.id)
result = await self.registry.call_tool(tool_name, arguments, context)
await writer.emit("tool_result", {"tool": tool_name, "result": result}, node.id)
return result, arguments
raise RuntimeError(f"Unsupported node type: {node.type}")
async def _execute_prompt(self, node: WorkflowNode, values: Dict[str, Any], writer: EventWriter, consume_llm_call, cancellation_event) -> tuple[Any, Any]:
source = node.config.get("model_source")
if source == "fixed":
model = str(node.config.get("model") or "")
elif source == "router_model":
model = str(values["run"].get("router_model") or values["run"].get("chat_model") or "")
elif source == "workflow_variable":
model = str(resolve_bindings(node.config.get("model"), values) or "")
else:
model = str(values["run"].get("chat_model") or "")
if not model:
raise RuntimeError(f"Prompt node {node.id} has no available model.")
system = resolve_bindings(str(node.config.get("system_template") or ""), values)
user = resolve_bindings(str(node.config.get("user_template") or ""), values)
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": user})
output_mode = node.config.get("output_mode") or "text"
format_schema = node.config.get("json_schema") if output_mode in {"json", "score", "decision"} else None
consume_llm_call()
result = await chat_typed(
model, messages,
format=format_schema,
options={"temperature": float(node.config.get("temperature") or 0), **(node.config.get("generation_options") or {})},
cancellation_event=cancellation_event,
)
if result.thinking and values["run"].get("show_thinking"):
await writer.emit("model_thinking", {"text": result.thinking}, node.id)
if result.content:
await writer.emit("model_token", {"text": result.content}, node.id)
if output_mode == "text":
output: Any = {"content": result.content}
else:
try:
output = json.loads(result.content)
except Exception:
if not node.config.get("json_repair"):
raise RuntimeError(f"Prompt node {node.id} returned invalid JSON.")
consume_llm_call()
repair = await chat_typed(
model,
[{"role": "user", "content": f"Repair this into valid JSON matching the schema. Return JSON only.\n{result.content}"}],
format=format_schema,
options={"temperature": 0},
cancellation_event=cancellation_event,
)
output = json.loads(repair.content)
return output, {"model": model, "messages": messages, "output_mode": output_mode}
async def _request_confirmation(
self, run_id: str, workflow_id: str, node_id: str, definition: ToolDefinition,
arguments: Dict[str, Any], writer: EventWriter,
) -> bool:
confirmation_id = str(uuid.uuid4())
db = self.db_factory()
try:
db.add(WorkflowConfirmation(
id=confirmation_id, workflow_run_id=run_id, node_id=node_id, tool_name=definition.name,
request_json=json.dumps(arguments, ensure_ascii=False, default=str),
))
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
run.status = "waiting_confirmation"
db.commit()
finally:
db.close()
await writer.emit("confirmation_required", {
"confirmation_id": confirmation_id, "tool": definition.name, "risk_level": definition.risk_level,
"arguments": arguments,
}, node_id)
future = asyncio.get_running_loop().create_future()
self.confirmation_futures[confirmation_id] = future
try:
approved = bool(await future)
finally:
self.confirmation_futures.pop(confirmation_id, None)
db = self.db_factory()
try:
confirmation = db.query(WorkflowConfirmation).filter(WorkflowConfirmation.id == confirmation_id).first()
if confirmation:
confirmation.status = "approved" if approved else "rejected"
confirmation.response_json = json.dumps({"approved": approved})
confirmation.resolved_at = datetime.utcnow()
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
if run:
run.status = "running"
db.commit()
finally:
db.close()
return approved
@staticmethod
def _condition(operation: str, left: Any, right: Any) -> bool:
if operation == "equals": return left == right
if operation == "not_equals": return left != right
if operation == "exists": return left not in (None, "", [], {})
if operation == "greater_than": return left > right
if operation == "less_than": return left < right
if operation == "contains": return right in left
if operation == "array_not_empty": return isinstance(left, list) and bool(left)
if operation == "score_at_least": return float(left or 0) >= float(right or 0)
raise RuntimeError(f"Unsupported condition operation: {operation}")
@staticmethod
def _limit_value(value: Any, maximum: int) -> Any:
if isinstance(value, str):
return value[:maximum]
if isinstance(value, dict):
result = dict(value)
if "context_block" in result:
result["context_block"] = str(result["context_block"])[:maximum]
result.pop("items", None)
return result
if isinstance(value, list):
result = []
for item in value:
if json_size(result + [item]) > maximum:
break
result.append(item)
return result
return value
async def _create_node_run(self, run_id: str, node_id: str, status: str) -> None:
db = self.db_factory()
try:
row = db.query(WorkflowNodeRun).filter(
WorkflowNodeRun.workflow_run_id == run_id,
WorkflowNodeRun.node_id == node_id,
WorkflowNodeRun.attempt == 1,
).first()
if row is None:
row = WorkflowNodeRun(workflow_run_id=run_id, node_id=node_id, attempt=1)
db.add(row)
row.status = status
if status == "running":
row.started_at = datetime.utcnow()
if status == "skipped":
row.finished_at = datetime.utcnow()
db.commit()
finally:
db.close()
async def _finish_node_run(self, run_id: str, node_id: str, status: str, resolved: Any, output: Any, error: Any, duration: float) -> None:
db = self.db_factory()
try:
row = db.query(WorkflowNodeRun).filter(
WorkflowNodeRun.workflow_run_id == run_id,
WorkflowNodeRun.node_id == node_id,
WorkflowNodeRun.attempt == 1,
).first()
if row:
row.status = status
row.resolved_inputs_json = json.dumps(resolved, ensure_ascii=False, default=str) if resolved is not None else None
row.outputs_json = json.dumps(output, ensure_ascii=False, default=str) if output is not None else None
row.error_json = json.dumps(error, ensure_ascii=False, default=str) if error is not None else None
row.finished_at = datetime.utcnow()
row.metrics_json = json.dumps({"duration_seconds": duration})
db.commit()
finally:
db.close()
async def _persist_assistant_message(self, run_id: str, output: Any, counters: Dict[str, int], duration: float) -> None:
content = output.get("content") if isinstance(output, dict) else str(output)
if not isinstance(content, str) or not content.strip():
raise RuntimeError("Workflow output did not contain assistant content.")
sources = collect_sources(output)
usage = output.get("usage") if isinstance(output, dict) and isinstance(output.get("usage"), dict) else {}
db = self.db_factory()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
if run is None or not run.session_id:
return
session = db.query(chat_models.ChatSession).filter(chat_models.ChatSession.session_id == run.session_id).first()
if session is None:
raise RuntimeError("Chat session no longer exists.")
db.add(chat_models.ChatMessage(
session_pk=session.id, role="assistant", content=content,
sources_json=json.dumps(sources, ensure_ascii=False, default=str),
workflow_id=run.workflow_id, workflow_revision_id=run.workflow_revision_id, workflow_run_id=run.id,
agent_summary_json=json.dumps({
"tool_calls": counters["tool_calls"],
"llm_calls": counters["llm_calls"],
"duration_seconds": duration,
"selection_mode": run.selection_mode,
}),
usage_json=json.dumps(usage),
))
db.commit()
safe_sync_chat_memory_for_session(db, run.session_id)
finally:
db.close()
async def _fail_run(self, run_id: str, writer: EventWriter, message: str, details: Dict[str, Any]) -> None:
error = {"message": message, **details}
db = self.db_factory()
try:
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
if run:
run.status = "failed"
run.error_json = json.dumps(error, ensure_ascii=False, default=str)
run.finished_at = datetime.utcnow()
db.commit()
finally:
db.close()
await writer.emit("run_failed", error)

128
backend/agent/schemas.py Normal file
View File

@@ -0,0 +1,128 @@
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
class WorkflowPosition(BaseModel):
x: float = 0
y: float = 0
class WorkflowNode(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
type: Literal["input", "output", "tool", "prompt", "agent", "condition", "merge", "template", "select", "limit"]
position: WorkflowPosition = Field(default_factory=WorkflowPosition)
config: Dict[str, Any] = Field(default_factory=dict)
class WorkflowEdge(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
source: str
source_handle: str = "output"
target: str
target_handle: str = "input"
class WorkflowLimits(BaseModel):
maximum_nodes: int = 40
maximum_tool_calls: int = 20
maximum_llm_calls: int = 8
maximum_runtime_seconds: int = 300
maximum_result_chars: int = 120_000
maximum_concurrency: int = 4
class WorkflowGraph(BaseModel):
model_config = ConfigDict(extra="forbid")
schema_version: int = 1
inputs: Dict[str, Dict[str, Any]] = Field(default_factory=dict)
outputs: Dict[str, Dict[str, Any]] = Field(default_factory=dict)
nodes: List[WorkflowNode]
edges: List[WorkflowEdge]
limits: WorkflowLimits = Field(default_factory=WorkflowLimits)
class ValidationIssue(BaseModel):
code: str
message: str
node_id: Optional[str] = None
field_path: Optional[str] = None
class WorkflowValidationResult(BaseModel):
valid: bool
errors: List[ValidationIssue] = Field(default_factory=list)
warnings: List[ValidationIssue] = Field(default_factory=list)
class WorkflowCreateRequest(BaseModel):
name: str
slug: Optional[str] = None
description: str = ""
routing_description: str = ""
routing_examples: List[str] = Field(default_factory=list)
enabled: bool = True
graph: Dict[str, Any]
class WorkflowUpdateRequest(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
routing_description: Optional[str] = None
routing_examples: Optional[List[str]] = None
enabled: Optional[bool] = None
class WorkflowRevisionRequest(BaseModel):
graph: Dict[str, Any]
created_by: str = "user"
class WorkflowValidateRequest(BaseModel):
graph: Dict[str, Any]
class WorkflowRunRequest(BaseModel):
session_id: Optional[str] = None
message: str = ""
model: str
selection_mode: Literal["direct", "automatic", "explicit"] = "direct"
workflow_id: Optional[str] = None
workflow_revision_id: Optional[str] = None
library_slug: Optional[str] = None
web_search_enabled: bool = False
searx_url: Optional[str] = None
searx_engines: List[str] = Field(default_factory=list)
attachments: List[Dict[str, Any]] = Field(default_factory=list)
vision_model: Optional[str] = None
transcription_model: Optional[str] = None
stream: bool = True
router_model: Optional[str] = None
show_thinking: bool = False
generation_options: Dict[str, Any] = Field(default_factory=dict)
sample_inputs: Dict[str, Any] = Field(default_factory=dict)
explicit_user_action: bool = False
regenerate_index: Optional[int] = Field(default=None, ge=0)
class ConfirmationResponseRequest(BaseModel):
approved: bool
note: Optional[str] = None
class RouterSelectRequest(BaseModel):
message: str
recent_messages: List[Dict[str, Any]] = Field(default_factory=list)
attachments: List[Dict[str, Any]] = Field(default_factory=list)
library_slug: Optional[str] = None
web_search_enabled: bool = False
model: Optional[str] = None
chat_model: Optional[str] = None
confidence_threshold: float = 0.55

View File

@@ -0,0 +1,15 @@
from .chat import register_chat_tools
from .knowledge import register_knowledge_tools
from .memory import register_memory_tools
from .saving import register_saving_tools
from .vision import register_vision_tools
from .web import register_web_tools
def register_native_tools(registry) -> None:
register_chat_tools(registry)
register_knowledge_tools(registry)
register_memory_tools(registry)
register_web_tools(registry)
register_vision_tools(registry)
register_saving_tools(registry)

269
backend/agent/tools/chat.py Normal file
View File

@@ -0,0 +1,269 @@
from __future__ import annotations
from typing import Any, Dict, List
from ... import models
from ...ollama_client import chat_stream_typed
from ..ollama_runtime import run_agent_loop
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
MESSAGE_SCHEMA = {
"type": "object",
"properties": {
"role": {"type": "string"},
"content": {"type": "string"},
"images": {"type": "array", "items": {"type": "string"}},
},
"required": ["role", "content"],
"additionalProperties": True,
}
def _usage_dict(usage: Any) -> Dict[str, int]:
return {
"prompt_eval_count": usage.prompt_eval_count,
"eval_count": usage.eval_count,
"total_duration": usage.total_duration,
"load_duration": usage.load_duration,
"prompt_eval_duration": usage.prompt_eval_duration,
"eval_duration": usage.eval_duration,
}
def _context_text(blocks: List[Any]) -> str:
parts: List[str] = []
for block in blocks or []:
if isinstance(block, str):
text = block
elif isinstance(block, dict):
text = str(block.get("context_block") or block.get("text") or block.get("content") or "")
else:
text = str(block or "")
if text.strip():
parts.append(text.strip())
return "\n\n".join(parts)
def _collect_sources(blocks: List[Any]) -> List[Any]:
sources: List[Any] = []
seen = set()
for block in blocks or []:
if not isinstance(block, dict):
continue
for source in block.get("sources") or []:
key = str(
(source.get("url") or source.get("source_message_id") or source.get("doc_id") or source)
if isinstance(source, dict) else source
)
if key and key not in seen:
seen.add(key)
sources.append(source)
return sources
def _model_error_summary(exc: Exception) -> str:
message = str(exc).strip().splitlines()[0] if str(exc).strip() else type(exc).__name__
return f"{type(exc).__name__}: {message}"
def _fallback_content_from_context(model: str, exc: Exception, context_blocks: List[Any], context_text: str) -> str:
sources = _collect_sources(context_blocks)
if not sources and not context_text.strip():
return ""
lines = [
f"The selected chat model failed before it could compose an answer ({_model_error_summary(exc)}).",
"Retrieved context is still available:",
]
if sources:
for index, source in enumerate(sources[:6], 1):
if isinstance(source, dict):
title = str(source.get("title") or source.get("url") or f"Source {index}").strip()
snippet = str(source.get("snippet") or source.get("text") or "").strip()
url = str(source.get("url") or "").strip()
lines.append(f"[{index}] {title}")
if snippet:
lines.append(snippet[:900])
if url:
lines.append(f"Source: {url}")
else:
lines.append(f"[{index}] {source}")
return "\n\n".join(lines)
cleaned_context = (
context_text
.replace("<websearch_context>", "")
.replace("</websearch_context>", "")
.replace("<chat_memory_context>", "")
.replace("</chat_memory_context>", "")
.strip()
)
if cleaned_context:
lines.append(cleaned_context[:5000])
return "\n\n".join(lines)
def _drop_superseded_trailing_user_rows(rows: List[Any]) -> List[Any]:
if not rows or getattr(rows[-1], "role", None) != "user":
return rows
first_trailing_user = len(rows) - 1
while first_trailing_user > 0 and getattr(rows[first_trailing_user - 1], "role", None) == "user":
first_trailing_user -= 1
if first_trailing_user == len(rows) - 1:
return rows
return [*rows[:first_trailing_user], rows[-1]]
def _append_context_to_last_user_message(messages: List[Dict[str, Any]], context_text: str) -> None:
if not context_text:
return
for index in range(len(messages) - 1, -1, -1):
if str(messages[index].get("role") or "") == "user":
content = str(messages[index].get("content") or "").strip()
messages[index]["content"] = f"{content}\n\n{context_text}".strip()
return
async def chat_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
messages = [dict(item) for item in arguments.get("messages") or []]
context_blocks = arguments.get("context_blocks") or []
context_text = _context_text(context_blocks)
context_applied = False
if context.session_id:
db = context.db_factory()
try:
session = db.query(models.ChatSession).filter(models.ChatSession.session_id == context.session_id).first()
rows = [] if not session else (
db.query(models.ChatMessage)
.filter(models.ChatMessage.session_pk == session.id)
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
.all()
)[-20:]
finally:
db.close()
if rows:
rows = _drop_superseded_trailing_user_rows(rows)
from ... import main as main_module
supports_vision = await main_module._model_supports_vision(arguments["model"])
override_index = len(rows) - 1 if rows[-1].role == "user" else None
prompt = rows[-1].content if override_index is not None else ""
override_content = f"{prompt}\n\n{context_text}".strip() if context_text else None
context_applied = bool(override_content)
messages = await main_module._build_ollama_messages_from_rows(
rows,
request_model_supports_vision=supports_vision,
vision_model=arguments.get("vision_model"),
transcription_model=arguments.get("transcription_model"),
override_user_row_index=override_index,
override_user_content=override_content,
)
if context_text and not context_applied:
_append_context_to_last_user_message(messages, context_text)
system_prompt = str(arguments.get("system_prompt") or "").strip()
if system_prompt:
messages.insert(0, {"role": "system", "content": system_prompt})
full_content = ""
full_thinking = ""
usage: Dict[str, int] = {}
try:
async for chunk in chat_stream_typed(
arguments["model"],
messages,
options=arguments.get("generation_options") or {},
think=bool(arguments.get("reasoning")),
cancellation_event=context.cancellation_event,
):
if chunk.thinking:
full_thinking += chunk.thinking
if context.show_thinking:
await context.emit("model_thinking", {"text": chunk.thinking})
if chunk.content:
full_content += chunk.content
await context.emit("model_token", {"text": chunk.content})
if chunk.done:
usage = _usage_dict(chunk.usage)
except Exception as exc:
fallback_content = _fallback_content_from_context(arguments["model"], exc, context_blocks, context_text)
if not fallback_content:
raise
full_content = fallback_content
await context.emit("model_token", {"text": full_content})
return {
"content": full_content,
"sources": _collect_sources(context_blocks),
"usage": usage,
"thinking_available": bool(full_thinking),
}
def register_chat_tools(registry: NativeToolProvider) -> None:
registry.register(ToolDefinition(
name="heimgeist.chat",
description="Generate an Ollama chat response from conversation history and supplied context blocks.",
input_schema={
"type": "object",
"properties": {
"model": {"type": "string", "minLength": 1},
"messages": {"type": "array", "items": MESSAGE_SCHEMA},
"system_prompt": {"type": "string"},
"context_blocks": {"type": "array"},
"attachments": {"type": "array"},
"vision_model": {"type": ["string", "null"]},
"transcription_model": {"type": ["string", "null"]},
"generation_options": {"type": "object"},
"stream": {"type": "boolean"},
"reasoning": {"type": "boolean"},
},
"required": ["model", "messages"],
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {
"content": {"type": "string"},
"sources": {"type": "array"},
"usage": {"type": "object"},
"thinking_available": {"type": "boolean"},
},
"required": ["content", "sources", "usage", "thinking_available"],
"additionalProperties": False,
},
handler=chat_handler,
timeout_seconds=600,
result_size_limit=180_000,
llm_call=True,
))
registry.register(ToolDefinition(
name="heimgeist.agent",
description="Run a bounded Ollama tool-calling loop over an approved native-tool allowlist.",
input_schema={
"type": "object",
"properties": {
"model": {"type": "string", "minLength": 1},
"messages": {"type": "array", "items": MESSAGE_SCHEMA},
"allowed_tool_names": {"type": "array", "items": {"type": "string"}, "maxItems": 12},
"maximum_rounds": {"type": "integer", "minimum": 1, "maximum": 8},
"maximum_output_chars": {"type": "integer", "minimum": 1000, "maximum": 120000},
"reasoning": {"type": "boolean"},
"generation_options": {"type": "object"},
},
"required": ["model", "messages", "allowed_tool_names", "maximum_rounds"],
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {
"content": {"type": "string"},
"tool_summary": {"type": "array"},
"usage": {"type": "object"},
"rounds": {"type": "integer"},
},
"required": ["content", "tool_summary", "usage", "rounds"],
"additionalProperties": False,
},
handler=run_agent_loop,
timeout_seconds=600,
result_size_limit=180_000,
))

View File

@@ -0,0 +1,114 @@
from __future__ import annotations
import asyncio
import multiprocessing
import time
from typing import Any, Dict
from ...local_rag import LibraryContextRequest, library_context
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
def _knowledge_source(source: Dict[str, Any], library_slug: str) -> Dict[str, Any]:
return {
"type": "knowledge",
"library_slug": library_slug,
"doc_id": source.get("doc_id"),
"title": source.get("title"),
"url": source.get("url"),
"record_type": source.get("record_type"),
"mime": source.get("mime"),
"lang": source.get("lang"),
"snippet": source.get("snippet"),
"scores": source.get("scores") or {},
}
def _knowledge_search_worker(connection, arguments: Dict[str, Any]) -> None:
try:
request = LibraryContextRequest(
prompt=arguments["prompt"],
top_k=arguments.get("top_k", 5),
embed_model=arguments.get("embedding_model"),
)
connection.send(("ok", library_context(arguments["library_slug"], request)))
except BaseException as exc:
detail = getattr(exc, "detail", None) or str(exc)
connection.send(("error", f"{type(exc).__name__}: {detail}"))
finally:
connection.close()
async def _isolated_library_context(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
process_context = multiprocessing.get_context("spawn")
parent_connection, child_connection = process_context.Pipe(duplex=False)
process = process_context.Process(target=_knowledge_search_worker, args=(child_connection, arguments), daemon=True)
process.start()
child_connection.close()
deadline = time.monotonic() + 170
try:
while True:
if context.cancellation_event.is_set():
raise asyncio.CancelledError()
if parent_connection.poll():
status, value = parent_connection.recv()
if status == "ok":
return value
raise RuntimeError(value)
if not process.is_alive():
raise RuntimeError(f"Local retrieval process exited unexpectedly (exit code {process.exitcode}).")
if time.monotonic() >= deadline:
raise TimeoutError("Local retrieval exceeded its process timeout.")
await asyncio.sleep(0.05)
finally:
parent_connection.close()
if process.is_alive():
process.terminate()
process.join(timeout=2)
async def knowledge_search_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
payload = await _isolated_library_context(arguments, context)
raw_hits = (payload.get("result") or {}).get("sources") or []
budget = int(arguments.get("context_character_budget") or 12_000)
context_block = str(payload.get("context_block") or "")[:budget]
sources = [_knowledge_source(item, arguments["library_slug"]) for item in raw_hits]
return {
"hits": sources,
"context_block": context_block,
"sources": sources,
"scores": [item.get("scores") or {} for item in sources],
}
def register_knowledge_tools(registry: NativeToolProvider) -> None:
registry.register(ToolDefinition(
name="heimgeist.knowledge_search",
description="Retrieve structured evidence from Heimgeist's indexed local Knowledge store.",
input_schema={
"type": "object",
"properties": {
"prompt": {"type": "string", "minLength": 1},
"library_slug": {"type": "string", "minLength": 1},
"top_k": {"type": "integer", "minimum": 1, "maximum": 20},
"context_character_budget": {"type": "integer", "minimum": 500, "maximum": 60000},
"embedding_model": {"type": ["string", "null"]},
},
"required": ["prompt", "library_slug"],
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {
"hits": {"type": "array"},
"context_block": {"type": "string"},
"sources": {"type": "array"},
"scores": {"type": "array"},
},
"required": ["hits", "context_block", "sources", "scores"],
"additionalProperties": False,
},
handler=knowledge_search_handler,
timeout_seconds=180,
result_size_limit=100_000,
))

View File

@@ -0,0 +1,96 @@
from __future__ import annotations
from typing import Any, Dict
from ...chat_memory import build_chat_memory_context, ensure_chat_memory_schema
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
def _int_argument(arguments: Dict[str, Any], key: str, default: int, minimum: int, maximum: int) -> int:
try:
value = int(arguments.get(key) or default)
except Exception:
value = default
return max(minimum, min(value, maximum))
def _memory_hit(item: Dict[str, Any]) -> Dict[str, Any]:
return {
"session_id": item.get("session_id"),
"session_name": item.get("session_name"),
"user_message_id": item.get("user_message_id"),
"assistant_message_id": item.get("assistant_message_id"),
"created_at": item.get("created_at"),
"score": round(float(item.get("_score") or item.get("score") or 0), 4),
"user_excerpt": item.get("user_content"),
"assistant_excerpt": item.get("assistant_content"),
}
async def chat_memory_search_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
top_k = _int_argument(arguments, "top_k", 6, 1, 20)
context_character_budget = _int_argument(arguments, "context_character_budget", 10_000, 500, 60_000)
mode = str(arguments.get("mode") or "search").strip().lower()
if mode not in {"search", "recent"}:
mode = "search"
exclude_current_session = bool(arguments.get("exclude_current_session", True))
exclude_session_id = context.session_id if exclude_current_session else None
db = context.db_factory()
try:
ensure_chat_memory_schema(db.get_bind())
payload = build_chat_memory_context(
db,
str(arguments.get("prompt") or ""),
exclude_session_id=exclude_session_id,
top_k=top_k,
context_character_budget=context_character_budget,
mode=mode,
)
finally:
db.close()
sources = payload.get("sources") or []
return {
"hits": [_memory_hit(item) for item in (payload.get("hits") or [])],
"context_block": str(payload.get("context_block") or ""),
"sources": sources,
"scores": [source.get("score") for source in sources if isinstance(source, dict)],
}
def register_memory_tools(registry: NativeToolProvider) -> None:
registry.register(ToolDefinition(
name="heimgeist.chat_memory_search",
description=(
"Retrieve relevant completed turns from past Heimgeist chats. Use only when a workflow or agent "
"decides previous chats are needed, such as questions about earlier conversations, prior decisions, "
"or remembered discussion context; it does not run automatically."
),
input_schema={
"type": "object",
"properties": {
"prompt": {"type": "string", "minLength": 1},
"top_k": {"type": "integer", "minimum": 1, "maximum": 20},
"context_character_budget": {"type": "integer", "minimum": 500, "maximum": 60000},
"mode": {"type": "string", "enum": ["search", "recent"]},
"exclude_current_session": {"type": "boolean"},
},
"required": ["prompt"],
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {
"hits": {"type": "array"},
"context_block": {"type": "string"},
"sources": {"type": "array"},
"scores": {"type": "array"},
},
"required": ["hits", "context_block", "sources", "scores"],
"additionalProperties": False,
},
handler=chat_memory_search_handler,
timeout_seconds=20,
result_size_limit=100_000,
))

View File

@@ -0,0 +1,86 @@
from __future__ import annotations
from typing import Any, Dict
from ...local_rag import CreateWebsiteRequest, create_library_website
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
async def save_message_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
from ... import main as main_module
db = context.db_factory()
try:
result = await main_module._save_message_to_knowledge_impl(
arguments["library_slug"],
arguments["message_id"],
db,
title=arguments.get("title"),
content=arguments.get("edited_content"),
saved_by="agent" if context.selection_mode == "automatic" else "user",
)
finally:
db.close()
return {"status": "saved", "confirmed": True, "result": result}
async def save_website_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
result = await create_library_website(
arguments["library_slug"],
CreateWebsiteRequest(url=arguments["url"], title=arguments.get("title")),
)
return {"status": "saved", "confirmed": True, "result": result}
SAVE_OUTPUT = {
"type": "object",
"properties": {
"status": {"type": "string"},
"confirmed": {"type": "boolean"},
"result": {"type": "object"},
},
"required": ["status", "confirmed", "result"],
"additionalProperties": False,
}
def register_saving_tools(registry: NativeToolProvider) -> None:
registry.register(ToolDefinition(
name="heimgeist.save_message_to_knowledge",
description="Save a stable chat message snapshot to Heimgeist's local Knowledge store.",
input_schema={
"type": "object",
"properties": {
"message_id": {"type": "string", "minLength": 1},
"library_slug": {"type": "string", "minLength": 1},
"title": {"type": ["string", "null"]},
"edited_content": {"type": ["string", "null"]},
},
"required": ["message_id", "library_slug"],
"additionalProperties": False,
},
output_schema=SAVE_OUTPUT,
handler=save_message_handler,
risk_level="write",
requires_confirmation=True,
timeout_seconds=180,
))
registry.register(ToolDefinition(
name="heimgeist.save_website_to_knowledge",
description="Fetch and save a durable website snapshot to Heimgeist's local Knowledge store.",
input_schema={
"type": "object",
"properties": {
"url": {"type": "string", "minLength": 1},
"library_slug": {"type": "string", "minLength": 1},
"title": {"type": ["string", "null"]},
},
"required": ["url", "library_slug"],
"additionalProperties": False,
},
output_schema=SAVE_OUTPUT,
handler=save_website_handler,
risk_level="write",
requires_confirmation=True,
timeout_seconds=180,
))

View File

@@ -0,0 +1,49 @@
from __future__ import annotations
from typing import Any, Dict
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
async def vision_analyze_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
from ... import main as main_module
prepared, _images, context_block = await main_module._prepare_chat_message_attachments(
arguments.get("attachments") or [],
request_model_supports_vision=False,
vision_model=arguments.get("vision_model"),
transcription_model=arguments.get("transcription_model"),
persist_file_text=False,
)
return {
"context_block": context_block,
"attachments": [main_module._attachment_history_payload(item) for item in prepared],
"sources": [],
}
def register_vision_tools(registry: NativeToolProvider) -> None:
registry.register(ToolDefinition(
name="heimgeist.vision_analyze",
description="Analyze chat attachments through Heimgeist's existing vision and extraction path.",
input_schema={
"type": "object",
"properties": {
"attachments": {"type": "array"},
"vision_model": {"type": "string", "minLength": 1},
"transcription_model": {"type": ["string", "null"]},
},
"required": ["attachments", "vision_model"],
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {"context_block": {"type": "string"}, "attachments": {"type": "array"}, "sources": {"type": "array"}},
"required": ["context_block", "attachments", "sources"],
"additionalProperties": False,
},
handler=vision_analyze_handler,
timeout_seconds=600,
result_size_limit=140_000,
llm_call=True,
))

378
backend/agent/tools/web.py Normal file
View File

@@ -0,0 +1,378 @@
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
import hashlib
import json
from typing import Any, Dict, List
from urllib.parse import urlparse
import httpx
from ...ollama_client import chat_typed
from ...websearch import (
DEFAULT_HEADERS,
HTTP_LIMITS,
HTTP_TIMEOUT,
fallback_rerank,
fetch_website_snapshot,
render_recent_context,
rerank,
searx_search,
)
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
QUERY_FORMAT = {
"type": "object",
"properties": {"queries": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 5}},
"required": ["queries"],
"additionalProperties": False,
}
FETCH_TEXT_LIMIT = 12_000
NOISE_HOSTS = (
"accounts.google.",
"collinsdictionary.com",
"consent.google.",
"de.langenscheidt.com",
"dict.cc",
"dict.leo.org",
"dictionary.cambridge.org",
"duden.de",
"dwds.de",
"langenscheidt.com",
"leo.org",
"linguee.",
"news.google.",
)
NOISE_TITLE_MARKERS = (
"before you continue",
"deutsch-ubersetzung",
"deutsch ubersetzung",
"deutsch-uebersetzung",
"deutsch uebersetzung",
"englisch-deutsch",
"english-german",
"google consent",
"worterbuch",
)
def _host_for(url: str) -> str:
try:
return str(urlparse(url).netloc or "").lower()
except Exception:
return ""
def _is_noise_result(url: str, title: str = "") -> bool:
host = _host_for(url)
title_norm = str(title or "").lower()
url_norm = str(url or "").lower()
if any(marker in host for marker in NOISE_HOSTS):
return True
if any(marker in title_norm for marker in NOISE_TITLE_MARKERS):
return True
if "nah-meaning" in url_norm or "what-does-nah-mean" in url_norm:
return True
return False
def _clean_queries(generated: List[Any], fallback: str) -> List[str]:
cleaned: List[str] = []
seen = set()
for query in generated:
text = " ".join(str(query or "").split()).strip()
if not text:
continue
key = text.casefold()
if key in seen:
continue
seen.add(key)
cleaned.append(text[:300])
if len(cleaned) >= 5:
break
if cleaned:
return cleaned
fallback_text = " ".join(str(fallback or "").split()).strip()
return [fallback_text[:300]] if fallback_text else []
async def generate_queries_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
recent = render_recent_context(arguments.get("messages") or [], char_limit=1600)
prompt = (
"Generate 3 concise, diverse web-search queries for the current request. "
"Resolve references using recent conversation. Every query must include the concrete topic, "
"entity, or location from the request. Never output standalone generic terms such as latest, "
"current, top, today, news, or weather. Return only valid JSON matching the schema.\n\n"
f"Current request:\n{arguments['prompt']}\n\nRecent conversation:\n{recent}"
)
result = await chat_typed(
arguments["model"],
[{"role": "user", "content": prompt}],
format=QUERY_FORMAT,
options={"temperature": 0.1},
cancellation_event=context.cancellation_event,
)
try:
parsed = json.loads(result.content)
queries = parsed.get("queries") if isinstance(parsed, dict) else None
except Exception:
queries = None
return {"queries": _clean_queries(queries or [], arguments["prompt"])}
async def web_search_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
queries = arguments.get("queries") or []
if arguments.get("query"):
queries = [arguments["query"], *queries]
unique_queries = []
for query in queries:
text = str(query or "").strip()
if text and text not in unique_queries:
unique_queries.append(text)
maximum = max(1, min(int(arguments.get("maximum_results") or 12), 32))
async with httpx.AsyncClient(
headers=DEFAULT_HEADERS,
follow_redirects=True,
http2=True,
limits=HTTP_LIMITS,
timeout=HTTP_TIMEOUT,
) as client:
responses = await asyncio.gather(*[
searx_search(
client,
query,
max_results=min(8, maximum),
searx_url=arguments.get("searx_url"),
engines=arguments.get("engines") or None,
)
for query in unique_queries[:5]
])
results: List[Dict[str, Any]] = []
seen = set()
for query, items in zip(unique_queries, responses):
for item in items:
url = str(item.get("url") or "")
title = str(item.get("title") or "")
if not url or url in seen:
continue
if _is_noise_result(url, title):
continue
seen.add(url)
results.append({"query": query, "url": url, "title": title, "engine": item.get("engine")})
if len(results) >= maximum:
break
return {"queries": unique_queries, "results": results, "unavailable": not results}
async def web_fetch_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
urls = arguments.get("urls") or []
if arguments.get("url"):
urls = [arguments["url"], *urls]
maximum = max(1, min(int(arguments.get("maximum_pages") or 6), 12))
unique = []
for item in urls:
url = item.get("url") if isinstance(item, dict) else item
url = str(url or "").strip()
title = str(item.get("title") or "") if isinstance(item, dict) else ""
query = str(item.get("query") or "") if isinstance(item, dict) else ""
if url and url not in unique and not _is_noise_result(url, title):
unique.append(url)
semaphore = asyncio.Semaphore(4)
async def fetch_one(url: str) -> Dict[str, Any]:
try:
async with semaphore:
snapshot = await fetch_website_snapshot(url)
full_text = str(snapshot.get("text") or "")
text = full_text[:FETCH_TEXT_LIMIT]
canonical_url = snapshot.get("url") or snapshot.get("final_url") or url
title = snapshot.get("title") or ""
if _is_noise_result(str(canonical_url), str(title)):
return {
"requested_url": snapshot.get("requested_url") or url,
"canonical_url": canonical_url,
"title": title,
"cleaned_text": "",
"fetch_timestamp": datetime.now(timezone.utc).isoformat(),
"content_hash": hashlib.sha256(full_text.encode("utf-8", errors="ignore")).hexdigest(),
"error": "filtered_noise_page",
}
return {
"requested_url": snapshot.get("requested_url") or url,
"canonical_url": canonical_url,
"title": title,
"cleaned_text": text,
"fetch_timestamp": datetime.now(timezone.utc).isoformat(),
"content_hash": hashlib.sha256(full_text.encode("utf-8", errors="ignore")).hexdigest(),
"error": None,
}
except Exception as exc:
return {
"requested_url": url,
"canonical_url": url,
"title": "",
"cleaned_text": "",
"fetch_timestamp": datetime.now(timezone.utc).isoformat(),
"content_hash": "",
"error": f"{type(exc).__name__}: {exc}",
}
pages = await asyncio.gather(*(fetch_one(url) for url in unique[:maximum]))
return {"pages": pages}
async def web_rerank_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
docs = []
for page in arguments.get("pages") or []:
if page.get("error") or not str(page.get("cleaned_text") or "").strip():
continue
url = str(page.get("canonical_url") or page.get("requested_url") or "")
title = str(page.get("title") or "")
text = str(page.get("cleaned_text") or "")
if _is_noise_result(url, title):
continue
docs.append((url, text))
context_excerpt = arguments.get("context_excerpt") or ""
try:
ranked = await rerank(
arguments["prompt"],
docs,
model=arguments.get("model") or "",
context_excerpt=context_excerpt,
embed_model=arguments.get("rerank_model"),
)
except Exception as exc:
ranked = fallback_rerank(
arguments["prompt"],
docs,
context_excerpt,
reason=f"rerank_exception:{type(exc).__name__}",
)
maximum = max(1, min(int(arguments.get("maximum_results") or 6), 12))
minimum_score = float(arguments.get("minimum_score") or 0)
selected = []
page_by_url = {
str(page.get("canonical_url") or page.get("requested_url") or ""): page
for page in arguments.get("pages") or []
}
for url, text, score in ranked:
if score < minimum_score:
continue
page = page_by_url.get(url) or {}
title = str(page.get("title") or "")
if _is_noise_result(url, title):
continue
selected.append({
"type": "web",
"url": url,
"title": page.get("title") or url,
"snippet": text[:1600],
"score": score,
})
if len(selected) >= maximum:
break
context_lines = ["<websearch_context>"]
if not selected:
context_lines.append("Web search completed but no suitable readable pages were available.")
for index, item in enumerate(selected, 1):
context_lines.append(f"[W{index}] {item['title']}\n{item['snippet']}\nSource: {item['url']}")
context_lines.append("</websearch_context>")
return {"results": selected, "context_block": "\n".join(context_lines), "sources": selected}
def register_web_tools(registry: NativeToolProvider) -> None:
registry.register(ToolDefinition(
name="heimgeist.web_generate_queries",
description="Generate validated web-search queries from a request and recent conversation.",
input_schema={
"type": "object",
"properties": {
"prompt": {"type": "string", "minLength": 1},
"model": {"type": "string", "minLength": 1},
"messages": {"type": "array"},
},
"required": ["prompt", "model"],
"additionalProperties": False,
},
output_schema=QUERY_FORMAT,
handler=generate_queries_handler,
timeout_seconds=120,
llm_call=True,
))
registry.register(ToolDefinition(
name="heimgeist.web_search",
description="Search the configured SearXNG service and return structured results without answering.",
input_schema={
"type": "object",
"properties": {
"query": {"type": ["string", "null"]},
"queries": {"type": "array", "items": {"type": "string"}, "maxItems": 5},
"engines": {"type": "array", "items": {"type": "string"}},
"maximum_results": {"type": "integer", "minimum": 1, "maximum": 32},
"searx_url": {"type": ["string", "null"]},
},
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {"queries": {"type": "array"}, "results": {"type": "array"}, "unavailable": {"type": "boolean"}},
"required": ["queries", "results", "unavailable"],
"additionalProperties": False,
},
handler=web_search_handler,
timeout_seconds=45,
))
registry.register(ToolDefinition(
name="heimgeist.web_fetch",
description="Fetch and extract selected web pages using Heimgeist's bounded website policy.",
input_schema={
"type": "object",
"properties": {
"url": {"type": ["string", "null"]},
"urls": {"type": "array", "maxItems": 32},
"maximum_pages": {"type": "integer", "minimum": 1, "maximum": 12},
},
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {"pages": {"type": "array"}},
"required": ["pages"],
"additionalProperties": False,
},
handler=web_fetch_handler,
timeout_seconds=90,
result_size_limit=180_000,
))
registry.register(ToolDefinition(
name="heimgeist.web_rerank",
description="Rank extracted web pages using Heimgeist's embedding-based reranker with lexical fallback.",
input_schema={
"type": "object",
"properties": {
"prompt": {"type": "string", "minLength": 1},
"pages": {"type": "array"},
"model": {"type": ["string", "null"]},
"rerank_model": {"type": ["string", "null"]},
"context_excerpt": {"type": "string"},
"maximum_results": {"type": "integer", "minimum": 1, "maximum": 12},
"minimum_score": {"type": "number", "minimum": 0, "maximum": 100},
},
"required": ["prompt", "pages"],
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {"results": {"type": "array"}, "context_block": {"type": "string"}, "sources": {"type": "array"}},
"required": ["results", "context_block", "sources"],
"additionalProperties": False,
},
handler=web_rerank_handler,
timeout_seconds=180,
result_size_limit=120_000,
))

157
backend/agent/validation.py Normal file
View File

@@ -0,0 +1,157 @@
from __future__ import annotations
from collections import defaultdict, deque
from typing import Any, Dict, List, Optional
from pydantic import ValidationError
from .bindings import iter_references
from .registry import NativeToolProvider, SchemaValidationError, validate_json_schema, validate_schema_definition
from .schemas import ValidationIssue, WorkflowGraph, WorkflowValidationResult
HOST_LIMITS = {
"maximum_nodes": 80,
"maximum_tool_calls": 40,
"maximum_llm_calls": 16,
"maximum_runtime_seconds": 600,
"maximum_result_chars": 240_000,
"maximum_concurrency": 8,
}
RUN_REFERENCE_FIELDS = {
"session_id", "chat_model", "router_model", "vision_model", "transcription_model",
"library_slug", "searx_url", "searx_engines", "messages", "attachments",
"generation_options", "context_blocks", "target_message_id", "target_message_content", "target_url",
"web_search_query", "web_search_queries",
}
def _issue(code: str, message: str, node_id: Optional[str] = None, field_path: Optional[str] = None) -> ValidationIssue:
return ValidationIssue(code=code, message=message, node_id=node_id, field_path=field_path)
def validate_workflow_graph(raw_graph: Dict[str, Any], registry: NativeToolProvider) -> WorkflowValidationResult:
errors: List[ValidationIssue] = []
warnings: List[ValidationIssue] = []
try:
graph = WorkflowGraph.model_validate(raw_graph)
except ValidationError as exc:
for item in exc.errors():
errors.append(_issue("malformed_graph", item["msg"], field_path=".".join(str(p) for p in item["loc"])))
return WorkflowValidationResult(valid=False, errors=errors)
if graph.schema_version != 1:
errors.append(_issue("unsupported_schema_version", "Only workflow schema_version 1 is supported.", field_path="schema_version"))
for name, schema in {**graph.inputs, **graph.outputs}.items():
try:
validate_schema_definition(schema, f"schema.{name}")
except SchemaValidationError as exc:
errors.append(_issue("malformed_schema", str(exc), field_path=f"inputs.{name}"))
node_ids = [node.id for node in graph.nodes]
edge_ids = [edge.id for edge in graph.edges]
for identifier, values, path in (("node", node_ids, "nodes"), ("edge", edge_ids, "edges")):
seen = set()
for value in values:
if not value:
errors.append(_issue(f"empty_{identifier}_id", f"{identifier.title()} IDs cannot be empty.", field_path=path))
elif value in seen:
errors.append(_issue(f"duplicate_{identifier}_id", f"Duplicate {identifier} ID: {value}", field_path=path))
seen.add(value)
nodes = {node.id: node for node in graph.nodes}
input_nodes = [node for node in graph.nodes if node.type == "input"]
output_nodes = [node for node in graph.nodes if node.type == "output"]
if not input_nodes:
errors.append(_issue("missing_input_node", "A workflow must contain an input node."))
if not output_nodes:
errors.append(_issue("missing_output_node", "A workflow must contain an output node."))
outgoing: Dict[str, List[Any]] = defaultdict(list)
incoming: Dict[str, List[Any]] = defaultdict(list)
for edge in graph.edges:
if edge.source not in nodes:
errors.append(_issue("missing_edge_source", f"Edge source does not exist: {edge.source}", field_path=f"edges.{edge.id}.source"))
if edge.target not in nodes:
errors.append(_issue("missing_edge_target", f"Edge target does not exist: {edge.target}", field_path=f"edges.{edge.id}.target"))
if edge.source in nodes and edge.target in nodes:
outgoing[edge.source].append(edge)
incoming[edge.target].append(edge)
indegree = {node_id: len(incoming[node_id]) for node_id in nodes}
queue = deque(node_id for node_id, degree in indegree.items() if degree == 0)
visited: List[str] = []
while queue:
node_id = queue.popleft()
visited.append(node_id)
for edge in outgoing[node_id]:
indegree[edge.target] -= 1
if indegree[edge.target] == 0:
queue.append(edge.target)
if len(visited) != len(nodes):
errors.append(_issue("cycle", "Workflow schema version 1 must be a DAG; cycles are not allowed."))
reachable = set()
frontier = [node.id for node in input_nodes]
while frontier:
node_id = frontier.pop()
if node_id in reachable:
continue
reachable.add(node_id)
frontier.extend(edge.target for edge in outgoing[node_id])
for node in graph.nodes:
if node.type not in {"input"} and node.id not in reachable:
errors.append(_issue("unreachable_node", f"Node {node.id} is not reachable from an input node.", node.id))
for node in graph.nodes:
if node.type == "tool":
tool_name = str(node.config.get("tool") or "")
try:
tool = registry.get_tool(tool_name)
except KeyError:
errors.append(_issue("unknown_tool", f"Unknown tool: {tool_name or '(missing)'}", node.id, "config.tool"))
else:
arguments = node.config.get("arguments", {})
if not isinstance(arguments, dict):
errors.append(_issue("invalid_tool_arguments", "Tool arguments must be an object.", node.id, "config.arguments"))
else:
literal_arguments = {
key: value for key, value in arguments.items()
if not (isinstance(value, dict) and set(value) == {"$ref"})
}
try:
validate_json_schema(literal_arguments, tool.input_schema, partial=True)
except SchemaValidationError as exc:
errors.append(_issue("invalid_tool_arguments", str(exc), node.id, "config.arguments"))
if node.type == "condition":
operation = node.config.get("operation")
allowed = {"equals", "not_equals", "exists", "greater_than", "less_than", "contains", "array_not_empty", "score_at_least"}
if operation not in allowed:
errors.append(_issue("invalid_condition", f"Unsupported condition operation: {operation}", node.id, "config.operation"))
handles = {edge.source_handle for edge in outgoing[node.id]}
if not {"true", "false"}.issubset(handles):
errors.append(_issue("invalid_branch", "Condition nodes require both true and false outgoing branches.", node.id))
if node.type == "prompt" and not node.config.get("model_source"):
errors.append(_issue("missing_model_source", "Prompt nodes require model_source.", node.id, "config.model_source"))
for field_path, reference in iter_references(node.config, f"nodes.{node.id}.config"):
parts = reference.split(".")
if parts[0] == "input" and (len(parts) < 2 or parts[1] not in graph.inputs):
errors.append(_issue("missing_reference", f"Unknown workflow input reference: {reference}", node.id, field_path))
elif parts[0] == "run" and (len(parts) < 2 or parts[1] not in RUN_REFERENCE_FIELDS):
errors.append(_issue("missing_reference", f"Unknown run reference: {reference}", node.id, field_path))
elif parts[0] == "nodes" and (len(parts) < 3 or parts[1] not in nodes):
errors.append(_issue("missing_reference", f"Unknown node reference: {reference}", node.id, field_path))
elif parts[0] not in {"input", "run", "nodes"}:
errors.append(_issue("missing_reference", f"Invalid reference: {reference}", node.id, field_path))
limits = graph.limits.model_dump()
for key, maximum in HOST_LIMITS.items():
value = limits[key]
if value < 1 or value > maximum:
errors.append(_issue("excessive_limit", f"{key} must be between 1 and {maximum}.", field_path=f"limits.{key}"))
if len(graph.nodes) > graph.limits.maximum_nodes:
errors.append(_issue("excessive_nodes", "The graph contains more nodes than its maximum_nodes limit.", field_path="nodes"))
return WorkflowValidationResult(valid=not errors, errors=errors, warnings=warnings)

View File

@@ -0,0 +1,3 @@
from .builtins import BUILTIN_WORKFLOWS, seed_builtin_workflows
__all__ = ["BUILTIN_WORKFLOWS", "seed_builtin_workflows"]

View File

@@ -0,0 +1,333 @@
from __future__ import annotations
from datetime import datetime
import hashlib
import json
from typing import Any, Dict, List
from sqlalchemy.orm import Session
from ..models import WorkflowDefinition, WorkflowRevision
LIMITS = {
"maximum_nodes": 40,
"maximum_tool_calls": 20,
"maximum_llm_calls": 8,
"maximum_runtime_seconds": 300,
"maximum_result_chars": 120000,
"maximum_concurrency": 4,
}
INPUTS = {"prompt": {"type": "string"}, "session_id": {"type": ["string", "null"]}}
def node(node_id: str, node_type: str, x: float, y: float, config: Dict[str, Any] | None = None) -> Dict[str, Any]:
return {"id": node_id, "type": node_type, "position": {"x": x, "y": y}, "config": config or {}}
def edge(source: str, target: str, source_handle: str = "output", suffix: str = "") -> Dict[str, Any]:
return {
"id": f"{source}-{target}{suffix}",
"source": source,
"source_handle": source_handle,
"target": target,
"target_handle": "input",
}
EVIDENCE_FIRST_SYSTEM_PROMPT = (
"Answer the current user request using the supplied retrieved context as the primary evidence. "
"If retrieved context conflicts with older chat history, prefer the retrieved context and explain the correction briefly. "
"Do not recommend that the user consult external sources when relevant retrieved sources are already present."
)
CHAT_MEMORY_SYSTEM_PROMPT = (
"Answer using the supplied previous-chat context as the primary evidence. "
"Treat it as memory of earlier Heimgeist chats, not as fresh external evidence. "
"If the retrieved chat context is empty or does not answer the request, say that no matching previous chat was found."
)
def chat_arguments(context_blocks: List[Dict[str, str]] | None = None, system_prompt: str = "") -> Dict[str, Any]:
return {
"model": {"$ref": "run.chat_model"},
"messages": {"$ref": "run.messages"},
"system_prompt": system_prompt,
"context_blocks": context_blocks or [],
"attachments": {"$ref": "run.attachments"},
"vision_model": {"$ref": "run.vision_model"},
"transcription_model": {"$ref": "run.transcription_model"},
"generation_options": {"$ref": "run.generation_options"},
"stream": True,
"reasoning": False,
}
def graph(nodes: List[Dict[str, Any]], edges: List[Dict[str, Any]], *, limits: Dict[str, Any] | None = None) -> Dict[str, Any]:
return {
"schema_version": 1,
"inputs": INPUTS,
"outputs": {"content": {"type": "string"}},
"nodes": nodes,
"edges": edges,
"limits": {**LIMITS, **(limits or {})},
}
DIRECT = graph(
[
node("input", "input", 0, 80),
node("chat", "tool", 320, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments()}),
node("output", "output", 680, 80, {"value": {"$ref": "nodes.chat.output"}}),
],
[edge("input", "chat"), edge("chat", "output")],
)
KNOWLEDGE = graph(
[
node("input", "input", 0, 80),
node("search", "tool", 280, 20, {"tool": "heimgeist.knowledge_search", "arguments": {
"prompt": {"$ref": "input.prompt"}, "library_slug": {"$ref": "run.library_slug"},
"top_k": 6, "context_character_budget": 14000, "embedding_model": None,
}}),
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.search.output"}])}),
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
],
[edge("input", "search"), edge("search", "chat"), edge("chat", "output")],
)
CHAT_MEMORY = graph(
[
node("input", "input", 0, 80),
node("memory", "tool", 280, 20, {"tool": "heimgeist.chat_memory_search", "arguments": {
"prompt": {"$ref": "input.prompt"}, "top_k": 6, "context_character_budget": 10000,
"mode": "search", "exclude_current_session": True,
}}),
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.memory.output"}], CHAT_MEMORY_SYSTEM_PROMPT)}),
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
],
[edge("input", "memory"), edge("memory", "chat"), edge("chat", "output")],
)
RECENT_CHAT_MEMORY = graph(
[
node("input", "input", 0, 80),
node("memory", "tool", 280, 20, {"tool": "heimgeist.chat_memory_search", "arguments": {
"prompt": {"$ref": "input.prompt"}, "top_k": 6, "context_character_budget": 10000,
"mode": "recent", "exclude_current_session": True,
}}),
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.memory.output"}], CHAT_MEMORY_SYSTEM_PROMPT)}),
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
],
[edge("input", "memory"), edge("memory", "chat"), edge("chat", "output")],
)
def web_graph() -> Dict[str, Any]:
return graph(
[
node("input", "input", 0, 100),
node("search", "tool", 300, 20, {"tool": "heimgeist.web_search", "arguments": {
"query": {"$ref": "run.web_search_query"}, "queries": {"$ref": "run.web_search_queries"}, "engines": {"$ref": "run.searx_engines"},
"maximum_results": 16, "searx_url": {"$ref": "run.searx_url"},
}}),
node("fetch", "tool", 760, 20, {"tool": "heimgeist.web_fetch", "arguments": {
"url": None, "urls": {"$ref": "nodes.search.output.results"}, "maximum_pages": 6,
}}),
node("rerank", "tool", 1010, 20, {"tool": "heimgeist.web_rerank", "arguments": {
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch.output.pages"}, "model": {"$ref": "run.chat_model"},
"rerank_model": None, "context_excerpt": "", "maximum_results": 6, "minimum_score": 55,
}}),
node("chat", "tool", 1260, 100, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.rerank.output"}], EVIDENCE_FIRST_SYSTEM_PROMPT)}),
node("output", "output", 1540, 100, {"value": {"$ref": "nodes.chat.output"}}),
],
[edge("input", "search"), edge("search", "fetch"), edge("fetch", "rerank"), edge("rerank", "chat"), edge("chat", "output")],
)
VISION = graph(
[
node("input", "input", 0, 80),
node("vision", "tool", 280, 20, {"tool": "heimgeist.vision_analyze", "arguments": {
"attachments": {"$ref": "run.attachments"}, "vision_model": {"$ref": "run.vision_model"},
"transcription_model": {"$ref": "run.transcription_model"},
}}),
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.vision.output"}])}),
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
],
[edge("input", "vision"), edge("vision", "chat"), edge("chat", "output")],
limits={"maximum_runtime_seconds": 600},
)
KNOWLEDGE_WEB = graph(
[
node("input", "input", 0, 150),
node("knowledge", "tool", 260, 20, {"tool": "heimgeist.knowledge_search", "arguments": {
"prompt": {"$ref": "input.prompt"}, "library_slug": {"$ref": "run.library_slug"}, "top_k": 5,
"context_character_budget": 10000, "embedding_model": None,
}}),
node("search", "tool", 520, 240, {"tool": "heimgeist.web_search", "arguments": {
"query": {"$ref": "run.web_search_query"}, "queries": {"$ref": "run.web_search_queries"}, "engines": {"$ref": "run.searx_engines"},
"maximum_results": 12, "searx_url": {"$ref": "run.searx_url"},
}}),
node("fetch", "tool", 780, 240, {"tool": "heimgeist.web_fetch", "arguments": {"url": None, "urls": {"$ref": "nodes.search.output.results"}, "maximum_pages": 5}}),
node("rerank", "tool", 1040, 240, {"tool": "heimgeist.web_rerank", "arguments": {
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch.output.pages"}, "model": {"$ref": "run.chat_model"},
"rerank_model": None, "context_excerpt": "", "maximum_results": 5, "minimum_score": 50,
}}),
node("merge", "merge", 1300, 130, {"values": [{"$ref": "nodes.knowledge.output"}, {"$ref": "nodes.rerank.output"}], "deduplicate_by": "url"}),
node("limit", "limit", 1520, 130, {"value": {"$ref": "nodes.merge.output"}, "maximum_chars": 22000}),
node("chat", "tool", 1760, 130, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.limit.output"}], EVIDENCE_FIRST_SYSTEM_PROMPT)}),
node("output", "output", 2040, 130, {"value": {"$ref": "nodes.chat.output"}}),
],
[
edge("input", "knowledge"), edge("input", "search"), edge("search", "fetch"), edge("fetch", "rerank"),
edge("knowledge", "merge"), edge("rerank", "merge"), edge("merge", "limit"), edge("limit", "chat"), edge("chat", "output"),
],
)
REMEMBER = graph(
[
node("input", "input", 0, 80),
node("save", "tool", 300, 80, {"tool": "heimgeist.save_message_to_knowledge", "arguments": {
"message_id": {"$ref": "run.target_message_id"}, "library_slug": {"$ref": "run.library_slug"}, "title": None, "edited_content": {"$ref": "run.target_message_content"},
}}),
node("confirmed", "condition", 570, 80, {"value": {"$ref": "nodes.save.output.confirmed"}, "operation": "equals", "compare_to": True}),
node("saved", "template", 830, 20, {"template": "Saved the selected message to knowledge."}),
node("rejected", "template", 830, 150, {"template": "The knowledge save was cancelled."}),
node("response", "merge", 1080, 80, {"values": [{"$ref": "nodes.saved.output"}, {"$ref": "nodes.rejected.output"}], "allow_missing": True}),
node("output", "output", 1320, 80, {"value": {"content": {"$ref": "nodes.response.output.context_block"}, "sources": [], "usage": {}}}),
],
[
edge("input", "save"), edge("save", "confirmed"),
edge("confirmed", "saved", "true"), edge("confirmed", "rejected", "false"),
edge("saved", "response"), edge("rejected", "response"), edge("response", "output"),
],
)
SAVE_SOURCE = graph(
[
node("input", "input", 0, 80),
node("save", "tool", 300, 80, {"tool": "heimgeist.save_website_to_knowledge", "arguments": {
"url": {"$ref": "run.target_url"}, "library_slug": {"$ref": "run.library_slug"}, "title": None,
}}),
node("confirmed", "condition", 570, 80, {"value": {"$ref": "nodes.save.output.confirmed"}, "operation": "equals", "compare_to": True}),
node("saved", "template", 830, 20, {"template": "Saved the website snapshot to knowledge."}),
node("rejected", "template", 830, 150, {"template": "The website save was cancelled."}),
node("response", "merge", 1080, 80, {"values": [{"$ref": "nodes.saved.output"}, {"$ref": "nodes.rejected.output"}], "allow_missing": True}),
node("output", "output", 1320, 80, {"value": {"content": {"$ref": "nodes.response.output.context_block"}, "sources": [], "usage": {}}}),
],
[
edge("input", "save"), edge("save", "confirmed"),
edge("confirmed", "saved", "true"), edge("confirmed", "rejected", "false"),
edge("saved", "response"), edge("rejected", "response"), edge("response", "output"),
],
)
RESEARCH = graph(
[
node("input", "input", 0, 180),
node("search1", "tool", 710, 80, {"tool": "heimgeist.web_search", "arguments": {
"query": {"$ref": "run.web_search_query"}, "queries": {"$ref": "run.web_search_queries"}, "engines": {"$ref": "run.searx_engines"},
"maximum_results": 18, "searx_url": {"$ref": "run.searx_url"},
}}),
node("fetch1", "tool", 950, 80, {"tool": "heimgeist.web_fetch", "arguments": {"url": None, "urls": {"$ref": "nodes.search1.output.results"}, "maximum_pages": 7}}),
node("rank1", "tool", 1190, 80, {"tool": "heimgeist.web_rerank", "arguments": {
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch1.output.pages"}, "model": {"$ref": "run.chat_model"},
"rerank_model": None, "context_excerpt": "", "maximum_results": 6, "minimum_score": 50,
}}),
node("evaluate", "prompt", 1430, 80, {
"model_source": "chat_model",
"system_template": (
"Judge whether the retrieved evidence directly answers the standalone request. "
"Return JSON only. Set sufficient=true only when the evidence contains relevant sourced facts for the main answer. "
"If sufficient=true, follow_up_query must be an empty string. "
"If sufficient=false, follow_up_query must be one concise web search query for the missing information, not an explanation."
),
"user_template": "Original user message: {{input.prompt}}\nResolved request and router inputs: {{nodes.input.output}}\nEvidence: {{nodes.rank1.output.context_block}}",
"output_mode": "json", "json_schema": {"type": "object", "properties": {"sufficient": {"type": "boolean"}, "follow_up_query": {"type": "string"}}, "required": ["sufficient", "follow_up_query"], "additionalProperties": False},
"temperature": 0.1, "json_repair": True,
}),
node("sufficient", "condition", 1690, 80, {"value": {"$ref": "nodes.evaluate.output.sufficient"}, "operation": "equals", "compare_to": True}),
node("queries2", "select", 1910, 220, {"value": {"$ref": "nodes.evaluate.output.follow_up_query"}}),
node("search2", "tool", 2130, 220, {"tool": "heimgeist.web_search", "arguments": {
"query": {"$ref": "nodes.queries2.output"}, "queries": [], "engines": {"$ref": "run.searx_engines"},
"maximum_results": 10, "searx_url": {"$ref": "run.searx_url"},
}}),
node("fetch2", "tool", 2350, 220, {"tool": "heimgeist.web_fetch", "arguments": {"url": None, "urls": {"$ref": "nodes.search2.output.results"}, "maximum_pages": 4}}),
node("rank2", "tool", 2570, 220, {"tool": "heimgeist.web_rerank", "arguments": {
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch2.output.pages"}, "model": {"$ref": "run.chat_model"},
"rerank_model": None, "context_excerpt": "", "maximum_results": 4, "minimum_score": 45,
}}),
node("empty2", "template", 1910, -80, {"template": "", "values": {}}),
node("merge", "merge", 2820, 80, {"values": [{"$ref": "nodes.rank1.output"}, {"$ref": "nodes.rank2.output"}], "deduplicate_by": "url", "allow_missing": True}),
node("limit", "limit", 3050, 80, {"value": {"$ref": "nodes.merge.output"}, "maximum_chars": 28000}),
node("chat", "tool", 3280, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.limit.output"}], EVIDENCE_FIRST_SYSTEM_PROMPT)}),
node("output", "output", 3520, 80, {"value": {"$ref": "nodes.chat.output"}}),
],
[
edge("input", "search1"), edge("search1", "fetch1"), edge("fetch1", "rank1"),
edge("rank1", "evaluate"), edge("evaluate", "sufficient"), edge("sufficient", "empty2", "true", "-true"), edge("sufficient", "queries2", "false", "-false"),
edge("queries2", "search2"), edge("search2", "fetch2"), edge("fetch2", "rank2"), edge("rank1", "merge"), edge("rank2", "merge"), edge("empty2", "merge"),
edge("merge", "limit"), edge("limit", "chat"), edge("chat", "output"),
],
limits={"maximum_tool_calls": 24, "maximum_llm_calls": 10, "maximum_runtime_seconds": 420},
)
BUILTIN_WORKFLOWS = [
{"slug": "input-output", "name": "Input -> Output", "description": "Normal Heimgeist chat with optional compatibility context.", "routing_description": "Choose only when no external tool is needed: conversational replies, writing, editing, reasoning, brainstorming, explanation, or stable knowledge the model can answer without retrieval. Do not choose when the standalone request needs facts outside the conversation/model context, source grounding, live local knowledge retrieval, attachment analysis, or knowledge-saving actions.", "routing_examples": ["Explain this concept", "Draft a reply", "Rewrite this paragraph", "What do you mean by that?"], "estimated_cost_class": "low", "required_capabilities": ["chat"], "graph": DIRECT},
{"slug": "chat-memory-answer", "name": "Chat Memory Answer", "description": "Search previous Heimgeist chats and answer from matching turns.", "routing_description": "Choose when the standalone request asks Heimgeist to use past chats, earlier conversations, remembered discussion context, previous decisions, or topics discussed before. This workflow searches previous chat turns before answering. Do not choose for general factual questions that merely resemble something discussed before; choose Web Answer, Knowledge Answer, or direct chat based on the requested evidence.", "routing_examples": ["What music did we talk about before?", "What did we decide earlier about packaging?", "Use our previous chat about Ollama settings"], "estimated_cost_class": "medium", "required_capabilities": ["chat_memory", "chat"], "graph": CHAT_MEMORY},
{"slug": "recent-chat-memory-answer", "name": "Recent Chat Memory Answer", "description": "Answer from the most recent previous Heimgeist chat.", "routing_description": "Choose when the standalone request specifically asks about the last, previous, latest, or most recent earlier Heimgeist chat or conversation. This workflow retrieves the most recent previous chat turn instead of doing a relevance search.", "routing_examples": ["What was the last conversation about?", "Worum ging es im letzten Gespräch?", "Continue from the previous chat"], "estimated_cost_class": "medium", "required_capabilities": ["chat_memory", "chat"], "graph": RECENT_CHAT_MEMORY},
{"slug": "knowledge-answer", "name": "Knowledge Answer", "description": "Answer from local knowledge.", "routing_description": "Choose when the standalone request asks about or should be grounded in Heimgeist's local Knowledge store, and current web evidence is not required. This workflow retrieves local knowledge before answering.", "routing_examples": ["What do my notes say about this?", "Summarize the saved knowledge entry"], "estimated_cost_class": "medium", "required_capabilities": ["rag"], "graph": KNOWLEDGE},
{"slug": "web-answer", "name": "Web Answer", "description": "Search, fetch, rank, and answer from current web sources.", "routing_description": "Choose when the standalone request needs web evidence and can likely be answered by one bounded search/fetch/rank pass: facts outside the conversation/model context, source-grounded lookup, public information that may have changed, or a follow-up that inherits such a web-grounded topic. This is the default web workflow for direct answer requests. Prefer it over Research unless the request itself requires investigation, comparison, validation, or broad synthesis.", "routing_examples": ["Look this up online", "What is the current status?", "Find the latest information about this topic", "What happened with that since then?"], "estimated_cost_class": "medium", "required_capabilities": ["web"], "graph": web_graph()},
{"slug": "vision-answer", "name": "Vision Answer", "description": "Analyze attachments and answer with a vision model.", "routing_description": "Use when image or document attachments must be analyzed.", "routing_examples": ["What is shown in this image?"], "estimated_cost_class": "medium", "required_capabilities": ["vision"], "graph": VISION},
{"slug": "knowledge-web-answer", "name": "Knowledge + Web Answer", "description": "Combine local knowledge and current web evidence.", "routing_description": "Choose when both capabilities are needed: Heimgeist's local Knowledge store is relevant, and the standalone request also requires web evidence or updated external facts.", "routing_examples": ["Compare my notes with the latest information", "Check my saved source against current web evidence"], "estimated_cost_class": "high", "required_capabilities": ["rag", "web"], "graph": KNOWLEDGE_WEB},
{"slug": "remember-this", "name": "Remember This", "description": "Save a selected chat message to knowledge.", "routing_description": "Use only when the user explicitly asks to remember or save a chat message.", "routing_examples": ["Remember this answer"], "estimated_cost_class": "low", "required_capabilities": ["knowledge_write"], "graph": REMEMBER},
{"slug": "save-source", "name": "Save Source", "description": "Save a website snapshot to knowledge.", "routing_description": "Use when the user explicitly asks to save a URL as a knowledge source.", "routing_examples": ["Save this website to Knowledge"], "estimated_cost_class": "low", "required_capabilities": ["web", "knowledge_write"], "graph": SAVE_SOURCE},
{"slug": "research", "name": "Research", "description": "Bounded two-round evidence research with source validation.", "routing_description": "Choose only when the standalone request needs an investigation rather than a direct lookup: compare sources, resolve uncertainty, validate claims, synthesize several angles, or perform a second search if first-pass evidence is insufficient. Do not choose this solely because web evidence is needed, because the topic is important, or because information is current. Choose Web Answer for direct web-grounded questions.", "routing_examples": ["Research the competing explanations and cite sources", "Compare the strongest evidence for both claims", "Investigate this topic in depth"], "estimated_cost_class": "high", "required_capabilities": ["web", "chat"], "graph": RESEARCH},
]
def _checksum(graph_value: Dict[str, Any]) -> str:
canonical = json.dumps(graph_value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def seed_builtin_workflows(session: Session) -> None:
for item in BUILTIN_WORKFLOWS:
workflow = session.query(WorkflowDefinition).filter(WorkflowDefinition.slug == item["slug"]).first()
if workflow is None:
workflow = WorkflowDefinition(
slug=item["slug"], name=item["name"], description=item["description"], built_in=True, enabled=True,
routing_description=item["routing_description"], routing_examples_json=json.dumps(item["routing_examples"]),
estimated_cost_class=item["estimated_cost_class"], required_capabilities_json=json.dumps(item["required_capabilities"]),
)
session.add(workflow)
session.flush()
else:
workflow.name = item["name"]
workflow.description = item["description"]
workflow.built_in = True
workflow.routing_description = item["routing_description"]
workflow.routing_examples_json = json.dumps(item["routing_examples"])
workflow.estimated_cost_class = item["estimated_cost_class"]
workflow.required_capabilities_json = json.dumps(item["required_capabilities"])
workflow.updated_at = datetime.utcnow()
checksum = _checksum(item["graph"])
revision = session.query(WorkflowRevision).filter(
WorkflowRevision.workflow_id == workflow.id,
WorkflowRevision.checksum == checksum,
).first()
if revision is None:
latest = session.query(WorkflowRevision).filter(WorkflowRevision.workflow_id == workflow.id).order_by(WorkflowRevision.version.desc()).first()
revision = WorkflowRevision(
workflow_id=workflow.id,
version=(latest.version + 1) if latest else 1,
graph_json=json.dumps(item["graph"], ensure_ascii=False),
created_by="system",
trusted=True,
checksum=checksum,
)
session.add(revision)
session.flush()
workflow.current_revision_id = revision.id
session.commit()

View File

@@ -0,0 +1 @@
"""Research workflow constants live in builtins.py to keep seeded graphs versioned together."""

View File

@@ -11,11 +11,25 @@ APP_NAME = "Heimgeist"
DEFAULT_BACKEND_API_URL = "http://127.0.0.1:8000" DEFAULT_BACKEND_API_URL = "http://127.0.0.1:8000"
DEFAULT_OLLAMA_API_URL = "http://127.0.0.1:11434" DEFAULT_OLLAMA_API_URL = "http://127.0.0.1:11434"
DEFAULT_EMBED_MODEL = "nomic-embed-text:latest" DEFAULT_EMBED_MODEL = "nomic-embed-text:latest"
DEFAULT_RERANK_MODEL = DEFAULT_EMBED_MODEL
DEFAULT_ENRICHMENT_MODEL = "qwen3:4b"
DEFAULT_TRANSCRIPTION_MODEL = "base"
DEFAULT_WORKFLOW_ROUTER_MODEL = ""
DEFAULT_WORKFLOW_SELECTION_MODE = "auto"
DEFAULT_AUTO_DEEP_ENRICHMENT = True
BGE_EMBED_MODEL = "bge-m3:latest" BGE_EMBED_MODEL = "bge-m3:latest"
DEFAULT_SETTINGS: Dict[str, Any] = { DEFAULT_SETTINGS: Dict[str, Any] = {
"backendApiUrl": DEFAULT_BACKEND_API_URL, "backendApiUrl": DEFAULT_BACKEND_API_URL,
"ollamaApiUrl": DEFAULT_OLLAMA_API_URL, "ollamaApiUrl": DEFAULT_OLLAMA_API_URL,
"chatModel": "llama3",
"visionModel": "",
"embedModel": DEFAULT_EMBED_MODEL, "embedModel": DEFAULT_EMBED_MODEL,
"rerankModel": DEFAULT_RERANK_MODEL,
"enrichmentModel": DEFAULT_ENRICHMENT_MODEL,
"transcriptionModel": DEFAULT_TRANSCRIPTION_MODEL,
"workflowRouterModel": DEFAULT_WORKFLOW_ROUTER_MODEL,
"workflowSelectionMode": DEFAULT_WORKFLOW_SELECTION_MODE,
"autoDeepEnrichment": DEFAULT_AUTO_DEEP_ENRICHMENT,
} }
@@ -63,10 +77,49 @@ def normalize_embed_model(value: Any) -> str:
if not isinstance(value, str): if not isinstance(value, str):
return DEFAULT_EMBED_MODEL return DEFAULT_EMBED_MODEL
trimmed = value.strip().lower() trimmed = value.strip()
if trimmed in {"bge", "bge-m3", BGE_EMBED_MODEL}: if not trimmed:
return DEFAULT_EMBED_MODEL
lowered = trimmed.lower()
if lowered in {"bge", "bge-m3", BGE_EMBED_MODEL}:
return BGE_EMBED_MODEL return BGE_EMBED_MODEL
return DEFAULT_EMBED_MODEL if lowered in {"nomic", "nomic-embed-text", DEFAULT_EMBED_MODEL}:
return DEFAULT_EMBED_MODEL
return trimmed
def normalize_rerank_model(value: Any) -> str:
return normalize_embed_model(value)
def normalize_model_name(value: Any, fallback: str = "") -> str:
if not isinstance(value, str):
return fallback
trimmed = value.strip()
return trimmed or fallback
def normalize_workflow_selection_mode(value: Any) -> str:
if isinstance(value, str) and value.strip().lower() == "manual":
return "manual"
return DEFAULT_WORKFLOW_SELECTION_MODE
def normalize_transcription_model(value: Any) -> str:
return normalize_model_name(value, DEFAULT_TRANSCRIPTION_MODEL)
def normalize_boolean(value: Any, default: bool = False) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"true", "1", "yes", "on"}:
return True
if normalized in {"false", "0", "no", "off", ""}:
return False
return default
def load_app_settings() -> Dict[str, Any]: def load_app_settings() -> Dict[str, Any]:
@@ -92,7 +145,25 @@ def load_app_settings() -> Dict[str, Any]:
else: else:
settings["backendApiUrl"] = _normalize_url(settings.get("backendApiUrl"), DEFAULT_BACKEND_API_URL) settings["backendApiUrl"] = _normalize_url(settings.get("backendApiUrl"), DEFAULT_BACKEND_API_URL)
settings["ollamaApiUrl"] = _normalize_url(settings.get("ollamaApiUrl"), DEFAULT_OLLAMA_API_URL) settings["ollamaApiUrl"] = _normalize_url(settings.get("ollamaApiUrl"), DEFAULT_OLLAMA_API_URL)
if "rerankModel" not in raw:
settings["rerankModel"] = settings.get("embedModel")
if "visionModel" not in raw:
settings["visionModel"] = settings.get("chatModel", "")
settings["embedModel"] = normalize_embed_model(settings.get("embedModel")) settings["embedModel"] = normalize_embed_model(settings.get("embedModel"))
settings["rerankModel"] = normalize_rerank_model(settings.get("rerankModel"))
settings["enrichmentModel"] = normalize_model_name(
settings.get("enrichmentModel"),
DEFAULT_ENRICHMENT_MODEL,
)
settings["chatModel"] = normalize_model_name(settings.get("chatModel"))
settings["visionModel"] = normalize_model_name(settings.get("visionModel"))
settings["transcriptionModel"] = normalize_transcription_model(settings.get("transcriptionModel"))
settings["workflowRouterModel"] = normalize_model_name(settings.get("workflowRouterModel"))
settings["workflowSelectionMode"] = normalize_workflow_selection_mode(settings.get("workflowSelectionMode"))
settings["autoDeepEnrichment"] = normalize_boolean(
settings.get("autoDeepEnrichment"),
DEFAULT_AUTO_DEEP_ENRICHMENT,
)
return settings return settings
@@ -105,3 +176,31 @@ def get_ollama_api_url() -> str:
def get_embed_model_preference() -> str: def get_embed_model_preference() -> str:
settings = load_app_settings() settings = load_app_settings()
return normalize_embed_model(settings.get("embedModel")) return normalize_embed_model(settings.get("embedModel"))
def get_rerank_model_preference() -> str:
settings = load_app_settings()
return normalize_rerank_model(settings.get("rerankModel"))
def get_enrichment_model_preference() -> str:
settings = load_app_settings()
return normalize_model_name(settings.get("enrichmentModel"), DEFAULT_ENRICHMENT_MODEL)
def get_transcription_model_preference() -> str:
settings = load_app_settings()
return normalize_transcription_model(settings.get("transcriptionModel"))
def get_workflow_router_model_preference() -> str:
settings = load_app_settings()
return normalize_model_name(settings.get("workflowRouterModel"))
def get_auto_deep_enrichment_preference() -> bool:
settings = load_app_settings()
return normalize_boolean(
settings.get("autoDeepEnrichment"),
DEFAULT_AUTO_DEEP_ENRICHMENT,
)

665
backend/chat_memory.py Normal file
View File

@@ -0,0 +1,665 @@
from __future__ import annotations
from datetime import datetime
import json
import re
from typing import Any, Dict, List, Optional, Sequence
from sqlalchemy import text
from sqlalchemy.orm import Session
from . import models
DEFAULT_MEMORY_TOP_K = 4
DEFAULT_MEMORY_CONTEXT_CHARS = 3600
_TOKEN_RE = re.compile(r"[\w][\w'_-]*", re.UNICODE)
_THINK_RE = re.compile(r"<think(?:ing)?>.*?</think(?:ing)?>", re.IGNORECASE | re.DOTALL)
def ensure_chat_memory_schema(engine) -> None:
"""Create the lightweight chat memory tables used for past-chat retrieval."""
with engine.begin() as conn:
conn.execute(text(
"""
CREATE TABLE IF NOT EXISTS chat_memory_turns (
turn_key TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
session_name TEXT NOT NULL DEFAULT '',
user_message_id TEXT NOT NULL,
assistant_message_id TEXT NOT NULL,
user_message_row_id INTEGER NOT NULL,
assistant_message_row_id INTEGER NOT NULL,
user_content TEXT NOT NULL,
assistant_content TEXT NOT NULL,
attachment_summary TEXT NOT NULL DEFAULT '',
search_text TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
"""
))
conn.execute(text(
"CREATE INDEX IF NOT EXISTS ix_chat_memory_turns_session_id "
"ON chat_memory_turns (session_id)"
))
conn.execute(text(
"CREATE INDEX IF NOT EXISTS ix_chat_memory_turns_assistant_row "
"ON chat_memory_turns (assistant_message_row_id)"
))
try:
conn.execute(text(
"""
CREATE VIRTUAL TABLE IF NOT EXISTS chat_memory_turns_fts USING fts5(
turn_key UNINDEXED,
session_id UNINDEXED,
session_name,
user_content,
assistant_content,
attachment_summary,
search_text,
tokenize = 'unicode61'
)
"""
))
except Exception as exc:
print("[chat-memory] FTS index unavailable:", exc)
def _ensure_schema_for_session(db: Session) -> None:
try:
ensure_chat_memory_schema(db.get_bind())
except Exception:
pass
def _clean_content(value: Any, limit: int = 12_000) -> str:
text_value = _THINK_RE.sub("", str(value or ""))
text_value = re.sub(r"\s+", " ", text_value).strip()
if len(text_value) > limit:
return text_value[:limit].rstrip() + "..."
return text_value
def _attachment_summary(raw_value: Any) -> str:
try:
items = json.loads(raw_value or "[]") if isinstance(raw_value, str) else (raw_value or [])
except Exception:
return ""
labels: List[str] = []
iterable = items if isinstance(items, list) else []
for item in iterable:
if not isinstance(item, dict):
continue
name = str(item.get("name") or item.get("source_path") or "").strip()
if name:
labels.append(name[:160])
return ", ".join(labels[:8])
def _is_memory_only_source_value(raw_value: Any) -> bool:
try:
sources = json.loads(raw_value or "[]")
except Exception:
return False
if not isinstance(sources, list) or not sources:
return False
for source in sources:
if not isinstance(source, dict) or source.get("type") != "chat_memory":
return False
return True
def _is_memory_only_response(row: models.ChatMessage) -> bool:
return _is_memory_only_source_value(getattr(row, "sources_json", None))
def _completed_turns(
session: models.ChatSession,
rows: Sequence[models.ChatMessage],
*,
skip_memory_only: bool = True,
) -> List[Dict[str, Any]]:
turns: List[Dict[str, Any]] = []
pending_user: Optional[models.ChatMessage] = None
session_title = _clean_content(session.name, limit=200) or "New Chat"
for row in rows:
if row.role == "user":
pending_user = row
continue
if row.role != "assistant" or pending_user is None:
continue
if skip_memory_only and _is_memory_only_response(row):
pending_user = None
continue
user_content = _clean_content(pending_user.content)
assistant_content = _clean_content(row.content)
if not user_content or not assistant_content:
pending_user = None
continue
attachments = _attachment_summary(getattr(pending_user, "attachments_json", None))
created_at = row.created_at.isoformat() if row.created_at else datetime.utcnow().isoformat()
turn_key = f"{pending_user.message_id}:{row.message_id}"
search_text = "\n".join(part for part in (
session_title,
attachments,
f"User: {user_content}",
f"Assistant: {assistant_content}",
) if part.strip())
turns.append({
"turn_key": turn_key,
"session_id": session.session_id,
"session_name": session_title,
"user_message_id": pending_user.message_id,
"assistant_message_id": row.message_id,
"user_message_row_id": pending_user.id,
"assistant_message_row_id": row.id,
"user_content": user_content,
"assistant_content": assistant_content,
"attachment_summary": attachments,
"search_text": search_text,
"created_at": created_at,
"updated_at": datetime.utcnow().isoformat(),
})
pending_user = None
return turns
def _delete_fts_rows(db: Session, keys: Sequence[str]) -> None:
if not keys:
return
try:
for turn_key in keys:
db.execute(text("DELETE FROM chat_memory_turns_fts WHERE turn_key = :turn_key"), {"turn_key": turn_key})
except Exception:
pass
def _insert_turn(db: Session, turn: Dict[str, Any]) -> None:
db.execute(text(
"""
INSERT OR REPLACE INTO chat_memory_turns (
turn_key, session_id, session_name, user_message_id, assistant_message_id,
user_message_row_id, assistant_message_row_id, user_content, assistant_content,
attachment_summary, search_text, created_at, updated_at
) VALUES (
:turn_key, :session_id, :session_name, :user_message_id, :assistant_message_id,
:user_message_row_id, :assistant_message_row_id, :user_content, :assistant_content,
:attachment_summary, :search_text, :created_at, :updated_at
)
"""
), turn)
_delete_fts_rows(db, [turn["turn_key"]])
try:
db.execute(text(
"""
INSERT INTO chat_memory_turns_fts (
turn_key, session_id, session_name, user_content, assistant_content,
attachment_summary, search_text
) VALUES (
:turn_key, :session_id, :session_name, :user_content, :assistant_content,
:attachment_summary, :search_text
)
"""
), turn)
except Exception:
pass
def delete_chat_memory_for_session(db: Session, session_id: str, *, commit: bool = True) -> None:
_ensure_schema_for_session(db)
keys = [
row[0]
for row in db.execute(
text("SELECT turn_key FROM chat_memory_turns WHERE session_id = :session_id"),
{"session_id": session_id},
).fetchall()
]
_delete_fts_rows(db, keys)
db.execute(text("DELETE FROM chat_memory_turns WHERE session_id = :session_id"), {"session_id": session_id})
if commit:
db.commit()
def sync_chat_memory_for_session(db: Session, session_id: str, *, commit: bool = True) -> int:
_ensure_schema_for_session(db)
session = db.query(models.ChatSession).filter(models.ChatSession.session_id == session_id).first()
if session is None:
delete_chat_memory_for_session(db, session_id, commit=commit)
return 0
rows = (
db.query(models.ChatMessage)
.filter(models.ChatMessage.session_pk == session.id)
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
.all()
)
turns = _completed_turns(session, rows)
delete_chat_memory_for_session(db, session_id, commit=False)
for turn in turns:
_insert_turn(db, turn)
if commit:
db.commit()
return len(turns)
def sync_all_chat_memory(db: Session, *, commit: bool = True) -> int:
_ensure_schema_for_session(db)
try:
db.execute(text("DELETE FROM chat_memory_turns_fts"))
except Exception:
pass
db.execute(text("DELETE FROM chat_memory_turns"))
count = 0
sessions = db.query(models.ChatSession).order_by(models.ChatSession.id.asc()).all()
for session in sessions:
rows = (
db.query(models.ChatMessage)
.filter(models.ChatMessage.session_pk == session.id)
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
.all()
)
for turn in _completed_turns(session, rows):
_insert_turn(db, turn)
count += 1
if commit:
db.commit()
return count
def safe_backfill_chat_memory(db_factory) -> None:
db = db_factory()
try:
count = sync_all_chat_memory(db)
print(f"[chat-memory] indexed {count} completed chat turns")
except Exception as exc:
db.rollback()
print("[chat-memory] backfill failed:", exc)
finally:
db.close()
def safe_sync_chat_memory_for_session(db: Session, session_id: Optional[str]) -> None:
if not session_id:
return
try:
sync_chat_memory_for_session(db, str(session_id))
except Exception as exc:
db.rollback()
print("[chat-memory] session sync failed:", exc)
def safe_delete_chat_memory_for_session(db: Session, session_id: Optional[str]) -> None:
if not session_id:
return
try:
delete_chat_memory_for_session(db, str(session_id), commit=False)
except Exception as exc:
print("[chat-memory] session delete failed:", exc)
def _query_tokens(prompt: str, limit: int = 24) -> List[str]:
tokens: List[str] = []
seen = set()
for raw in _TOKEN_RE.findall(str(prompt or "").casefold()):
token = raw.strip("'_-")
if len(token) < 2 or token in seen:
continue
seen.add(token)
tokens.append(token)
if len(tokens) >= limit:
break
return tokens
def _fts_match_query(tokens: Sequence[str]) -> str:
safe_terms = []
for token in tokens:
cleaned = re.sub(r"[^0-9A-Za-z_\u0080-\uffff]", "", token)
if cleaned:
safe_terms.append(f'"{cleaned}"')
return " OR ".join(safe_terms)
def _row_mapping(row: Any) -> Dict[str, Any]:
if isinstance(row, dict):
return row
try:
return dict(row._mapping)
except Exception:
return dict(row)
def _score_hit(
row: Dict[str, Any],
tokens: Sequence[str],
fts_rank: Optional[float] = None,
) -> float:
title = str(row.get("session_name") or "").casefold()
user_text = str(row.get("user_content") or "").casefold()
assistant_text = str(row.get("assistant_content") or "").casefold()
attachment_text = str(row.get("attachment_summary") or "").casefold()
combined = f"{title} {attachment_text} {user_text} {assistant_text}"
hits = [token for token in tokens if token in combined]
if not hits:
return 0.0
score = len(hits) / max(1, min(len(tokens), 8))
score += 0.18 * sum(1 for token in hits if token in title)
score += 0.10 * sum(1 for token in hits if token in user_text)
if fts_rank is not None:
try:
score += min(0.08, 1.0 / (1.0 + abs(float(fts_rank))))
except Exception:
pass
try:
assistant_row = int(row.get("assistant_message_row_id") or 0)
score += min(0.04, assistant_row / 2_000_000)
except Exception:
pass
return score
def _load_fts_candidates(
db: Session,
tokens: Sequence[str],
*,
exclude_session_id: Optional[str],
limit: int,
) -> List[Dict[str, Any]]:
match = _fts_match_query(tokens)
if not match:
return []
try:
rows = db.execute(text(
"""
SELECT
t.turn_key, t.session_id, t.session_name, t.user_message_id,
t.assistant_message_id, t.user_message_row_id, t.assistant_message_row_id,
t.user_content, t.assistant_content, t.attachment_summary, t.search_text,
t.created_at, bm25(chat_memory_turns_fts) AS fts_rank
FROM chat_memory_turns_fts
JOIN chat_memory_turns t ON t.turn_key = chat_memory_turns_fts.turn_key
WHERE chat_memory_turns_fts MATCH :match
AND (:exclude_session_id IS NULL OR t.session_id != :exclude_session_id)
ORDER BY fts_rank ASC, t.assistant_message_row_id DESC
LIMIT :limit
"""
), {
"match": match,
"exclude_session_id": exclude_session_id,
"limit": max(limit, 1),
}).mappings().all()
except Exception:
return []
candidates: List[Dict[str, Any]] = []
for row in rows:
item = _row_mapping(row)
item["_score"] = _score_hit(item, tokens, item.get("fts_rank"))
if item["_score"] > 0:
candidates.append(item)
return candidates
def _load_table_candidates(
db: Session,
tokens: Sequence[str],
*,
exclude_session_id: Optional[str],
limit: int,
) -> List[Dict[str, Any]]:
try:
rows = db.execute(text(
"""
SELECT
turn_key, session_id, session_name, user_message_id, assistant_message_id,
user_message_row_id, assistant_message_row_id, user_content, assistant_content,
attachment_summary, search_text, created_at
FROM chat_memory_turns
WHERE (:exclude_session_id IS NULL OR session_id != :exclude_session_id)
ORDER BY assistant_message_row_id DESC
LIMIT :limit
"""
), {
"exclude_session_id": exclude_session_id,
"limit": max(limit, 1),
}).mappings().all()
except Exception:
return []
candidates: List[Dict[str, Any]] = []
for row in rows:
item = _row_mapping(row)
item["_score"] = _score_hit(item, tokens)
if item["_score"] > 0:
candidates.append(item)
return candidates
def _load_live_candidates(
db: Session,
tokens: Sequence[str],
*,
exclude_session_id: Optional[str],
limit: int,
) -> List[Dict[str, Any]]:
try:
rows = db.execute(text(
"""
SELECT
s.session_id, s.name AS session_name,
m.id AS message_row_id, m.message_id, m.role, m.content,
m.sources_json, m.attachments_json, m.created_at
FROM chat_messages m
JOIN chat_sessions s ON s.id = m.session_pk
WHERE (:exclude_session_id IS NULL OR s.session_id != :exclude_session_id)
ORDER BY s.id ASC, m.created_at ASC, m.id ASC
LIMIT :limit
"""
), {
"exclude_session_id": exclude_session_id,
"limit": max(limit, 1),
}).mappings().all()
except Exception:
return []
turns: List[Dict[str, Any]] = []
pending_by_session: Dict[str, Dict[str, Any]] = {}
for row in rows:
item = _row_mapping(row)
session_id = str(item.get("session_id") or "")
if item.get("role") == "user":
pending_by_session[session_id] = item
continue
if item.get("role") != "assistant" or session_id not in pending_by_session:
continue
if _is_memory_only_source_value(item.get("sources_json")):
pending_by_session.pop(session_id, None)
continue
user = pending_by_session.pop(session_id)
user_content = _clean_content(user.get("content"))
assistant_content = _clean_content(item.get("content"))
if not user_content or not assistant_content:
continue
attachments = _attachment_summary(user.get("attachments_json"))
turn = {
"turn_key": f"{user.get('message_id')}:{item.get('message_id')}",
"session_id": session_id,
"session_name": _clean_content(item.get("session_name"), limit=200) or "New Chat",
"user_message_id": user.get("message_id"),
"assistant_message_id": item.get("message_id"),
"user_message_row_id": user.get("message_row_id"),
"assistant_message_row_id": item.get("message_row_id"),
"user_content": user_content,
"assistant_content": assistant_content,
"attachment_summary": attachments,
"created_at": str(item.get("created_at") or ""),
}
turn["_score"] = _score_hit(turn, tokens)
if turn["_score"] > 0:
turns.append(turn)
return turns
def _trim(value: Any, limit: int) -> str:
text_value = _clean_content(value, limit=max(limit * 2, limit))
if len(text_value) <= limit:
return text_value
return text_value[:limit].rstrip() + "..."
def _dedupe_hits(candidates: Sequence[Dict[str, Any]], top_k: int) -> List[Dict[str, Any]]:
seen = set()
ordered = sorted(candidates, key=lambda item: (float(item.get("_score") or 0), int(item.get("assistant_message_row_id") or 0)), reverse=True)
hits: List[Dict[str, Any]] = []
for item in ordered:
key = item.get("turn_key") or (item.get("session_id"), item.get("assistant_message_id"))
if key in seen:
continue
seen.add(key)
hits.append(item)
if len(hits) >= top_k:
break
return hits
def _context_payload_from_hits(
hits: Sequence[Dict[str, Any]],
*,
context_character_budget: int,
intro: str,
) -> Dict[str, Any]:
if not hits:
return {"context_block": "", "sources": [], "hits": []}
header = f"<chat_memory_context>\n{intro}"
blocks = [header]
sources: List[Dict[str, Any]] = []
remaining = max(600, int(context_character_budget)) - len(header) - len("</chat_memory_context>")
for idx, hit in enumerate(hits, start=1):
title = _trim(hit.get("session_name") or "Previous chat", 120)
date = str(hit.get("created_at") or "")[:10]
user = _trim(hit.get("user_content"), 520)
assistant = _trim(hit.get("assistant_content"), 900)
attachments = _trim(hit.get("attachment_summary"), 180)
attachment_line = f"\nAttachments: {attachments}" if attachments else ""
chunk = (
f"[M{idx}] {title}{f' ({date})' if date else ''}{attachment_line}\n"
f"User: {user}\n"
f"Assistant: {assistant}"
)
if len(chunk) > remaining:
if remaining < 500:
break
chunk = chunk[:remaining].rstrip() + "..."
blocks.append(chunk)
remaining -= len(chunk) + 2
sources.append({
"type": "chat_memory",
"title": f"Chat memory: {title}",
"source_session_id": hit.get("session_id"),
"source_message_id": hit.get("assistant_message_id"),
"snippet": assistant[:500],
"score": round(float(hit.get("_score") or 0), 4),
"created_at": hit.get("created_at"),
})
if remaining <= 0:
break
blocks.append("</chat_memory_context>")
return {"context_block": "\n\n".join(blocks), "sources": sources, "hits": list(hits[:len(sources)])}
def _load_previous_session_hits(
db: Session,
*,
exclude_session_id: Optional[str],
limit: int,
) -> List[Dict[str, Any]]:
current_created_at = None
if exclude_session_id:
try:
current_session = db.query(models.ChatSession).filter(models.ChatSession.session_id == exclude_session_id).first()
current_created_at = current_session.created_at if current_session else None
except Exception:
current_created_at = None
try:
query = db.query(models.ChatSession)
if exclude_session_id:
query = query.filter(models.ChatSession.session_id != exclude_session_id)
if current_created_at:
query = query.filter(models.ChatSession.created_at < current_created_at)
sessions = query.order_by(models.ChatSession.created_at.desc(), models.ChatSession.id.desc()).limit(20).all()
except Exception:
return []
for session in sessions:
rows = (
db.query(models.ChatMessage)
.filter(models.ChatMessage.session_pk == session.id)
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
.all()
)
hits = _completed_turns(session, rows, skip_memory_only=False)[:max(1, limit)]
if hits:
for hit in hits:
hit["_score"] = 1.0
return hits
return []
def build_chat_memory_context(
db: Session,
prompt: str,
*,
exclude_session_id: Optional[str] = None,
top_k: int = DEFAULT_MEMORY_TOP_K,
context_character_budget: int = DEFAULT_MEMORY_CONTEXT_CHARS,
mode: str = "search",
) -> Dict[str, Any]:
if mode == "recent":
hits = _load_previous_session_hits(db, exclude_session_id=exclude_session_id, limit=max(1, top_k))
return _context_payload_from_hits(
hits,
context_character_budget=context_character_budget,
intro=(
"Most recent previous chat. Use this to answer questions about the last or previous conversation; "
"do not treat it as fresh external evidence."
),
)
tokens = _query_tokens(prompt)
if not tokens:
return {"context_block": "", "sources": [], "hits": []}
candidate_limit = max(80, top_k * 24)
candidates = _load_fts_candidates(
db,
tokens,
exclude_session_id=exclude_session_id,
limit=candidate_limit,
)
if len(candidates) < top_k:
candidates.extend(_load_table_candidates(
db,
tokens,
exclude_session_id=exclude_session_id,
limit=max(300, candidate_limit),
))
if len(candidates) < top_k:
candidates.extend(_load_live_candidates(
db,
tokens,
exclude_session_id=exclude_session_id,
limit=1500,
))
hits = _dedupe_hits(candidates, max(1, top_k))
return _context_payload_from_hits(
hits,
context_character_budget=context_character_budget,
intro=(
"Relevant excerpts from previous chats. Use these only when they help answer the current request; "
"they may be outdated and should not override explicit current context or fresh retrieved evidence."
),
)

View File

@@ -1,22 +1,25 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from sqlalchemy import text from sqlalchemy import text
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
import uuid
from .paths import database_path, sqlite_database_url
""" """
Database utilities and configuration. This module defines the SQLAlchemy Database utilities and configuration. This module defines the SQLAlchemy
engine, session factory and base class for models. It also contains a engine, session factory and base class for models. It also contains a
lightweight migration helper used to evolve the schema over time. The lightweight migration helper used to evolve the schema over time. The
`ensure_sources_column` helper adds a new `sources_json` column to the `ensure_sources_column` helper adds the JSON-backed columns used by chat
`chat_messages` table if it does not already exist. This is required messages when they do not already exist.
for persisting citation sources alongside assistant messages.
The migration uses SQLite's `ALTER TABLE` syntax and therefore should The migration uses SQLite's `ALTER TABLE` syntax and therefore should
only run once on startup. It is safe to call repeatedly: when the only run once on startup. It is safe to call repeatedly: when a column
column already exists, the function will simply no‑op. already exists, the function will simply no-op.
""" """
DATABASE_URL = "sqlite:///./backend/app.db" DATABASE_PATH = database_path()
DATABASE_URL = sqlite_database_url(DATABASE_PATH)
engine = create_engine( engine = create_engine(
DATABASE_URL, connect_args={"check_same_thread": False} DATABASE_URL, connect_args={"check_same_thread": False}
@@ -30,9 +33,38 @@ class Base(DeclarativeBase):
def ensure_sources_column(engine): def ensure_sources_column(engine):
try: try:
with engine.connect() as conn: with engine.begin() as conn:
cols = [row[1] for row in conn.execute(text("PRAGMA table_info(chat_messages)"))] cols = [row[1] for row in conn.execute(text("PRAGMA table_info(chat_messages)"))]
if "message_id" not in cols:
conn.execute(text("ALTER TABLE chat_messages ADD COLUMN message_id TEXT"))
if "sources_json" not in cols: if "sources_json" not in cols:
conn.execute(text("ALTER TABLE chat_messages ADD COLUMN sources_json TEXT DEFAULT '[]'")) conn.execute(text("ALTER TABLE chat_messages ADD COLUMN sources_json TEXT DEFAULT '[]'"))
if "attachments_json" not in cols:
conn.execute(text("ALTER TABLE chat_messages ADD COLUMN attachments_json TEXT DEFAULT '[]'"))
for column_name, definition in (
("workflow_id", "TEXT"),
("workflow_revision_id", "TEXT"),
("workflow_run_id", "TEXT"),
("agent_summary_json", "TEXT DEFAULT '{}'"),
("usage_json", "TEXT DEFAULT '{}'"),
):
if column_name not in cols:
conn.execute(text(f"ALTER TABLE chat_messages ADD COLUMN {column_name} {definition}"))
missing_ids = conn.execute(
text("SELECT id FROM chat_messages WHERE message_id IS NULL OR message_id = ''")
).fetchall()
for row in missing_ids:
conn.execute(
text("UPDATE chat_messages SET message_id = :message_id WHERE id = :id"),
{"message_id": str(uuid.uuid4()), "id": row[0]},
)
conn.execute(text(
"CREATE UNIQUE INDEX IF NOT EXISTS ix_chat_messages_message_id "
"ON chat_messages (message_id)"
))
conn.execute(text(
"CREATE INDEX IF NOT EXISTS ix_chat_messages_workflow_run_id "
"ON chat_messages (workflow_run_id)"
))
except Exception as e: except Exception as e:
print("[db] ensure_sources_column error:", e) print("[db] ensure_sources_column error:", e)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,7 @@
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from datetime import datetime from datetime import datetime
import uuid
from .database import Base from .database import Base
class ChatSession(Base): class ChatSession(Base):
@@ -17,11 +18,19 @@ class ChatMessage(Base):
__tablename__ = 'chat_messages' __tablename__ = 'chat_messages'
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
message_id = Column(String(36), unique=True, index=True, nullable=False, default=lambda: str(uuid.uuid4()))
session_pk = Column(Integer, ForeignKey('chat_sessions.id'), nullable=False) session_pk = Column(Integer, ForeignKey('chat_sessions.id'), nullable=False)
role = Column(String(16), nullable=False) # 'user' | 'assistant' role = Column(String(16), nullable=False) # 'user' | 'assistant'
content = Column(Text, nullable=False) content = Column(Text, nullable=False)
# JSON-encoded list of citation URLs; null/empty => no chips # JSON-encoded list of citation URLs; null/empty => no chips
sources_json = Column(Text, nullable=True, default='[]') sources_json = Column(Text, nullable=True, default='[]')
# JSON-encoded list of inline image attachments for user messages.
attachments_json = Column(Text, nullable=True, default='[]')
workflow_id = Column(String(36), nullable=True)
workflow_revision_id = Column(String(36), nullable=True)
workflow_run_id = Column(String(36), nullable=True, index=True)
agent_summary_json = Column(Text, nullable=True, default='{}')
usage_json = Column(Text, nullable=True, default='{}')
created_at = Column(DateTime, default=datetime.utcnow, nullable=False) created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
session = relationship("ChatSession", back_populates="messages") session = relationship("ChatSession", back_populates="messages")

View File

@@ -9,8 +9,15 @@ from urllib.parse import urlparse
import httpx import httpx
from .app_settings import get_embed_model_preference, get_ollama_api_url, normalize_embed_model from .app_settings import (
from .whisper_admin import DEFAULT_WHISPER_MODEL, ensure_whisper_model_downloaded, inspect_whisper_model get_embed_model_preference,
get_ollama_api_url,
get_rerank_model_preference,
get_transcription_model_preference,
normalize_embed_model,
normalize_rerank_model,
)
from .whisper_admin import ensure_whisper_model_downloaded, inspect_whisper_model
LOCAL_OLLAMA_HOSTS = {"127.0.0.1", "localhost", "::1"} LOCAL_OLLAMA_HOSTS = {"127.0.0.1", "localhost", "::1"}
@@ -56,9 +63,11 @@ async def _list_model_names(ollama_url: str, *, timeout: float = 5.0) -> List[st
async def inspect_ollama_startup() -> Dict[str, Any]: async def inspect_ollama_startup() -> Dict[str, Any]:
ollama_url = get_ollama_api_url() ollama_url = get_ollama_api_url()
embed_model = get_embed_model_preference() embed_model = get_embed_model_preference()
rerank_model = get_rerank_model_preference()
transcription_model = get_transcription_model_preference()
ollama_bin = _ollama_binary() ollama_bin = _ollama_binary()
is_local = _is_local_ollama_url(ollama_url) is_local = _is_local_ollama_url(ollama_url)
whisper_status = inspect_whisper_model(DEFAULT_WHISPER_MODEL) whisper_status = inspect_whisper_model(transcription_model)
available_models: List[str] = [] available_models: List[str] = []
error = "" error = ""
running = False running = False
@@ -70,13 +79,17 @@ async def inspect_ollama_startup() -> Dict[str, Any]:
error = str(exc) error = str(exc)
available = bool(set(available_models) & _model_aliases(embed_model)) available = bool(set(available_models) & _model_aliases(embed_model))
rerank_available = bool(set(available_models) & _model_aliases(rerank_model))
return { return {
"ollama_url": ollama_url, "ollama_url": ollama_url,
"ollama_running": running, "ollama_running": running,
"ollama_binary_found": bool(ollama_bin), "ollama_binary_found": bool(ollama_bin),
"can_manage_locally": bool(ollama_bin) and is_local, "can_manage_locally": bool(ollama_bin) and is_local,
"selected_embed_model": embed_model, "selected_embed_model": embed_model,
"selected_rerank_model": rerank_model,
"selected_transcription_model": transcription_model,
"embedding_model_available": available, "embedding_model_available": available,
"reranking_model_available": rerank_available,
"available_models": available_models, "available_models": available_models,
"whisper_model": whisper_status["model"], "whisper_model": whisper_status["model"],
"whisper_model_available": bool(whisper_status["available"]), "whisper_model_available": bool(whisper_status["available"]),
@@ -167,13 +180,24 @@ async def prepare_startup_models() -> Dict[str, Any]:
"skipped": False, "skipped": False,
"reason": "", "reason": "",
} }
rerank_result: Dict[str, Any] = {
"model": status["selected_rerank_model"],
"available": bool(status["reranking_model_available"]),
"downloaded": False,
"skipped": False,
"reason": "",
}
if not status["ollama_running"]: if not status["ollama_running"]:
embedding_result["skipped"] = True embedding_result["skipped"] = True
embedding_result["reason"] = "Ollama is not running." embedding_result["reason"] = "Ollama is not running."
rerank_result["skipped"] = True
rerank_result["reason"] = "Ollama is not running."
elif not status["can_manage_locally"]: elif not status["can_manage_locally"]:
embedding_result["skipped"] = True embedding_result["skipped"] = True
embedding_result["reason"] = "Automatic model pulls are only available for local Ollama." embedding_result["reason"] = "Automatic model pulls are only available for local Ollama."
rerank_result["skipped"] = True
rerank_result["reason"] = "Automatic model pulls are only available for local Ollama."
elif not status["embedding_model_available"]: elif not status["embedding_model_available"]:
pulled = await pull_local_model(status["selected_embed_model"]) pulled = await pull_local_model(status["selected_embed_model"])
status = pulled["status"] status = pulled["status"]
@@ -185,8 +209,24 @@ async def prepare_startup_models() -> Dict[str, Any]:
"reason": "", "reason": "",
} }
rerank_model = normalize_rerank_model(status["selected_rerank_model"])
if rerank_model == normalize_embed_model(status["selected_embed_model"]):
rerank_result["available"] = bool(status["embedding_model_available"])
rerank_result["downloaded"] = bool(embedding_result.get("downloaded"))
elif not rerank_result["skipped"] and not status["reranking_model_available"]:
pulled = await pull_local_model(rerank_model)
status = pulled["status"]
rerank_result = {
"model": pulled["model"],
"available": bool(status["reranking_model_available"]),
"downloaded": bool(pulled.get("downloaded")),
"skipped": False,
"reason": "",
}
return { return {
"ollama": status, "ollama": status,
"whisper": whisper_result, "whisper": whisper_result,
"embedding_model": embedding_result, "embedding_model": embedding_result,
"reranking_model": rerank_result,
} }

View File

@@ -1,10 +1,179 @@
import asyncio
import httpx import httpx
import json import json
from typing import Dict, Any, List, AsyncGenerator import re
import time
from dataclasses import dataclass, field
from typing import Dict, Any, List, AsyncGenerator, Optional, Tuple
from .app_settings import get_ollama_api_url from .app_settings import get_ollama_api_url
_MODEL_DETAILS_CACHE: Dict[Tuple[str, str], Tuple[float, Dict[str, Any]]] = {}
_MODEL_DETAILS_TTL_S = 15.0
@dataclass
class OllamaToolCall:
name: str
arguments: Dict[str, Any]
raw: Dict[str, Any] = field(default_factory=dict)
@dataclass
class OllamaUsage:
prompt_eval_count: int = 0
eval_count: int = 0
total_duration: int = 0
load_duration: int = 0
prompt_eval_duration: int = 0
eval_duration: int = 0
@dataclass
class OllamaChatResult:
content: str = ""
thinking: str = ""
tool_calls: List[OllamaToolCall] = field(default_factory=list)
usage: OllamaUsage = field(default_factory=OllamaUsage)
done_reason: Optional[str] = None
raw: Dict[str, Any] = field(default_factory=dict)
@dataclass
class OllamaStreamChunk:
content: str = ""
thinking: str = ""
tool_calls: List[OllamaToolCall] = field(default_factory=list)
done: bool = False
usage: OllamaUsage = field(default_factory=OllamaUsage)
raw: Dict[str, Any] = field(default_factory=dict)
def _cache_key(model: str) -> Tuple[str, str]:
ollama_url = get_ollama_api_url()
return (ollama_url.rstrip('/'), str(model or '').strip())
def _get_cached_model_details(model: str) -> Dict[str, Any]:
cached = _MODEL_DETAILS_CACHE.get(_cache_key(model))
return cached[1] if cached else {}
def _string_tokens(value: Any) -> List[str]:
if isinstance(value, str):
trimmed = value.strip()
return [trimmed] if trimmed else []
if isinstance(value, dict):
out: List[str] = []
for key, item in value.items():
out.extend(_string_tokens(key))
out.extend(_string_tokens(item))
return out
if isinstance(value, (list, tuple, set)):
out: List[str] = []
for item in value:
out.extend(_string_tokens(item))
return out
return []
def _normalize_capabilities(model_data: Dict[str, Any]) -> List[str]:
out = []
for item in model_data.get("capabilities") or []:
text = str(item).strip().lower()
if text and text not in out:
out.append(text)
return out
def _combined_model_tokens(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> str:
return " ".join(
token.lower()
for token in _string_tokens(name) + _string_tokens(tag_item.get("details")) + _string_tokens(model_data)
)
def _is_embedding_model(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> bool:
capabilities = set(_normalize_capabilities(model_data))
if "embedding" in capabilities or "embeddings" in capabilities:
return True
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
return any(
marker in lowered_tokens
for marker in (
" embed ",
" embedding ",
"embed-",
"-embed",
"nomic-embed",
"mxbai-embed",
"snowflake-arctic-embed",
"bge-m3",
"bge ",
)
) or lowered_tokens.startswith("bge")
def _is_rerank_model(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> bool:
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
return (
_is_embedding_model(name, model_data, tag_item)
or "rerank" in lowered_tokens
or "cross-encoder" in lowered_tokens
)
def _supports_vision_fast(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> bool:
if supports_vision(model_data):
return True
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
return any(
marker in lowered_tokens
for marker in (
" vision ",
"-vision",
" vision-",
"vision:",
"llava",
"bakllava",
"moondream",
"minicpm-v",
"minicpmv",
"pixtral",
"qwen-vl",
"qwen2vl",
"qwen2.5vl",
"qwen2.5-omni",
"granite3.2-vision",
"llama3.2-vision",
"gemma3",
"gemma4",
"-vl",
" vl ",
)
)
def _build_model_catalog_entry(tag_item: Dict[str, Any], model_data: Dict[str, Any]) -> Dict[str, Any]:
name = str((tag_item or {}).get("name") or "").strip()
capabilities = _normalize_capabilities(model_data)
is_embedding = _is_embedding_model(name, model_data, tag_item)
is_rerank = _is_rerank_model(name, model_data, tag_item)
has_vision = _supports_vision_fast(name, model_data, tag_item)
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
is_non_chat = is_embedding or "rerank" in lowered_tokens or "cross-encoder" in lowered_tokens
return {
"name": name,
"capabilities": capabilities,
"supports_vision": has_vision,
"is_embedding": is_embedding,
"can_chat": not is_non_chat,
"can_rerank": is_rerank,
}
async def list_models() -> Dict[str, Any]: async def list_models() -> Dict[str, Any]:
ollama_url = get_ollama_api_url() ollama_url = get_ollama_api_url()
async with httpx.AsyncClient(timeout=30.0) as client: async with httpx.AsyncClient(timeout=30.0) as client:
@@ -15,44 +184,189 @@ async def list_models() -> Dict[str, Any]:
models = [m.get('name') for m in data.get('models', [])] models = [m.get('name') for m in data.get('models', [])]
return {"models": models} return {"models": models}
async def chat(model: str, messages: List[Dict[str, str]]) -> str:
async def list_model_catalog() -> Dict[str, Any]:
ollama_url = get_ollama_api_url() ollama_url = get_ollama_api_url()
payload = { async with httpx.AsyncClient(timeout=30.0) as client:
"model": model, r = await client.get(f"{ollama_url}/api/tags")
"messages": messages, r.raise_for_status()
"stream": False payload = r.json()
raw_models = payload.get("models", []) or []
models = [
_build_model_catalog_entry(
item or {},
_get_cached_model_details(str((item or {}).get("name") or "").strip()),
)
for item in raw_models
if str((item or {}).get("name") or "").strip()
]
return {
"models": models,
"chat_models": [model["name"] for model in models if model["can_chat"]],
"embedding_models": [model["name"] for model in models if model["is_embedding"]],
"vision_models": [model["name"] for model in models if model["supports_vision"]],
"reranking_models": [model["name"] for model in models if model["can_rerank"]],
} }
async def show_model(model: str, *, refresh: bool = False) -> Dict[str, Any]:
ollama_url = get_ollama_api_url()
cache_key = (ollama_url.rstrip('/'), str(model or '').strip())
cached = _MODEL_DETAILS_CACHE.get(cache_key)
now = time.monotonic()
if not refresh and cached and (now - cached[0]) < _MODEL_DETAILS_TTL_S:
return cached[1]
async with httpx.AsyncClient(timeout=30.0) as client:
r = await client.post(f"{ollama_url}/api/show", json={"model": model})
r.raise_for_status()
data = r.json()
_MODEL_DETAILS_CACHE[cache_key] = (now, data)
return data
def supports_vision(model_data: Dict[str, Any]) -> bool:
capabilities = model_data.get("capabilities") or []
if any(str(item).strip().lower() == "vision" for item in capabilities):
return True
model_info = model_data.get("model_info") or {}
if isinstance(model_info, dict):
for key in model_info.keys():
lowered = str(key).strip().lower()
if ".vision." in lowered or lowered.endswith(".vision"):
return True
if lowered.endswith("tokens_per_image") or re.search(r"\bmm\b", lowered):
return True
return False
def _parse_tool_calls(value: Any) -> List[OllamaToolCall]:
calls: List[OllamaToolCall] = []
for item in value or []:
if not isinstance(item, dict):
continue
function = item.get("function") if isinstance(item.get("function"), dict) else item
name = str(function.get("name") or "").strip()
arguments = function.get("arguments") or {}
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except Exception:
arguments = {}
if name and isinstance(arguments, dict):
calls.append(OllamaToolCall(name=name, arguments=arguments, raw=item))
return calls
def _usage_from_payload(data: Dict[str, Any]) -> OllamaUsage:
return OllamaUsage(
prompt_eval_count=int(data.get("prompt_eval_count") or 0),
eval_count=int(data.get("eval_count") or 0),
total_duration=int(data.get("total_duration") or 0),
load_duration=int(data.get("load_duration") or 0),
prompt_eval_duration=int(data.get("prompt_eval_duration") or 0),
eval_duration=int(data.get("eval_duration") or 0),
)
def _chat_payload(
model: str,
messages: List[Dict[str, Any]],
*,
stream: bool,
options: Optional[Dict[str, Any]] = None,
tools: Optional[List[Dict[str, Any]]] = None,
format: Optional[Any] = None,
think: Optional[bool] = None,
) -> Dict[str, Any]:
payload: Dict[str, Any] = {"model": model, "messages": messages, "stream": stream}
if options:
payload["options"] = options
if tools:
payload["tools"] = tools
if format is not None:
payload["format"] = format
if think is not None:
payload["think"] = bool(think)
return payload
async def chat_typed(
model: str,
messages: List[Dict[str, Any]],
*,
options: Dict[str, Any] | None = None,
tools: Optional[List[Dict[str, Any]]] = None,
format: Optional[Any] = None,
think: Optional[bool] = None,
cancellation_event: Optional[Any] = None,
) -> OllamaChatResult:
ollama_url = get_ollama_api_url()
if cancellation_event is not None and cancellation_event.is_set():
raise asyncio.CancelledError()
payload = _chat_payload(model, messages, stream=False, options=options, tools=tools, format=format, think=think)
async with httpx.AsyncClient(timeout=600.0) as client: async with httpx.AsyncClient(timeout=600.0) as client:
r = await client.post(f"{ollama_url}/api/chat", json=payload) r = await client.post(f"{ollama_url}/api/chat", json=payload)
r.raise_for_status() r.raise_for_status()
data = r.json() data = r.json()
# Ollama returns full conversation; pick last message content message = data.get("message") if isinstance(data.get("message"), dict) else {}
try: if not message and data.get("messages"):
return data["message"]["content"] message = data["messages"][-1] or {}
except Exception: return OllamaChatResult(
# Newer Ollama formats may return messages list content=str(message.get("content") or data.get("content") or ""),
msgs = data.get("messages") or [] thinking=str(message.get("thinking") or data.get("thinking") or ""),
if msgs: tool_calls=_parse_tool_calls(message.get("tool_calls") or data.get("tool_calls")),
return msgs[-1].get("content", "") usage=_usage_from_payload(data),
return data.get("content", "") done_reason=data.get("done_reason"),
raw=data,
)
async def chat_stream(model: str, messages: List[Dict[str, str]]) -> AsyncGenerator[str, None]:
async def chat_stream_typed(
model: str,
messages: List[Dict[str, Any]],
*,
options: Optional[Dict[str, Any]] = None,
tools: Optional[List[Dict[str, Any]]] = None,
format: Optional[Any] = None,
think: Optional[bool] = None,
cancellation_event: Optional[Any] = None,
) -> AsyncGenerator[OllamaStreamChunk, None]:
ollama_url = get_ollama_api_url() ollama_url = get_ollama_api_url()
payload = { payload = _chat_payload(model, messages, stream=True, options=options, tools=tools, format=format, think=think)
"model": model,
"messages": messages,
"stream": True
}
async with httpx.AsyncClient(timeout=600.0) as client: async with httpx.AsyncClient(timeout=600.0) as client:
async with client.stream("POST", f"{ollama_url}/api/chat", json=payload) as r: async with client.stream("POST", f"{ollama_url}/api/chat", json=payload) as response:
r.raise_for_status() response.raise_for_status()
async for line in r.aiter_lines(): async for line in response.aiter_lines():
if line: if cancellation_event is not None and cancellation_event.is_set():
try: raise asyncio.CancelledError()
chunk = json.loads(line) if not line:
if "content" in chunk: # Newer Ollama format continue
yield chunk["content"] try:
elif "message" in chunk and "content" in chunk["message"]: # Older format data = json.loads(line)
yield chunk["message"]["content"] except json.JSONDecodeError:
except json.JSONDecodeError: continue
pass # Ignore invalid JSON lines message = data.get("message") if isinstance(data.get("message"), dict) else {}
yield OllamaStreamChunk(
content=str(message.get("content") or data.get("content") or ""),
thinking=str(message.get("thinking") or data.get("thinking") or ""),
tool_calls=_parse_tool_calls(message.get("tool_calls") or data.get("tool_calls")),
done=bool(data.get("done")),
usage=_usage_from_payload(data),
raw=data,
)
async def chat(
model: str,
messages: List[Dict[str, Any]],
*,
options: Dict[str, Any] | None = None,
) -> str:
return (await chat_typed(model, messages, options=options)).content
async def chat_stream(model: str, messages: List[Dict[str, Any]]) -> AsyncGenerator[str, None]:
async for chunk in chat_stream_typed(model, messages):
if chunk.content:
yield chunk.content

112
backend/paths.py Normal file
View File

@@ -0,0 +1,112 @@
from __future__ import annotations
import os
import sys
from pathlib import Path
BACKEND_DIR = Path(__file__).resolve().parent
DEFAULT_DB_PATH = BACKEND_DIR / "app.db"
DEFAULT_LIB_ROOT = BACKEND_DIR / "libraries"
def _clean_env(name: str) -> str:
return os.getenv(name, "").strip()
def _path_from_env(name: str) -> Path | None:
value = _clean_env(name)
if not value:
return None
return Path(value).expanduser()
def _ensure_parent(path: Path) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
return path
def _ensure_dir(path: Path) -> Path:
path.mkdir(parents=True, exist_ok=True)
return path
def data_dir() -> Path | None:
"""
Optional app-managed data root for packaged deployments.
HEIMGEIST_DATA_DIR is internal sidecar plumbing. Normal users should not
need to configure it manually, and development intentionally leaves it
unset so data stays in backend/app.db and backend/libraries.
"""
path = _path_from_env("HEIMGEIST_DATA_DIR")
if path is None:
return None
return _ensure_dir(path)
def database_path() -> Path:
"""
Resolve the SQLite database path.
Precedence:
1. HEIMGEIST_DB_PATH, for explicit packaged sidecar plumbing.
2. HEIMGEIST_DATA_DIR/app.db, for packaged app-managed data.
3. backend/app.db, for unchanged local development behavior.
"""
explicit_path = _path_from_env("HEIMGEIST_DB_PATH")
if explicit_path is not None:
return _ensure_parent(explicit_path)
base_dir = data_dir()
if base_dir is not None:
return _ensure_parent(base_dir / "app.db")
return _ensure_parent(DEFAULT_DB_PATH)
def library_root() -> Path:
"""
Resolve the local RAG library root.
Precedence:
1. HEIMGEIST_LIB_ROOT, for explicit packaged sidecar plumbing.
2. HEIMGEIST_DATA_DIR/libraries, for packaged app-managed data.
3. backend/libraries, for unchanged local development behavior.
"""
explicit_path = _path_from_env("HEIMGEIST_LIB_ROOT")
if explicit_path is not None:
return _ensure_dir(explicit_path)
base_dir = data_dir()
if base_dir is not None:
return _ensure_dir(base_dir / "libraries")
return _ensure_dir(DEFAULT_LIB_ROOT)
def tool_root() -> Path:
explicit_path = _path_from_env("HEIMGEIST_TOOL_DIR")
if explicit_path is not None:
return _ensure_dir(explicit_path)
base_dir = data_dir()
if base_dir is not None:
return _ensure_dir(base_dir / "tools")
if sys.platform == "darwin":
return _ensure_dir(Path.home() / "Library" / "Application Support" / "Heimgeist" / "tools")
if os.name == "nt":
appdata = os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
root = Path(appdata) if appdata else Path.home() / "AppData" / "Local"
return _ensure_dir(root / "Heimgeist" / "tools")
xdg_data = Path(os.getenv("XDG_DATA_HOME", str(Path.home() / ".local" / "share")))
return _ensure_dir(xdg_data / "Heimgeist" / "tools")
def sqlite_database_url(path: Path | None = None) -> str:
target = path or database_path()
return f"sqlite:///{target.as_posix()}"

View File

@@ -68,7 +68,7 @@ import multiprocessing as mp_context
try: try:
import orjson as _orjson import orjson as _orjson
def json_dumps(obj) -> str: def json_dumps(obj) -> str:
return _orjson.dumps(obj, option=_orjson.OPT_NON_STR_KEYS | _orjson.OPT_SERIALIZABLE).decode("utf-8") return _orjson.dumps(obj, option=_orjson.OPT_NON_STR_KEYS).decode("utf-8")
def json_loads(s: str) -> Any: def json_loads(s: str) -> Any:
return _orjson.loads(s) return _orjson.loads(s)
except Exception: except Exception:
@@ -91,7 +91,7 @@ except Exception:
# Constants & helpers # Constants & helpers
# ------------------------- # -------------------------
PROMPT_VERSION = "v3.0" PROMPT_VERSION = "v4.1-standard-deep"
ENTITY_CANON = { ENTITY_CANON = {
"PERSON": "PERSON", "PERSON": "PERSON",
@@ -301,8 +301,7 @@ def ollama_generate_json(
return json_loads(m.group(0)) return json_loads(m.group(0))
except Exception: except Exception:
pass pass
# last resort minimal structure raise ValueError("Ollama returned incomplete or invalid JSON.")
return {"headline": "", "summary": raw, "keywords": [], "entities": [], "qa": []}
def ollama_generate_text( def ollama_generate_text(
host: str, host: str,
@@ -343,12 +342,17 @@ def build_system(summary_lang: str) -> str:
f"Output language for headline/summary/keywords/Q&A must be '{summary_lang}'." f"Output language for headline/summary/keywords/Q&A must be '{summary_lang}'."
) )
def build_user_main(text: str, summary_lang: str, doc_hint: str, want_qa: int) -> str: def build_user_main(text: str, summary_lang: str, doc_hint: str, want_qa: int, *, include_qa: bool) -> str:
want_qa = max(2, min(4, int(want_qa))) want_qa = max(2, min(4, int(want_qa))) if include_qa else 0
qa_style = "Also produce 2–4 useful QA pairs." if include_qa else "Set qa to an empty list."
qa_constraint = (
"- Q&A must be answerable ONLY from the TEXT; keep questions <= 16 words; answers concise (<= ~80 words).\n"
if include_qa else "- Return an empty qa list.\n"
)
# Fixed internal instruction for style/tone # Fixed internal instruction for style/tone
fixed_instruction = ( fixed_instruction = (
"Produce concise headlines (≤12 words) and 2–4 sentence summaries; " "Produce concise headlines (≤12 words) and 2–4 sentence summaries; "
"5–12 normalized keywords (kebab-case); named entities with types; 2–4 useful QA pairs. " f"5–12 normalized keywords (kebab-case) and named entities with types. {qa_style} "
"Keep strictly grounded in the source." "Keep strictly grounded in the source."
) )
return ( return (
@@ -369,11 +373,30 @@ def build_user_main(text: str, summary_lang: str, doc_hint: str, want_qa: int) -
f"Constraints:\n" f"Constraints:\n"
f"- Headline and summary MUST be in {summary_lang}.\n" f"- Headline and summary MUST be in {summary_lang}.\n"
"- Extract proper nouns and salient terms as entities; deduplicate by name.\n" "- Extract proper nouns and salient terms as entities; deduplicate by name.\n"
"- Q&A must be answerable ONLY from the TEXT; keep questions <= 16 words; answers concise (<= ~80 words).\n" f"{qa_constraint}"
"- Be terse and informative; no filler.\n\n" "- Be terse and informative; no filler.\n\n"
"TEXT:\n" + text "TEXT:\n" + text
) )
def unwrap_enrichment_response(value: Any) -> Dict[str, Any]:
if not isinstance(value, dict):
raise ValueError("Enrichment response is not a JSON object.")
nested = value.get("summary")
if not value.get("headline") and isinstance(nested, str) and nested.lstrip().startswith("{"):
try:
decoded = json_loads(nested)
except Exception as exc:
raise ValueError("Enrichment response contains truncated nested JSON.") from exc
if isinstance(decoded, dict):
value = decoded
if not isinstance(value.get("summary"), str) or not str(value.get("summary") or "").strip():
raise ValueError("Enrichment response is missing a summary.")
for field in ("keywords", "entities", "qa"):
if field in value and not isinstance(value[field], list):
raise ValueError(f"Enrichment response field '{field}' must be a list.")
return value
def build_user_qa_topup(text: str, summary_lang: str, need: int) -> str: def build_user_qa_topup(text: str, summary_lang: str, need: int) -> str:
need = max(1, min(3, int(need))) need = max(1, min(3, int(need)))
return ( return (
@@ -505,6 +528,7 @@ def enforce_schema_and_language(
target_lang: str, target_lang: str,
rec_text_sample: str, rec_text_sample: str,
rec_is_short: bool, rec_is_short: bool,
include_qa: bool,
perform_translate, perform_translate,
stats: Dict[str, int], stats: Dict[str, int],
) -> Dict[str, Any]: ) -> Dict[str, Any]:
@@ -547,30 +571,29 @@ def enforce_schema_and_language(
# QA # QA
qas = [] qas = []
for qa in out.get("qa", []) or []: if include_qa:
if not isinstance(qa, dict): continue for qa in out.get("qa", []) or []:
q = clamp_words(sanitize_text(str(qa.get("q", ""))), 16) if not isinstance(qa, dict): continue
a = sanitize_text(str(qa.get("a", ""))) q = clamp_words(sanitize_text(str(qa.get("q", ""))), 16)
if q and a and len(a) >= 30: a = sanitize_text(str(qa.get("a", "")))
qas.append({"q": q, "a": a}) if q and a and len(a) >= 30:
# ensure minimum count target qas.append({"q": q, "a": a})
target = QA_TARGET_SHORT if rec_is_short else QA_TARGET_DEFAULT target = QA_TARGET_SHORT if rec_is_short else QA_TARGET_DEFAULT
if len(qas) < target: if len(qas) < target:
need = target - len(qas) need = target - len(qas)
# ask for a top-up add = perform_translate("__QATOPUP__", rec_text_sample, need)
add = perform_translate("__QATOPUP__", rec_text_sample, need) # overloaded: returns dict {"qa":[...]} extra = []
extra = [] if isinstance(add, dict):
if isinstance(add, dict): for qa in add.get("qa", []) or []:
for qa in add.get("qa", []) or []: if not isinstance(qa, dict): continue
if not isinstance(qa, dict): continue q = clamp_words(sanitize_text(str(qa.get("q", ""))), 16)
q = clamp_words(sanitize_text(str(qa.get("q", ""))), 16) a = sanitize_text(str(qa.get("a", "")))
a = sanitize_text(str(qa.get("a", ""))) if q and a and len(a) >= 30:
if q and a and len(a) >= 30: extra.append({"q": q, "a": a})
extra.append({"q": q, "a": a}) if extra:
if extra: qas.extend(extra[:need])
qas.extend(extra[:need]) quality_flags.append("qa_topped_up")
quality_flags.append("qa_topped_up") stats["qa_topped_up"] += 1
stats["qa_topped_up"] += 1
# Language guard (per-field) # Language guard (per-field)
def _guard_lang(field_value: str, field_name: str) -> str: def _guard_lang(field_value: str, field_name: str) -> str:
@@ -628,6 +651,7 @@ class Args:
force: bool force: bool
cache_dir: str cache_dir: str
verbose: bool verbose: bool
deep_source_paths: frozenset[str]
def enrich_one( def enrich_one(
rec: Dict[str, Any], rec: Dict[str, Any],
@@ -645,8 +669,15 @@ def enrich_one(
rec_id = str(rec.get("id") or "") rec_id = str(rec.get("id") or "")
rec_type = str(rec.get("record_type") or "") rec_type = str(rec.get("record_type") or "")
doc_hint = build_doc_hint(rec) doc_hint = build_doc_hint(rec)
source_path = str(rec.get("source_path") or "")
try:
source_key = str(Path(source_path).expanduser().resolve())
except Exception:
source_key = source_path
include_qa = source_key in args.deep_source_paths
level = "deep" if include_qa else "standard"
is_short = len(base_text) < args.min_chars is_short = len(base_text) < args.min_chars and not include_qa
sampled = base_text if len(base_text) <= args.max_text else head_mid_tail_sample(base_text, args.max_text) sampled = base_text if len(base_text) <= args.max_text else head_mid_tail_sample(base_text, args.max_text)
target_lang = args.summary_lang target_lang = args.summary_lang
if target_lang == "auto": if target_lang == "auto":
@@ -665,6 +696,7 @@ def enrich_one(
"prompt_version": PROMPT_VERSION, "prompt_version": PROMPT_VERSION,
"cached": True, "cached": True,
"strategy": "short-fastpath", "strategy": "short-fastpath",
"level": level,
} }
enr = dict(rec) enr = dict(rec)
enr.update({ enr.update({
@@ -678,6 +710,7 @@ def enrich_one(
"prompt_version": PROMPT_VERSION, "prompt_version": PROMPT_VERSION,
"cached": True, "cached": True,
"strategy": "short-fastpath", "strategy": "short-fastpath",
"level": level,
"ok": True, "ok": True,
"error": None, "error": None,
} }
@@ -692,7 +725,7 @@ def enrich_one(
doc_hint += " The TEXT appears noisy/garbled (possibly OCR). Summarize what the document likely conveys and any clearly legible details; avoid copying garbled strings." doc_hint += " The TEXT appears noisy/garbled (possibly OCR). Summarize what the document likely conveys and any clearly legible details; avoid copying garbled strings."
# caching # caching
key = stable_hash(sampled, args.model, target_lang, rec_id, rec_type) key = stable_hash(sampled, args.model, target_lang, rec_id, f"{rec_type}:{level}")
if not args.force: if not args.force:
hit = cache_main.get(key) hit = cache_main.get(key)
if hit is not None: if hit is not None:
@@ -708,6 +741,7 @@ def enrich_one(
"prompt_version": hit.get("prompt_version"), "prompt_version": hit.get("prompt_version"),
"cached": True, "cached": True,
"strategy": hit.get("strategy"), "strategy": hit.get("strategy"),
"level": hit.get("level") or level,
"ok": True, "ok": True,
"error": None, "error": None,
} }
@@ -765,8 +799,13 @@ def enrich_one(
# main call # main call
system = build_system(target_lang) system = build_system(target_lang)
user = build_user_main(sampled, target_lang, doc_hint, qa_target) user = build_user_main(sampled, target_lang, doc_hint, qa_target, include_qa=include_qa)
options = {"temperature": 0.2, "repeat_penalty": 1.1, "top_p": 0.9, "num_predict": 320} options = {
"temperature": 0.2,
"repeat_penalty": 1.1,
"top_p": 0.9,
"num_predict": 1000 if include_qa else 700,
}
with sem: with sem:
tries, backoff, last_exc = 3, 1.5, None tries, backoff, last_exc = 3, 1.5, None
@@ -774,33 +813,31 @@ def enrich_one(
try: try:
out = ollama_generate_json(args.ollama, args.model, system, user, out = ollama_generate_json(args.ollama, args.model, system, user,
keep_alive=args.keep_alive, timeout=args.timeout, options=options) keep_alive=args.keep_alive, timeout=args.timeout, options=options)
out = unwrap_enrichment_response(out)
# sanitize + normalize structure # sanitize + normalize structure
if not isinstance(out, dict): for k in ("headline", "summary"):
out = {"headline": "", "summary": sanitize_text(str(out)), "keywords": [], "entities": [], "qa": []} if k in out and isinstance(out[k], str):
else: out[k] = sanitize_text(out[k])
for k in ("headline", "summary"):
if k in out and isinstance(out[k], str):
out[k] = sanitize_text(out[k])
# normalize arrays to expected types # normalize arrays to expected types
out["keywords"] = [sanitize_text(str(x)) for x in out.get("keywords", []) if str(x).strip()] out["keywords"] = [sanitize_text(str(x)) for x in out.get("keywords", []) if str(x).strip()]
ents = [] ents = []
for e in out.get("entities", []) or []: for e in out.get("entities", []) or []:
if isinstance(e, dict): if isinstance(e, dict):
name = sanitize_text(str(e.get("name", ""))) name = sanitize_text(str(e.get("name", "")))
typ = sanitize_text(str(e.get("type", "OTHER"))) typ = sanitize_text(str(e.get("type", "OTHER")))
if name: if name:
ents.append({"name": name, "type": typ}) ents.append({"name": name, "type": typ})
out["entities"] = ents out["entities"] = ents
qas = [] qas = []
for qa in out.get("qa", []) or []: for qa in out.get("qa", []) or []:
if isinstance(qa, dict): if isinstance(qa, dict):
q = sanitize_text(str(qa.get("q", ""))) q = sanitize_text(str(qa.get("q", "")))
a = sanitize_text(str(qa.get("a", ""))) a = sanitize_text(str(qa.get("a", "")))
if q and a: if q and a:
qas.append({"q": q, "a": a}) qas.append({"q": q, "a": a})
out["qa"] = qas out["qa"] = qas
# post-enforce schema + language # post-enforce schema + language
fixed = enforce_schema_and_language( fixed = enforce_schema_and_language(
@@ -808,6 +845,7 @@ def enrich_one(
target_lang=target_lang, target_lang=target_lang,
rec_text_sample=sampled, rec_text_sample=sampled,
rec_is_short=is_short, rec_is_short=is_short,
include_qa=include_qa,
perform_translate=perform_translate, perform_translate=perform_translate,
stats=stats, stats=stats,
) )
@@ -823,6 +861,7 @@ def enrich_one(
"prompt_version": PROMPT_VERSION, "prompt_version": PROMPT_VERSION,
"cached": False, "cached": False,
"strategy": "sampled" if len(base_text) > args.max_text else "full", "strategy": "sampled" if len(base_text) > args.max_text else "full",
"level": level,
} }
# save to cache # save to cache
@@ -840,6 +879,7 @@ def enrich_one(
"prompt_version": PROMPT_VERSION, "prompt_version": PROMPT_VERSION,
"cached": False, "cached": False,
"strategy": result["strategy"], "strategy": result["strategy"],
"level": level,
"ok": True, "ok": True,
"error": None, "error": None,
"quality_flags": result["quality_flags"], "quality_flags": result["quality_flags"],
@@ -866,6 +906,7 @@ def enrich_one(
"prompt_version": PROMPT_VERSION, "prompt_version": PROMPT_VERSION,
"cached": False, "cached": False,
"strategy": f"fallback:{type(last_exc).__name__ if last_exc else 'error'}", "strategy": f"fallback:{type(last_exc).__name__ if last_exc else 'error'}",
"level": level,
"quality_flags": ["fallback"], "quality_flags": ["fallback"],
} }
enriched = dict(rec) enriched = dict(rec)
@@ -880,6 +921,7 @@ def enrich_one(
"prompt_version": PROMPT_VERSION, "prompt_version": PROMPT_VERSION,
"cached": False, "cached": False,
"strategy": fallback["strategy"], "strategy": fallback["strategy"],
"level": level,
"ok": False, "ok": False,
"error": str(last_exc) if last_exc else "unknown", "error": str(last_exc) if last_exc else "unknown",
"quality_flags": ["fallback"], "quality_flags": ["fallback"],
@@ -943,6 +985,13 @@ def run_enrich(inp: Path, out: Path, shadow_out: Path, *,
summary_lang: str = "auto", summary_lang: str = "auto",
on_progress: Optional[Callable[[str, float, str], None]] = None, on_progress: Optional[Callable[[str, float, str], None]] = None,
cancellation_event: Optional[threading.Event] = None, **opts) -> dict: cancellation_event: Optional[threading.Event] = None, **opts) -> dict:
deep_source_paths = set()
for value in opts.get("deep_source_paths", []) or []:
try:
deep_source_paths.add(str(Path(str(value)).expanduser().resolve()))
except Exception:
deep_source_paths.add(str(value))
args = Args( args = Args(
inp=str(inp), inp=str(inp),
out=str(out), out=str(out),
@@ -958,6 +1007,7 @@ def run_enrich(inp: Path, out: Path, shadow_out: Path, *,
force=opts.get("force", False), force=opts.get("force", False),
cache_dir=opts.get("cache_dir", ".rag_cache"), cache_dir=opts.get("cache_dir", ".rag_cache"),
verbose=opts.get("verbose", False), verbose=opts.get("verbose", False),
deep_source_paths=frozenset(deep_source_paths),
) )
src = Path(args.inp).expanduser().resolve() src = Path(args.inp).expanduser().resolve()

View File

@@ -110,10 +110,16 @@ def chunk_text(txt: str, target_chars: int = 2500, overlap_chars: int = 200) ->
paras = [p.strip() for p in (txt or "").split("\n\n") if p.strip()] paras = [p.strip() for p in (txt or "").split("\n\n") if p.strip()]
if not paras: if not paras:
if txt.strip(): if txt.strip():
yield txt.strip() yield from _split_oversized_text(txt.strip(), target_chars, overlap_chars)
return return
buf, size = [], 0 buf, size = [], 0
for p in paras: for p in paras:
if len(p) > target_chars:
if buf:
yield "\n\n".join(buf)
buf, size = [], 0
yield from _split_oversized_text(p, target_chars, overlap_chars)
continue
if size + len(p) + 2 > target_chars and buf: if size + len(p) + 2 > target_chars and buf:
chunk = "\n\n".join(buf) chunk = "\n\n".join(buf)
yield chunk yield chunk
@@ -127,6 +133,26 @@ def chunk_text(txt: str, target_chars: int = 2500, overlap_chars: int = 200) ->
if buf: if buf:
yield "\n\n".join(buf) yield "\n\n".join(buf)
def _split_oversized_text(txt: str, target_chars: int, overlap_chars: int) -> Iterable[str]:
clean = (txt or "").strip()
target = max(400, int(target_chars))
overlap = min(max(0, int(overlap_chars)), target // 3)
start = 0
while start < len(clean):
limit = min(len(clean), start + target)
end = limit
if limit < len(clean):
search_from = start + max(1, target // 2)
whitespace = max(clean.rfind(" ", search_from, limit), clean.rfind("\n", search_from, limit))
if whitespace > start:
end = whitespace
chunk = clean[start:end].strip()
if chunk:
yield chunk
if end >= len(clean):
break
start = max(start + 1, end - overlap)
def clamp_int(value: int, low: int, high: int) -> int: def clamp_int(value: int, low: int, high: int) -> int:
return max(low, min(high, value)) return max(low, min(high, value))

View File

@@ -1,11 +1,28 @@
from pydantic import BaseModel, ConfigDict from pydantic import BaseModel, ConfigDict
from typing import List, Optional from typing import Any, Dict, List, Optional
from datetime import datetime from datetime import datetime
class ChatAttachment(BaseModel):
kind: Optional[str] = None
name: str
mime_type: Optional[str] = None
data_url: Optional[str] = None
source_path: Optional[str] = None
size: Optional[int] = None
record_type: Optional[str] = None
text: Optional[str] = None
class Message(BaseModel): class Message(BaseModel):
message_id: Optional[str] = None
role: str role: str
content: str content: str
sources: Optional[List[str]] = None sources: Optional[List[Any]] = None
attachments: Optional[List[ChatAttachment]] = None
workflow_id: Optional[str] = None
workflow_revision_id: Optional[str] = None
workflow_run_id: Optional[str] = None
agent_summary: Optional[Dict[str, Any]] = None
usage: Optional[Dict[str, Any]] = None
class ChatRequest(BaseModel): class ChatRequest(BaseModel):
session_id: str session_id: str
@@ -14,6 +31,9 @@ class ChatRequest(BaseModel):
enriched_message: Optional[str] = None enriched_message: Optional[str] = None
stream: Optional[bool] = False stream: Optional[bool] = False
sources: Optional[List[str]] = None sources: Optional[List[str]] = None
attachments: Optional[List[ChatAttachment]] = None
vision_model: Optional[str] = None
transcription_model: Optional[str] = None
class ChatResponse(BaseModel): class ChatResponse(BaseModel):
reply: str reply: str
@@ -21,6 +41,12 @@ class ChatResponse(BaseModel):
class HistoryResponse(BaseModel): class HistoryResponse(BaseModel):
messages: List[Message] messages: List[Message]
class SaveMessageToKnowledgeRequest(BaseModel):
message_id: str
title: Optional[str] = None
content: Optional[str] = None
class GenerateTitleRequest(BaseModel): class GenerateTitleRequest(BaseModel):
session_id: str session_id: str
message: str message: str
@@ -52,6 +78,8 @@ class RegenerateRequest(BaseModel):
enriched_message: Optional[str] = None enriched_message: Optional[str] = None
stream: bool = True stream: bool = True
sources: Optional[List[str]] = None sources: Optional[List[str]] = None
vision_model: Optional[str] = None
transcription_model: Optional[str] = None
# Request payload for the web search enrichment endpoint. # Request payload for the web search enrichment endpoint.
class WebSearchRequest(BaseModel): class WebSearchRequest(BaseModel):
@@ -71,3 +99,16 @@ class WebSearchResponse(BaseModel):
class OllamaPullRequest(BaseModel): class OllamaPullRequest(BaseModel):
model: Optional[str] = None model: Optional[str] = None
class AudioTranscriptionRequest(BaseModel):
mime_type: str
audio_base64: str
model: Optional[str] = None
language: Optional[str] = None
class AudioTranscriptionResponse(BaseModel):
text: str
language: Optional[str] = None
model: str

27
backend/sidecar_main.py Normal file
View File

@@ -0,0 +1,27 @@
from __future__ import annotations
import multiprocessing
import os
import uvicorn
def main() -> None:
multiprocessing.freeze_support()
os.environ.setdefault("HEIMGEIST_BACKEND_SIDECAR", "1")
host = os.getenv("HEIMGEIST_BACKEND_HOST", "127.0.0.1")
port = int(os.getenv("HEIMGEIST_BACKEND_PORT", "8000"))
log_level = os.getenv("HEIMGEIST_BACKEND_LOG_LEVEL", "info")
uvicorn.run(
"backend.main:app",
host=host,
port=port,
log_level=log_level,
reload=False,
workers=1,
)
if __name__ == "__main__":
main()

View File

View File

@@ -0,0 +1,71 @@
import asyncio
import unittest
from types import SimpleNamespace
from unittest.mock import patch
from backend.agent.tools.chat import _drop_superseded_trailing_user_rows, chat_handler
class ChatToolTests(unittest.TestCase):
def test_drops_unanswered_trailing_user_messages_except_latest(self):
rows = [
SimpleNamespace(role="user", content="first question"),
SimpleNamespace(role="assistant", content="first answer"),
SimpleNamespace(role="user", content="interrupted follow-up"),
SimpleNamespace(role="user", content="latest prompt"),
]
result = _drop_superseded_trailing_user_rows(rows)
self.assertEqual([row.content for row in result], ["first question", "first answer", "latest prompt"])
def test_keeps_normal_alternating_history(self):
rows = [
SimpleNamespace(role="user", content="first question"),
SimpleNamespace(role="assistant", content="first answer"),
SimpleNamespace(role="user", content="latest prompt"),
]
self.assertIs(_drop_superseded_trailing_user_rows(rows), rows)
class ChatToolAsyncTests(unittest.IsolatedAsyncioTestCase):
async def test_chat_handler_returns_context_fallback_when_model_fails(self):
async def emit(_event_type, _payload):
return None
async def failing_stream(*_args, **_kwargs):
raise RuntimeError("model returned 502")
if False:
yield None
context = SimpleNamespace(
session_id=None,
db_factory=lambda: None,
emit=emit,
cancellation_event=asyncio.Event(),
show_thinking=False,
)
arguments = {
"model": "broken-model",
"messages": [{"role": "user", "content": "weather?"}],
"context_blocks": [{
"context_block": "<websearch_context>Weather context</websearch_context>",
"sources": [{
"type": "web",
"title": "Schwäbisch Gmünd Weather",
"snippet": "Sunny intervals and light wind.",
"url": "https://weather.example/schwaebisch-gmuend",
}],
}],
"generation_options": {},
"reasoning": False,
}
with patch("backend.agent.tools.chat.chat_stream_typed", failing_stream):
result = await chat_handler(arguments, context)
self.assertIn("selected chat model failed", result["content"])
self.assertIn("Schwäbisch Gmünd Weather", result["content"])
self.assertIn("https://weather.example/schwaebisch-gmuend", result["content"])
self.assertEqual(result["sources"][0]["url"], "https://weather.example/schwaebisch-gmuend")

View File

@@ -0,0 +1,71 @@
import asyncio
import unittest
from backend.agent.registry import (
NativeToolProvider,
SchemaValidationError,
ToolDefinition,
ToolExecutionContext,
)
INPUT = {
"type": "object",
"properties": {"value": {"type": "string"}},
"required": ["value"],
"additionalProperties": False,
}
OUTPUT = {
"type": "object",
"properties": {"result": {"type": "string"}},
"required": ["result"],
"additionalProperties": False,
}
def context(registry):
return ToolExecutionContext(
run_id="run", workflow_id="workflow", node_id="node", session_id=None,
selection_mode="explicit", explicit_user_action=True,
emit=lambda *_args: asyncio.sleep(0), cancellation_event=asyncio.Event(),
db_factory=lambda: None, registry=registry,
)
class RegistryTests(unittest.IsolatedAsyncioTestCase):
async def test_duplicate_names_are_rejected(self):
async def handler(arguments, _context): return {"result": arguments["value"]}
registry = NativeToolProvider()
definition = ToolDefinition("test.echo", "echo", INPUT, OUTPUT, handler)
registry.register(definition)
with self.assertRaises(ValueError):
registry.register(definition)
async def test_arguments_and_outputs_are_validated(self):
async def handler(arguments, _context): return {"result": arguments["value"]}
registry = NativeToolProvider()
registry.register(ToolDefinition("test.echo", "echo", INPUT, OUTPUT, handler))
self.assertEqual((await registry.call_tool("test.echo", {"value": "ok"}, context(registry)))["result"], "ok")
with self.assertRaises(SchemaValidationError):
await registry.call_tool("test.echo", {"value": 1}, context(registry))
async def invalid_output(_arguments, _context): return {"result": 1}
invalid = NativeToolProvider()
invalid.register(ToolDefinition("test.invalid", "invalid", INPUT, OUTPUT, invalid_output))
with self.assertRaises(SchemaValidationError):
await invalid.call_tool("test.invalid", {"value": "x"}, context(invalid))
async def test_timeout_and_result_size_are_enforced(self):
async def slow(_arguments, _context):
await asyncio.sleep(0.05)
return {"result": "ok"}
registry = NativeToolProvider()
registry.register(ToolDefinition("test.slow", "slow", INPUT, OUTPUT, slow, timeout_seconds=0.01))
with self.assertRaises(TimeoutError):
await registry.call_tool("test.slow", {"value": "x"}, context(registry))
async def large(_arguments, _context): return {"result": "x" * 100}
limited = NativeToolProvider()
limited.register(ToolDefinition("test.large", "large", INPUT, OUTPUT, large, result_size_limit=20))
with self.assertRaises(ValueError):
await limited.call_tool("test.large", {"value": "x"}, context(limited))

View File

@@ -0,0 +1,262 @@
import asyncio
import json
import unittest
from unittest.mock import AsyncMock, patch
from backend.agent.registry import NativeToolProvider, ToolExecutionContext
from backend.agent.tools.web import FETCH_TEXT_LIMIT, register_web_tools
from backend.ollama_client import OllamaChatResult
from backend.websearch import build_enriched_prompt, rerank
def context(registry):
return ToolExecutionContext(
run_id="run",
workflow_id="workflow",
node_id="fetch",
session_id=None,
selection_mode="explicit",
explicit_user_action=True,
emit=lambda *_args: asyncio.sleep(0),
cancellation_event=asyncio.Event(),
db_factory=lambda: None,
registry=registry,
)
class WebToolTests(unittest.IsolatedAsyncioTestCase):
async def test_generate_queries_returns_llm_queries_without_topic_parser(self):
registry = NativeToolProvider()
register_web_tools(registry)
result_payload = {"queries": [" latest ", "top stories", "latest Iran news headlines", "latest"]}
with patch(
"backend.agent.tools.web.chat_typed",
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps(result_payload))),
):
result = await registry.call_tool(
"heimgeist.web_generate_queries",
{"prompt": "what's the news in iran today", "model": "model", "messages": []},
context(registry),
)
queries = result["queries"]
self.assertEqual(queries, ["latest", "top stories", "latest Iran news headlines"])
async def test_search_filters_dictionary_noise_for_current_lookup(self):
registry = NativeToolProvider()
register_web_tools(registry)
async def fake_search(_client, _query, **_kwargs):
return [
{"url": "https://dict.leo.org/englisch-deutsch/latest", "title": "latest - Deutsch-Uebersetzung", "engine": "bing"},
{"url": "https://www.reuters.com/world/middle-east/iran-example", "title": "Iran latest news", "engine": "bing"},
{"url": "https://consent.google.com/ml?continue=https://news.google.com/topics/iran", "title": "Before you continue", "engine": "bing"},
]
with patch("backend.agent.tools.web.searx_search", new=AsyncMock(side_effect=fake_search)):
result = await registry.call_tool(
"heimgeist.web_search",
{
"query": None,
"queries": ["latest Iran news headlines"],
"engines": [],
"maximum_results": 8,
"searx_url": "http://127.0.0.1:8888",
},
context(registry),
)
urls = [item["url"] for item in result["results"]]
self.assertEqual(urls, ["https://www.reuters.com/world/middle-east/iran-example"])
async def test_search_does_not_require_parsed_topic_terms(self):
registry = NativeToolProvider()
register_web_tools(registry)
async def fake_search(_client, _query, **_kwargs):
return [
{"url": "https://www.aljazeera.com/where/iran/", "title": "Iran news", "engine": "bing"},
{"url": "https://www.bbc.com/news/world-middle-east", "title": "Middle East latest", "engine": "bing"},
]
with patch("backend.agent.tools.web.searx_search", new=AsyncMock(side_effect=fake_search)):
result = await registry.call_tool(
"heimgeist.web_search",
{
"query": None,
"queries": ["what happened in iran today"],
"engines": [],
"maximum_results": 8,
"searx_url": "http://127.0.0.1:8888",
},
context(registry),
)
urls = [item["url"] for item in result["results"]]
self.assertEqual(urls, ["https://www.aljazeera.com/where/iran/", "https://www.bbc.com/news/world-middle-east"])
async def test_fetch_accepts_search_result_batches_and_caps_page_text(self):
registry = NativeToolProvider()
register_web_tools(registry)
urls = [{"url": f"https://example.test/{index}"} for index in range(16)]
async def fake_fetch(url):
return {
"requested_url": url,
"url": url,
"title": "Example",
"text": "x" * (FETCH_TEXT_LIMIT + 500),
}
with patch("backend.agent.tools.web.fetch_website_snapshot", new=AsyncMock(side_effect=fake_fetch)):
result = await registry.call_tool(
"heimgeist.web_fetch",
{"url": None, "urls": urls, "maximum_pages": 6},
context(registry),
)
self.assertEqual(len(result["pages"]), 6)
self.assertTrue(all(len(page["cleaned_text"]) == FETCH_TEXT_LIMIT for page in result["pages"]))
async def test_fetch_filters_consent_pages_after_redirects(self):
registry = NativeToolProvider()
register_web_tools(registry)
async def fake_fetch(url):
return {
"requested_url": url,
"url": "https://consent.google.com/ml?continue=https://news.google.com/topics/iran",
"title": "Before you continue",
"text": "Google privacy controls",
}
with patch("backend.agent.tools.web.fetch_website_snapshot", new=AsyncMock(side_effect=fake_fetch)):
result = await registry.call_tool(
"heimgeist.web_fetch",
{"url": None, "urls": [{"url": "https://example.test/iran"}], "maximum_pages": 1},
context(registry),
)
self.assertEqual(result["pages"][0]["error"], "filtered_noise_page")
self.assertEqual(result["pages"][0]["cleaned_text"], "")
async def test_rerank_filters_pages_without_prompt_topic(self):
registry = NativeToolProvider()
register_web_tools(registry)
pages = [
{
"requested_url": "https://de.langenscheidt.com/englisch-deutsch/latest",
"canonical_url": "https://de.langenscheidt.com/englisch-deutsch/latest",
"title": "latest - Deutsch-Uebersetzung",
"cleaned_text": "latest means occurring most recently",
"error": None,
},
{
"requested_url": "https://www.reuters.com/world/middle-east/iran-example",
"canonical_url": "https://www.reuters.com/world/middle-east/iran-example",
"title": "Iran latest news",
"cleaned_text": "Iran officials and regional sources reported new developments today.",
"error": None,
},
]
ranked = [
("https://de.langenscheidt.com/englisch-deutsch/latest", "latest means occurring most recently", 99),
("https://www.reuters.com/world/middle-east/iran-example", "Iran officials reported new developments today.", 60),
]
with patch("backend.agent.tools.web.rerank", new=AsyncMock(return_value=ranked)):
result = await registry.call_tool(
"heimgeist.web_rerank",
{
"prompt": "what's the news in iran today",
"pages": pages,
"model": "model",
"rerank_model": None,
"context_excerpt": "",
"maximum_results": 6,
"minimum_score": 55,
},
context(registry),
)
self.assertEqual(len(result["results"]), 1)
self.assertEqual(result["results"][0]["url"], "https://www.reuters.com/world/middle-east/iran-example")
async def test_rerank_falls_back_when_embedding_model_is_unavailable(self):
class FailingAsyncClient:
def __init__(self, *_args, **_kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *_args):
return None
async def post(self, *_args, **_kwargs):
raise RuntimeError("model not found")
docs = [
(
"https://example.test/weather",
"A general weather page with forecasts and temperatures.",
),
(
"https://www.reuters.com/world/middle-east/iran-example",
"Iran officials reported new sanctions and regional developments today.",
),
]
with patch("backend.websearch.httpx.AsyncClient", FailingAsyncClient):
ranked = await rerank(
"latest Iran sanctions news",
docs,
model="chat-model",
context_excerpt="",
embed_model="missing-embed:latest",
)
enriched, sources = build_enriched_prompt("latest Iran sanctions news", ranked, top_k=3)
self.assertEqual(ranked[0][0], "https://www.reuters.com/world/middle-east/iran-example")
self.assertIn("https://www.reuters.com/world/middle-east/iran-example", sources)
self.assertIn("<websearch_context>", enriched)
async def test_rerank_tool_uses_fallback_when_rerank_errors(self):
registry = NativeToolProvider()
register_web_tools(registry)
pages = [
{
"requested_url": "https://example.test/weather",
"canonical_url": "https://example.test/weather",
"title": "Weather",
"cleaned_text": "A general weather page with forecasts and temperatures.",
"error": None,
},
{
"requested_url": "https://www.reuters.com/world/middle-east/iran-example",
"canonical_url": "https://www.reuters.com/world/middle-east/iran-example",
"title": "Iran latest news",
"cleaned_text": "Iran officials reported new sanctions and regional developments today.",
"error": None,
},
]
with patch("backend.agent.tools.web.rerank", new=AsyncMock(side_effect=RuntimeError("missing model"))):
result = await registry.call_tool(
"heimgeist.web_rerank",
{
"prompt": "latest Iran sanctions news",
"pages": pages,
"model": "model",
"rerank_model": None,
"context_excerpt": "",
"maximum_results": 6,
"minimum_score": 55,
},
context(registry),
)
self.assertGreaterEqual(len(result["results"]), 1)
self.assertEqual(result["results"][0]["url"], "https://www.reuters.com/world/middle-east/iran-example")
self.assertIn("<websearch_context>", result["context_block"])

View File

@@ -0,0 +1,203 @@
from pathlib import Path
import asyncio
from datetime import datetime, timedelta
import json
import tempfile
import unittest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.chat_memory import (
build_chat_memory_context,
ensure_chat_memory_schema,
sync_all_chat_memory,
sync_chat_memory_for_session,
)
from backend.agent.tools.memory import chat_memory_search_handler
from backend.database import Base
from backend.models import ChatMessage, ChatSession
class ChatMemoryTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.engine = create_engine(
f"sqlite:///{Path(self.temp.name) / 'memory.db'}",
connect_args={"check_same_thread": False},
)
Base.metadata.create_all(self.engine)
ensure_chat_memory_schema(self.engine)
self.Session = sessionmaker(bind=self.engine)
def tearDown(self):
self.engine.dispose()
self.temp.cleanup()
def _turn(self, db, session_id, title, user_content, assistant_content, created_at=None):
created_at = created_at or datetime.utcnow()
session = ChatSession(session_id=session_id, name=title, created_at=created_at)
db.add(session)
db.flush()
db.add(ChatMessage(session_pk=session.id, role="user", content=user_content, created_at=created_at))
db.flush()
db.add(ChatMessage(session_pk=session.id, role="assistant", content=assistant_content, created_at=created_at + timedelta(seconds=1)))
db.flush()
return session
def _turn_with_sources(self, db, session_id, title, user_content, assistant_content, sources):
session = ChatSession(session_id=session_id, name=title)
db.add(session)
db.flush()
db.add(ChatMessage(session_pk=session.id, role="user", content=user_content))
db.flush()
db.add(ChatMessage(
session_pk=session.id,
role="assistant",
content=assistant_content,
sources_json=json.dumps(sources),
))
db.flush()
return session
def test_retrieves_completed_past_turns(self):
db = self.Session()
try:
self._turn(
db,
"past",
"Tauri Packaging",
"What did we decide about mac packaging?",
"Use the PyInstaller backend sidecar and keep app data outside the bundle.",
)
db.commit()
sync_all_chat_memory(db)
context = build_chat_memory_context(db, "remind me about the backend sidecar packaging plan")
finally:
db.close()
self.assertIn("chat_memory_context", context["context_block"])
self.assertIn("PyInstaller backend sidecar", context["context_block"])
self.assertEqual(context["sources"][0]["source_session_id"], "past")
def test_excludes_active_session(self):
db = self.Session()
try:
self._turn(db, "current", "Current", "secret kiwi topic", "Only the current chat mentions kiwi.")
db.commit()
sync_all_chat_memory(db)
excluded = build_chat_memory_context(db, "kiwi topic", exclude_session_id="current")
included = build_chat_memory_context(db, "kiwi topic")
finally:
db.close()
self.assertEqual(excluded["context_block"], "")
self.assertIn("kiwi", included["context_block"])
def test_resync_removes_stale_turn_content(self):
db = self.Session()
try:
session = self._turn(db, "past", "Old Decision", "deployment detail", "Keep using the banana corridor plan.")
db.commit()
sync_all_chat_memory(db)
assistant = db.query(ChatMessage).filter(ChatMessage.role == "assistant").one()
assistant.content = "This turn now discusses an unrelated renderer detail."
db.commit()
sync_chat_memory_for_session(db, session.session_id)
context = build_chat_memory_context(db, "banana corridor plan")
finally:
db.close()
self.assertEqual(context["context_block"], "")
def test_recent_mode_returns_most_recent_previous_session(self):
db = self.Session()
try:
base = datetime(2026, 1, 1, 12, 0, 0)
self._turn(db, "older", "Weather", "what is the weather?", "It is rainy.", created_at=base)
self._turn(db, "previous", "Crowley", "tell me about Crowley", "The previous chat discussed Crowley.", created_at=base + timedelta(minutes=1))
current = ChatSession(session_id="current", name="Letztes Gespräch", created_at=base + timedelta(minutes=2))
db.add(current)
db.commit()
sync_all_chat_memory(db)
context = build_chat_memory_context(
db,
"worum ging es im letzten gespräch?",
exclude_session_id="current",
mode="recent",
)
finally:
db.close()
self.assertIn("Crowley", context["context_block"])
self.assertNotIn("rainy", context["context_block"])
def test_search_mode_uses_supplied_query_terms(self):
db = self.Session()
try:
self._turn(db, "song", "Identify this song", "what is this song?", "We discussed a track by an electronic artist.")
self._turn(db, "lied", "Lied: Hintergründe suchen", "suche hintergründe zu diesem lied", "Das Lied wurde im Kontext einer Band besprochen.")
db.commit()
sync_all_chat_memory(db)
context = build_chat_memory_context(db, "song lied")
finally:
db.close()
self.assertIn("song", context["context_block"].casefold())
self.assertIn("lied", context["context_block"].casefold())
def test_chat_memory_tool_returns_context_block_and_sources(self):
db = self.Session()
try:
self._turn(
db,
"past",
"Backend Sidecar",
"What was the sidecar plan?",
"Use PyInstaller for the backend sidecar and keep runtime data outside the app bundle.",
)
db.commit()
sync_all_chat_memory(db)
finally:
db.close()
context = type("Context", (), {
"session_id": "current",
"db_factory": self.Session,
})()
result = asyncio.run(chat_memory_search_handler({
"prompt": "backend sidecar runtime data",
"top_k": 3,
"context_character_budget": 4000,
"exclude_current_session": True,
}, context))
self.assertIn("PyInstaller", result["context_block"])
self.assertEqual(result["sources"][0]["type"], "chat_memory")
self.assertEqual(result["hits"][0]["session_id"], "past")
def test_memory_only_answers_are_not_reindexed(self):
db = self.Session()
try:
self._turn_with_sources(
db,
"poison",
"Backfire Basics",
"erzähl mir über backfire basics",
"Backfire Basics is a hallucinated project description.",
[{"type": "chat_memory", "source_session_id": "older", "source_message_id": "m1"}],
)
db.commit()
sync_all_chat_memory(db)
context = build_chat_memory_context(db, "backfire basics")
finally:
db.close()
self.assertEqual(context["context_block"], "")

View File

@@ -0,0 +1,162 @@
from pathlib import Path
from types import SimpleNamespace
from datetime import datetime
import json
import tempfile
import unittest
from unittest.mock import AsyncMock, patch
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.agent import api
from backend.agent.models import WorkflowDefinition, WorkflowRun
from backend.agent.schemas import WorkflowRunRequest
from backend.agent.workflows.builtins import seed_builtin_workflows
from backend.database import Base
from backend.models import ChatMessage, ChatSession
class WorkflowApiTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.temp = tempfile.TemporaryDirectory()
self.engine = create_engine(
f"sqlite:///{Path(self.temp.name) / 'api.db'}",
connect_args={"check_same_thread": False},
)
Base.metadata.create_all(self.engine)
self.Session = sessionmaker(bind=self.engine)
db = self.Session()
seed_builtin_workflows(db)
direct = db.query(WorkflowDefinition).filter_by(slug="input-output").one()
chat = ChatSession(session_id="regenerate-chat")
db.add(chat)
db.flush()
user = ChatMessage(session_pk=chat.id, role="user", content="original")
db.add(user)
db.flush()
assistant = ChatMessage(
session_pk=chat.id,
role="assistant",
content="old answer",
workflow_id=direct.id,
workflow_revision_id=direct.current_revision_id,
)
db.add(assistant)
db.flush()
db.commit()
self.user_message_id = user.message_id
self.assistant_message_id = assistant.message_id
self.direct_workflow_id = direct.id
self.direct_revision_id = direct.current_revision_id
db.close()
async def asyncTearDown(self):
self.engine.dispose()
self.temp.cleanup()
async def test_regeneration_reuses_user_row_and_prunes_old_answer(self):
started = []
fake_runtime = SimpleNamespace(start=started.append)
request = WorkflowRunRequest(
session_id="regenerate-chat",
message="edited",
model="test-model",
selection_mode="direct",
workflow_revision_id=self.direct_revision_id,
regenerate_index=0,
)
with patch.object(api, "SessionLocal", self.Session), patch.object(api, "runtime", fake_runtime):
response = await api.create_workflow_run(request)
self.assertEqual(started, [response["run_id"]])
db = self.Session()
rows = db.query(ChatMessage).order_by(ChatMessage.id.asc()).all()
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0].message_id, self.user_message_id)
self.assertEqual(rows[0].content, "edited")
run = db.query(WorkflowRun).filter_by(id=response["run_id"]).one()
self.assertEqual(run.user_message_id, self.user_message_id)
db.close()
async def test_run_resolves_previous_assistant_and_message_url_targets(self):
fake_runtime = SimpleNamespace(start=lambda _run_id: None)
request = WorkflowRunRequest(
session_id="regenerate-chat",
message="Save https://example.com/source for later.",
model="test-model",
selection_mode="explicit",
workflow_id=self.direct_workflow_id,
)
with patch.object(api, "SessionLocal", self.Session), patch.object(api, "runtime", fake_runtime):
response = await api.create_workflow_run(request)
db = self.Session()
run = db.query(WorkflowRun).filter_by(id=response["run_id"]).one()
run_values = json.loads(run.inputs_json)["run"]
self.assertEqual(run_values["target_message_id"], self.assistant_message_id)
self.assertEqual(run_values["target_url"], "https://example.com/source")
db.close()
async def test_automatic_run_persists_router_web_search_inputs(self):
db = self.Session()
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
web_id = web.id
db.close()
started = []
fake_runtime = SimpleNamespace(start=started.append)
router_result = {
"workflow_id": web_id,
"workflow_slug": "web-answer",
"confidence": 0.95,
"reason": "current information",
"inputs": {"web_search_query": "Iran news today", "web_search_queries": ["Iran news today", "Iran latest news"]},
"fallback": False,
}
request = WorkflowRunRequest(
session_id=None,
message="what happened in iran today",
model="test-model",
selection_mode="automatic",
)
with (
patch.object(api, "SessionLocal", self.Session),
patch.object(api, "runtime", fake_runtime),
patch.object(api, "select_workflow", new=AsyncMock(return_value=router_result)),
):
response = await api.create_workflow_run(request)
self.assertEqual(started, [response["run_id"]])
db = self.Session()
run = db.query(WorkflowRun).filter_by(id=response["run_id"]).one()
run_values = json.loads(run.inputs_json)["run"]
self.assertEqual(run_values["web_search_query"], "Iran news today")
self.assertEqual(run_values["web_search_queries"], ["Iran news today", "Iran latest news"])
db.close()
async def test_interrupted_run_event_stream_emits_terminal_event(self):
db = self.Session()
workflow = db.query(WorkflowDefinition).filter_by(slug="research").one()
run = WorkflowRun(
workflow_id=workflow.id,
workflow_revision_id=workflow.current_revision_id,
status="interrupted",
selection_mode="automatic",
inputs_json=json.dumps({"input": {"prompt": "x"}, "run": {}}),
error_json=json.dumps({"message": "Backend restarted before the workflow completed."}),
finished_at=datetime.utcnow(),
)
db.add(run)
db.commit()
run_id = run.id
db.close()
with patch.object(api, "SessionLocal", self.Session):
response = api.get_workflow_events(run_id, after_sequence=0, follow=True)
body = b""
async for chunk in response.body_iterator:
body += chunk.encode("utf-8") if isinstance(chunk, str) else chunk
events = [json.loads(line) for line in body.decode("utf-8").splitlines() if line.strip()]
interrupted = next(event for event in events if event["type"] == "run_interrupted")
self.assertEqual(interrupted["payload"]["message"], "Backend restarted before the workflow completed.")

View File

@@ -0,0 +1,253 @@
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import AsyncMock, patch
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.agent.models import WorkflowDefinition
from backend.agent.registry import NativeToolProvider
from backend.agent.router import _format_message_for_router, _router_prompt, select_workflow
from backend.agent.tools import register_native_tools
from backend.agent.validation import validate_workflow_graph
from backend.agent.workflows.builtins import BUILTIN_WORKFLOWS, seed_builtin_workflows
from backend.database import Base
from backend.ollama_client import OllamaChatResult
class RouterAndBuiltinTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.temp = tempfile.TemporaryDirectory()
engine = create_engine(f"sqlite:///{Path(self.temp.name) / 'router.db'}")
Base.metadata.create_all(engine)
self.Session = sessionmaker(bind=engine)
self.engine = engine
db = self.Session(); seed_builtin_workflows(db); db.close()
async def asyncTearDown(self):
self.engine.dispose(); self.temp.cleanup()
async def test_valid_selection_malformed_disabled_and_low_confidence_fallback(self):
db = self.Session()
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({"workflow_id": web.id, "confidence": 0.9, "reason": "current", "inputs": {}})))):
result = await select_workflow(db, message="tell me something useful", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model")
self.assertEqual(result["workflow_slug"], "web-answer")
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content="not json"))):
self.assertEqual((await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model"))["workflow_slug"], "input-output")
web.enabled = False; db.commit()
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({"workflow_id": web.id, "confidence": 0.9, "reason": "x", "inputs": {}})))):
self.assertEqual((await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model"))["workflow_slug"], "input-output")
web.enabled = True; db.commit()
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({"workflow_id": web.id, "confidence": 0.2, "reason": "x", "inputs": {}})))):
self.assertEqual((await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model"))["workflow_slug"], "input-output")
db.close()
async def test_fast_paths_auto_select_or_force_web(self):
db = self.Session()
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
combined = db.query(WorkflowDefinition).filter_by(slug="knowledge-web-answer").one()
with patch(
"backend.agent.router.chat_typed",
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
"workflow_id": web.id,
"confidence": 0.95,
"reason": "forced web",
"inputs": {"web_search_query": "Iran news today", "web_search_queries": ["Iran news today", "Iran latest news"]},
}))),
) as mocked:
result = await select_workflow(
db, message="hello", recent_messages=[], attachments=[],
library_slug=None, router_model=None, chat_model="model", web_search_enabled=True,
)
self.assertEqual(result["workflow_slug"], "web-answer")
self.assertEqual(result["inputs"]["web_search_query"], "Iran news today")
mocked.assert_awaited()
direct = db.query(WorkflowDefinition).filter_by(slug="input-output").one()
with patch(
"backend.agent.router.chat_typed",
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
"workflow_id": direct.id,
"confidence": 0.95,
"reason": "bad router choice",
"inputs": {},
}))),
):
result = await select_workflow(
db, message="what happened in Iran today", recent_messages=[], attachments=[],
library_slug=None, router_model=None, chat_model="model", web_search_enabled=True,
)
self.assertEqual(result["workflow_slug"], "web-answer")
self.assertEqual(result["inputs"]["web_search_query"], "what happened in Iran today")
with patch(
"backend.agent.router.chat_typed",
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
"workflow_id": web.id,
"confidence": 0.95,
"reason": "current",
"inputs": {"web_search_queries": ["latest Iran news"]},
}))),
):
result = await select_workflow(
db, message="latest news today", recent_messages=[], attachments=[],
library_slug=None, router_model=None, chat_model="model", web_search_enabled=False,
)
self.assertEqual(result["workflow_slug"], "web-answer")
self.assertEqual(result["inputs"]["web_search_query"], "latest Iran news")
with patch(
"backend.agent.router.chat_typed",
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
"workflow_id": combined.id,
"confidence": 0.95,
"reason": "forced web with knowledge",
"inputs": {"web_search_query": "compare notes with latest docs", "web_search_queries": ["compare notes with latest docs"]},
}))),
):
result = await select_workflow(
db, message="hello", recent_messages=[], attachments=[],
library_slug="notes", router_model=None, chat_model="model", web_search_enabled=True,
)
self.assertEqual(result["workflow_slug"], "knowledge-web-answer")
self.assertEqual(result["inputs"]["web_search_query"], "compare notes with latest docs")
with patch("backend.agent.router.chat_typed", new=AsyncMock()) as mocked:
result = await select_workflow(
db, message="hello", recent_messages=[], attachments=[],
library_slug=None, router_model=None, chat_model="model", web_search_enabled=False,
)
self.assertEqual(result["workflow_slug"], "input-output")
mocked.assert_not_awaited()
result = await select_workflow(
db, message="remember this: I prefer short answers", recent_messages=[], attachments=[],
library_slug="memory", router_model=None, chat_model="model", web_search_enabled=False,
)
self.assertEqual(result["workflow_slug"], "remember-this")
db.close()
async def test_missing_router_model_falls_back_to_chat_model(self):
db = self.Session()
with patch("backend.agent.router.list_model_catalog", new=AsyncMock(return_value={"chat_models": ["chat"]})), patch("backend.agent.router.chat_typed", new=AsyncMock(side_effect=RuntimeError("bad response"))) as mocked:
result = await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model="missing", chat_model="chat")
self.assertEqual(result["workflow_slug"], "input-output")
self.assertEqual(mocked.await_args.args[0], "chat")
db.close()
async def test_router_prompt_formats_followup_context_and_filters_for_forced_web(self):
db = self.Session()
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
with patch(
"backend.agent.router.chat_typed",
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
"workflow_id": web.id,
"confidence": 0.95,
"reason": "current follow-up",
"inputs": {"web_search_query": "Iran political news today", "web_search_queries": ["Iran political news today"]},
}))),
) as mocked:
result = await select_workflow(
db,
message="and what's the news politically?",
recent_messages=[
{"role": "user", "content": "what's the weather in Iran today"},
{"role": "assistant", "content": "The weather in Tehran, Iran today is clear."},
],
attachments=[],
library_slug=None,
router_model=None,
chat_model="model",
web_search_enabled=True,
)
prompt = mocked.await_args.args[1][0]["content"]
self.assertEqual(result["inputs"]["web_search_query"], "Iran political news today")
self.assertIn("Recent conversation:\n1. User: what's the weather in Iran today", prompt)
self.assertIn("Resolve the current message into a standalone request", prompt)
self.assertIn("capabilities cover the required work", prompt)
self.assertIn("Do not choose a workflow because an example sounds similar", prompt)
self.assertIn("Choose a web-answer workflow when the missing capability is external facts", prompt)
self.assertIn("Short follow-ups usually inherit the previous subject", prompt)
self.assertIn("Routing contract:", prompt)
self.assertIn("default web workflow for direct answer requests", prompt)
self.assertIn("Choose only when the standalone request needs an investigation", prompt)
self.assertIn("Allowed workflows. This list is already filtered", prompt)
self.assertIn("web-answer", prompt)
self.assertNotIn("input-output", prompt)
self.assertNotIn("Cost:", prompt)
self.assertNotIn("Web search mode:", prompt)
self.assertNotIn("Selected knowledge database:", prompt)
db.close()
async def test_long_message_digest_preserves_request_boundaries(self):
message = (
"Please summarize the pasted material and keep the answer short.\n"
+ ("A" * 3600)
+ "\nMiddle note: focus on the security implications.\n"
+ ("B" * 3600)
+ "\nActually, compare the risks and benefits instead."
)
digest = _format_message_for_router(message)
self.assertLess(len(digest), len(message))
self.assertIn("<long_user_message_digest>", digest)
self.assertIn("Please summarize the pasted material", digest)
self.assertIn("Middle note: focus on the security implications", digest)
self.assertIn("Actually, compare the risks and benefits instead.", digest)
self.assertIn("Original length:", digest)
async def test_router_prompt_uses_bounded_digest_and_attachment_summary(self):
message = (
"Instruction before payload: analyze this local document.\n"
+ "\n".join(f"payload line {index} " + ("x" * 80) for index in range(400))
+ "\nInstruction after payload: do not search the web unless needed."
)
manifest = {
"workflow_id": "direct",
"slug": "input-output",
"name": "Input -> Output",
"routing_description": "Use when no external tool is needed.",
"examples": [],
"required_capabilities": ["chat"],
}
prompt = _router_prompt(
message=message,
recent_messages=[{"role": "assistant", "content": "previous " + ("y" * 2000)}],
attachments=[{
"kind": "file",
"name": "large-report.pdf",
"mime_type": "application/pdf",
"size": 12345,
"text": "attachment text " * 1000,
}],
manifests=[manifest],
)
self.assertLess(len(prompt), 9000)
self.assertIn("Current user message or routing digest:", prompt)
self.assertIn("Instruction before payload", prompt)
self.assertIn("Instruction after payload", prompt)
self.assertIn("large-report.pdf", prompt)
self.assertIn("text_chars=", prompt)
self.assertNotIn("attachment text attachment text attachment text", prompt)
async def test_all_builtins_validate(self):
registry = NativeToolProvider(); register_native_tools(registry)
for item in BUILTIN_WORKFLOWS:
with self.subTest(item=item["slug"]):
self.assertTrue(validate_workflow_graph(item["graph"], registry).valid)
async def test_research_evaluator_contract_avoids_contradictory_followups(self):
research = next(item for item in BUILTIN_WORKFLOWS if item["slug"] == "research")
evaluate = next(node for node in research["graph"]["nodes"] if node["id"] == "evaluate")
config = evaluate["config"]
self.assertIn("If sufficient=true, follow_up_query must be an empty string", config["system_template"])
self.assertIn("If sufficient=false, follow_up_query must be one concise web search query", config["system_template"])
self.assertIn("Resolved request and router inputs", config["user_template"])

View File

@@ -0,0 +1,167 @@
import asyncio
import json
from pathlib import Path
import tempfile
import unittest
import uuid
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.agent.models import WorkflowDefinition, WorkflowEvent, WorkflowRevision, WorkflowRun
from backend.agent.registry import NativeToolProvider, ToolDefinition
from backend.agent.runtime import WorkflowRuntime
from backend.database import Base
from backend.models import ChatMessage, ChatSession
def graph(nodes, edges, maximum_tool_calls=10):
return {
"schema_version": 1,
"inputs": {"prompt": {"type": "string"}},
"outputs": {"content": {"type": "string"}},
"nodes": nodes,
"edges": edges,
"limits": {"maximum_nodes": 20, "maximum_tool_calls": maximum_tool_calls, "maximum_llm_calls": 5, "maximum_runtime_seconds": 5, "maximum_result_chars": 20000, "maximum_concurrency": 4},
}
def node(node_id, node_type, config=None):
return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, "config": config or {}}
def edge(source, target, handle="output"):
return {"id": f"{source}-{target}-{handle}", "source": source, "source_handle": handle, "target": target, "target_handle": "input"}
class RuntimeTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.temp = tempfile.TemporaryDirectory()
self.engine = create_engine(f"sqlite:///{Path(self.temp.name) / 'test.db'}", connect_args={"check_same_thread": False})
Base.metadata.create_all(self.engine)
self.Session = sessionmaker(bind=self.engine)
self.registry = NativeToolProvider()
async def echo(arguments, _context):
await asyncio.sleep(arguments.get("delay", 0))
if arguments.get("fail"):
raise RuntimeError("requested failure")
return {"content": arguments.get("text", ""), "sources": arguments.get("sources", [])}
schema = {
"type": "object",
"properties": {"text": {"type": "string"}, "delay": {"type": "number"}, "fail": {"type": "boolean"}, "sources": {"type": "array"}},
"required": ["text"], "additionalProperties": False,
}
output = {"type": "object", "properties": {"content": {"type": "string"}, "sources": {"type": "array"}}, "required": ["content", "sources"], "additionalProperties": False}
self.registry.register(ToolDefinition("test.echo", "echo", schema, output, echo))
self.runtime = WorkflowRuntime(self.registry, self.Session)
async def asyncTearDown(self):
self.engine.dispose()
self.temp.cleanup()
def create_run(self, graph_value, session=True):
db = self.Session()
workflow = WorkflowDefinition(slug=f"w-{uuid.uuid4().hex}", name="Test", built_in=False, enabled=True)
db.add(workflow); db.flush()
revision = WorkflowRevision(workflow_id=workflow.id, version=1, graph_json=json.dumps(graph_value), checksum="x", created_by="test")
db.add(revision); db.flush(); workflow.current_revision_id = revision.id
session_id = None
user_id = None
if session:
chat = ChatSession(session_id=f"s-{id(graph_value)}")
db.add(chat); db.flush()
user = ChatMessage(session_pk=chat.id, role="user", content="hello")
db.add(user); db.flush(); session_id = chat.session_id; user_id = user.message_id
run = WorkflowRun(
workflow_id=workflow.id, workflow_revision_id=revision.id, session_id=session_id, user_message_id=user_id,
selection_mode="explicit", inputs_json=json.dumps({"input": {"prompt": "hello"}, "run": {"messages": [{"role": "user", "content": "hello"}]}}),
)
db.add(run); db.commit(); run_id = run.id; db.close()
return run_id
async def execute(self, run_id):
await self.runtime.execute(run_id)
db = self.Session(); run = db.query(WorkflowRun).filter_by(id=run_id).first(); db.expunge(run); db.close(); return run
async def test_basic_persistence_and_source_propagation(self):
value = graph(
[node("input", "input"), node("echo", "tool", {"tool": "test.echo", "arguments": {"text": {"$ref": "input.prompt"}, "sources": [{"url": "https://example.com"}]}}), node("output", "output", {"value": {"$ref": "nodes.echo.output"}})],
[edge("input", "echo"), edge("echo", "output")],
)
run = await self.execute(self.create_run(value))
self.assertEqual(run.status, "completed")
db = self.Session()
assistant = db.query(ChatMessage).filter(ChatMessage.role == "assistant").one()
self.assertEqual(assistant.content, "hello")
self.assertEqual(json.loads(assistant.sources_json)[0]["url"], "https://example.com")
self.assertTrue(db.query(WorkflowEvent).filter(WorkflowEvent.event_type == "source_found").count())
db.close()
test_run = await self.execute(self.create_run(value, session=False))
self.assertEqual(test_run.status, "completed")
async def test_concurrent_nodes_and_condition_branch(self):
value = graph(
[
node("input", "input"),
node("a", "tool", {"tool": "test.echo", "arguments": {"text": "a", "delay": 0.04}}),
node("b", "tool", {"tool": "test.echo", "arguments": {"text": "b", "delay": 0.04}}),
node("condition", "condition", {"value": True, "operation": "equals", "compare_to": True}),
node("yes", "template", {"template": "yes"}),
node("no", "template", {"template": "no"}),
node("output", "output", {"value": {"content": {"$ref": "nodes.yes.output"}, "sources": []}}),
],
[edge("input", "a"), edge("input", "b"), edge("a", "condition"), edge("b", "condition"), edge("condition", "yes", "true"), edge("condition", "no", "false"), edge("yes", "output")],
)
run = await self.execute(self.create_run(value))
self.assertEqual(run.status, "completed")
db = self.Session()
statuses = {row.node_id: row.status for row in db.query(__import__('backend.agent.models', fromlist=['WorkflowNodeRun']).WorkflowNodeRun).all()}
self.assertEqual(statuses["no"], "skipped")
db.close()
async def test_limit_preserves_sources_from_merged_context(self):
value = graph(
[
node("input", "input"),
node("a", "tool", {"tool": "test.echo", "arguments": {"text": "a" * 2000, "sources": [{"url": "https://a.example", "snippet": "a" * 500}]}}),
node("b", "tool", {"tool": "test.echo", "arguments": {"text": "b" * 2000, "sources": [{"url": "https://b.example", "snippet": "b" * 500}]}}),
node("merge", "merge", {"values": [{"$ref": "nodes.a.output"}, {"$ref": "nodes.b.output"}], "deduplicate_by": "url"}),
node("limit", "limit", {"value": {"$ref": "nodes.merge.output"}, "maximum_chars": 80}),
node("output", "output", {"value": {"content": "done", "sources": {"$ref": "nodes.limit.output.sources"}}}),
],
[edge("input", "a"), edge("a", "b"), edge("b", "merge"), edge("merge", "limit"), edge("limit", "output")],
)
run = await self.execute(self.create_run(value))
self.assertEqual(run.status, "completed")
db = self.Session()
assistant = db.query(ChatMessage).filter(ChatMessage.role == "assistant").one()
self.assertEqual([item["url"] for item in json.loads(assistant.sources_json)], ["https://a.example", "https://b.example"])
db.close()
async def test_failure_cancellation_and_tool_limit(self):
failing = graph(
[node("input", "input"), node("bad", "tool", {"tool": "test.echo", "arguments": {"text": "x", "fail": True}}), node("output", "output", {"value": {"$ref": "nodes.bad.output"}})],
[edge("input", "bad"), edge("bad", "output")],
)
self.assertEqual((await self.execute(self.create_run(failing))).status, "failed")
limited = graph(
[node("input", "input"), node("a", "tool", {"tool": "test.echo", "arguments": {"text": "a"}}), node("b", "tool", {"tool": "test.echo", "arguments": {"text": "b"}}), node("output", "output", {"value": {"$ref": "nodes.b.output"}})],
[edge("input", "a"), edge("a", "b"), edge("b", "output")], maximum_tool_calls=1,
)
self.assertEqual((await self.execute(self.create_run(limited))).status, "failed")
slow = graph(
[node("input", "input"), node("slow", "tool", {"tool": "test.echo", "arguments": {"text": "x", "delay": 0.3}}), node("output", "output", {"value": {"$ref": "nodes.slow.output"}})],
[edge("input", "slow"), edge("slow", "output")],
)
run_id = self.create_run(slow)
task = asyncio.create_task(self.runtime.execute(run_id))
await asyncio.sleep(0.03)
self.runtime.cancel(run_id)
await task
db = self.Session(); status = db.query(WorkflowRun).filter_by(id=run_id).one().status; db.close()
self.assertEqual(status, "cancelled")

View File

@@ -0,0 +1,72 @@
import copy
import unittest
from backend.agent.registry import NativeToolProvider, ToolDefinition
from backend.agent.validation import validate_workflow_graph
async def handler(arguments, _context):
return {"content": arguments["text"]}
def registry():
value = NativeToolProvider()
value.register(ToolDefinition(
"test.echo", "echo",
{"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"], "additionalProperties": False},
{"type": "object", "properties": {"content": {"type": "string"}}, "required": ["content"], "additionalProperties": False},
handler,
))
return value
def valid_graph():
return {
"schema_version": 1,
"inputs": {"prompt": {"type": "string"}},
"outputs": {"content": {"type": "string"}},
"nodes": [
{"id": "input", "type": "input", "position": {"x": 0, "y": 0}, "config": {}},
{"id": "echo", "type": "tool", "position": {"x": 200, "y": 0}, "config": {"tool": "test.echo", "arguments": {"text": {"$ref": "input.prompt"}}}},
{"id": "output", "type": "output", "position": {"x": 400, "y": 0}, "config": {"value": {"$ref": "nodes.echo.output"}}},
],
"edges": [
{"id": "a", "source": "input", "source_handle": "output", "target": "echo", "target_handle": "input"},
{"id": "b", "source": "echo", "source_handle": "output", "target": "output", "target_handle": "input"},
],
"limits": {"maximum_nodes": 10, "maximum_tool_calls": 5, "maximum_llm_calls": 2, "maximum_runtime_seconds": 30, "maximum_result_chars": 10000, "maximum_concurrency": 2},
}
class ValidationTests(unittest.TestCase):
def setUp(self):
self.registry = registry()
def codes(self, graph):
return {item.code for item in validate_workflow_graph(graph, self.registry).errors}
def test_valid_dag(self):
self.assertTrue(validate_workflow_graph(valid_graph(), self.registry).valid)
def test_unknown_tool_missing_reference_unreachable_duplicate_and_cycle(self):
graph = valid_graph(); graph["nodes"][1]["config"]["tool"] = "missing"
self.assertIn("unknown_tool", self.codes(graph))
graph = valid_graph(); graph["nodes"][1]["config"]["arguments"]["text"] = {"$ref": "input.missing"}
self.assertIn("missing_reference", self.codes(graph))
graph = valid_graph(); graph["nodes"].append({"id": "orphan", "type": "template", "position": {"x": 0, "y": 0}, "config": {"template": "x"}})
self.assertIn("unreachable_node", self.codes(graph))
graph = valid_graph(); graph["nodes"].append(copy.deepcopy(graph["nodes"][1]))
self.assertIn("duplicate_node_id", self.codes(graph))
graph = valid_graph(); graph["edges"].append({"id": "cycle", "source": "output", "source_handle": "output", "target": "echo", "target_handle": "input"})
self.assertIn("cycle", self.codes(graph))
def test_invalid_branch_limits_and_schema(self):
graph = valid_graph()
graph["nodes"].insert(2, {"id": "condition", "type": "condition", "position": {"x": 300, "y": 0}, "config": {"value": True, "operation": "equals", "compare_to": True}})
graph["edges"][1]["target"] = "condition"
graph["edges"].append({"id": "condition-output", "source": "condition", "source_handle": "true", "target": "output", "target_handle": "input"})
self.assertIn("invalid_branch", self.codes(graph))
graph = valid_graph(); graph["limits"]["maximum_nodes"] = 999
self.assertIn("excessive_limit", self.codes(graph))
graph = valid_graph(); graph["inputs"]["prompt"] = {"type": "made-up"}
self.assertIn("malformed_schema", self.codes(graph))

445
backend/video_ingest.py Normal file
View File

@@ -0,0 +1,445 @@
from __future__ import annotations
import json
import math
import multiprocessing as mp
import os
import platform
import re
import shutil
import subprocess
import tempfile
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
import httpx
from .app_settings import (
get_enrichment_model_preference,
get_ollama_api_url,
get_transcription_model_preference,
)
from .ollama_client import chat as ollama_chat
from .paths import tool_root
from .rag.corpus_builder import (
_transcribe_slice,
_whisper_pool_init,
merge_transcripts,
slice_audio,
)
from .whisper_admin import ensure_whisper_model_downloaded
YTDLP_RELEASE_URL = "https://github.com/yt-dlp/yt-dlp/releases/latest/download"
YTDLP_UPDATE_INTERVAL_SECONDS = 6 * 60 * 60
YTDLP_STATUS_FILE = "update.json"
SUMMARY_PROMPT_TEMPLATE = """You are an expert summarizer. Summarize the following video concisely:
Title: {title}
Transcript:
{transcript}
Summary:"""
OLLAMA_CHARS_PER_TOKEN = 3.5
OLLAMA_OUTPUT_TOKEN_BUDGET = 2048
OLLAMA_CONTEXT_BUCKETS = (4096, 8192, 16384, 32768, 65536)
NUM_SLICES = 8
OVERLAP_SECONDS = 1.0
MAX_OVERLAP_WORDS = 7
MEDIA_HOST_MARKERS = (
"youtube.com",
"youtu.be",
"vimeo.com",
"tiktok.com",
"instagram.com",
"twitch.tv",
"soundcloud.com",
"facebook.com",
"fb.watch",
"dailymotion.com",
)
_YTDLP_LOCK = threading.Lock()
class UnsupportedVideoUrl(RuntimeError):
pass
def _yt_dlp_asset_name() -> str:
system = platform.system().lower()
machine = platform.machine().lower()
if system == "windows":
return "yt-dlp_arm64.exe" if machine in {"arm64", "aarch64"} else "yt-dlp.exe"
if system == "darwin":
return "yt-dlp_macos"
if system == "linux":
if machine in {"arm64", "aarch64"}:
return "yt-dlp_linux_aarch64"
if machine.startswith("armv7"):
return "yt-dlp_linux_armv7l"
return "yt-dlp_linux"
return "yt-dlp"
def _yt_dlp_binary_name() -> str:
return "yt-dlp.exe" if os.name == "nt" else "yt-dlp"
def _executable_version(path: Path) -> Optional[str]:
try:
result = subprocess.run(
[str(path), "--version"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=20,
)
except Exception:
return None
if result.returncode != 0:
return None
return (result.stdout or result.stderr).strip().splitlines()[0].strip() or None
def _read_update_status(status_path: Path) -> Dict[str, Any]:
try:
payload = json.loads(status_path.read_text(encoding="utf-8"))
return payload if isinstance(payload, dict) else {}
except Exception:
return {}
def _update_due(binary_path: Path, status_path: Path) -> bool:
if not binary_path.exists() or not _executable_version(binary_path):
return True
last_check = _read_update_status(status_path).get("last_check")
if not isinstance(last_check, (int, float)):
return True
return (time.time() - float(last_check)) >= YTDLP_UPDATE_INTERVAL_SECONDS
def _download_latest_yt_dlp(binary_path: Path, status_path: Path) -> Optional[str]:
url = f"{YTDLP_RELEASE_URL}/{_yt_dlp_asset_name()}"
tmp_path = binary_path.with_suffix(binary_path.suffix + ".download")
try:
timeout = httpx.Timeout(120.0, connect=10.0)
with httpx.stream("GET", url, follow_redirects=True, timeout=timeout) as response:
response.raise_for_status()
with tmp_path.open("wb") as handle:
for chunk in response.iter_bytes(chunk_size=1024 * 1024):
if chunk:
handle.write(chunk)
if os.name != "nt":
tmp_path.chmod(0o755)
version = _executable_version(tmp_path)
if not version:
raise RuntimeError("Downloaded yt-dlp executable did not run.")
os.replace(tmp_path, binary_path)
if os.name != "nt":
binary_path.chmod(0o755)
status_path.write_text(
json.dumps({"last_check": time.time(), "version": version, "source": url}, indent=2),
encoding="utf-8",
)
return version
except Exception:
try:
tmp_path.unlink(missing_ok=True)
except Exception:
pass
return None
def resolve_yt_dlp() -> Tuple[str, str]:
override = str(os.getenv("HEIMGEIST_YTDLP_PATH") or "").strip()
if override:
path = Path(override).expanduser()
version = _executable_version(path)
if not version:
raise RuntimeError(f"Configured yt-dlp executable is unavailable: {path}")
return str(path), version
with _YTDLP_LOCK:
target_dir = tool_root() / "yt-dlp"
target_dir.mkdir(parents=True, exist_ok=True)
binary_path = target_dir / _yt_dlp_binary_name()
status_path = target_dir / YTDLP_STATUS_FILE
version = _executable_version(binary_path)
if _update_due(binary_path, status_path):
updated = _download_latest_yt_dlp(binary_path, status_path)
if updated:
return str(binary_path), updated
if version := _executable_version(binary_path):
return str(binary_path), version
system_path = shutil.which("yt-dlp")
if system_path and (version := _executable_version(Path(system_path))):
return system_path, version
raise RuntimeError("Heimgeist could not download or locate yt-dlp.")
def _ffmpeg_binary() -> str:
candidate = str(os.getenv("HEIMGEIST_FFMPEG_PATH") or shutil.which("ffmpeg") or "").strip()
if not candidate:
raise RuntimeError("Video ingestion requires ffmpeg.")
return candidate
def _ffprobe_binary() -> str:
candidate = str(os.getenv("HEIMGEIST_FFPROBE_PATH") or shutil.which("ffprobe") or "").strip()
if not candidate:
raise RuntimeError("Video ingestion requires ffprobe.")
return candidate
def _run_yt_dlp(args: List[str], *, timeout: Optional[float] = None) -> subprocess.CompletedProcess:
executable, _version = resolve_yt_dlp()
env = os.environ.copy()
ffmpeg_dir = str(Path(_ffmpeg_binary()).parent)
path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry]
if ffmpeg_dir and ffmpeg_dir not in path_entries:
path_entries.insert(0, ffmpeg_dir)
env["PATH"] = os.pathsep.join(path_entries)
result = subprocess.run(
[executable, *args],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
env=env,
)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "yt-dlp failed").strip()
if "Unsupported URL" in detail:
raise UnsupportedVideoUrl(detail)
raise RuntimeError(detail)
return result
def _parse_metadata(stdout: str) -> Dict[str, Any]:
for line in reversed([line.strip() for line in stdout.splitlines() if line.strip()]):
try:
payload = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(payload, dict):
return payload
raise RuntimeError("yt-dlp returned no usable metadata.")
def _looks_like_video_metadata(metadata: Dict[str, Any]) -> bool:
formats = metadata.get("formats")
if not isinstance(formats, list) or not formats:
return False
return bool(
metadata.get("duration")
or metadata.get("acodec") not in {None, "none"}
or metadata.get("vcodec") not in {None, "none"}
)
def is_likely_media_url(url: str) -> bool:
lowered = str(url or "").lower()
return any(marker in lowered for marker in MEDIA_HOST_MARKERS)
def probe_video_url(url: str) -> Optional[Dict[str, Any]]:
result = _run_yt_dlp(
["--no-playlist", "--skip-download", "--dump-single-json", "--no-warnings", url],
timeout=180,
)
metadata = _parse_metadata(result.stdout)
return metadata if _looks_like_video_metadata(metadata) else None
def _download_audio(url: str, temp_dir: Path) -> Path:
output_template = str(temp_dir / "audio.%(ext)s")
args = [
"--no-playlist",
"--format", "bestaudio/best",
"--output", output_template,
"--no-progress",
"--no-part",
"--no-continue",
"--force-overwrites",
"--retries", "3",
"--fragment-retries", "3",
"--extract-audio",
"--audio-format", "wav",
"--ffmpeg-location", str(Path(_ffmpeg_binary()).parent),
url,
]
_run_yt_dlp(args, timeout=60 * 60)
expected = temp_dir / "audio.wav"
if expected.exists():
return expected
matches = list(temp_dir.glob("audio*.wav"))
if matches:
return matches[0]
raise RuntimeError("yt-dlp completed without producing an audio file.")
def _transcription_workers(model_name: str, slice_count: int) -> int:
override = str(os.getenv("HEIMGEIST_VIDEO_WHISPER_WORKERS") or "").strip()
if override:
try:
return max(1, min(slice_count, int(override)))
except ValueError:
pass
if any(marker in model_name.lower() for marker in ("medium", "large")):
return 1
return max(1, min(slice_count, 2, max(1, (os.cpu_count() or 2) // 2)))
def _transcribe_audio(audio_path: Path, temp_dir: Path, model_name: str) -> Tuple[str, Dict[str, Any]]:
ensure_whisper_model_downloaded(model_name)
slice_dir = temp_dir / "slices"
slice_dir.mkdir(parents=True, exist_ok=True)
slices = slice_audio(
audio_path,
slice_dir,
NUM_SLICES,
OVERLAP_SECONDS,
_ffprobe_binary(),
_ffmpeg_binary(),
)
workers = _transcription_workers(model_name, len(slices))
context = mp.get_context("spawn")
pool = context.Pool(
processes=workers,
initializer=_whisper_pool_init,
initargs=(model_name, "cpu"),
)
try:
jobs = [(path, index, audio_path.stem) for index, (path, _start, _end) in enumerate(slices)]
results = pool.starmap(_transcribe_slice, [("transcribe", job) for job in jobs])
except BaseException:
pool.terminate()
pool.join()
raise
else:
pool.close()
pool.join()
transcript = merge_transcripts(results, MAX_OVERLAP_WORDS).strip()
if not transcript:
raise RuntimeError("Whisper returned an empty transcript.")
return transcript, {"model": model_name, "workers": workers, "slices": len(slices)}
def _choose_num_ctx(prompt: str) -> int:
estimated_input_tokens = math.ceil(len(prompt) / OLLAMA_CHARS_PER_TOKEN)
needed = estimated_input_tokens + OLLAMA_OUTPUT_TOKEN_BUDGET
for bucket in OLLAMA_CONTEXT_BUCKETS:
if needed <= bucket:
return bucket
return OLLAMA_CONTEXT_BUCKETS[-1]
async def _summarize(title: str, transcript: str, model_name: str) -> str:
prompt = SUMMARY_PROMPT_TEMPLATE.replace("{title}", title).replace("{transcript}", transcript)
summary = await ollama_chat(
model_name,
[
{"role": "system", "content": "You are an intelligent summarizer."},
{"role": "user", "content": prompt},
],
options={"num_ctx": _choose_num_ctx(prompt)},
)
clean = re.sub(r"<think>.*?</think>", "", str(summary or ""), flags=re.DOTALL | re.IGNORECASE).strip()
clean = re.sub(r"^\s*Summary:\s*", "", clean, flags=re.IGNORECASE).strip()
if not clean:
raise RuntimeError("Ollama returned an empty video summary.")
return clean
def _format_duration(value: Any) -> str:
try:
total = max(0, int(float(value)))
except Exception:
return ""
hours, remainder = divmod(total, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{hours:d}:{minutes:02d}:{seconds:02d}" if hours else f"{minutes:d}:{seconds:02d}"
def build_video_document(metadata: Dict[str, Any], summary: str, transcript: str) -> str:
title = str(metadata.get("title") or "Video").strip()
url = str(metadata.get("webpage_url") or metadata.get("original_url") or "").strip()
uploader = str(metadata.get("channel") or metadata.get("uploader") or "").strip()
duration = _format_duration(metadata.get("duration"))
lines = [f"# {title}"]
if url:
lines.append(f"Source: {url}")
if uploader:
lines.append(f"Channel: {uploader}")
if duration:
lines.append(f"Duration: {duration}")
lines.extend(["", "## Summary", summary.strip(), "", "## Transcript", transcript.strip()])
return "\n".join(lines).strip() + "\n"
async def ingest_video_url(
url: str,
metadata: Dict[str, Any],
*,
progress: Optional[Callable[[str, float, str], None]] = None,
) -> Dict[str, Any]:
def report(phase: str, pct: float, detail: str) -> None:
if progress:
progress(phase, pct, detail)
title = str(metadata.get("title") or metadata.get("id") or "Video").strip()
transcription_model = get_transcription_model_preference()
summary_model = get_enrichment_model_preference()
_executable, yt_dlp_version = await _to_thread(resolve_yt_dlp)
with tempfile.TemporaryDirectory(prefix="heimgeist-video-") as raw_temp_dir:
temp_dir = Path(raw_temp_dir)
report("download", 0.08, "Downloading video audio...")
audio_path = await _to_thread(_download_audio, url, temp_dir)
report("transcribe", 0.25, f"Transcribing audio with Whisper {transcription_model}...")
transcript, transcription = await _to_thread(
_transcribe_audio,
audio_path,
temp_dir,
transcription_model,
)
report("summarize", 0.72, f"Summarizing transcript with {summary_model}...")
summary = await _summarize(title, transcript, summary_model)
report("save", 0.9, "Saving transcript and metadata...")
canonical_url = str(metadata.get("webpage_url") or metadata.get("original_url") or url).strip()
return {
"title": title,
"url": canonical_url,
"requested_url": url,
"video_id": str(metadata.get("id") or "").strip() or None,
"extractor": str(metadata.get("extractor_key") or metadata.get("extractor") or "").strip() or None,
"channel": str(metadata.get("channel") or metadata.get("uploader") or "").strip() or None,
"duration": metadata.get("duration"),
"duration_text": _format_duration(metadata.get("duration")),
"upload_date": metadata.get("upload_date"),
"thumbnail_url": metadata.get("thumbnail"),
"transcript": transcript,
"summary": summary,
"document": build_video_document(metadata, summary, transcript),
"transcription_model": transcription["model"],
"transcription_workers": transcription["workers"],
"transcription_slices": transcription["slices"],
"summary_model": summary_model,
"yt_dlp_version": yt_dlp_version,
"fetched_at": datetime.utcnow().isoformat(timespec="seconds") + "Z",
}
async def _to_thread(fn, *args):
import asyncio
return await asyncio.to_thread(fn, *args)

View File

@@ -7,7 +7,7 @@ import json
import traceback import traceback
import hashlib import hashlib
from .app_settings import get_embed_model_preference, get_ollama_api_url from .app_settings import get_ollama_api_url, get_rerank_model_preference
from .ollama_client import chat as ollama_chat from .ollama_client import chat as ollama_chat
# Configure your local SearXNG instance URL (no trailing slash) # Configure your local SearXNG instance URL (no trailing slash)
@@ -58,7 +58,7 @@ def render_recent_context(messages: Optional[List[Dict[str, str]]], char_limit:
# ----- SearXNG search & fetching ------------------------------------------------- # ----- SearXNG search & fetching -------------------------------------------------
from urllib.parse import urlparse from urllib.parse import urljoin, urlparse
import itertools import itertools
# HTTP client tuning (keep-alive pool + HTTP/2) # HTTP client tuning (keep-alive pool + HTTP/2)
@@ -84,6 +84,94 @@ SKIP_EXTS = {
_PAGE_CACHE: Dict[str, str] = {} # naive in-proc cache (speeds repeated calls) _PAGE_CACHE: Dict[str, str] = {} # naive in-proc cache (speeds repeated calls)
_EMB_CACHE: Dict[str, List[float]] = {} # NEW: embedding cache by SHA1 of snippet _EMB_CACHE: Dict[str, List[float]] = {} # NEW: embedding cache by SHA1 of snippet
_RANK_STOPWORDS = {
"about", "after", "again", "against", "also", "and", "any", "are", "because",
"been", "before", "being", "but", "can", "could", "current", "does", "for",
"from", "had", "has", "have", "how", "into", "its", "latest", "more", "most",
"new", "news", "not", "now", "off", "out", "over", "please", "should", "than",
"that", "the", "their", "them", "then", "there", "these", "they", "this",
"today", "was", "were", "what", "when", "where", "which", "while", "who",
"why", "will", "with", "would", "you", "your",
}
def _rank_tokens(text: str) -> List[str]:
return [
token.casefold()
for token in re.findall(r"\b[\w-]{3,}\b", text or "", flags=re.UNICODE)
if token.casefold() not in _RANK_STOPWORDS
]
def fallback_rerank(
prompt: str,
docs: List[Tuple[str, str]],
context_excerpt: str = "",
*,
reason: str = "embedding_unavailable",
) -> List[Tuple[str, str, float]]:
"""
Rank pages without embeddings so web search can still produce context when
the configured embedding/reranking model is missing or Ollama is offline.
"""
if not docs:
return []
query_text = f"{prompt or ''} {context_excerpt[-600:] if context_excerpt else ''}"
query_terms = list(dict.fromkeys(_rank_tokens(query_text)))[:36]
prompt_phrase = " ".join(str(prompt or "").casefold().split())
if len(prompt_phrase) < 6 or len(prompt_phrase) > 160:
prompt_phrase = ""
scored: List[Tuple[str, str, float]] = []
doc_count = max(1, len(docs))
for index, (url, text) in enumerate(docs):
sample = f"{url} {(text or '')[:6000]}"
sample_lower = sample.casefold()
sample_tokens = _rank_tokens(sample)
sample_set = set(sample_tokens)
coverage = 0.0
frequency = 0.0
if query_terms:
matches = [term for term in query_terms if term in sample_set or term in sample_lower]
coverage = len(matches) / len(query_terms)
frequency = min(
1.0,
sum(min(sample_lower.count(term), 3) for term in query_terms)
/ max(1, len(query_terms) * 2),
)
order_signal = 1.0 - (index / doc_count)
length_signal = min(1.0, len(text or "") / 2500.0)
phrase_signal = 1.0 if prompt_phrase and prompt_phrase in sample_lower else 0.0
raw = (
0.52 * coverage
+ 0.18 * frequency
+ 0.16 * order_signal
+ 0.08 * length_signal
+ 0.06 * phrase_signal
)
score = 58.0 + min(1.0, raw) * 34.0
if coverage > 0 or phrase_signal > 0:
score = max(score, 72.0 - min(index, 4) * 1.25)
scored.append((url, text, max(0.0, min(100.0, score))))
scored.sort(key=lambda item: item[2], reverse=True)
if scored and scored[0][2] < 70.0:
# SearXNG already ranked these URLs. If lexical signals are weak, keep
# web search usable by passing through a small ordered sample.
adjusted: List[Tuple[str, str, float]] = []
for rank, (url, text, score) in enumerate(scored):
passthrough_score = 72.0 - rank
adjusted.append((url, text, max(score, passthrough_score if rank < 3 else score)))
scored = adjusted
print(f"[web] embedding rerank unavailable ({reason}); using lexical fallback over {len(docs)} docs")
return scored
def _is_probably_html_url(url: str) -> bool: def _is_probably_html_url(url: str) -> bool:
try: try:
path = urlparse(url).path.lower() path = urlparse(url).path.lower()
@@ -199,6 +287,86 @@ async def fetch_page(client: httpx.AsyncClient, url: str) -> str:
print(f"[web] fetch_page error url={url}: {repr(e)}") print(f"[web] fetch_page error url={url}: {repr(e)}")
return "" return ""
async def fetch_website_snapshot(url: str) -> Dict[str, Any]:
"""Fetch one user-supplied web page and return a durable text snapshot."""
requested_url = str(url or "").strip()
parsed = urlparse(requested_url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("Enter a valid http:// or https:// website URL.")
if not _is_probably_html_url(requested_url):
raise ValueError("This URL does not appear to point to a web page.")
async with httpx.AsyncClient(
headers=DEFAULT_HEADERS,
follow_redirects=True,
http2=True,
limits=HTTP_LIMITS,
timeout=HTTP_TIMEOUT,
) as client:
async with client.stream("GET", requested_url) as response:
response.raise_for_status()
content_type = (response.headers.get("content-type") or "").lower()
if content_type and not (
"text/html" in content_type
or "application/xhtml+xml" in content_type
or content_type.startswith("text/")
):
raise ValueError(f"Unsupported website content type: {content_type.split(';', 1)[0]}")
payload = bytearray()
async for chunk in response.aiter_bytes():
if not chunk:
continue
remaining = MAX_BYTES_PER_PAGE - len(payload)
if remaining <= 0:
break
payload.extend(chunk[:remaining])
encoding = response.encoding or "utf-8"
html = bytes(payload).decode(encoding, errors="ignore")
final_url = str(response.url)
try:
soup = BeautifulSoup(html, "lxml")
except Exception:
soup = BeautifulSoup(html, "html.parser")
title = ""
if soup.title:
title = re.sub(r"\s+", " ", soup.title.get_text(" ", strip=True)).strip()
if not title:
heading = soup.find(["h1", "h2"])
if heading:
title = re.sub(r"\s+", " ", heading.get_text(" ", strip=True)).strip()
canonical_url = final_url
canonical = soup.find("link", rel=lambda value: value and "canonical" in str(value).lower())
if canonical and canonical.get("href"):
candidate = urljoin(final_url, str(canonical.get("href")).strip())
candidate_parsed = urlparse(candidate)
if candidate_parsed.scheme in {"http", "https"} and candidate_parsed.netloc:
canonical_url = candidate
text = clean_text(html)
if len(text.strip()) < 80:
raise ValueError("The website did not contain enough readable text to save.")
if not title:
first_line = next((line.strip() for line in text.splitlines() if line.strip()), "")
title = re.sub(r"^[#>*_`\-\s]+", "", first_line).strip()[:240]
return {
"requested_url": requested_url,
"url": canonical_url,
"final_url": final_url,
"title": title or urlparse(final_url).netloc,
"text": text.strip(),
"html": html,
"content_type": content_type.split(";", 1)[0] or "text/html",
"etag": response.headers.get("etag"),
"last_modified": response.headers.get("last-modified"),
}
async def gather_pages( async def gather_pages(
client: httpx.AsyncClient, client: httpx.AsyncClient,
urls: List[str], urls: List[str],
@@ -267,7 +435,7 @@ async def rerank(
embed_model: Optional[str] = None, embed_model: Optional[str] = None,
) -> List[Tuple[str, str, float]]: ) -> List[Tuple[str, str, float]]:
""" """
Embedding-based reranker (bge-m3 via Ollama) using cosine similarity. Embedding-based reranker via Ollama using cosine similarity.
Robustness upgrades: Robustness upgrades:
- Try embed_model; if needed fallback to the ':latest' or untagged alias. - Try embed_model; if needed fallback to the ':latest' or untagged alias.
@@ -278,7 +446,7 @@ async def rerank(
""" """
import time import time
t0 = time.perf_counter() t0 = time.perf_counter()
embed_model = (embed_model or get_embed_model_preference()).strip() embed_model = (embed_model or get_rerank_model_preference()).strip()
ollama_url = get_ollama_api_url().rstrip("/") ollama_url = get_ollama_api_url().rstrip("/")
# --- optional fast cosine via NumPy --------------------------------------- # --- optional fast cosine via NumPy ---------------------------------------
@@ -420,13 +588,18 @@ async def rerank(
embed_model = alt embed_model = alt
else: else:
print(f"[web] embed() FAILED (models tried={tried + [alt]}, meta={meta or meta2})") print(f"[web] embed() FAILED (models tried={tried + [alt]}, meta={meta or meta2})")
return [(u, t, 0.0) for (u, t) in docs] return fallback_rerank(
prompt,
docs,
context_excerpt,
reason=f"model_failed:{embed_model}",
)
# split q vs passages and update cache # split q vs passages and update cache
q_emb = embeddings[0] if embeddings else [] q_emb = embeddings[0] if embeddings else []
if not q_emb: if not q_emb:
print("[web] embed() empty query vector — aborting rerank") print("[web] embed() empty query vector — aborting rerank")
return [(u, t, 0.0) for (u, t) in docs] return fallback_rerank(prompt, docs, context_excerpt, reason="empty_query_vector")
# positions >=1 correspond to passages (only those that weren’t cached) # positions >=1 correspond to passages (only those that weren’t cached)
for pos, emb_vec in enumerate(embeddings[1:], start=1): for pos, emb_vec in enumerate(embeddings[1:], start=1):
@@ -438,6 +611,9 @@ async def rerank(
# build aligned passage vectors # build aligned passage vectors
p_emb_list: List[List[float]] = [emb_cache.get(k, []) for k in keys] p_emb_list: List[List[float]] = [emb_cache.get(k, []) for k in keys]
if docs and not any(len(vec) for vec in p_emb_list):
print("[web] embed() empty passage vectors — aborting rerank")
return fallback_rerank(prompt, docs, context_excerpt, reason="empty_passage_vectors")
# logging # logging
q_dim = len(q_emb) q_dim = len(q_emb)
@@ -629,8 +805,12 @@ async def enrich_prompt(
pass pass
except Exception: except Exception:
print("[web] ERROR in rerank:\n" + traceback.format_exc()) print("[web] ERROR in rerank:\n" + traceback.format_exc())
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s") ranked = fallback_rerank(
return _no_results_enriched("rerank_failed", queries) user_prompt,
docs,
context_excerpt,
reason="rerank_exception",
)
# 5) build prompt # 5) build prompt
try: try:

View File

@@ -3,6 +3,9 @@ from __future__ import annotations
import importlib import importlib
import importlib.util import importlib.util
import os import os
import shutil
import subprocess
import tempfile
import threading import threading
from pathlib import Path from pathlib import Path
from typing import Any, Dict, Optional from typing import Any, Dict, Optional
@@ -10,6 +13,20 @@ from typing import Any, Dict, Optional
DEFAULT_WHISPER_MODEL = "base" DEFAULT_WHISPER_MODEL = "base"
_WHISPER_DOWNLOAD_LOCK = threading.Lock() _WHISPER_DOWNLOAD_LOCK = threading.Lock()
_WHISPER_MODEL_LOCK = threading.Lock()
_WHISPER_MODELS: Dict[tuple[str, str], Any] = {}
_AUDIO_SUFFIXES = {
"audio/aac": ".aac",
"audio/flac": ".flac",
"audio/mp4": ".m4a",
"audio/mpeg": ".mp3",
"audio/mpga": ".mp3",
"audio/ogg": ".ogg",
"audio/wav": ".wav",
"audio/wave": ".wav",
"audio/webm": ".webm",
"audio/x-wav": ".wav",
}
def _default_download_root() -> Path: def _default_download_root() -> Path:
@@ -24,6 +41,13 @@ def _load_whisper_module():
return None return None
def _load_torch_module():
try:
return importlib.import_module("torch")
except Exception:
return None
def whisper_runtime_error() -> Optional[str]: def whisper_runtime_error() -> Optional[str]:
if importlib.util.find_spec("whisper") is None: if importlib.util.find_spec("whisper") is None:
return ( return (
@@ -85,6 +109,52 @@ def inspect_whisper_model(model_name: str = DEFAULT_WHISPER_MODEL) -> Dict[str,
} }
def list_whisper_models() -> Dict[str, Any]:
error = whisper_runtime_error()
if error:
return {
"models": [
{
"name": DEFAULT_WHISPER_MODEL,
"available": False,
"downloaded": False,
}
],
"error": error,
}
whisper_mod = _load_whisper_module()
if whisper_mod is None:
return {
"models": [
{
"name": DEFAULT_WHISPER_MODEL,
"available": False,
"downloaded": False,
}
],
"error": "Failed to import the Whisper runtime.",
}
try:
names = list(whisper_mod.available_models())
except Exception:
names = [DEFAULT_WHISPER_MODEL]
out = []
for name in names:
status = inspect_whisper_model(name)
out.append(
{
"name": name,
"available": bool(status.get("available")),
"downloaded": bool(status.get("available")),
}
)
return {"models": out, "error": ""}
def ensure_whisper_model_downloaded(model_name: str = DEFAULT_WHISPER_MODEL) -> Dict[str, Any]: def ensure_whisper_model_downloaded(model_name: str = DEFAULT_WHISPER_MODEL) -> Dict[str, Any]:
status = inspect_whisper_model(model_name) status = inspect_whisper_model(model_name)
if status["error"]: if status["error"]:
@@ -123,3 +193,134 @@ def ensure_whisper_model_downloaded(model_name: str = DEFAULT_WHISPER_MODEL) ->
"path": str(target), "path": str(target),
"error": "", "error": "",
} }
def _resolve_whisper_device() -> str:
try:
torch_mod = _load_torch_module()
if torch_mod is not None and getattr(torch_mod.cuda, "is_available", lambda: False)():
return "cuda"
backends = getattr(torch_mod, "backends", None)
mps_backend = getattr(backends, "mps", None)
if mps_backend is not None and getattr(mps_backend, "is_available", lambda: False)():
return "mps"
except Exception:
pass
return "cpu"
def _resolve_ffmpeg_binary() -> Optional[str]:
candidate = os.getenv("HEIMGEIST_FFMPEG_PATH") or shutil.which("ffmpeg") or "/usr/bin/ffmpeg"
if not candidate:
return None
if Path(candidate).exists() or shutil.which(candidate):
return str(candidate)
return None
def _audio_suffix_for_mime_type(mime_type: str) -> str:
base_mime = str(mime_type or "").split(";", 1)[0].strip().lower()
return _AUDIO_SUFFIXES.get(base_mime, ".webm")
def _load_transcription_model(model_name: str = DEFAULT_WHISPER_MODEL) -> tuple[Any, str]:
error = whisper_runtime_error()
if error:
raise RuntimeError(error)
whisper_mod = _load_whisper_module()
if whisper_mod is None:
raise RuntimeError("Failed to import the Whisper runtime.")
ensure_whisper_model_downloaded(model_name)
device = _resolve_whisper_device()
cache_key = (model_name, device)
with _WHISPER_MODEL_LOCK:
model = _WHISPER_MODELS.get(cache_key)
if model is None:
try:
model = whisper_mod.load_model(model_name, device=device)
except TypeError:
model = whisper_mod.load_model(model_name)
_WHISPER_MODELS[cache_key] = model
return model, device
def _convert_audio_to_wav(input_path: Path, output_path: Path) -> None:
ffmpeg_bin = _resolve_ffmpeg_binary()
if not ffmpeg_bin:
raise RuntimeError(
"Audio transcription requires ffmpeg. Heimgeist could not resolve it from HEIMGEIST_FFMPEG_PATH or PATH."
)
process = subprocess.run(
[
ffmpeg_bin,
"-y",
"-hide_banner",
"-loglevel",
"error",
"-i",
str(input_path),
"-ac",
"1",
"-ar",
"16000",
"-f",
"wav",
str(output_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
if process.returncode != 0:
detail = (process.stderr or process.stdout or "ffmpeg audio conversion failed").strip()
raise RuntimeError(detail)
def transcribe_audio_bytes(
audio_bytes: bytes,
mime_type: str,
model_name: str = DEFAULT_WHISPER_MODEL,
language: Optional[str] = None,
) -> Dict[str, Any]:
if not audio_bytes:
raise RuntimeError("Recorded audio was empty.")
model, device = _load_transcription_model(model_name)
input_path = Path(tempfile.mkstemp(suffix=_audio_suffix_for_mime_type(mime_type))[1])
wav_path = Path(tempfile.mkstemp(suffix=".wav")[1])
try:
input_path.write_bytes(audio_bytes)
source_path = input_path
if input_path.suffix.lower() != ".wav":
_convert_audio_to_wav(input_path, wav_path)
source_path = wav_path
transcription_options = {
"task": "transcribe",
"fp16": device == "cuda",
}
if language:
transcription_options["language"] = str(language).strip().lower()
result = model.transcribe(str(source_path), **transcription_options)
return {
"model": model_name,
"device": device,
"language": str(result.get("language") or "").strip(),
"text": str(result.get("text") or "").strip(),
}
finally:
for path in (input_path, wav_path):
try:
if path.exists():
path.unlink()
except Exception:
pass

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

14
dist/index.html vendored
View File

@@ -1,14 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LLM Desktop</title>
<script type="module" crossorigin src="/assets/index-BRSJQ8EZ.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-D21amC2P.css">
</head>
<body>
<div id="root"></div>
</body>
</html>

90
docs/tauri-migration.md Normal file
View File

@@ -0,0 +1,90 @@
# Tauri Migration Notes
Tauri is now Heimgeist's active desktop shell for local development. The former desktop shell runtime files and npm scripts have been removed from active development code.
## Current Development Workflow
- Primary dev command: `npm run dev`.
- Compatibility alias: `npm run dev:tauri`.
- The dev wrapper is `scripts/run-tauri-dev.cjs`.
- The wrapper starts or reuses FastAPI on `127.0.0.1:8000`, waits for `/health`, then launches Tauri.
- The Vite renderer runs on strict port `127.0.0.1:5174`.
- `npm run dev:tauri:shell` launches raw `tauri dev` when the backend lifecycle is managed separately.
The development backend is still the normal FastAPI backend started from the repository root through `scripts/run-backend.cjs`.
## User Data Continuity
- Chats continue to use `backend/app.db` through the existing FastAPI backend.
- Local RAG libraries continue to use `backend/libraries` through the existing FastAPI backend.
- No database or library state is moved, rewritten, or migrated by the Tauri shell.
- `HEIMGEIST_SETTINGS_FILE` remains an explicit shared settings override. When set, Tauri reads and writes that file directly and skips first-run import.
- Without `HEIMGEIST_SETTINGS_FILE`, Tauri stores settings in its app config `settings.json`.
- On first Tauri run only, when the Tauri settings file does not exist, Tauri attempts to import the historical Electron settings file from the platform config directory, including `Heimgeist/settings.json`.
- Existing Tauri settings are never overwritten by imported settings.
## Packaged Backend Data Paths
The backend now centralizes runtime data paths in `backend/paths.py`.
- Development remains unchanged when no internal deployment hooks are set: chat data uses `backend/app.db` and local RAG data uses `backend/libraries`.
- Packaged Tauri builds launch the backend with an app-managed data root so the backend stores data under the OS-appropriate app data directory.
- The intended packaged locations are Application Support on macOS, LocalAppData on Windows, and the XDG data directory or `~/.local/share` equivalent on Linux.
- `HEIMGEIST_DATA_DIR`, `HEIMGEIST_DB_PATH`, and `HEIMGEIST_LIB_ROOT` are internal app/sidecar plumbing hooks for packaged launchers and developer verification. They are not user-facing settings.
- Packaging does not move or migrate existing development data.
## macOS Packaged App
The first local macOS `.app` flow is implemented.
- Packaging command: `npm run package:mac`.
- Sidecar build command: `npm run build:sidecar`.
- Output app: `src-tauri/target/release/bundle/macos/Heimgeist.app`.
- `backend/sidecar_main.py` starts Uvicorn for `backend.main:app` on `127.0.0.1:8000`.
- `scripts/build-backend-sidecar.cjs` uses `backend/.venv`, installs PyInstaller there if needed, detects the Rust host target triple, and writes Tauri external binaries under `src-tauri/binaries/`.
- `src-tauri/tauri.conf.json` bundles the backend sidecar plus ffmpeg/ffprobe helper binaries through `bundle.externalBin`.
- In release builds, `src-tauri/src/main.rs` starts the bundled sidecar when no compatible Heimgeist backend is already healthy on `127.0.0.1:8000`, waits for `/health`, and fails clearly if the port is occupied by a different service.
- The Tauri shell passes `HEIMGEIST_DATA_DIR` and `HEIMGEIST_SETTINGS_FILE` to the sidecar. ffmpeg and ffprobe paths are passed when the bundled helpers exist.
- The sidecar is stopped when the Tauri app exits.
Ollama remains an external service. SearXNG remains optional.
## Desktop Bridge Surface
Renderer code should continue to call only `src/desktop/desktopApi.js` for desktop functions. That bridge owns direct access to the Tauri global and maps the renderer API to Tauri commands/events.
Current Tauri-backed desktop methods:
- `getSettings`
- `setSetting`
- `updateSettings`
- `pickPaths`
- `openPath`
- `openExternalLink`
- `onWindowFocus`
- `offWindowFocus`
- `applyUiScale`
- update/changelog placeholders
## Historical Removal Notes
This pass removed the former Electron runtime and development entry points:
- `electron/main.cjs`
- `electron/preload.cjs`
- `scripts/run-electron-dev.cjs`
- Electron npm metadata, dependencies, and scripts from `package.json`
- Electron-specific branches from `src/desktop/desktopApi.js`
The only remaining Electron references should be historical migration documentation or the Tauri first-run settings import note.
## Remaining Production-Release Tasks
- Replace update/changelog placeholders with a signed Tauri update flow or another release strategy.
- Finalize signing and notarization for macOS distribution.
- Implement updater/changelog parity or decide on a different release strategy.
- Add full Windows/Linux sidecar and bundle scripts, including platform-specific helper binaries and process shutdown behavior.
- Polish installer behavior and final bundle metadata/icons.
- Audit the PyInstaller sidecar contents and size before public release.
- Decide whether the settings route needs a dedicated Tauri window for production parity.
- Expand the basic Tauri menu if product-specific app menu actions are needed.

View File

@@ -1,528 +0,0 @@
const { app, BrowserWindow, Menu, dialog, ipcMain, shell } = require('electron')
const path = require('path')
const { is } = require('@electron-toolkit/utils')
const fs = require('fs')
const { execFile } = require('child_process')
const { promisify } = require('util')
let mainWindow
let settingsWindow = null
const execFileAsync = promisify(execFile)
const DEFAULT_BACKEND_API_URL = 'http://127.0.0.1:8000'
const DEFAULT_OLLAMA_API_URL = 'http://127.0.0.1:11434'
const DEFAULT_EMBED_MODEL = 'nomic-embed-text:latest'
const BGE_EMBED_MODEL = 'bge-m3:latest'
const REPO_ROOT = path.resolve(__dirname, '..')
const UPDATE_REMOTE_URL = 'https://giers10.uber.space/giers10/Heimgeist.git'
const UPDATE_BRANCH = 'master'
const GIT_ENV = { ...process.env, GIT_TERMINAL_PROMPT: '0' }
const DEV_WRAPPER_RELAUNCH_CODE = Number(process.env.HEIMGEIST_DEV_RELAUNCH_CODE || 75)
const settingsFilePath = process.env.HEIMGEIST_SETTINGS_FILE || path.join(app.getPath('userData'), 'settings.json')
let appSettings = {}
let lastUpdateCheckResult = null
let activeUpdateCheck = null
const DEFAULT_UI_SCALE = 1
const MIN_UI_SCALE = 0.7
const MAX_UI_SCALE = 1.3
const defaultSettings = {
backendApiUrl: DEFAULT_BACKEND_API_URL,
ollamaApiUrl: DEFAULT_OLLAMA_API_URL,
embedModel: DEFAULT_EMBED_MODEL,
colorScheme: 'Default',
uiScale: DEFAULT_UI_SCALE,
chatModel: 'llama3',
}
function normalizeEmbedModel(value) {
const trimmed = String(value || '').trim().toLowerCase()
if (trimmed === 'bge' || trimmed === 'bge-m3' || trimmed === BGE_EMBED_MODEL) {
return BGE_EMBED_MODEL
}
return DEFAULT_EMBED_MODEL
}
function looksLikeOllamaUrl(value) {
if (typeof value !== 'string') {
return false
}
try {
const parsed = new URL(value)
if (parsed.port === '11434') {
return true
}
return /^\/api\/?$/i.test(parsed.pathname || '')
} catch (_error) {
return false
}
}
function migrateSettings(rawSettings) {
const source = rawSettings && typeof rawSettings === 'object' ? rawSettings : {}
const nextSettings = { ...defaultSettings, ...source }
let migrated = false
if (!Object.prototype.hasOwnProperty.call(source, 'backendApiUrl') && typeof source.ollamaApiUrl === 'string') {
if (looksLikeOllamaUrl(source.ollamaApiUrl)) {
nextSettings.backendApiUrl = DEFAULT_BACKEND_API_URL
nextSettings.ollamaApiUrl = source.ollamaApiUrl
} else {
nextSettings.backendApiUrl = source.ollamaApiUrl
nextSettings.ollamaApiUrl = DEFAULT_OLLAMA_API_URL
}
migrated = true
}
nextSettings.backendApiUrl = String(nextSettings.backendApiUrl || '').trim()
nextSettings.ollamaApiUrl = String(nextSettings.ollamaApiUrl || '').trim()
nextSettings.embedModel = normalizeEmbedModel(nextSettings.embedModel)
return { nextSettings, migrated }
}
function normalizeUiScale(value) {
const numericValue = Number(value)
if (!Number.isFinite(numericValue)) {
return DEFAULT_UI_SCALE
}
return Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, Math.round(numericValue * 100) / 100))
}
function applyUiScaleToWindow(window) {
if (!window || window.isDestroyed()) {
return
}
window.webContents.setZoomFactor(normalizeUiScale(appSettings.uiScale))
}
function applyUiScaleToAllWindows() {
BrowserWindow.getAllWindows().forEach(applyUiScaleToWindow)
}
function loadSettings() {
try {
if (fs.existsSync(settingsFilePath)) {
const data = fs.readFileSync(settingsFilePath, 'utf8')
const { nextSettings, migrated } = migrateSettings(JSON.parse(data))
appSettings = nextSettings
if (migrated) {
saveSettings()
}
} else {
appSettings = { ...defaultSettings }
saveSettings()
}
appSettings.uiScale = normalizeUiScale(appSettings.uiScale)
} catch (error) {
console.error('Failed to load settings:', error)
appSettings = { ...defaultSettings }
}
}
function saveSettings() {
try {
fs.mkdirSync(path.dirname(settingsFilePath), { recursive: true })
fs.writeFileSync(settingsFilePath, JSON.stringify(appSettings, null, 2), 'utf8')
} catch (error) {
console.error('Failed to save settings:', error)
}
}
function setUpdateStatus(status) {
lastUpdateCheckResult = {
state: 'idle',
message: '',
checkedAt: new Date().toISOString(),
localCommit: null,
remoteCommit: null,
branch: null,
restartScheduled: false,
...status,
}
return lastUpdateCheckResult
}
async function runGitCommand(args, options = {}) {
return execFileAsync('git', ['-C', REPO_ROOT, ...args], {
env: GIT_ENV,
maxBuffer: 1024 * 1024,
timeout: options.timeout ?? 15000,
})
}
function scheduleAppRestart() {
setTimeout(() => {
if (process.env.HEIMGEIST_DEV_WRAPPER === '1') {
app.exit(DEV_WRAPPER_RELAUNCH_CODE)
return
}
app.relaunch()
app.exit(0)
}, 300)
}
function parseGitStatusPaths(statusOutput) {
return statusOutput
.split('\n')
.map((line) => line.trimEnd())
.filter(Boolean)
.map((line) => line.slice(3).trim())
}
function formatChangedPaths(paths) {
if (!Array.isArray(paths) || paths.length === 0) {
return ''
}
const preview = paths.slice(0, 3).join(', ')
return paths.length > 3 ? `${preview}, ...` : preview
}
async function performUpdateCheck(trigger = 'manual') {
if (!fs.existsSync(path.join(REPO_ROOT, '.git'))) {
return setUpdateStatus({
state: 'unavailable',
trigger,
message: 'Update check unavailable: no Git checkout found.',
})
}
setUpdateStatus({
state: 'checking',
trigger,
message: 'Checking remote repository for updates...',
})
try {
const [
{ stdout: localStdout },
{ stdout: branchStdout },
{ stdout: remoteStdout },
{ stdout: worktreeStdout },
] = await Promise.all([
runGitCommand(['rev-parse', 'HEAD']),
runGitCommand(['branch', '--show-current']),
runGitCommand(['ls-remote', UPDATE_REMOTE_URL, `refs/heads/${UPDATE_BRANCH}`]),
runGitCommand(['status', '--porcelain', '--untracked-files=no']),
])
const localCommit = localStdout.trim()
const branch = branchStdout.trim() || null
const remoteCommit = remoteStdout.trim().split(/\s+/)[0] || null
const changedPaths = parseGitStatusPaths(worktreeStdout)
const worktreeDirty = changedPaths.length > 0
if (!localCommit) {
throw new Error('Could not resolve the current local commit hash.')
}
if (!remoteCommit) {
throw new Error(`Could not resolve the remote ${UPDATE_BRANCH} commit hash.`)
}
if (localCommit === remoteCommit) {
return setUpdateStatus({
state: 'up-to-date',
trigger,
branch,
localCommit,
remoteCommit,
message: 'Heimgeist is already up to date.',
})
}
if (branch && branch !== UPDATE_BRANCH) {
return setUpdateStatus({
state: 'skipped',
trigger,
branch,
localCommit,
remoteCommit,
message: `Update skipped: current branch is "${branch}", expected "${UPDATE_BRANCH}".`,
})
}
if (worktreeDirty) {
const changedPathSummary = formatChangedPaths(changedPaths)
return setUpdateStatus({
state: 'skipped',
trigger,
branch: branch || UPDATE_BRANCH,
localCommit,
remoteCommit,
message: changedPathSummary
? `Update skipped: tracked local changes detected in ${changedPathSummary}.`
: 'Update skipped: tracked local changes detected.',
})
}
setUpdateStatus({
state: 'updating',
trigger,
branch: branch || UPDATE_BRANCH,
localCommit,
remoteCommit,
message: 'Update found. Pulling latest changes and restarting Heimgeist...',
})
await runGitCommand(['pull', '--ff-only', UPDATE_REMOTE_URL, UPDATE_BRANCH], { timeout: 120000 })
const { stdout: updatedStdout } = await runGitCommand(['rev-parse', 'HEAD'])
const updatedLocalCommit = updatedStdout.trim()
if (!updatedLocalCommit || updatedLocalCommit === localCommit) {
return setUpdateStatus({
state: 'up-to-date',
trigger,
branch: branch || UPDATE_BRANCH,
localCommit,
remoteCommit,
message: 'No newer remote update was applied. Local checkout already contains the latest pulled state.',
})
}
const result = setUpdateStatus({
state: 'updated',
trigger,
branch: branch || UPDATE_BRANCH,
localCommit: updatedLocalCommit || localCommit,
remoteCommit,
message: 'Update installed. Heimgeist restarts now.',
restartScheduled: true,
})
scheduleAppRestart()
return result
} catch (error) {
console.error('Failed to check for updates:', error)
return setUpdateStatus({
state: 'error',
trigger,
message: `Update check failed: ${error.message || String(error)}`,
})
}
}
function checkForUpdates(trigger = 'manual') {
if (!activeUpdateCheck) {
activeUpdateCheck = performUpdateCheck(trigger).finally(() => {
activeUpdateCheck = null
})
}
return activeUpdateCheck
}
async function createMainWindow() {
console.log('Electron: creating main window')
mainWindow = new BrowserWindow({
width: 1000,
height: 720,
minWidth: 680,
minHeight: 300,
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
},
})
applyUiScaleToWindow(mainWindow)
mainWindow.on('ready-to-show', () => {
mainWindow.show()
})
mainWindow.webContents.on('did-finish-load', () => {
applyUiScaleToWindow(mainWindow)
})
mainWindow.webContents.on('did-fail-load', (_event, errorCode, errorDescription, validatedURL) => {
console.error('Main window failed to load:', { errorCode, errorDescription, validatedURL })
})
mainWindow.on('focus', () => {
mainWindow.webContents.send('window-focused')
})
if (is.dev && process.env.VITE_DEV_SERVER_URL) {
console.log(`Electron: loading renderer ${process.env.VITE_DEV_SERVER_URL}`)
await mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
mainWindow.webContents.openDevTools({ mode: 'detach' })
} else {
console.log('Electron: loading bundled renderer')
await mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
}
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url)
return { action: 'deny' }
})
}
async function createSettingsWindow() {
if (settingsWindow) {
settingsWindow.focus()
return
}
settingsWindow = new BrowserWindow({
width: 800,
height: 600,
title: 'Settings',
parent: mainWindow,
modal: true,
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
},
})
applyUiScaleToWindow(settingsWindow)
settingsWindow.on('ready-to-show', () => {
settingsWindow.show()
})
settingsWindow.webContents.on('did-finish-load', () => {
applyUiScaleToWindow(settingsWindow)
})
settingsWindow.webContents.on('did-fail-load', (_event, errorCode, errorDescription, validatedURL) => {
console.error('Settings window failed to load:', { errorCode, errorDescription, validatedURL })
})
settingsWindow.on('closed', () => {
settingsWindow = null
})
if (is.dev && process.env.VITE_DEV_SERVER_URL) {
await settingsWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}#/settings`)
settingsWindow.webContents.openDevTools({ mode: 'detach' })
} else {
await settingsWindow.loadFile(path.join(__dirname, '../dist/index.html'), { hash: '/settings' })
}
}
app.whenReady().then(async () => {
console.log('Electron: app ready')
loadSettings()
const startupUpdateResult = await checkForUpdates('startup')
if (startupUpdateResult?.restartScheduled) {
return
}
await createMainWindow()
const menuTemplate = [
{
label: 'File',
submenu: [
{
label: 'Settings',
accelerator: 'CmdOrCtrl+,',
click: createSettingsWindow,
},
{ type: 'separator' },
{ role: 'quit' },
],
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'delete' },
{ type: 'separator' },
{ role: 'selectAll' },
],
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forcereload' },
{ role: 'toggledevtools' },
{ type: 'separator' },
{ role: 'resetzoom' },
{ role: 'zoomin' },
{ role: 'zoomout' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
},
]
const menu = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(menu)
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
})
})
ipcMain.handle('get-settings', () => appSettings)
ipcMain.handle('get-update-status', () => lastUpdateCheckResult)
ipcMain.handle('check-for-updates', () => checkForUpdates('manual'))
ipcMain.handle('set-setting', (event, key, value) => {
if (key === 'uiScale') {
appSettings[key] = normalizeUiScale(value)
} else if (key === 'embedModel') {
appSettings[key] = normalizeEmbedModel(value)
} else {
appSettings[key] = value
}
saveSettings()
if (key === 'uiScale') {
applyUiScaleToAllWindows()
}
return true
})
ipcMain.handle('update-settings', (event, settings) => {
appSettings = { ...appSettings, ...settings }
appSettings.uiScale = normalizeUiScale(appSettings.uiScale)
appSettings.embedModel = normalizeEmbedModel(appSettings.embedModel)
saveSettings()
if (Object.prototype.hasOwnProperty.call(settings, 'uiScale')) {
applyUiScaleToAllWindows()
}
return true
})
ipcMain.handle('pick-paths', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile', 'multiSelections'],
})
return result.canceled ? [] : result.filePaths
})
ipcMain.handle('open-path', async (event, filePath) => {
if (!filePath) return false
const err = await shell.openPath(filePath)
return err === ''
})
ipcMain.on('open-external-link', (event, url) => {
shell.openExternal(url)
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})

View File

@@ -1,19 +0,0 @@
const { contextBridge, ipcRenderer } = require('electron')
// Expose a secure API to the renderer process
contextBridge.exposeInMainWorld('electronAPI', {
getSettings: () => ipcRenderer.invoke('get-settings'),
getUpdateStatus: () => ipcRenderer.invoke('get-update-status'),
checkForUpdates: () => ipcRenderer.invoke('check-for-updates'),
setSetting: (key, value) => ipcRenderer.invoke('set-setting', key, value),
updateSettings: (settings) => ipcRenderer.invoke('update-settings', settings),
pickPaths: () => ipcRenderer.invoke('pick-paths'),
openPath: (filePath) => ipcRenderer.invoke('open-path', filePath),
openExternalLink: (event) => {
event.preventDefault();
const url = event.currentTarget.href;
ipcRenderer.send('open-external-link', url);
},
onWindowFocus: (callback) => ipcRenderer.on('window-focused', callback)
})

View File

@@ -2,18 +2,22 @@
"name": "Heimgeist", "name": "Heimgeist",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"main": "electron/main.cjs",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "concurrently -k \"npm:dev:backend\" \"npm:dev:renderer\" \"npm:dev:electron\"", "dev": "node scripts/run-tauri-dev.cjs",
"dev:tauri": "node scripts/run-tauri-dev.cjs",
"dev:backend": "node scripts/run-backend.cjs", "dev:backend": "node scripts/run-backend.cjs",
"dev:renderer": "vite --port 5173 --strictPort", "dev:renderer": "vite --host 127.0.0.1 --port 5174 --strictPort",
"dev:electron": "node scripts/run-electron-dev.cjs", "dev:tauri:shell": "tauri dev",
"tauri": "tauri",
"build": "vite build", "build": "vite build",
"start": "electron ." "build:sidecar": "node scripts/build-backend-sidecar.cjs",
"package:mac": "npm run build:sidecar && tauri build --bundles app",
"build:app": "npm run package:mac",
"start": "npm run dev"
}, },
"dependencies": { "dependencies": {
"@electron-toolkit/utils": "^4.0.0", "@xyflow/react": "^12.11.0",
"ffmpeg-static": "^5.3.0", "ffmpeg-static": "^5.3.0",
"ffprobe-static": "^3.1.0", "ffprobe-static": "^3.1.0",
"react": "^18.3.1", "react": "^18.3.1",
@@ -22,10 +26,8 @@
"react-textarea-autosize": "^8.5.9" "react-textarea-autosize": "^8.5.9"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2.11.0",
"@vitejs/plugin-react": "^4.3.1", "@vitejs/plugin-react": "^4.3.1",
"concurrently": "^9.0.1",
"cross-env": "^7.0.3",
"electron": "^31.2.0",
"vite": "^5.4.2", "vite": "^5.4.2",
"wait-on": "^7.2.0" "wait-on": "^7.2.0"
} }

528
run.sh
View File

@@ -1,15 +1,508 @@
#!/bin/sh #!/bin/sh
set -eu set -eu
SCRIPT_DIR="$(CDPATH= cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"
PYTHON_BIN_WAS_SET=0
if [ -n "${PYTHON_BIN:-}" ]; then
PYTHON_BIN_WAS_SET=1
fi
PYTHON_BIN="${PYTHON_BIN:-python3.13}" PYTHON_BIN="${PYTHON_BIN:-python3.13}"
VENV_DIR="backend/.venv" VENV_DIR="backend/.venv"
TORCH_FLAVOR_FILE="$VENV_DIR/.heimgeist-torch-flavor" TORCH_FLAVOR_FILE="$VENV_DIR/.heimgeist-torch-flavor"
TORCH_STATE_FILE="$VENV_DIR/.heimgeist-torch-state" TORCH_STATE_FILE="$VENV_DIR/.heimgeist-torch-state"
PYTHON_DEPS_STATE_FILE="$VENV_DIR/.heimgeist-python-deps-state" PYTHON_DEPS_STATE_FILE="$VENV_DIR/.heimgeist-python-deps-state"
NODE_DEPS_STATE_FILE="node_modules/.heimgeist-node-deps-state" NODE_DEPS_STATE_FILE="node_modules/.heimgeist-node-deps-state"
HEIMGEIST_NODE_MAJOR="${HEIMGEIST_NODE_MAJOR:-22}"
HEIMGEIST_NODE_DIR="${HEIMGEIST_NODE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/heimgeist/node-v$HEIMGEIST_NODE_MAJOR}"
HEIMGEIST_TOOL_BIN_DIR="${HEIMGEIST_TOOL_BIN_DIR:-$HOME/.local/bin}"
HEIMGEIST_SKIP_SYSTEM_DEPS="${HEIMGEIST_SKIP_SYSTEM_DEPS:-0}"
HEIMGEIST_STRICT_SYSTEM_DEPS="${HEIMGEIST_STRICT_SYSTEM_DEPS:-0}"
HEIMGEIST_BOOTSTRAP_ONLY="${HEIMGEIST_BOOTSTRAP_ONLY:-0}"
HEIMGEIST_STEAMOS_DEVMODE="${HEIMGEIST_STEAMOS_DEVMODE:-auto}"
HEIMGEIST_TORCH_FLAVOR="${HEIMGEIST_TORCH_FLAVOR:-auto}" HEIMGEIST_TORCH_FLAVOR="${HEIMGEIST_TORCH_FLAVOR:-auto}"
HEIMGEIST_TORCH_INDEX_URL="${HEIMGEIST_TORCH_INDEX_URL:-}" HEIMGEIST_TORCH_INDEX_URL="${HEIMGEIST_TORCH_INDEX_URL:-}"
HEIMGEIST_FORCE_BOOTSTRAP="${HEIMGEIST_FORCE_BOOTSTRAP:-0}" HEIMGEIST_FORCE_BOOTSTRAP="${HEIMGEIST_FORCE_BOOTSTRAP:-0}"
CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}"
PATH="$HEIMGEIST_TOOL_BIN_DIR:$CARGO_HOME/bin:$PATH"
export CARGO_HOME RUSTUP_HOME PATH
as_root() {
if [ "$(id -u)" -eq 0 ]; then
"$@"
return
fi
if ! command -v sudo >/dev/null 2>&1; then
echo "Installing native build dependencies requires root access, but sudo is unavailable." >&2
exit 1
fi
if ! sudo -v; then
if is_steamos; then
echo "SteamOS needs a local user password for sudo. Run 'passwd', then rerun ./run.sh." >&2
fi
exit 1
fi
sudo "$@"
}
is_steamos() {
[ -r /etc/os-release ] \
&& grep -Eiq '(^ID=steamos$|^NAME=.*SteamOS|^PRETTY_NAME=.*SteamOS)' /etc/os-release
}
linux_native_deps_usable() {
command -v cc >/dev/null 2>&1 \
&& command -v file >/dev/null 2>&1 \
&& command -v pkg-config >/dev/null 2>&1 \
&& pkg-config --exists webkit2gtk-4.1 gtk+-3.0 openssl librsvg-2.0
}
print_native_dependency_report() {
echo "Native dependency preflight report:" >&2
for command_name in cc file pkg-config; do
if command -v "$command_name" >/dev/null 2>&1; then
echo " ok: command '$command_name' -> $(command -v "$command_name")" >&2
else
echo " missing: command '$command_name'" >&2
fi
done
if ! command -v pkg-config >/dev/null 2>&1; then
return
fi
for pkg_config_name in webkit2gtk-4.1 gtk+-3.0 openssl librsvg-2.0; do
if pkg-config --exists "$pkg_config_name"; then
pkg_config_version="$(pkg-config --modversion "$pkg_config_name" 2>/dev/null || true)"
echo " ok: pkg-config '$pkg_config_name' ${pkg_config_version}" >&2
else
echo " missing: pkg-config '$pkg_config_name'" >&2
fi
done
}
handle_incomplete_native_dependencies() {
echo "The native Tauri dependency preflight is still incomplete after package installation." >&2
print_native_dependency_report
if [ "$HEIMGEIST_STRICT_SYSTEM_DEPS" = "1" ]; then
exit 1
fi
echo "Continuing because the package manager reported success." >&2
echo "If the Tauri build still fails, rerun with HEIMGEIST_STRICT_SYSTEM_DEPS=1 for a hard preflight failure." >&2
}
STEAMOS_RESTORE_READONLY=0
restore_steamos_readonly() {
if [ "$STEAMOS_RESTORE_READONLY" -eq 1 ]; then
echo "Re-enabling the SteamOS read-only filesystem"
as_root steamos-readonly enable
STEAMOS_RESTORE_READONLY=0
fi
}
prepare_steamos_package_install() {
if ! is_steamos || ! command -v steamos-readonly >/dev/null 2>&1; then
return
fi
readonly_status="$(as_root steamos-readonly status || true)"
if printf '%s\n' "$readonly_status" | grep -Eqi '(^|[[:space:]])enable(d)?($|[[:space:]])'; then
echo "Temporarily disabling the SteamOS read-only filesystem"
as_root steamos-readonly disable
STEAMOS_RESTORE_READONLY=1
fi
}
pacman_keyring_names() {
for keyring_file in /usr/share/pacman/keyrings/*.gpg; do
[ -e "$keyring_file" ] || continue
keyring_name="$(basename "$keyring_file" .gpg)"
printf ' %s' "$keyring_name"
done
}
ensure_steamos_pacman_keyring() {
if ! is_steamos; then
return
fi
if ! command -v pacman-key >/dev/null 2>&1; then
echo "SteamOS package signing cannot be repaired because pacman-key is unavailable." >&2
exit 1
fi
echo "Initializing and populating the SteamOS pacman keyring"
as_root pacman-key --init
keyring_names="$(pacman_keyring_names)"
if [ -n "$keyring_names" ]; then
# shellcheck disable=SC2086
as_root pacman-key --populate $keyring_names
else
as_root pacman-key --populate
fi
}
run_steamos_devmode_bootstrap() {
if ! is_steamos || [ "$HEIMGEIST_STEAMOS_DEVMODE" = "0" ]; then
return 1
fi
if ! command -v steamos-devmode >/dev/null 2>&1; then
return 1
fi
echo "Pacman still cannot install packages; running SteamOS devmode bootstrap"
as_root steamos-devmode enable
}
install_pacman_packages() {
if as_root pacman "$@"; then
return
fi
if ! is_steamos; then
return 1
fi
echo "Pacman failed on SteamOS. Refreshing package-signing trust and retrying once."
ensure_steamos_pacman_keyring
if as_root pacman "$@"; then
return
fi
if run_steamos_devmode_bootstrap && as_root pacman "$@"; then
return
fi
echo "SteamOS pacman package installation still failed." >&2
echo "This is usually a broken SteamOS pacman keyring, not a corrupt Heimgeist download." >&2
echo "Try running 'sudo steamos-devmode enable' manually, then rerun ./run.sh." >&2
return 1
}
install_arch_native_deps() {
set -- \
webkit2gtk-4.1 \
base-devel \
pkgconf \
gtk3 \
curl \
wget \
file \
openssl \
appmenu-gtk-module \
libappindicator-gtk3 \
librsvg \
xdotool
missing_packages=""
for package_name in "$@"; do
if ! pacman -Q "$package_name" >/dev/null 2>&1; then
missing_packages="$missing_packages $package_name"
fi
done
if [ -z "$missing_packages" ]; then
return
fi
echo "Installing missing Tauri/Arch packages:$missing_packages"
echo "SteamOS/Arch may ask for your sudo password."
prepare_steamos_package_install
trap 'restore_steamos_readonly' EXIT
trap 'restore_steamos_readonly; exit 130' HUP INT TERM
ensure_steamos_pacman_keyring
install_status=0
if is_steamos; then
# SteamOS system updates own the base image, so only install missing packages.
install_pacman_packages -S --needed --noconfirm $missing_packages || install_status=$?
else
# Arch requires a full upgrade when synchronizing/installing packages.
install_pacman_packages -Syu --needed --noconfirm $missing_packages || install_status=$?
fi
restore_steamos_readonly
trap - EXIT HUP INT TERM
return "$install_status"
}
install_debian_native_deps() {
set -- \
libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libxdo-dev \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev \
pkg-config
missing_packages=""
for package_name in "$@"; do
if ! dpkg-query -W -f='${Status}' "$package_name" 2>/dev/null | grep -q 'ok installed'; then
missing_packages="$missing_packages $package_name"
fi
done
if [ -z "$missing_packages" ]; then
return
fi
echo "Installing missing Tauri/Debian packages:$missing_packages"
as_root apt-get update
as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y $missing_packages
}
ensure_native_build_dependencies() {
if [ "$HEIMGEIST_SKIP_SYSTEM_DEPS" = "1" ]; then
return
fi
case "$(uname -s)" in
Darwin)
if ! xcode-select -p >/dev/null 2>&1; then
echo "Installing the Xcode Command Line Tools required by Tauri."
xcode-select --install || true
echo "Complete the Xcode Command Line Tools installation, then run ./run.sh again." >&2
exit 1
fi
;;
Linux)
if linux_native_deps_usable; then
return
fi
if command -v pacman >/dev/null 2>&1; then
install_arch_native_deps
elif command -v apt-get >/dev/null 2>&1 && command -v dpkg-query >/dev/null 2>&1; then
install_debian_native_deps
else
echo "Native dependency installation currently supports Arch/SteamOS and Debian/Ubuntu." >&2
echo "Install your distribution's Tauri 2 system prerequisites, then run ./run.sh again." >&2
exit 1
fi
if ! linux_native_deps_usable; then
handle_incomplete_native_dependencies
fi
;;
esac
}
node_runtime_usable() {
command -v node >/dev/null 2>&1 \
&& command -v npm >/dev/null 2>&1 \
&& node -e 'const major = Number(process.versions.node.split(".")[0]); process.exit(major >= 18 ? 0 : 1)' >/dev/null 2>&1
}
download_file() {
download_url="$1"
download_target="$2"
if command -v curl >/dev/null 2>&1; then
curl --fail --location --silent --show-error "$download_url" --output "$download_target"
return
fi
if command -v wget >/dev/null 2>&1; then
wget --quiet --output-document="$download_target" "$download_url"
return
fi
echo "A required tool is missing and neither curl nor wget is available to download it." >&2
echo "Install curl or wget, then run ./run.sh again." >&2
exit 1
}
file_sha256() {
checksum_file="$1"
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$checksum_file" | awk '{print $1}'
return
fi
if command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$checksum_file" | awk '{print $1}'
return
fi
echo "Cannot verify the Node.js download because sha256sum/shasum is unavailable." >&2
exit 1
}
install_uv() {
uv_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimgeist-uv.XXXXXX")"
trap 'rm -rf "$uv_tmp_dir"' EXIT HUP INT TERM
echo "Python 3.13 is missing; installing the uv runtime manager locally"
download_file "https://astral.sh/uv/install.sh" "$uv_tmp_dir/install.sh"
mkdir -p "$HEIMGEIST_TOOL_BIN_DIR"
UV_UNMANAGED_INSTALL="$HEIMGEIST_TOOL_BIN_DIR" UV_NO_MODIFY_PATH=1 sh "$uv_tmp_dir/install.sh"
rm -rf "$uv_tmp_dir"
trap - EXIT HUP INT TERM
}
ensure_uv() {
if command -v uv >/dev/null 2>&1; then
return
fi
install_uv
if ! command -v uv >/dev/null 2>&1; then
echo "The local uv installation did not provide an executable." >&2
exit 1
fi
}
python_runtime_usable() {
command -v "$PYTHON_BIN" >/dev/null 2>&1 \
&& "$PYTHON_BIN" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 13) else 1)' >/dev/null 2>&1
}
ensure_python_runtime() {
if python_runtime_usable; then
return
fi
if [ "$PYTHON_BIN_WAS_SET" -eq 1 ]; then
echo "PYTHON_BIN '$PYTHON_BIN' is unavailable or is not Python 3.13." >&2
exit 1
fi
ensure_uv
echo "Installing Python 3.13 locally"
uv python install 3.13
PYTHON_BIN="$(uv python find 3.13)"
if ! python_runtime_usable; then
echo "The local Python 3.13 installation is incomplete." >&2
exit 1
fi
}
rust_runtime_usable() {
command -v cargo >/dev/null 2>&1 \
&& command -v rustc >/dev/null 2>&1 \
&& rustc --version | awk '
{
split($2, version, ".")
exit !((version[1] > 1) || (version[1] == 1 && version[2] >= 77))
}
'
}
install_rustup() {
rustup_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimgeist-rustup.XXXXXX")"
trap 'rm -rf "$rustup_tmp_dir"' EXIT HUP INT TERM
echo "Rust/Cargo 1.77+ was not found; installing the stable Rust toolchain locally"
download_file "https://sh.rustup.rs" "$rustup_tmp_dir/rustup-init.sh"
sh "$rustup_tmp_dir/rustup-init.sh" -y --profile minimal --default-toolchain stable --no-modify-path
rm -rf "$rustup_tmp_dir"
trap - EXIT HUP INT TERM
}
ensure_rust_runtime() {
if rust_runtime_usable; then
return
fi
if command -v rustup >/dev/null 2>&1; then
echo "Installing/updating the stable Rust toolchain"
rustup toolchain install stable --profile minimal
rustup default stable
else
install_rustup
fi
if ! rust_runtime_usable; then
echo "The Rust installation is incomplete; cargo and rustc 1.77+ are required." >&2
exit 1
fi
}
install_project_node() {
case "$(uname -s)" in
Linux) node_platform="linux" ;;
Darwin) node_platform="darwin" ;;
*)
echo "Automatic Node.js installation is only supported on Linux and macOS." >&2
echo "Install Node.js 18+ and npm, then run ./run.sh again." >&2
exit 1
;;
esac
case "$(uname -m)" in
x86_64|amd64) node_arch="x64" ;;
arm64|aarch64) node_arch="arm64" ;;
*)
echo "Automatic Node.js installation does not support architecture $(uname -m)." >&2
echo "Install Node.js 18+ and npm, then run ./run.sh again." >&2
exit 1
;;
esac
node_release_url="https://nodejs.org/dist/latest-v$HEIMGEIST_NODE_MAJOR.x"
node_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimgeist-node.XXXXXX")"
trap 'rm -rf "$node_tmp_dir"' EXIT HUP INT TERM
echo "Node.js 18+ with npm was not found; installing Node.js v$HEIMGEIST_NODE_MAJOR locally"
download_file "$node_release_url/SHASUMS256.txt" "$node_tmp_dir/SHASUMS256.txt"
node_archive="$(awk -v suffix="-$node_platform-$node_arch.tar.xz" '
length($2) >= length(suffix) && substr($2, length($2) - length(suffix) + 1) == suffix {
print $2
exit
}
' "$node_tmp_dir/SHASUMS256.txt")"
if [ -z "$node_archive" ]; then
echo "No Node.js v$HEIMGEIST_NODE_MAJOR archive is available for $node_platform-$node_arch." >&2
exit 1
fi
expected_sha256="$(awk -v archive="$node_archive" '$2 == archive {print $1; exit}' "$node_tmp_dir/SHASUMS256.txt")"
download_file "$node_release_url/$node_archive" "$node_tmp_dir/$node_archive"
actual_sha256="$(file_sha256 "$node_tmp_dir/$node_archive")"
if [ "$actual_sha256" != "$expected_sha256" ]; then
echo "Node.js download checksum verification failed." >&2
exit 1
fi
tar -xJf "$node_tmp_dir/$node_archive" -C "$node_tmp_dir"
mkdir -p "$(dirname "$HEIMGEIST_NODE_DIR")"
rm -rf "$HEIMGEIST_NODE_DIR"
mv "$node_tmp_dir/${node_archive%.tar.xz}" "$HEIMGEIST_NODE_DIR"
rm -rf "$node_tmp_dir"
trap - EXIT HUP INT TERM
}
ensure_node_runtime() {
if node_runtime_usable; then
return
fi
if [ -x "$HEIMGEIST_NODE_DIR/bin/node" ] && [ -x "$HEIMGEIST_NODE_DIR/bin/npm" ]; then
original_path="$PATH"
PATH="$HEIMGEIST_NODE_DIR/bin:$PATH"
export PATH
if node_runtime_usable; then
return
fi
PATH="$original_path"
export PATH
fi
install_project_node
PATH="$HEIMGEIST_NODE_DIR/bin:$PATH"
export PATH
if ! node_runtime_usable; then
echo "The local Node.js installation is incomplete or older than version 18." >&2
exit 1
fi
}
manifest_state() { manifest_state() {
for manifest_path in "$@"; do for manifest_path in "$@"; do
@@ -64,12 +557,15 @@ PY
node_deps_usable() { node_deps_usable() {
node - <<'NODE' >/dev/null 2>&1 node - <<'NODE' >/dev/null 2>&1
require('concurrently')
require('electron')
require('react') require('react')
require('vite') require('vite')
require('wait-on') require('wait-on')
NODE NODE
if [ "$?" -ne 0 ]; then
return 1
fi
[ -x node_modules/.bin/tauri ] || [ -x node_modules/.bin/tauri.cmd ]
} }
is_linux_x86_64() { is_linux_x86_64() {
@@ -161,29 +657,14 @@ install_selected_torch() {
esac esac
} }
if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then ensure_native_build_dependencies
echo "Python 3.13 is required. Set PYTHON_BIN to a Python 3.13 executable if needed." >&2 ensure_node_runtime
exit 1 ensure_python_runtime
fi ensure_rust_runtime
TORCH_FLAVOR="$(resolve_torch_flavor)" TORCH_FLAVOR="$(resolve_torch_flavor)"
RECREATE_VENV=0 RECREATE_VENV=0
if [ -z "${HEIMGEIST_SETTINGS_FILE:-}" ]; then
case "$(uname -s)" in
Darwin)
HEIMGEIST_SETTINGS_FILE="${HOME}/Library/Application Support/Heimgeist/settings.json"
;;
Linux)
HEIMGEIST_SETTINGS_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/Heimgeist/settings.json"
;;
esac
if [ -n "${HEIMGEIST_SETTINGS_FILE:-}" ]; then
export HEIMGEIST_SETTINGS_FILE
mkdir -p "$(dirname "$HEIMGEIST_SETTINGS_FILE")"
fi
fi
if [ ! -x "$VENV_DIR/bin/python" ] || ! "$VENV_DIR/bin/python" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 13) else 1)'; then if [ ! -x "$VENV_DIR/bin/python" ] || ! "$VENV_DIR/bin/python" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 13) else 1)'; then
RECREATE_VENV=1 RECREATE_VENV=1
fi fi
@@ -274,4 +755,9 @@ if [ "$NEED_NODE_DEPS_INSTALL" -eq 1 ]; then
write_state "$NODE_DEPS_STATE_FILE" package.json package-lock.json write_state "$NODE_DEPS_STATE_FILE" package.json package-lock.json
fi fi
if [ "$HEIMGEIST_BOOTSTRAP_ONLY" = "1" ]; then
echo "Heimgeist development dependencies are ready."
exit 0
fi
npm run dev npm run dev

View File

@@ -0,0 +1,178 @@
const { execFileSync, spawnSync } = require('child_process')
const fs = require('fs')
const path = require('path')
const projectRoot = path.resolve(__dirname, '..')
const pythonBin = path.join(projectRoot, 'backend', '.venv', 'bin', 'python')
const binariesDir = path.join(projectRoot, 'src-tauri', 'binaries')
const targetTriple = resolveTargetTriple()
const executableExtension = process.platform === 'win32' ? '.exe' : ''
const backendOutputName = `heimgeist-backend-${targetTriple}${executableExtension}`
const backendOutputPath = path.join(binariesDir, backendOutputName)
const ffmpegOutputPath = outputPathForBaseName('heimgeist-ffmpeg')
const ffprobeOutputPath = outputPathForBaseName('heimgeist-ffprobe')
function resolveTargetTriple() {
const output = execFileSync('rustc', ['-vV'], { encoding: 'utf8' })
const match = output.match(/^host:\s+(\S+)/m)
if (!match) {
throw new Error('Could not determine Rust target triple from rustc -vV output.')
}
return match[1]
}
function run(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: projectRoot,
stdio: 'inherit',
env: process.env,
...options,
})
if (result.status !== 0) {
throw new Error(`${command} ${args.join(' ')} failed with exit code ${result.status}`)
}
}
function outputPathForBaseName(outputBaseName) {
return path.join(binariesDir, `${outputBaseName}-${targetTriple}${executableExtension}`)
}
function ensurePython() {
if (!fs.existsSync(pythonBin)) {
throw new Error(`Missing backend Python virtualenv at ${pythonBin}. Run ./run.sh or create backend/.venv first.`)
}
}
function ensurePyInstaller() {
const result = spawnSync(pythonBin, ['-c', 'import PyInstaller'], {
cwd: projectRoot,
stdio: 'ignore',
})
if (result.status === 0) {
return
}
console.log('Installing PyInstaller into backend/.venv for sidecar packaging.')
run(pythonBin, ['-m', 'pip', 'install', '--upgrade', 'pyinstaller'])
}
function copyExecutable(sourcePath, outputBaseName) {
if (!sourcePath || !fs.existsSync(sourcePath)) {
return null
}
fs.mkdirSync(binariesDir, { recursive: true })
const outputPath = outputPathForBaseName(outputBaseName)
fs.copyFileSync(sourcePath, outputPath)
fs.chmodSync(outputPath, 0o755)
return outputPath
}
function copyRequiredFfmpeg() {
const ffmpegPath = require('ffmpeg-static')
const outputPath = copyExecutable(ffmpegPath, 'heimgeist-ffmpeg')
if (!outputPath) {
throw new Error('Could not bundle ffmpeg-static: package did not provide a binary path.')
}
console.log(`Bundled ffmpeg helper: ${outputPath}`)
}
function copyRequiredFfprobe() {
const ffprobeStatic = require('ffprobe-static')
const ffprobePath = ffprobeStatic && ffprobeStatic.path
if (!ffprobePath || !fs.existsSync(ffprobePath)) {
throw new Error('Could not bundle ffprobe-static: package did not provide a binary path.')
}
const probe = spawnSync(ffprobePath, ['-version'], {
encoding: 'utf8',
timeout: 20000,
stdio: ['ignore', 'pipe', 'pipe'],
})
if (probe.status !== 0) {
throw new Error(
`Could not bundle ffprobe-static: ${ffprobePath} did not run successfully on this machine.`,
)
}
const outputPath = copyExecutable(ffprobePath, 'heimgeist-ffprobe')
console.log(`Bundled ffprobe helper: ${outputPath}`)
}
function writeBinariesIgnore() {
fs.mkdirSync(binariesDir, { recursive: true })
const ignorePath = path.join(binariesDir, '.gitignore')
if (!fs.existsSync(ignorePath)) {
fs.writeFileSync(ignorePath, '*\n!.gitignore\n', 'utf8')
}
}
function buildBackendSidecar() {
const pyinstallerRoot = path.join('/tmp', `heimgeist-pyinstaller-${targetTriple}`)
const distPath = path.join(pyinstallerRoot, 'dist')
const workPath = path.join(pyinstallerRoot, 'build')
const specPath = path.join(pyinstallerRoot, 'spec')
fs.rmSync(pyinstallerRoot, { recursive: true, force: true })
fs.rmSync(backendOutputPath, { force: true })
fs.rmSync(ffmpegOutputPath, { force: true })
fs.rmSync(ffprobeOutputPath, { force: true })
fs.mkdirSync(distPath, { recursive: true })
fs.mkdirSync(workPath, { recursive: true })
fs.mkdirSync(specPath, { recursive: true })
run(pythonBin, [
'-m',
'PyInstaller',
'--noconfirm',
'--clean',
'--onefile',
'--name',
'heimgeist-backend',
'--distpath',
distPath,
'--workpath',
workPath,
'--specpath',
specPath,
'--paths',
projectRoot,
'--collect-submodules',
'backend.rag',
'--collect-submodules',
'whisper',
'--collect-data',
'whisper',
'--hidden-import',
'backend.main',
'--hidden-import',
'backend.sidecar_main',
'--hidden-import',
'uvicorn.logging',
'--hidden-import',
'uvicorn.loops.auto',
'--hidden-import',
'uvicorn.protocols.http.auto',
'--hidden-import',
'uvicorn.protocols.websockets.auto',
'--hidden-import',
'uvicorn.lifespan.on',
path.join(projectRoot, 'backend', 'sidecar_main.py'),
])
const builtBinary = path.join(distPath, `heimgeist-backend${executableExtension}`)
if (!fs.existsSync(builtBinary)) {
throw new Error(`PyInstaller did not produce expected binary at ${builtBinary}`)
}
fs.mkdirSync(binariesDir, { recursive: true })
fs.copyFileSync(builtBinary, backendOutputPath)
fs.chmodSync(backendOutputPath, 0o755)
console.log(`Built backend sidecar: ${backendOutputPath}`)
}
ensurePython()
ensurePyInstaller()
writeBinariesIgnore()
buildBackendSidecar()
copyRequiredFfmpeg()
copyRequiredFfprobe()

View File

@@ -1,70 +0,0 @@
const { spawn } = require('child_process')
const path = require('path')
const waitOn = require('wait-on')
const projectRoot = path.resolve(__dirname, '..')
const electronBinary = require('electron')
const relaunchExitCode = 75
const devServerUrl = process.env.VITE_DEV_SERVER_URL || 'http://127.0.0.1:5173'
const startupResources = ['http-get://127.0.0.1:5173', 'http-get://127.0.0.1:8000/health']
const env = {
...process.env,
VITE_DEV_SERVER_URL: devServerUrl,
HEIMGEIST_DEV_WRAPPER: '1',
HEIMGEIST_DEV_RELAUNCH_CODE: String(relaunchExitCode),
}
async function waitForDependencies() {
await waitOn({
resources: startupResources,
proxy: false,
timeout: 120000,
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
function runElectronOnce() {
return new Promise((resolve) => {
const child = spawn(electronBinary, ['.'], {
cwd: projectRoot,
env,
stdio: 'inherit',
})
child.on('exit', (code, signal) => {
resolve({ code, signal })
})
})
}
async function main() {
await waitForDependencies()
console.log(`Electron dev wrapper: dependencies ready, launching ${env.VITE_DEV_SERVER_URL}`)
while (true) {
const { code, signal } = await runElectronOnce()
if (signal) {
process.kill(process.pid, signal)
return
}
if (code === relaunchExitCode) {
await sleep(750)
await waitForDependencies()
continue
}
process.exit(code ?? 0)
}
}
main().catch((error) => {
console.error('Failed to launch Electron dev wrapper:', error)
process.exit(1)
})

184
scripts/run-tauri-dev.cjs Normal file
View File

@@ -0,0 +1,184 @@
const { spawn, spawnSync } = require('child_process')
const fs = require('fs')
const http = require('http')
const path = require('path')
const waitOn = require('wait-on')
const projectRoot = path.resolve(__dirname, '..')
const backendHealthUrl = 'http://127.0.0.1:8000/health'
const backendHealthResource = `http-get://${backendHealthUrl.replace(/^https?:\/\//, '')}`
const tauriCliPackage = '@tauri-apps/cli@2.11.0'
const localTauriBin = path.join(
projectRoot,
'node_modules',
'.bin',
process.platform === 'win32' ? 'tauri.cmd' : 'tauri',
)
let backendProcess = null
let tauriProcess = null
let shuttingDown = false
function isBackendHealthy(timeoutMs = 1500) {
return new Promise((resolve) => {
const request = http.get(backendHealthUrl, { timeout: timeoutMs }, (response) => {
response.resume()
resolve(response.statusCode >= 200 && response.statusCode < 300)
})
request.on('timeout', () => {
request.destroy()
resolve(false)
})
request.on('error', () => resolve(false))
})
}
function spawnBackend() {
backendProcess = spawn(process.execPath, [path.join('scripts', 'run-backend.cjs')], {
cwd: projectRoot,
env: process.env,
stdio: 'inherit',
})
backendProcess.on('exit', (code, signal) => {
if (!shuttingDown && code !== 0) {
console.error(`Tauri dev wrapper: backend exited before shutdown (${signal || code}).`)
}
})
}
function resolveTauriCommand() {
if (fs.existsSync(localTauriBin)) {
return { command: localTauriBin, args: ['dev'] }
}
return {
command: process.platform === 'win32' ? 'npm.cmd' : 'npm',
args: ['exec', '--yes', '--package', tauriCliPackage, '--', 'tauri', 'dev'],
}
}
function getChildPids(pid) {
if (process.platform === 'win32') {
return []
}
const result = spawnSync('pgrep', ['-P', String(pid)], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
})
if (result.status !== 0 || !result.stdout.trim()) {
return []
}
return result.stdout.trim().split(/\s+/).map(Number).filter(Number.isFinite)
}
function stopPidTree(pid, signal = 'SIGTERM') {
for (const childPid of getChildPids(pid)) {
stopPidTree(childPid, signal)
}
try {
process.kill(pid, signal)
} catch (_error) {
// The process may already have exited while walking the tree.
}
}
function stopChild(child, signal = 'SIGTERM') {
if (!child || child.killed || !child.pid) {
return
}
if (process.platform === 'win32') {
spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
stdio: 'ignore',
})
return
}
stopPidTree(child.pid, signal)
}
function stopSpawnedBackend(signal = 'SIGTERM') {
if (backendProcess) {
stopChild(backendProcess, signal)
}
}
function handleShutdown(signal) {
if (shuttingDown) {
return
}
shuttingDown = true
stopChild(tauriProcess, signal)
stopSpawnedBackend(signal)
setTimeout(() => process.exit(0), 750).unref()
}
async function waitForBackend() {
await waitOn({
resources: [backendHealthResource],
proxy: false,
timeout: 120000,
})
}
async function launchTauri() {
const { command, args } = resolveTauriCommand()
const env = {
...process.env,
HEIMGEIST_DEV_WRAPPER: '1',
}
tauriProcess = spawn(command, args, {
cwd: projectRoot,
env,
stdio: 'inherit',
})
tauriProcess.on('exit', (code, signal) => {
const wasShuttingDown = shuttingDown
shuttingDown = true
stopSpawnedBackend()
if (wasShuttingDown) {
process.exit(0)
return
}
if (signal) {
process.exit(signal === 'SIGINT' || signal === 'SIGTERM' ? 0 : 1)
return
}
process.exit(code ?? 0)
})
}
async function main() {
process.on('SIGINT', () => handleShutdown('SIGINT'))
process.on('SIGTERM', () => handleShutdown('SIGTERM'))
if (await isBackendHealthy()) {
console.log('Tauri dev wrapper: FastAPI backend already healthy on 127.0.0.1:8000; reusing it.')
} else {
console.log('Tauri dev wrapper: starting FastAPI backend from scripts/run-backend.cjs.')
spawnBackend()
await waitForBackend()
}
console.log('Tauri dev wrapper: backend ready, launching Tauri on the Tauri renderer port.')
await launchTauri()
}
main().catch((error) => {
shuttingDown = true
stopChild(tauriProcess)
stopSpawnedBackend()
console.error('Failed to launch Tauri dev wrapper:', error)
process.exit(1)
})

18
src-tauri/Cargo.toml Normal file
View File

@@ -0,0 +1,18 @@
[package]
name = "heimgeist-tauri"
version = "0.1.0"
description = "Tauri migration spike for Heimgeist"
authors = ["Heimgeist"]
edition = "2021"
rust-version = "1.77"
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = { version = "2", features = [] }
tauri-plugin-dialog = "2"
tauri-plugin-opener = "2"
tauri-plugin-shell = "2"

2
src-tauri/binaries/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

3
src-tauri/build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build();
}

View File

@@ -0,0 +1,12 @@
{
"identifier": "default",
"description": "Default capability for the Heimgeist Tauri migration spike.",
"windows": ["main"],
"permissions": [
"core:default",
"dialog:allow-open",
"opener:allow-default-urls",
"opener:allow-open-path",
"opener:allow-open-url"
]
}

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 757 B

866
src-tauri/src/main.rs Normal file
View File

@@ -0,0 +1,866 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::{
fs,
io::{Read, Write},
net::{SocketAddr, TcpStream},
path::{Path, PathBuf},
process::Command as StdCommand,
sync::Mutex,
thread,
time::{Duration, Instant},
};
use serde::Deserialize;
use serde_json::{json, Map, Value};
use tauri::{AppHandle, Emitter, Manager, State, WindowEvent};
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_opener::OpenerExt;
use tauri_plugin_shell::{
process::{CommandChild, CommandEvent},
ShellExt,
};
const DEFAULT_BACKEND_API_URL: &str = "http://127.0.0.1:8000";
const BACKEND_HOST: &str = "127.0.0.1";
const BACKEND_PORT: u16 = 8000;
const BACKEND_SIDECAR_NAME: &str = "heimgeist-backend";
const BACKEND_STARTUP_TIMEOUT: Duration = Duration::from_secs(45);
const DEFAULT_OLLAMA_API_URL: &str = "http://127.0.0.1:11434";
const DEFAULT_EMBED_MODEL: &str = "nomic-embed-text:latest";
const DEFAULT_ENRICHMENT_MODEL: &str = "qwen3:4b";
const DEFAULT_TRANSCRIPTION_MODEL: &str = "base";
const BGE_EMBED_MODEL: &str = "bge-m3:latest";
const DEFAULT_UI_SCALE: f64 = 1.0;
const MIN_UI_SCALE: f64 = 0.7;
const MAX_UI_SCALE: f64 = 1.3;
const SETTINGS_FILE_NAME: &str = "settings.json";
const CHANGELOG_PAGE_SIZE: u64 = 50;
type SettingsMap = Map<String, Value>;
struct SettingsStore {
path: PathBuf,
settings: Mutex<SettingsMap>,
}
struct BackendSidecar {
child: Mutex<Option<CommandChild>>,
}
impl BackendSidecar {
fn empty() -> Self {
Self {
child: Mutex::new(None),
}
}
fn running(child: CommandChild) -> Self {
Self {
child: Mutex::new(Some(child)),
}
}
fn shutdown(&self) {
let child = match self.child.lock() {
Ok(mut child) => child.take(),
Err(_) => None,
};
if let Some(child) = child {
let pid = child.pid();
terminate_process_tree(pid);
if let Err(error) = child.kill() {
eprintln!("Failed to stop Heimgeist backend sidecar pid {pid}: {error}");
}
}
}
}
impl Drop for BackendSidecar {
fn drop(&mut self) {
self.shutdown();
}
}
#[cfg(unix)]
fn terminate_process_tree(pid: u32) {
let pid = pid.to_string();
let _ = StdCommand::new("pkill")
.args(["-TERM", "-P", &pid])
.status();
}
#[cfg(windows)]
fn terminate_process_tree(pid: u32) {
let _ = StdCommand::new("taskkill")
.args(["/PID", &pid.to_string(), "/T", "/F"])
.status();
}
#[cfg(not(any(unix, windows)))]
fn terminate_process_tree(_pid: u32) {}
#[derive(Debug, Deserialize)]
struct PickPathsOptions {
title: Option<String>,
filters: Option<Vec<DialogFilter>>,
multiple: Option<bool>,
}
#[derive(Debug, Deserialize)]
struct DialogFilter {
name: Option<String>,
extensions: Option<Vec<String>>,
}
fn default_settings() -> SettingsMap {
let mut settings = SettingsMap::new();
settings.insert("backendApiUrl".into(), json!(DEFAULT_BACKEND_API_URL));
settings.insert("ollamaApiUrl".into(), json!(DEFAULT_OLLAMA_API_URL));
settings.insert("chatModel".into(), json!("llama3"));
settings.insert("visionModel".into(), json!(""));
settings.insert("embedModel".into(), json!(DEFAULT_EMBED_MODEL));
settings.insert("rerankModel".into(), json!(DEFAULT_EMBED_MODEL));
settings.insert("enrichmentModel".into(), json!(DEFAULT_ENRICHMENT_MODEL));
settings.insert(
"transcriptionModel".into(),
json!(DEFAULT_TRANSCRIPTION_MODEL),
);
settings.insert("workflowSelectionMode".into(), json!("auto"));
settings.insert("autoDeepEnrichment".into(), json!(true));
settings.insert("colorScheme".into(), json!("Default"));
settings.insert("uiScale".into(), json!(DEFAULT_UI_SCALE));
settings.insert("openDevToolsOnStartup".into(), json!(false));
settings.insert("audioInputEnabled".into(), json!(true));
settings.insert("audioInputDeviceId".into(), json!(""));
settings.insert("audioInputLanguage".into(), json!(""));
settings
}
fn value_to_trimmed_string(value: Option<&Value>) -> String {
match value {
Some(Value::String(text)) => text.trim().to_string(),
Some(Value::Number(number)) => number.to_string(),
Some(Value::Bool(value)) => value.to_string(),
_ => String::new(),
}
}
fn value_to_number(value: Option<&Value>) -> Option<f64> {
match value {
Some(Value::Number(number)) => number.as_f64(),
Some(Value::String(text)) => text.trim().parse::<f64>().ok(),
_ => None,
}
}
fn normalize_ui_scale(value: Option<&Value>) -> f64 {
let scale = value_to_number(value).unwrap_or(DEFAULT_UI_SCALE);
let clamped = scale.clamp(MIN_UI_SCALE, MAX_UI_SCALE);
(clamped * 100.0).round() / 100.0
}
fn normalize_boolean_setting(value: Option<&Value>) -> bool {
match value {
Some(Value::String(text)) => match text.trim().to_lowercase().as_str() {
"true" | "1" | "yes" | "on" => true,
"false" | "0" | "no" | "off" | "" => false,
_ => false,
},
Some(Value::Bool(value)) => *value,
_ => false,
}
}
fn normalize_model_name(value: Option<&Value>, fallback: &str) -> String {
let trimmed = value_to_trimmed_string(value);
if trimmed.is_empty() {
fallback.to_string()
} else {
trimmed
}
}
fn normalize_embed_model(value: Option<&Value>) -> String {
let trimmed = value_to_trimmed_string(value);
if trimmed.is_empty() {
return DEFAULT_EMBED_MODEL.to_string();
}
match trimmed.to_lowercase().as_str() {
"bge" | "bge-m3" | BGE_EMBED_MODEL => BGE_EMBED_MODEL.to_string(),
"nomic" | "nomic-embed-text" | DEFAULT_EMBED_MODEL => DEFAULT_EMBED_MODEL.to_string(),
_ => trimmed,
}
}
fn looks_like_ollama_url(value: &str) -> bool {
tauri::Url::parse(value)
.map(|parsed| {
parsed.port() == Some(11434)
|| parsed
.path()
.trim_end_matches('/')
.eq_ignore_ascii_case("/api")
})
.unwrap_or(false)
}
fn migrate_settings(source: Option<SettingsMap>) -> (SettingsMap, bool) {
let source = source.unwrap_or_default();
let mut next = default_settings();
let mut migrated = false;
for (key, value) in source.iter() {
next.insert(key.clone(), value.clone());
}
if !source.contains_key("backendApiUrl") {
if let Some(Value::String(ollama_api_url)) = source.get("ollamaApiUrl") {
if looks_like_ollama_url(ollama_api_url) {
next.insert("backendApiUrl".into(), json!(DEFAULT_BACKEND_API_URL));
next.insert("ollamaApiUrl".into(), json!(ollama_api_url.trim()));
} else {
next.insert("backendApiUrl".into(), json!(ollama_api_url.trim()));
next.insert("ollamaApiUrl".into(), json!(DEFAULT_OLLAMA_API_URL));
}
migrated = true;
}
}
if !source.contains_key("openDevToolsOnStartup") {
migrated = true;
}
if !source.contains_key("rerankModel") {
let embed_model = next
.get("embedModel")
.cloned()
.unwrap_or_else(|| json!(DEFAULT_EMBED_MODEL));
next.insert("rerankModel".into(), embed_model);
migrated = true;
}
if !source.contains_key("visionModel") {
let chat_model = value_to_trimmed_string(next.get("chatModel"));
next.insert("visionModel".into(), json!(chat_model));
migrated = true;
}
if !source.contains_key("enrichmentModel") {
next.insert("enrichmentModel".into(), json!(DEFAULT_ENRICHMENT_MODEL));
migrated = true;
}
if !source.contains_key("transcriptionModel") {
next.insert(
"transcriptionModel".into(),
json!(DEFAULT_TRANSCRIPTION_MODEL),
);
migrated = true;
}
if !source.contains_key("autoDeepEnrichment") {
next.insert("autoDeepEnrichment".into(), json!(true));
migrated = true;
}
if !source.contains_key("workflowSelectionMode") {
next.insert("workflowSelectionMode".into(), json!("auto"));
migrated = true;
}
normalize_settings(&mut next);
(next, migrated)
}
fn normalize_settings(settings: &mut SettingsMap) {
let backend_api_url = value_to_trimmed_string(settings.get("backendApiUrl"));
let ollama_api_url = value_to_trimmed_string(settings.get("ollamaApiUrl"));
let chat_model = normalize_model_name(settings.get("chatModel"), "");
let vision_model = normalize_model_name(settings.get("visionModel"), "");
let embed_model = normalize_embed_model(settings.get("embedModel"));
let rerank_model = normalize_embed_model(settings.get("rerankModel"));
let enrichment_model =
normalize_model_name(settings.get("enrichmentModel"), DEFAULT_ENRICHMENT_MODEL);
let transcription_model = normalize_model_name(
settings.get("transcriptionModel"),
DEFAULT_TRANSCRIPTION_MODEL,
);
let workflow_selection_mode =
if value_to_trimmed_string(settings.get("workflowSelectionMode")).eq_ignore_ascii_case("manual") {
"manual"
} else {
"auto"
};
let auto_deep_enrichment = normalize_boolean_setting(settings.get("autoDeepEnrichment"));
let ui_scale = normalize_ui_scale(settings.get("uiScale"));
let open_devtools_on_startup = normalize_boolean_setting(settings.get("openDevToolsOnStartup"));
let audio_input_enabled = normalize_boolean_setting(settings.get("audioInputEnabled"));
let audio_input_device_id = value_to_trimmed_string(settings.get("audioInputDeviceId"));
let audio_input_language =
value_to_trimmed_string(settings.get("audioInputLanguage")).to_lowercase();
settings.insert("backendApiUrl".into(), json!(backend_api_url));
settings.insert("ollamaApiUrl".into(), json!(ollama_api_url));
settings.insert("chatModel".into(), json!(chat_model));
settings.insert("visionModel".into(), json!(vision_model));
settings.insert("embedModel".into(), json!(embed_model));
settings.insert("rerankModel".into(), json!(rerank_model));
settings.insert("enrichmentModel".into(), json!(enrichment_model));
settings.insert("transcriptionModel".into(), json!(transcription_model));
settings.insert("workflowSelectionMode".into(), json!(workflow_selection_mode));
settings.insert("autoDeepEnrichment".into(), json!(auto_deep_enrichment));
settings.insert("uiScale".into(), json!(ui_scale));
settings.insert(
"openDevToolsOnStartup".into(),
json!(open_devtools_on_startup),
);
settings.insert("audioInputEnabled".into(), json!(audio_input_enabled));
settings.insert("audioInputDeviceId".into(), json!(audio_input_device_id));
settings.insert("audioInputLanguage".into(), json!(audio_input_language));
}
fn explicit_settings_file_path() -> Option<PathBuf> {
if let Ok(path) = std::env::var("HEIMGEIST_SETTINGS_FILE") {
let trimmed = path.trim();
if !trimmed.is_empty() {
return Some(PathBuf::from(trimmed));
}
}
None
}
fn tauri_settings_file_path(app: &AppHandle) -> Result<PathBuf, String> {
app.path()
.app_config_dir()
.map(|dir| dir.join(SETTINGS_FILE_NAME))
.map_err(|error| format!("Could not resolve Tauri settings path: {error}"))
}
fn settings_file_path(app: &AppHandle) -> Result<PathBuf, String> {
explicit_settings_file_path()
.map(Ok)
.unwrap_or_else(|| tauri_settings_file_path(app))
}
fn paths_equal(first: &Path, second: &Path) -> bool {
match (first.canonicalize(), second.canonicalize()) {
(Ok(first), Ok(second)) => first == second,
_ => first == second,
}
}
fn push_unique_candidate(candidates: &mut Vec<PathBuf>, candidate: PathBuf, tauri_path: &Path) {
if paths_equal(&candidate, tauri_path)
|| candidates
.iter()
.any(|existing| paths_equal(existing, &candidate))
{
return;
}
candidates.push(candidate);
}
fn legacy_settings_candidates(app: &AppHandle, tauri_path: &Path) -> Vec<PathBuf> {
let mut candidates = Vec::new();
if let Ok(config_dir) = app.path().config_dir() {
let product_name = app.config().product_name.as_deref().unwrap_or("Heimgeist");
for app_dir in [product_name, "Heimgeist", "heimgeist"] {
push_unique_candidate(
&mut candidates,
config_dir.join(app_dir).join(SETTINGS_FILE_NAME),
tauri_path,
);
}
}
candidates
}
fn import_legacy_settings_if_available(app: &AppHandle, tauri_path: &Path) -> Option<SettingsMap> {
for candidate in legacy_settings_candidates(app, tauri_path) {
match read_settings_file(&candidate) {
Ok(Some(settings)) => {
println!(
"Imported legacy Heimgeist settings for first Tauri run from {}",
candidate.display()
);
return Some(settings);
}
Ok(None) => {}
Err(error) => {
eprintln!(
"Skipping legacy settings import from {}: {error}",
candidate.display()
);
}
}
}
None
}
fn read_settings_file(path: &PathBuf) -> Result<Option<SettingsMap>, String> {
if !path.exists() {
return Ok(None);
}
let data = fs::read_to_string(path)
.map_err(|error| format!("Could not read settings from {}: {error}", path.display()))?;
let value: Value = serde_json::from_str(&data)
.map_err(|error| format!("Could not parse settings from {}: {error}", path.display()))?;
match value {
Value::Object(settings) => Ok(Some(settings)),
_ => Ok(None),
}
}
fn write_settings_file(path: &PathBuf, settings: &SettingsMap) -> Result<(), String> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|error| {
format!(
"Could not create settings directory {}: {error}",
parent.display()
)
})?;
}
let data = serde_json::to_string_pretty(settings)
.map_err(|error| format!("Could not serialize settings: {error}"))?;
fs::write(path, format!("{data}\n"))
.map_err(|error| format!("Could not write settings to {}: {error}", path.display()))
}
enum BackendHealth {
Healthy,
Unavailable,
Incompatible(String),
}
fn check_backend_health() -> BackendHealth {
let address = SocketAddr::from(([127, 0, 0, 1], BACKEND_PORT));
let mut stream = match TcpStream::connect_timeout(&address, Duration::from_millis(500)) {
Ok(stream) => stream,
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::TimedOut
) =>
{
return BackendHealth::Unavailable;
}
Err(error) => {
return BackendHealth::Incompatible(format!(
"Could not connect to backend health port {BACKEND_PORT}: {error}"
));
}
};
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
if let Err(error) = stream.write_all(
format!("GET /health HTTP/1.1\r\nHost: {BACKEND_HOST}\r\nConnection: close\r\n\r\n")
.as_bytes(),
) {
return BackendHealth::Incompatible(format!(
"Port {BACKEND_PORT} is occupied but did not accept a health request: {error}"
));
}
let mut response = String::new();
if let Err(error) = stream.read_to_string(&mut response) {
return BackendHealth::Incompatible(format!(
"Port {BACKEND_PORT} is occupied but did not return a readable health response: {error}"
));
}
if response.contains("200 OK") && response.contains("\"ok\"") {
BackendHealth::Healthy
} else {
let preview = response.lines().next().unwrap_or("empty response");
BackendHealth::Incompatible(format!(
"Port {BACKEND_PORT} is occupied but /health did not return Heimgeist health OK ({preview})."
))
}
}
fn wait_for_backend_health(timeout: Duration) -> Result<(), String> {
let deadline = Instant::now() + timeout;
loop {
match check_backend_health() {
BackendHealth::Healthy => return Ok(()),
BackendHealth::Unavailable => {
if Instant::now() >= deadline {
return Err(format!(
"Timed out waiting for Heimgeist backend /health on {BACKEND_HOST}:{BACKEND_PORT}."
));
}
thread::sleep(Duration::from_millis(250));
}
BackendHealth::Incompatible(detail) => return Err(detail),
}
}
}
fn should_start_backend_sidecar() -> bool {
!cfg!(debug_assertions)
|| std::env::var("HEIMGEIST_USE_BACKEND_SIDECAR")
.map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
.unwrap_or(false)
}
fn bundled_executable_path(name: &str) -> Option<PathBuf> {
let exe_path = std::env::current_exe().ok()?;
let exe_dir = exe_path.parent()?;
#[cfg(not(windows))]
let path = exe_dir.join(name);
#[cfg(windows)]
{
let mut path = exe_dir.join(name);
path.set_extension("exe");
path.exists().then_some(path)
}
#[cfg(not(windows))]
{
path.exists().then_some(path)
}
}
fn app_managed_data_dir(app: &AppHandle) -> Result<PathBuf, String> {
let data_dir = app
.path()
.app_data_dir()
.map_err(|error| format!("Could not resolve app data directory: {error}"))?;
fs::create_dir_all(&data_dir).map_err(|error| {
format!(
"Could not create app data directory {}: {error}",
data_dir.display()
)
})?;
Ok(data_dir)
}
fn start_backend_sidecar(app: &AppHandle, settings_path: &Path) -> Result<BackendSidecar, String> {
match check_backend_health() {
BackendHealth::Healthy => {
println!("Reusing healthy Heimgeist backend on {BACKEND_HOST}:{BACKEND_PORT}.");
return Ok(BackendSidecar::empty());
}
BackendHealth::Unavailable => {}
BackendHealth::Incompatible(detail) => return Err(detail),
}
if !should_start_backend_sidecar() {
println!(
"Heimgeist backend is not running; dev shell expects an external backend wrapper."
);
return Ok(BackendSidecar::empty());
}
let data_dir = app_managed_data_dir(app)?;
let mut command = app
.shell()
.sidecar(BACKEND_SIDECAR_NAME)
.map_err(|error| format!("Could not resolve bundled backend sidecar: {error}"))?
.env("HEIMGEIST_DATA_DIR", data_dir.as_os_str())
.env("HEIMGEIST_SETTINGS_FILE", settings_path.as_os_str())
.env("HEIMGEIST_BACKEND_HOST", BACKEND_HOST)
.env("HEIMGEIST_BACKEND_PORT", BACKEND_PORT.to_string());
if let Some(ffmpeg_path) = bundled_executable_path("heimgeist-ffmpeg") {
command = command.env("HEIMGEIST_FFMPEG_PATH", ffmpeg_path.as_os_str());
}
if let Some(ffprobe_path) = bundled_executable_path("heimgeist-ffprobe") {
command = command.env("HEIMGEIST_FFPROBE_PATH", ffprobe_path.as_os_str());
}
let (mut events, child) = command
.spawn()
.map_err(|error| format!("Failed to start bundled backend sidecar: {error}"))?;
let pid = child.pid();
println!("Started bundled Heimgeist backend sidecar with pid {pid}.");
tauri::async_runtime::spawn(async move {
while let Some(event) = events.recv().await {
match event {
CommandEvent::Stdout(bytes) => {
let line = String::from_utf8_lossy(&bytes);
println!("[backend] {}", line.trim_end());
}
CommandEvent::Stderr(bytes) => {
let line = String::from_utf8_lossy(&bytes);
eprintln!("[backend] {}", line.trim_end());
}
CommandEvent::Error(error) => {
eprintln!("[backend] {error}");
}
CommandEvent::Terminated(status) => {
eprintln!(
"[backend] sidecar terminated code={:?} signal={:?}",
status.code, status.signal
);
break;
}
_ => {}
}
}
});
let sidecar = BackendSidecar::running(child);
wait_for_backend_health(BACKEND_STARTUP_TIMEOUT)?;
Ok(sidecar)
}
fn load_settings_store(app: &AppHandle) -> Result<SettingsStore, String> {
let path = settings_file_path(app)?;
let raw_settings = read_settings_file(&path)?;
let (settings, should_write) = match raw_settings {
Some(raw_settings) => {
let (settings, migrated) = migrate_settings(Some(raw_settings));
(settings, migrated)
}
None => {
let imported_settings = if explicit_settings_file_path().is_none() {
import_legacy_settings_if_available(app, &path)
} else {
None
};
let (settings, _migrated) = migrate_settings(imported_settings);
(settings, true)
}
};
if should_write {
write_settings_file(&path, &settings)?;
}
Ok(SettingsStore {
path,
settings: Mutex::new(settings),
})
}
fn unavailable_update_status(message: &str) -> Value {
json!({
"state": "unavailable",
"message": message,
"checkedAt": null,
"localCommit": null,
"remoteCommit": null,
"branch": null,
"restartScheduled": false
})
}
fn normalize_changelog_page(page: Option<u64>) -> u64 {
page.filter(|value| *value > 0).unwrap_or(1)
}
#[tauri::command]
fn get_settings(store: State<'_, SettingsStore>) -> Result<Value, String> {
let settings = store
.settings
.lock()
.map_err(|_| "Settings store is unavailable.".to_string())?;
Ok(Value::Object(settings.clone()))
}
#[tauri::command]
fn set_setting(key: String, value: Value, store: State<'_, SettingsStore>) -> Result<bool, String> {
let mut settings = store
.settings
.lock()
.map_err(|_| "Settings store is unavailable.".to_string())?;
settings.insert(key, value);
normalize_settings(&mut settings);
write_settings_file(&store.path, &settings)?;
Ok(true)
}
#[tauri::command]
fn update_settings(settings: SettingsMap, store: State<'_, SettingsStore>) -> Result<bool, String> {
let mut current_settings = store
.settings
.lock()
.map_err(|_| "Settings store is unavailable.".to_string())?;
current_settings.extend(settings);
normalize_settings(&mut current_settings);
write_settings_file(&store.path, &current_settings)?;
Ok(true)
}
#[tauri::command]
fn get_update_status() -> Value {
unavailable_update_status(
"Tauri update checks are not implemented in this production release phase.",
)
}
#[tauri::command]
fn check_for_updates() -> Value {
unavailable_update_status(
"Tauri update checks are not implemented in this production release phase.",
)
}
#[tauri::command]
fn get_changelog_page(page: Option<u64>) -> Value {
json!({
"page": normalize_changelog_page(page),
"pageSize": CHANGELOG_PAGE_SIZE,
"hasMore": false,
"entries": []
})
}
#[tauri::command]
async fn pick_paths(
app: AppHandle,
options: Option<PickPathsOptions>,
) -> Result<Vec<String>, String> {
let options = options.unwrap_or(PickPathsOptions {
title: None,
filters: None,
multiple: None,
});
let mut dialog = app.dialog().file();
if let Some(title) = options
.title
.as_deref()
.map(str::trim)
.filter(|title| !title.is_empty())
{
dialog = dialog.set_title(title);
}
for filter in options.filters.unwrap_or_default() {
let name = filter
.name
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("Files")
.to_string();
let extensions: Vec<String> = filter
.extensions
.unwrap_or_default()
.into_iter()
.map(|extension| extension.trim().trim_start_matches('.').to_string())
.filter(|extension| !extension.is_empty())
.collect();
if !extensions.is_empty() {
let extension_refs: Vec<&str> = extensions.iter().map(String::as_str).collect();
dialog = dialog.add_filter(name, &extension_refs);
}
}
let paths = if options.multiple.unwrap_or(true) {
dialog.blocking_pick_files().unwrap_or_default()
} else {
dialog.blocking_pick_file().into_iter().collect()
};
paths
.into_iter()
.map(|path| {
path.into_path()
.map(|path| path.to_string_lossy().into_owned())
.map_err(|error| format!("Could not resolve selected file path: {error}"))
})
.collect()
}
#[tauri::command]
fn open_path(app: AppHandle, file_path: String) -> Result<bool, String> {
let file_path = file_path.trim();
if file_path.is_empty() {
return Ok(false);
}
match app.opener().open_path(file_path, None::<&str>) {
Ok(_) => Ok(true),
Err(error) => {
eprintln!("Failed to open path {file_path}: {error}");
Ok(false)
}
}
}
fn is_allowed_external_url(url: &str) -> bool {
tauri::Url::parse(url)
.map(|parsed| matches!(parsed.scheme(), "http" | "https" | "mailto" | "tel"))
.unwrap_or(false)
}
#[tauri::command]
fn open_external_link(app: AppHandle, url: String) -> Result<bool, String> {
let url = url.trim();
if url.is_empty() || !is_allowed_external_url(url) {
return Ok(false);
}
match app.opener().open_url(url, None::<&str>) {
Ok(_) => Ok(true),
Err(error) => {
eprintln!("Failed to open URL {url}: {error}");
Ok(false)
}
}
}
fn shutdown_backend_sidecar(app: &AppHandle) {
if let Some(sidecar) = app.try_state::<BackendSidecar>() {
sidecar.shutdown();
}
}
fn main() {
let app = tauri::Builder::default()
.menu(|handle| tauri::menu::Menu::default(handle))
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_shell::init())
.setup(|app| {
let store = load_settings_store(app.handle()).map_err(std::io::Error::other)?;
let backend_sidecar =
start_backend_sidecar(app.handle(), &store.path).map_err(std::io::Error::other)?;
app.manage(store);
app.manage(backend_sidecar);
Ok(())
})
.on_window_event(|window, event| {
if matches!(event, WindowEvent::Focused(true)) {
let _ = window.emit("window-focused", ());
}
})
.invoke_handler(tauri::generate_handler![
get_settings,
set_setting,
update_settings,
get_update_status,
check_for_updates,
get_changelog_page,
pick_paths,
open_path,
open_external_link
])
.build(tauri::generate_context!())
.expect("failed to build Heimgeist Tauri desktop shell");
app.run(|app_handle, event| {
if matches!(
event,
tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit
) {
shutdown_backend_sidecar(app_handle);
}
});
}

38
src-tauri/tauri.conf.json Normal file
View File

@@ -0,0 +1,38 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Heimgeist",
"version": "0.1.0",
"identifier": "com.giers.heimgeist",
"build": {
"beforeDevCommand": "npm run dev:renderer",
"beforeBuildCommand": "npm run build",
"devUrl": "http://127.0.0.1:5174",
"frontendDist": "../dist"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"label": "main",
"title": "Heimgeist",
"width": 1000,
"height": 720,
"minWidth": 680,
"minHeight": 300
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": ["app"],
"icon": ["icons/icon.png"],
"externalBin": [
"binaries/heimgeist-backend",
"binaries/heimgeist-ffmpeg",
"binaries/heimgeist-ffprobe"
]
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,82 @@
import React from 'react'
import { markdownToHTML } from './markdown'
import { enrichOllamaErrorText, splitThinkBlocks } from './chatText'
import desktopApi from './desktop/desktopApi'
export default function AssistantMessageContent({ content, streamOutput, sources }) {
const displayContent = enrichOllamaErrorText(content || '')
const { think, answer } = splitThinkBlocks(displayContent)
const [open, setOpen] = React.useState(false)
const showThinkButton = !!think
return (
<div className="assistant-message">
{showThinkButton && (
<div className="assistant-thoughts">
<button
className="think-toggle"
onClick={() => setOpen(o => !o)}
aria-expanded={open ? 'true' : 'false'}
aria-controls="think-content"
>
<span className="think-toggle-icon" aria-hidden="true">
{open ? '▾' : '▸'}
</span>
Thoughts
</button>
{open && (
<div
id="think-content"
className="think-content"
dangerouslySetInnerHTML={{ __html: markdownToHTML(think) }}
/>
)}
</div>
)}
<div
className="msg-content"
dangerouslySetInnerHTML={{ __html: markdownToHTML(answer || displayContent || '') }}
/>
{Array.isArray(sources) && sources.length > 0 && (
<div className="msg-sources chips">
{sources.map((source, i) => {
const u = typeof source === 'string' ? source : (source?.url || source?.canonical_url || '')
let label = typeof source === 'object' && source?.title ? source.title : u
let isFile = false
try {
const parsed = new URL(u)
if (parsed.protocol === 'file:') {
isFile = true
const parts = parsed.pathname.split('/').filter(Boolean)
label = decodeURIComponent(parts[parts.length - 1] || u)
} else {
const host = parsed.hostname || u
label = host.replace(/^www\./i, '')
}
} catch {}
return (
<a
key={(u || JSON.stringify(source)) + i}
className="chip"
href={u || undefined}
target="_blank"
rel="noreferrer"
title={typeof source === 'object' ? (source.snippet || u) : u}
onClick={(event) => {
if (!isFile || !u) return
event.preventDefault()
try {
const parsed = new URL(u)
desktopApi.openPath(decodeURIComponent(parsed.pathname))
} catch {}
}}
>
{label}
</a>
)
})}
</div>
)}
</div>
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,11 @@
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { colorSchemes, applyColorScheme } from './colorSchemes' import { colorSchemes, applyColorScheme } from './colorSchemes'
import desktopApi from './desktop/desktopApi'
const COLOR_SCHEME_KEY = 'colorScheme' const COLOR_SCHEME_KEY = 'colorScheme'
const STREAM_KEY = 'streamOutput'
const UI_SCALE_KEY = 'uiScale' const UI_SCALE_KEY = 'uiScale'
const OPEN_DEVTOOLS_ON_STARTUP_KEY = 'openDevToolsOnStartup'
const DEFAULT_UI_SCALE = 1 const DEFAULT_UI_SCALE = 1
const MIN_UI_SCALE = 0.7 const MIN_UI_SCALE = 0.7
const MAX_UI_SCALE = 1.3 const MAX_UI_SCALE = 1.3
@@ -17,16 +20,23 @@ function normalizeUiScale(value) {
return Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, Math.round(numericValue * 100) / 100)) return Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, Math.round(numericValue * 100) / 100))
} }
export default function InterfaceSettings() { export default function InterfaceSettings({
streamOutput = false,
onStreamOutputChange,
}) {
const [selectedColorScheme, setSelectedColorScheme] = useState('Default') const [selectedColorScheme, setSelectedColorScheme] = useState('Default')
const [uiScale, setUiScale] = useState(DEFAULT_UI_SCALE) const [uiScale, setUiScale] = useState(DEFAULT_UI_SCALE)
const [openDevToolsOnStartup, setOpenDevToolsOnStartup] = useState(false)
useEffect(() => { useEffect(() => {
window.electronAPI.getSettings().then(settings => { desktopApi.getSettings().then(settings => {
const schemeName = settings.colorScheme || 'Default' const schemeName = settings.colorScheme || 'Default'
const nextUiScale = normalizeUiScale(settings.uiScale)
setSelectedColorScheme(schemeName) setSelectedColorScheme(schemeName)
setUiScale(normalizeUiScale(settings.uiScale)) setUiScale(nextUiScale)
setOpenDevToolsOnStartup(settings.openDevToolsOnStartup === true)
applyColorScheme(schemeName) applyColorScheme(schemeName)
desktopApi.applyUiScale(nextUiScale)
}) })
}, []) }, [])
@@ -37,13 +47,14 @@ export default function InterfaceSettings() {
const handleColorSchemeChange = (event) => { const handleColorSchemeChange = (event) => {
const newScheme = event.target.value const newScheme = event.target.value
setSelectedColorScheme(newScheme) setSelectedColorScheme(newScheme)
window.electronAPI.setSetting(COLOR_SCHEME_KEY, newScheme) desktopApi.setSetting(COLOR_SCHEME_KEY, newScheme)
} }
const persistUiScale = (value) => { const persistUiScale = (value) => {
const nextScale = normalizeUiScale(value) const nextScale = normalizeUiScale(value)
setUiScale(nextScale) setUiScale(nextScale)
window.electronAPI.setSetting(UI_SCALE_KEY, nextScale) desktopApi.applyUiScale(nextScale)
desktopApi.setSetting(UI_SCALE_KEY, nextScale)
} }
const handleUiScaleChange = (event) => { const handleUiScaleChange = (event) => {
@@ -54,6 +65,20 @@ export default function InterfaceSettings() {
persistUiScale(DEFAULT_UI_SCALE) persistUiScale(DEFAULT_UI_SCALE)
} }
const handleOpenDevToolsOnStartupToggle = () => {
const nextValue = !openDevToolsOnStartup
setOpenDevToolsOnStartup(nextValue)
desktopApi.setSetting(OPEN_DEVTOOLS_ON_STARTUP_KEY, nextValue)
}
const handleStreamOutputToggle = () => {
const nextValue = !streamOutput
desktopApi.setSetting(STREAM_KEY, nextValue)
if (onStreamOutputChange) {
onStreamOutputChange(nextValue)
}
}
return ( return (
<div className="settings-content-panel"> <div className="settings-content-panel">
<div className="setting-section"> <div className="setting-section">
@@ -96,6 +121,34 @@ export default function InterfaceSettings() {
Scales the whole interface, including fonts, spacing, and controls. 100% is the default size. Scales the whole interface, including fonts, spacing, and controls. 100% is the default size.
</p> </p>
</div> </div>
<div className="setting-section">
<h3>Open DevTools on Startup</h3>
<label className="toggle-switch">
<input
type="checkbox"
checked={openDevToolsOnStartup}
onChange={handleOpenDevToolsOnStartupToggle}
/>
<span className="slider"></span>
</label>
<p className="setting-description">
Stored for future desktop diagnostics. Tauri does not currently apply this preference automatically.
</p>
</div>
<div className="setting-section">
<h3>Stream Output</h3>
<label className="toggle-switch">
<input
type="checkbox"
checked={streamOutput}
onChange={handleStreamOutputToggle}
/>
<span className="slider"></span>
</label>
<p className="setting-description">
Shows assistant replies token by token while they are generating instead of waiting for the full message to finish first.
</p>
</div>
</div> </div>
) )
} }

View File

@@ -1,4 +1,5 @@
import React, { useEffect, useRef, useState } from 'react' import React, { useEffect, useMemo, useRef, useState } from 'react'
import desktopApi from './desktop/desktopApi'
const TOAST_DURATION_MS = { const TOAST_DURATION_MS = {
info: 3600, info: 3600,
@@ -6,41 +7,42 @@ const TOAST_DURATION_MS = {
warning: 5600 warning: 5600
} }
function fileSyncMeta(file) { function itemSyncMeta(item) {
const sync = file?.sync || {} const sync = item?.sync || {}
const status = String(sync.status || 'pending') const status = String(sync.status || 'pending')
const progress = Math.max(0, Math.min(100, Number(sync.progress) || 0)) const progress = Math.max(0, Math.min(100, Number(sync.progress) || 0))
const detail = String(sync.detail || '').trim() const detail = String(sync.detail || '').trim()
const error = String(sync.error || '').trim() const enrichEnabled = !!item?.enrich_enabled
const enrichEnabled = !!file?.enrich_enabled const metadataReady = ['ready', 'fallback'].includes(item?.metadata?.status)
if (status === 'ready') { if (status === 'ready') {
return { return {
status, status,
progress: 100, progress: 100,
label: 'Available', label: 'Available',
detail: detail || (enrichEnabled ? 'Ready in chat with enrichment enabled.' : 'Ready in chat with raw indexing only.') detail: detail || (
metadataReady
? (enrichEnabled ? 'Ready with standard metadata and deep enrichment.' : 'Ready with standard metadata.')
: 'Ready for chat. Automatic metadata has not been generated yet.'
)
} }
} }
if (status === 'failed') { if (status === 'failed') {
return { return {
status, status,
progress: 100, progress: 100,
label: 'Sync failed', label: 'Sync failed',
detail: error || detail || 'Heimgeist could not finish syncing this file.' detail: String(sync.error || '').trim() || detail || 'Heimgeist could not finish syncing this content.'
} }
} }
if (status === 'syncing') { if (status === 'syncing') {
return { return {
status, status,
progress, progress,
label: progress > 0 ? `Syncing ${Math.round(progress)}%` : 'Syncing', label: progress > 0 ? `Syncing ${Math.round(progress)}%` : 'Syncing',
detail: detail || 'Rebuilding the corpus and indexes. Selected files may also be enriched.' detail: detail || 'Rebuilding Knowledge search indexes.'
} }
} }
return { return {
status: 'pending', status: 'pending',
progress: 6, progress: 6,
@@ -49,29 +51,56 @@ function fileSyncMeta(file) {
} }
} }
export default function LibraryManager({ function kindLabel(item) {
apiBase, if (item?.kind === 'text') return 'Text'
library, if (item?.kind === 'website') return 'Website'
jobs, if (item?.kind === 'video') return 'Video'
onRefresh if (item?.kind === 'chat_message') return 'Chat Message'
}) { return 'File'
}
async function expectJson(response) {
const raw = await response.text()
let data = null
try {
data = raw ? JSON.parse(raw) : null
} catch {}
if (!response.ok) {
throw new Error(data?.detail || raw || `HTTP ${response.status}`)
}
return data
}
export default function LibraryManager({ apiBase, library, jobs, onOpenChatMessage, onRefresh }) {
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [errorMessage, setErrorMessage] = useState('') const [errorMessage, setErrorMessage] = useState('')
const [toasts, setToasts] = useState([]) const [toasts, setToasts] = useState([])
const [search, setSearch] = useState('')
const [formMode, setFormMode] = useState(null)
const [editingItemId, setEditingItemId] = useState(null)
const [textTitle, setTextTitle] = useState('')
const [textContent, setTextContent] = useState('')
const [websiteTitle, setWebsiteTitle] = useState('')
const [websiteUrl, setWebsiteUrl] = useState('')
const [websiteProcessing, setWebsiteProcessing] = useState(false)
const [expandedItemId, setExpandedItemId] = useState(null)
const [contentPreviews, setContentPreviews] = useState({})
const toastTimeoutsRef = useRef(new Map()) const toastTimeoutsRef = useRef(new Map())
const toastIdRef = useRef(0) const toastIdRef = useRef(0)
const previousLibraryStateRef = useRef(null) const previousLibraryStateRef = useRef(null)
useEffect(() => { useEffect(() => {
setErrorMessage('') setErrorMessage('')
setSearch('')
setExpandedItemId(null)
setContentPreviews({})
closeForm()
}, [library?.slug, library?.name]) }, [library?.slug, library?.name])
function dismissToast(id) { function dismissToast(id) {
const timeoutId = toastTimeoutsRef.current.get(id) const timeoutId = toastTimeoutsRef.current.get(id)
if (timeoutId) { if (timeoutId) clearTimeout(timeoutId)
clearTimeout(timeoutId) toastTimeoutsRef.current.delete(id)
toastTimeoutsRef.current.delete(id)
}
setToasts(current => current.filter(toast => toast.id !== id)) setToasts(current => current.filter(toast => toast.id !== id))
} }
@@ -83,15 +112,11 @@ export default function LibraryManager({
function queueToast(message, tone = 'info') { function queueToast(message, tone = 'info') {
setToasts(current => { setToasts(current => {
if (current.some(toast => toast.message === message && toast.tone === tone)) { if (current.some(toast => toast.message === message && toast.tone === tone)) return current
return current
}
const id = `library-toast-${toastIdRef.current++}` const id = `library-toast-${toastIdRef.current++}`
const next = [...current, { id, message, tone }].slice(-3)
const timeoutId = window.setTimeout(() => dismissToast(id), TOAST_DURATION_MS[tone] || TOAST_DURATION_MS.info) const timeoutId = window.setTimeout(() => dismissToast(id), TOAST_DURATION_MS[tone] || TOAST_DURATION_MS.info)
toastTimeoutsRef.current.set(id, timeoutId) toastTimeoutsRef.current.set(id, timeoutId)
return next return [...current, { id, message, tone }].slice(-3)
}) })
} }
@@ -100,89 +125,231 @@ export default function LibraryManager({
toastTimeoutsRef.current.clear() toastTimeoutsRef.current.clear()
}, []) }, [])
async function expectOk(response) { function closeForm() {
if (response.ok) return response setFormMode(null)
const detail = await response.text() setEditingItemId(null)
throw new Error(detail || `HTTP ${response.status}`) setTextTitle('')
setTextContent('')
setWebsiteTitle('')
setWebsiteUrl('')
} }
async function runAction(fn) { async function toggleContentPreview(item) {
setBusy(true) const itemId = item?.item_id
if (!library || !itemId) return
if (expandedItemId === itemId) {
setExpandedItemId(null)
return
}
setExpandedItemId(itemId)
if (contentPreviews[itemId]) return
setContentPreviews(current => ({ ...current, [itemId]: { loading: true } }))
try { try {
setErrorMessage('') const response = await fetch(`${apiBase}/knowledge/items/${itemId}`)
await fn() const data = await expectJson(response)
setContentPreviews(current => ({ ...current, [itemId]: { data } }))
} catch (error) {
setContentPreviews(current => ({
...current,
[itemId]: { error: String(error?.message || error) }
}))
}
}
async function runAction(fn, successMessage) {
setBusy(true)
setErrorMessage('')
try {
const result = await fn()
if (successMessage) queueToast(successMessage, 'success')
return result
} catch (error) {
setErrorMessage(String(error?.message || error))
throw error
} finally { } finally {
setBusy(false) setBusy(false)
await onRefresh() await onRefresh()
} }
} }
async function registerPaths(paths) {
await runAction(async () => {
const response = await fetch(`${apiBase}/libraries/${library.slug}/files/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths })
})
await expectOk(response)
})
}
async function addPaths() { async function addPaths() {
if (!library) return if (!library) return
const paths = await window.electronAPI?.pickPaths?.() const paths = await desktopApi.pickPaths()
if (!Array.isArray(paths) || paths.length === 0) return if (!Array.isArray(paths) || paths.length === 0) return
try { try {
await registerPaths(paths) await runAction(async () => {
} catch (error) { const response = await fetch(`${apiBase}/knowledge/files/register`, {
setErrorMessage(String(error?.message || error)) method: 'POST',
} headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths })
})
return expectJson(response)
}, 'Files added. Heimgeist is updating Knowledge.')
} catch {}
} }
async function removeFile(rel) { async function submitText(event) {
event.preventDefault()
if (!library) return if (!library) return
try { try {
await runAction(async () => { await runAction(async () => {
const response = await fetch(`${apiBase}/libraries/${library.slug}/files`, { const editing = Boolean(editingItemId)
const response = await fetch(
editing
? `${apiBase}/knowledge/texts/${editingItemId}`
: `${apiBase}/knowledge/texts`,
{
method: editing ? 'PATCH' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: textTitle, content: textContent })
}
)
return expectJson(response)
}, editingItemId ? 'Text updated.' : 'Text added to Knowledge.')
if (editingItemId) {
setContentPreviews(current => {
const next = { ...current }
delete next[editingItemId]
return next
})
setExpandedItemId(current => current === editingItemId ? null : current)
}
closeForm()
} catch {}
}
async function editText(item) {
if (!library || !item?.item_id) return
setBusy(true)
setErrorMessage('')
try {
const response = await fetch(`${apiBase}/knowledge/items/${item.item_id}`)
const data = await expectJson(response)
setEditingItemId(item.item_id)
setTextTitle(data.title || item.title || item.name || '')
setTextContent(data.content || '')
setFormMode('text')
} catch (error) {
setErrorMessage(String(error?.message || error))
} finally {
setBusy(false)
}
}
async function submitWebsite(event) {
event.preventDefault()
if (!library) return
setWebsiteProcessing(true)
try {
const result = await runAction(async () => {
const response = await fetch(`${apiBase}/knowledge/websites`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: websiteUrl, title: websiteTitle || null })
})
return expectJson(response)
})
queueToast(
result?.content_kind === 'video'
? 'Video transcribed and summarized. Heimgeist is indexing it.'
: 'Website saved. Heimgeist is indexing its text.',
'success'
)
closeForm()
} catch {
} finally {
setWebsiteProcessing(false)
}
}
async function refreshWebsite(item) {
if (!library || !item?.item_id) return
try {
const result = await runAction(async () => {
const response = await fetch(`${apiBase}/knowledge/websites/${item.item_id}/refresh`, {
method: 'POST'
})
return expectJson(response)
})
setContentPreviews(current => {
const next = { ...current }
delete next[item.item_id]
return next
})
setExpandedItemId(current => current === item.item_id ? null : current)
queueToast(result?.changed ? 'Website changed and is being reindexed.' : 'Website checked. No text changes found.', 'success')
} catch {}
}
async function refreshVideo(item) {
if (!library || !item?.item_id) return
setWebsiteProcessing(true)
try {
const result = await runAction(async () => {
const response = await fetch(`${apiBase}/knowledge/videos/${item.item_id}/refresh`, {
method: 'POST'
})
return expectJson(response)
})
setContentPreviews(current => {
const next = { ...current }
delete next[item.item_id]
return next
})
setExpandedItemId(current => current === item.item_id ? null : current)
queueToast(result?.changed ? 'Video reprocessed and changed.' : 'Video reprocessed. Transcript content is unchanged.', 'success')
} catch {
} finally {
setWebsiteProcessing(false)
}
}
async function removeItem(item) {
if (!library) return
try {
await runAction(async () => {
const response = await fetch(`${apiBase}/knowledge/files`, {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ rel }) body: JSON.stringify({ rel: item.rel })
}) })
await expectOk(response) return expectJson(response)
}) }, `${kindLabel(item)} removed.`)
} catch (error) { } catch {}
setErrorMessage(String(error?.message || error))
}
} }
async function updateFileEnrichment(rel, enabled) { async function updateEnrichment(item, enabled) {
if (!library) return if (!library) return
try { try {
await runAction(async () => { await runAction(async () => {
const response = await fetch(`${apiBase}/libraries/${library.slug}/files/enrichment`, { const response = await fetch(`${apiBase}/knowledge/files/enrichment`, {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ rel, enabled }) body: JSON.stringify({ rel: item.rel, enabled })
}) })
await expectOk(response) return expectJson(response)
}) }, enabled ? 'Deep enrichment enabled. Metadata is being updated.' : 'Using standard metadata only.')
} catch (error) { } catch {}
setErrorMessage(String(error?.message || error)) }
}
async function generateMetadata() {
if (!library) return
try {
await runAction(async () => {
const response = await fetch(`${apiBase}/knowledge/jobs/prepare`, { method: 'POST' })
return expectJson(response)
}, 'Generating metadata for Knowledge.')
} catch {}
} }
async function retrySync() { async function retrySync() {
if (!library) return if (!library) return
try { try {
await runAction(async () => { await runAction(async () => {
const response = await fetch(`${apiBase}/libraries/${library.slug}/jobs/prepare`, { const response = await fetch(`${apiBase}/knowledge/jobs/prepare`, { method: 'POST' })
method: 'POST' return expectJson(response)
})
await expectOk(response)
}) })
} catch (error) { } catch {}
setErrorMessage(String(error?.message || error))
}
} }
const librarySlug = library?.slug || null const librarySlug = library?.slug || null
@@ -190,7 +357,29 @@ export default function LibraryManager({
job => job.slug === librarySlug && (job.status === 'queued' || job.status === 'running') job => job.slug === librarySlug && (job.status === 'queued' || job.status === 'running')
) )
const isReadyForChat = !!library?.states?.is_indexed const isReadyForChat = !!library?.states?.is_indexed
const hasFailedFiles = (library?.files || []).some(file => file?.sync?.status === 'failed') const items = library?.files || []
const hasFailedItems = items.some(item => item?.sync?.status === 'failed')
const filteredItems = useMemo(() => {
const term = search.trim().toLowerCase()
if (!term) return items
return items.filter(item => [
item.title,
item.name,
item.path,
item.url,
item.kind,
item.source_session_title,
item.source_role,
item.channel,
item.video_summary,
item.metadata?.headline,
item.metadata?.summary,
...(item.metadata?.keywords || []),
...(item.metadata?.entities || []).map(entity => entity?.name)
]
.some(value => String(value || '').toLowerCase().includes(term)))
}, [items, search])
const hasMissingMetadata = items.some(item => !['ready', 'fallback'].includes(item?.metadata?.status))
useEffect(() => { useEffect(() => {
if (!library?.slug) { if (!library?.slug) {
@@ -198,66 +387,29 @@ export default function LibraryManager({
clearToasts() clearToasts()
return return
} }
const nextState = { const nextState = {
slug: library.slug, slug: library.slug,
hasFiles: !!library.files?.length, hasItems: items.length > 0,
isSyncing, isSyncing,
isReadyForChat, isReadyForChat,
hasFailedFiles hasFailedItems
} }
const previousState = previousLibraryStateRef.current const previousState = previousLibraryStateRef.current
if (!previousState || previousState.slug !== nextState.slug) { if (!previousState || previousState.slug !== nextState.slug) {
previousLibraryStateRef.current = nextState previousLibraryStateRef.current = nextState
clearToasts()
return return
} }
if (!previousState.isSyncing && nextState.isSyncing) { if (!previousState.isSyncing && nextState.isSyncing) {
queueToast( queueToast('Syncing Knowledge. Heimgeist is rebuilding its search indexes.')
'Syncing this database. Heimgeist is rebuilding the corpus and indexes automatically, and only selected files will run through enrichment.' } else if (previousState.isSyncing && !nextState.isSyncing) {
) if (nextState.hasFailedItems) queueToast('Some content did not finish syncing.', 'warning')
else if (nextState.isReadyForChat) queueToast('Sync complete. Knowledge is ready in chat.', 'success')
} }
if (previousState.isSyncing && !nextState.isSyncing) {
if (nextState.hasFailedFiles) {
queueToast(
'Some files did not finish syncing. Their tiles show the failure state and error details.',
'warning'
)
} else if (nextState.isReadyForChat) {
queueToast(
'Sync complete. This database is ready in chat. Raw indexing stays on by default; enable enrichment only for files that need deeper recall.',
'success'
)
} else if (!nextState.hasFiles) {
queueToast('Add files to make this database available in chat.')
}
} else if (previousState.hasFiles && !nextState.hasFiles && !nextState.isSyncing) {
queueToast('All files were removed. Add files to make this database available in chat.')
} else if (!previousState.hasFailedFiles && nextState.hasFailedFiles && !nextState.isSyncing) {
queueToast(
'Some files did not finish syncing. Their tiles show the failure state and error details.',
'warning'
)
}
previousLibraryStateRef.current = nextState previousLibraryStateRef.current = nextState
}, [ }, [library?.slug, items.length, hasFailedItems, isReadyForChat, isSyncing])
library?.slug,
library?.files?.length,
hasFailedFiles,
isReadyForChat,
isSyncing
])
if (!library) { if (!library) {
return ( return <div className="placeholder-view"><p>Add files, your own texts, or websites to Knowledge.</p></div>
<div className="placeholder-view">
<p>Create a database and add files. Heimgeist will raw-index them automatically, and you can opt specific files into enrichment.</p>
</div>
)
} }
return ( return (
@@ -265,64 +417,215 @@ export default function LibraryManager({
<div className="library-panel-scroll"> <div className="library-panel-scroll">
{errorMessage && <div className="form-error">{errorMessage}</div>} {errorMessage && <div className="form-error">{errorMessage}</div>}
<div className="library-files"> {formMode === 'text' && (
<h2>Files</h2> <form className="library-inline-form library-content-form" onSubmit={submitText}>
{library.files?.length ? ( <div className="library-form-header">
<div className="library-file-list"> <strong>{editingItemId ? 'Edit text' : 'Add text'}</strong>
{library.files.map(file => { <button type="button" className="button ghost" onClick={closeForm}>Cancel</button>
const sync = fileSyncMeta(file) </div>
return ( <label>
<div key={file.sha256 || file.rel} className="library-file-row"> Title
<div className="library-file-meta"> <input value={textTitle} onChange={event => setTextTitle(event.target.value)} autoFocus required />
<div className="library-file-name">{file.name || file.path}</div> </label>
<div className="library-file-path">{file.path}</div> <label>
<div className={`library-file-mode ${file.enrich_enabled ? 'enabled' : ''}`}> Text
{file.enrich_enabled ? 'Enrichment on' : 'Raw only'} <textarea value={textContent} onChange={event => setTextContent(event.target.value)} rows={12} required />
</div> </label>
<div className="library-file-sync"> <div className="library-form-actions">
<div className="library-file-sync-row"> <button className="button" type="submit" disabled={busy}>{editingItemId ? 'Save Changes' : 'Add Text'}</button>
<span className={`library-file-sync-label ${sync.status}`}>{sync.label}</span> </div>
<span className="library-file-sync-detail">{sync.detail}</span> </form>
</div> )}
<div
className={`library-file-progress ${sync.status}`} {formMode === 'website' && (
role="progressbar" <form className="library-inline-form library-content-form" onSubmit={submitWebsite}>
aria-valuemin="0" <div className="library-form-header">
aria-valuemax="100" <strong>Add website or video</strong>
aria-valuenow={Math.round(sync.progress)} <button type="button" className="button ghost" onClick={closeForm}>Cancel</button>
aria-label={`${file.name || file.path} sync progress`} </div>
> <p className="muted-copy library-video-help">
<div Supported video links are detected automatically, downloaded temporarily, transcribed with Whisper, and summarized locally. Video and audio files are discarded afterwards.
className="library-file-progress-bar" </p>
style={{ width: `${sync.progress}%` }} <label>
/> Website or video URL
</div> <input type="url" value={websiteUrl} onChange={event => setWebsiteUrl(event.target.value)} placeholder="https://example.com/article-or-video" autoFocus required />
</label>
<label>
Custom title <span className="muted-copy">(optional)</span>
<input value={websiteTitle} onChange={event => setWebsiteTitle(event.target.value)} />
</label>
<p className="muted-copy">Normal webpages are saved as one local text snapshot. Heimgeist will not crawl linked pages.</p>
<div className="library-form-actions">
<button className="button" type="submit" disabled={busy}>{websiteProcessing ? 'Processing content...' : 'Add Content'}</button>
</div>
{websiteProcessing && <div className="library-video-processing">Video processing can take several minutes. Heimgeist is downloading audio, transcribing it, and generating a local summary.</div>}
</form>
)}
<div className="library-content-heading">
<div>
<h2>Contents</h2>
<p className="muted-copy">Files, texts, website snapshots, videos, and saved chat messages are searched together through Knowledge workflows.</p>
</div>
<input
className="library-search"
value={search}
onChange={event => setSearch(event.target.value)}
placeholder="Search contents"
aria-label="Search Knowledge contents"
/>
</div>
{filteredItems.length ? (
<div className="library-content-grid">
{filteredItems.map(item => {
const sync = itemSyncMeta(item)
const label = kindLabel(item)
const source = item.kind === 'website'
? item.url
: item.kind === 'video'
? `${item.channel ? `${item.channel} · ` : ''}${item.duration_text || 'Saved video'}`
: item.kind === 'text'
? 'Written in Heimgeist'
: item.kind === 'chat_message'
? `${item.source_role === 'user' ? 'User message' : 'Assistant message'} · ${item.source_session_title || 'Chat'}`
: item.path
const itemId = item.item_id || item.sha256 || item.rel
const isExpanded = expandedItemId === itemId
const preview = contentPreviews[itemId]
const metadata = item.metadata || {}
const keywords = Array.isArray(metadata.keywords) ? metadata.keywords : []
const entities = Array.isArray(metadata.entities) ? metadata.entities : []
const qaPairs = Array.isArray(metadata.qa) ? metadata.qa : []
const qualityFlags = Array.isArray(metadata.quality_flags) ? metadata.quality_flags : []
return (
<article key={itemId} className={`library-content-card kind-${item.kind || 'file'} ${isExpanded ? 'expanded' : ''}`}>
<div className="library-content-card-header">
<span className="library-kind-badge">{label}</span>
<span className={`library-file-sync-label ${sync.status}`}>{sync.label}</span>
</div>
<div className="library-file-name">{item.title || item.name || item.path}</div>
<div className="library-file-path">{source}</div>
<div className={`library-file-mode ${item.enrich_enabled ? 'enabled' : ''}`}>
{item.enrich_enabled ? 'Deep enrichment' : 'Standard'}
</div>
{item.kind === 'video' && item.video_summary && (
<div className="library-video-summary">
<div className="library-metadata-label">Video summary</div>
<p>{item.video_summary}</p>
<div className="library-metadata-details">
{item.extractor && <span>Provider: {item.extractor}</span>}
{item.video_id && <span>Video ID: {item.video_id}</span>}
{item.upload_date && <span>Uploaded: {item.upload_date}</span>}
{item.transcription_model && <span>Whisper: {item.transcription_model}</span>}
{item.transcription_workers && <span>Workers: {item.transcription_workers}</span>}
{item.transcription_slices && <span>Audio slices: {item.transcription_slices}</span>}
{item.transcript_chars && <span>Transcript: {Number(item.transcript_chars).toLocaleString()} characters</span>}
{item.summary_model && <span>Summary: {item.summary_model}</span>}
{item.yt_dlp_version && <span>yt-dlp: {item.yt_dlp_version}</span>}
{item.fetched_at && <span>Processed: {new Date(item.fetched_at).toLocaleString()}</span>}
</div> </div>
{item.url && <div className="library-video-source">Source: {item.url}</div>}
{item.thumbnail_url && <button type="button" className="button ghost library-video-thumbnail" onClick={() => desktopApi.openExternalLink(item.thumbnail_url)}>Open thumbnail</button>}
</div> </div>
<div className="library-file-actions"> )}
<button <div className={`library-item-metadata status-${metadata.status || 'missing'}`}>
className="button ghost" {metadata.headline && <h3>{metadata.headline}</h3>}
disabled={busy || isSyncing} {metadata.summary ? (
onClick={() => updateFileEnrichment(file.rel, !file.enrich_enabled)} <p>{metadata.summary}</p>
> ) : (
{file.enrich_enabled ? 'Use Raw Only' : 'Enable Enrich'} <p className="muted-copy">
</button> {metadata.status === 'pending' ? 'Metadata is being generated.' : 'No automatic metadata has been generated yet.'}
<button className="button ghost" onClick={() => window.electronAPI?.openPath?.(file.path)}>Open</button> </p>
<button className="button ghost" disabled={busy || isSyncing} onClick={() => removeFile(file.rel)}>Remove</button> )}
{keywords.length > 0 && (
<div className="library-metadata-chips" aria-label="Keywords">
{keywords.map(keyword => <span key={keyword}>{keyword}</span>)}
</div>
)}
{entities.length > 0 && (
<div className="library-metadata-entities">
{entities.map(entity => (
<span key={`${entity.name}-${entity.type}`}>{entity.name}{entity.type ? ` · ${entity.type}` : ''}</span>
))}
</div>
)}
{qaPairs.length > 0 && (
<div className="library-metadata-qa">
<div className="library-metadata-label">Generated Q&amp;A</div>
{qaPairs.map((qa, index) => (
<div className="library-metadata-qa-pair" key={`${qa.q}-${index}`}>
<strong>{qa.q}</strong>
<span>{qa.a}</span>
</div>
))}
</div>
)}
{(metadata.model || metadata.language || metadata.strategy || qualityFlags.length > 0) && (
<div className="library-metadata-details">
{metadata.model && <span>Model: {metadata.model}</span>}
{metadata.language && <span>Language: {metadata.language}</span>}
{metadata.strategy && <span>Strategy: {metadata.strategy}</span>}
{qualityFlags.length > 0 && <span>Flags: {qualityFlags.join(', ')}</span>}
</div>
)}
{metadata.status === 'fallback' && <div className="library-metadata-warning">Local model metadata was unavailable; Heimgeist used a text fallback.</div>}
{metadata.status === 'failed' && <div className="library-metadata-warning">{metadata.error || 'Metadata generation failed.'}</div>}
</div>
<div className="library-file-sync">
<div className="library-file-sync-detail">{sync.detail}</div>
<div className={`library-file-progress ${sync.status}`} role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow={Math.round(sync.progress)}>
<div className="library-file-progress-bar" style={{ width: `${sync.progress}%` }} />
</div> </div>
</div> </div>
) {isExpanded && (
})} <div className="library-content-preview">
</div> <div className="library-content-preview-label">
) : ( {item.kind === 'website' ? 'Saved website text' : item.kind === 'video' ? 'Video summary and transcript' : item.kind === 'chat_message' ? 'Stored chat knowledge' : item.kind === 'text' ? 'Stored text' : 'Extracted text used by RAG'}
<p className="muted-copy">No files registered yet.</p> </div>
)} {preview?.loading && <div className="muted-copy">Loading content…</div>}
</div> {preview?.error && <div className="form-error">{preview.error}</div>}
{preview?.data && (
<>
<pre>{preview.data.content || 'No readable text was extracted from this item.'}</pre>
{preview.data.content_truncated && <div className="muted-copy">Preview shortened. The indexed source contains more text.</div>}
</>
)}
</div>
)}
<div className="library-file-actions">
<button className="button ghost" disabled={busy} onClick={() => toggleContentPreview(item)}>
{isExpanded ? 'Hide Content' : 'View Content'}
</button>
{(item.kind === 'text' || item.kind === 'chat_message') && <button className="button ghost" disabled={busy} onClick={() => editText(item)}>Edit</button>}
{item.kind === 'chat_message' && <button className="button ghost" onClick={() => onOpenChatMessage?.(item)}>Open Chat</button>}
{item.kind === 'website' && <button className="button ghost" onClick={() => desktopApi.openExternalLink(item.url)}>Open</button>}
{item.kind === 'website' && <button className="button ghost" disabled={busy} onClick={() => refreshWebsite(item)}>Refresh</button>}
{item.kind === 'video' && <button className="button ghost" onClick={() => desktopApi.openExternalLink(item.url)}>Open</button>}
{item.kind === 'video' && <button className="button ghost" disabled={busy} onClick={() => refreshVideo(item)}>Reprocess</button>}
{(!item.kind || item.kind === 'file') && <button className="button ghost" onClick={() => desktopApi.openPath(item.path)}>Open</button>}
<button className="button ghost" disabled={busy || isSyncing} onClick={() => updateEnrichment(item, !item.enrich_enabled)}>
{item.enrich_enabled ? 'Use Standard' : 'Enable Deep'}
</button>
<button className="button ghost" disabled={busy || isSyncing} onClick={() => removeItem(item)}>Remove</button>
</div>
</article>
)
})}
</div>
) : (
<p className="muted-copy">{items.length ? 'No matching contents.' : 'No content added yet.'}</p>
)}
</div> </div>
<div className="library-footer-actions"> <div className="library-footer-actions">
<button className="button" disabled={busy} onClick={addPaths}>Add Files</button> <button className="button" disabled={busy} onClick={addPaths}>Add Files</button>
{library.files?.length > 0 && !isSyncing && !isReadyForChat && ( <button className="button" disabled={busy} onClick={() => { closeForm(); setFormMode('text') }}>Add Text</button>
<button className="button" disabled={busy} onClick={() => { closeForm(); setFormMode('website') }}>Add Website / Video</button>
{items.length > 0 && hasMissingMetadata && !isSyncing && isReadyForChat && (
<button className="button ghost" disabled={busy} onClick={generateMetadata}>Generate Metadata</button>
)}
{items.length > 0 && !isSyncing && !isReadyForChat && (
<button className="button ghost" disabled={busy} onClick={retrySync}>Retry Sync</button> <button className="button ghost" disabled={busy} onClick={retrySync}>Retry Sync</button>
)} )}
</div> </div>
@@ -330,11 +633,7 @@ export default function LibraryManager({
{toasts.length > 0 && ( {toasts.length > 0 && (
<div className="library-toast-stack" aria-live="polite"> <div className="library-toast-stack" aria-live="polite">
{toasts.map(toast => ( {toasts.map(toast => (
<div <div key={toast.id} className={`library-toast ${toast.tone}`} role={toast.tone === 'warning' ? 'alert' : 'status'}>
key={toast.id}
className={`library-toast ${toast.tone}`}
role={toast.tone === 'warning' ? 'alert' : 'status'}
>
{toast.message} {toast.message}
</div> </div>
))} ))}

View File

@@ -0,0 +1,125 @@
import React, { useEffect, useState } from 'react'
import { splitThinkBlocks } from './chatText'
function cleanAssistantContent(content) {
const raw = String(content || '')
try {
const { answer } = splitThinkBlocks(raw)
return String(answer || raw).trim()
} catch {
return raw.trim()
}
}
function defaultTitle(message) {
const prefix = message?.role === 'user' ? 'User note' : 'Saved answer'
const content = message?.role === 'assistant'
? cleanAssistantContent(message?.content)
: String(message?.content || '').trim()
const compact = content.replace(/\s+/g, ' ')
if (!compact) return prefix
const excerpt = compact.length > 90 ? `${compact.slice(0, 87).trim()}...` : compact
return `${prefix}: ${excerpt}`
}
function defaultKnowledgeContent(message, precedingUserMessage) {
const content = message?.role === 'assistant'
? cleanAssistantContent(message?.content)
: String(message?.content || '').trim()
if (message?.role !== 'assistant' || !precedingUserMessage?.content?.trim()) {
return content
}
return `User question:\n${precedingUserMessage.content.trim()}\n\nAssistant response:\n${content}`
}
async function expectJson(response) {
const raw = await response.text()
let data = null
try {
data = raw ? JSON.parse(raw) : null
} catch {}
if (!response.ok) {
throw new Error(data?.detail || raw || `HTTP ${response.status}`)
}
return data
}
export default function SaveMessageToKnowledgeDialog({
apiBase,
message,
onClose,
onSaved,
precedingUserMessage,
}) {
const [title, setTitle] = useState(() => defaultTitle(message))
const [content, setContent] = useState(() => defaultKnowledgeContent(message, precedingUserMessage))
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
const onKeyDown = event => {
if (event.key === 'Escape' && !busy) onClose()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [busy, onClose])
async function submit(event) {
event.preventDefault()
if (!message?.message_id) return
setBusy(true)
setError('')
try {
const response = await fetch(`${apiBase}/knowledge/chat-messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message_id: message.message_id,
title,
content,
}),
})
const data = await expectJson(response)
await onSaved(data)
} catch (submitError) {
setError(String(submitError?.message || submitError))
} finally {
setBusy(false)
}
}
return (
<div className="knowledge-save-overlay" role="presentation" onMouseDown={event => {
if (event.target === event.currentTarget && !busy) onClose()
}}>
<form className="knowledge-save-dialog" role="dialog" aria-modal="true" aria-labelledby="knowledge-save-title" onSubmit={submit}>
<div className="knowledge-save-header">
<div>
<strong id="knowledge-save-title">Save message to knowledge</strong>
<p>The saved snapshot becomes a normal item in Knowledge.</p>
</div>
<button type="button" className="icon-button" title="Close" aria-label="Close" onClick={onClose} disabled={busy}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12" /></svg>
</button>
</div>
<label>
Title
<input value={title} onChange={event => setTitle(event.target.value)} required autoFocus disabled={busy} />
</label>
<label>
Knowledge content
<textarea value={content} onChange={event => setContent(event.target.value)} rows={12} required disabled={busy} />
</label>
{error && <div className="form-error">{error}</div>}
<div className="knowledge-save-actions">
<button type="button" className="button ghost" onClick={onClose} disabled={busy}>Cancel</button>
<button type="submit" className="button" disabled={busy || !title.trim() || !content.trim()}>
{busy ? 'Saving...' : 'Save to Knowledge'}
</button>
</div>
</form>
</div>
)
}

88
src/SettingsPanels.jsx Normal file
View File

@@ -0,0 +1,88 @@
import GeneralSettings from './GeneralSettings'
import InterfaceSettings from './InterfaceSettings'
import WebsearchSettings from './WebsearchSettings'
import { normalizeWebsearchEngines } from './websearchEngines'
const SETTINGS_SECTIONS = ['General', 'AI Models', 'Interface', 'Backend', 'Updates', 'Advanced']
export function SettingsSidebar({ activeSection, onSelect }) {
return (
<div className="settings-list">
{SETTINGS_SECTIONS.map(section => (
<div
key={section}
className={`settings-item ${activeSection === section ? 'active' : ''}`}
onClick={() => onSelect(section)}
>
{section}
</div>
))}
</div>
)
}
export function SettingsPanel({
activeSection,
onAudioInputDeviceChange,
onAudioInputLanguageChange,
onBackendApiUrlChange,
onLibrariesPurged,
onModelChange,
onStreamOutputChange,
onTranscriptionModelChange,
onVisionModelChange,
onWorkflowRouterModelChange,
onWorkflowSelectionModeChange,
searxEngines,
searxUrl,
setSearxEngines,
setSearxUrl,
streamOutput,
}) {
return (
<>
<div className="header">
<strong>{activeSection} Settings</strong>
</div>
{activeSection === 'General' && (
<GeneralSettings
panel="General"
onAudioInputDeviceChange={onAudioInputDeviceChange}
onAudioInputLanguageChange={onAudioInputLanguageChange}
/>
)}
{activeSection === 'AI Models' && (
<GeneralSettings
panel="AI Models"
onModelChange={onModelChange}
onVisionModelChange={onVisionModelChange}
onWorkflowRouterModelChange={onWorkflowRouterModelChange}
onWorkflowSelectionModeChange={onWorkflowSelectionModeChange}
onTranscriptionModelChange={onTranscriptionModelChange}
onLibrariesPurged={onLibrariesPurged}
/>
)}
{activeSection === 'Interface' && (
<InterfaceSettings
streamOutput={streamOutput}
onStreamOutputChange={onStreamOutputChange}
/>
)}
{activeSection === 'Backend' && (
<WebsearchSettings
onBackendApiUrlChange={onBackendApiUrlChange}
searxUrl={searxUrl}
setSearxUrl={setSearxUrl}
engines={searxEngines}
setEngines={(next) => setSearxEngines(normalizeWebsearchEngines(next))}
/>
)}
{activeSection === 'Updates' && (
<GeneralSettings panel="Updates" />
)}
{activeSection === 'Advanced' && (
<GeneralSettings panel="Advanced" onLibrariesPurged={onLibrariesPurged} />
)}
</>
)
}

View File

@@ -1,21 +1,90 @@
// src/WebsearchSettings.jsx // src/WebsearchSettings.jsx
import React from 'react'; import React, { useEffect, useState } from 'react';
import { WEBSEARCH_ENGINE_OPTIONS, normalizeWebsearchEngines } from './websearchEngines' import { WEBSEARCH_ENGINE_OPTIONS, normalizeWebsearchEngines } from './websearchEngines'
import desktopApi from './desktop/desktopApi'
const BACKEND_API_URL_KEY = 'backendApiUrl'
const OLLAMA_API_URL_KEY = 'ollamaApiUrl'
const DEFAULT_BACKEND_API_URL = 'http://127.0.0.1:8000'
const DEFAULT_OLLAMA_API_URL = 'http://127.0.0.1:11434'
function resolveBackendApiUrl(settings) {
return settings.backendApiUrl || settings.ollamaApiUrl || DEFAULT_BACKEND_API_URL
}
export default function WebsearchSettings({ export default function WebsearchSettings({
onBackendApiUrlChange,
searxUrl, searxUrl,
setSearxUrl, setSearxUrl,
engines, engines,
setEngines, setEngines,
}) { }) {
const [backendApiUrl, setBackendApiUrl] = useState('')
const [ollamaApiUrl, setOllamaApiUrl] = useState('')
useEffect(() => {
let cancelled = false
desktopApi.getSettings().then(settings => {
if (cancelled) {
return
}
setBackendApiUrl(resolveBackendApiUrl(settings))
setOllamaApiUrl(settings.ollamaApiUrl || DEFAULT_OLLAMA_API_URL)
})
return () => {
cancelled = true
}
}, [])
const toggleEngine = (name) => { const toggleEngine = (name) => {
const set = new Set(engines || []); const set = new Set(engines || []);
if (set.has(name)) set.delete(name); else set.add(name); if (set.has(name)) set.delete(name); else set.add(name);
setEngines(normalizeWebsearchEngines(Array.from(set))); setEngines(normalizeWebsearchEngines(Array.from(set)));
} }
const handleBackendUrlChange = (event) => {
const newUrl = event.target.value
setBackendApiUrl(newUrl)
desktopApi.setSetting(BACKEND_API_URL_KEY, newUrl)
if (onBackendApiUrlChange) {
onBackendApiUrlChange(newUrl)
}
}
const handleOllamaUrlChange = (event) => {
const newUrl = event.target.value
setOllamaApiUrl(newUrl)
desktopApi.setSetting(OLLAMA_API_URL_KEY, newUrl)
}
return ( return (
<div className="settings-content-panel"> <div className="settings-content-panel">
<div className="setting-section">
<h3>Heimgeist Backend URL</h3>
<input
type="text"
className="input"
value={backendApiUrl}
onChange={handleBackendUrlChange}
placeholder={`e.g., ${DEFAULT_BACKEND_API_URL}`}
/>
<p className="setting-description">Internal UI requests like chats, sessions, and Knowledge go to this URL.</p>
</div>
<div className="setting-section">
<h3>Ollama URL</h3>
<input
type="text"
className="input"
value={ollamaApiUrl}
onChange={handleOllamaUrlChange}
placeholder={`e.g., ${DEFAULT_OLLAMA_API_URL}`}
/>
<p className="setting-description">Heimgeist uses this URL to talk to Ollama for models and chat generation.</p>
</div>
<div className="setting-section"> <div className="setting-section">
<h3>SearXNG URL</h3> <h3>SearXNG URL</h3>
<input <input

24
src/appConfig.js Normal file
View File

@@ -0,0 +1,24 @@
export const API_URL_KEY = 'backendApiUrl'
export const COLOR_SCHEME_KEY = 'colorScheme'
export const WEBSEARCH_URL_KEY = 'websearch.searxUrl'
export const WEBSEARCH_ENGINES_KEY = 'websearch.engines'
export const CHAT_WORKFLOW_MAP_KEY = 'chat.workflowBySession'
export const DEFAULT_SEARX_URL = 'http://127.0.0.1:8888'
export const DEFAULT_BACKEND_API_URL = import.meta.env.VITE_API_URL ?? 'http://127.0.0.1:8000'
export const MAX_IMAGE_ATTACHMENTS = 6
export const MAX_IMAGE_ATTACHMENT_BYTES = 20 * 1024 * 1024
export const MAX_AUDIO_RECORDING_MS = 5 * 60 * 1000
export const AUDIO_RECORDING_TICK_MS = 200
export const TOP_ALIGN_OFFSET = 48
export const BOTTOM_EPSILON = 24
export function resolveBackendApiUrl(settings) {
return settings?.backendApiUrl || settings?.ollamaApiUrl || DEFAULT_BACKEND_API_URL
}
export function migrateLegacySearxUrl(value) {
const trimmed = typeof value === 'string' ? value.trim() : ''
if (!trimmed) return DEFAULT_SEARX_URL
if (trimmed === 'http://localhost:8888') return DEFAULT_SEARX_URL
return trimmed
}

203
src/attachments.jsx Normal file
View File

@@ -0,0 +1,203 @@
const CHAT_IMAGE_EXTENSION_LIST = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.tif', '.tiff', '.heic', '.avif']
const CHAT_FILE_EXTENSION_LIST = [
'.pdf', '.html', '.htm', '.txt', '.md', '.rst', '.epub',
'.mp3', '.wav', '.m4a', '.flac', '.ogg', '.opus', '.aac',
'.mp4', '.mkv', '.mov', '.webm', '.avi', '.ts',
]
const CHAT_IMAGE_EXTENSION_SET = new Set(CHAT_IMAGE_EXTENSION_LIST)
const CHAT_FILE_EXTENSION_SET = new Set(CHAT_FILE_EXTENSION_LIST)
const CHAT_AUDIO_EXTENSION_SET = new Set(['.mp3', '.wav', '.m4a', '.flac', '.ogg', '.opus', '.aac'])
const CHAT_VIDEO_EXTENSION_SET = new Set(['.mp4', '.mkv', '.mov', '.webm', '.avi', '.ts'])
const CHAT_TEXT_EXTENSION_SET = new Set(['.txt', '.md', '.rst'])
export const CHAT_FILE_PICKER_FILTERS = [
{ name: 'Documents and Media', extensions: CHAT_FILE_EXTENSION_LIST.map(extension => extension.slice(1)) },
]
export function getFileExtension(value) {
const text = String(value || '').trim()
const match = /(?:\.([A-Za-z0-9]+))$/.exec(text)
return match ? `.${match[1].toLowerCase()}` : ''
}
export function getFileName(value, fallback = 'attachment') {
const text = String(value || '').trim()
if (!text) return fallback
const parts = text.split(/[\\/]/)
return parts[parts.length - 1] || fallback
}
export function guessMimeTypeFromName(value) {
const extension = getFileExtension(value)
switch (extension) {
case '.pdf': return 'application/pdf'
case '.html':
case '.htm': return 'text/html'
case '.txt': return 'text/plain'
case '.md': return 'text/markdown'
case '.rst': return 'text/x-rst'
case '.epub': return 'application/epub+zip'
case '.mp3': return 'audio/mpeg'
case '.wav': return 'audio/wav'
case '.m4a': return 'audio/mp4'
case '.flac': return 'audio/flac'
case '.ogg': return 'audio/ogg'
case '.opus': return 'audio/opus'
case '.aac': return 'audio/aac'
case '.mp4': return 'video/mp4'
case '.mkv': return 'video/x-matroska'
case '.mov': return 'video/quicktime'
case '.webm': return 'video/webm'
case '.avi': return 'video/x-msvideo'
case '.ts': return 'video/mp2t'
default: return ''
}
}
export function attachmentIsImage(attachment) {
return Boolean(attachment?.data_url) || String(attachment?.kind || '').toLowerCase() === 'image'
}
export function attachmentIsFile(attachment) {
return Boolean(attachment) && !attachmentIsImage(attachment)
}
export function isSupportedChatFilePath(value) {
return CHAT_FILE_EXTENSION_SET.has(getFileExtension(value))
}
export function isSupportedChatImagePath(value) {
return CHAT_IMAGE_EXTENSION_SET.has(getFileExtension(value))
}
export function isImageFile(file) {
if (!file) return false
if (typeof file.type === 'string' && file.type.toLowerCase().startsWith('image/')) {
return true
}
return /\.(png|jpe?g|gif|bmp|webp|tiff?|heic|avif)$/i.test(file.name || '')
}
export function isSupportedChatFile(file) {
if (!file || isImageFile(file)) return false
return isSupportedChatFilePath(file.name || '')
}
export function getAttachmentDisplayName(attachment, fallback = 'attachment') {
return String(attachment?.name || '').trim() || getFileName(attachment?.source_path, fallback)
}
export function getFileAttachmentBadge(attachment) {
const mimeType = String(attachment?.mime_type || '').toLowerCase()
const extension = getFileExtension(attachment?.name || attachment?.source_path || '')
if (mimeType.startsWith('audio/') || CHAT_AUDIO_EXTENSION_SET.has(extension)) return 'AUDIO'
if (mimeType.startsWith('video/') || CHAT_VIDEO_EXTENSION_SET.has(extension)) return 'VIDEO'
if (CHAT_TEXT_EXTENSION_SET.has(extension)) return 'TEXT'
return 'DOC'
}
export function buildComposerAttachmentId(prefix = 'attachment') {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`
}
export function buildComposerFileAttachment({ sourcePath, name, mimeType, size }) {
const displayName = String(name || '').trim() || getFileName(sourcePath, 'file')
return {
id: buildComposerAttachmentId('file'),
kind: 'file',
name: displayName,
mime_type: String(mimeType || '').trim() || guessMimeTypeFromName(displayName || sourcePath),
source_path: sourcePath,
size: Number.isFinite(Number(size)) ? Number(size) : undefined,
}
}
export function hasFilePayload(event) {
const types = Array.from(event?.dataTransfer?.types || [])
return types.includes('Files')
}
export function eventHasImageFiles(event) {
const items = Array.from(event?.dataTransfer?.items || [])
if (items.length > 0) {
return items.some(item => item.kind === 'file' && isImageFile(item.getAsFile?.()))
}
const files = Array.from(event?.dataTransfer?.files || [])
return files.some(isImageFile)
}
export function readFileAsDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onerror = () => reject(reader.error || new Error(`Failed to read ${file?.name || 'image'}`))
reader.onload = () => resolve(String(reader.result || ''))
reader.readAsDataURL(file)
})
}
export function AttachmentStrip({ attachments, className = '', removable = false, onRemove }) {
if (!Array.isArray(attachments) || attachments.length === 0) {
return null
}
return (
<div className={`attachment-strip ${className}`.trim()}>
{attachments.map((attachment, index) => {
const isImage = attachmentIsImage(attachment)
const keySeed = isImage
? attachment?.data_url?.length || attachment?.name || index
: attachment?.source_path || attachment?.name || index
const key = attachment.id || `${getAttachmentDisplayName(attachment, 'attachment')}-${index}-${keySeed}`
if (isImage) {
const src = attachment?.data_url
if (!src) return null
return (
<div key={key} className="image-attachment-card">
{removable && (
<button
type="button"
className="attachment-remove"
onClick={() => onRemove?.(attachment.id)}
aria-label={`Remove ${getAttachmentDisplayName(attachment, 'image')}`}
title="Remove attachment"
>
×
</button>
)}
<img
className="image-attachment-thumb"
src={src}
alt={getAttachmentDisplayName(attachment, `Attachment ${index + 1}`)}
loading="lazy"
/>
</div>
)
}
const label = getAttachmentDisplayName(attachment, `Attachment ${index + 1}`)
return (
<div
key={key}
className="file-attachment-card"
title={attachment?.source_path || label}
>
{removable && (
<button
type="button"
className="attachment-remove attachment-remove--file"
onClick={() => onRemove?.(attachment.id)}
aria-label={`Remove ${label}`}
title="Remove attachment"
>
×
</button>
)}
<span className="file-attachment-badge">{getFileAttachmentBadge(attachment)}</span>
<span className="file-attachment-name">{label}</span>
</div>
)
})}
</div>
)
}

102
src/audioInput.js Normal file
View File

@@ -0,0 +1,102 @@
export const AUDIO_INPUT_ENABLED_KEY = 'audioInputEnabled'
export const AUDIO_INPUT_DEVICE_ID_KEY = 'audioInputDeviceId'
export const AUDIO_INPUT_LANGUAGE_KEY = 'audioInputLanguage'
export const AUDIO_INPUT_LANGUAGE_OPTIONS = [
{ value: '', label: 'Auto' },
{ value: 'de', label: 'German' },
{ value: 'en', label: 'English' },
{ value: 'fr', label: 'French' },
{ value: 'es', label: 'Spanish' },
{ value: 'it', label: 'Italian' },
{ value: 'pt', label: 'Portuguese' },
{ value: 'nl', label: 'Dutch' },
{ value: 'pl', label: 'Polish' },
{ value: 'tr', label: 'Turkish' },
{ value: 'ru', label: 'Russian' },
{ value: 'ja', label: 'Japanese' },
{ value: 'zh', label: 'Chinese' },
]
const AUDIO_RECORDER_MIME_CANDIDATES = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/mp4',
'audio/ogg;codecs=opus',
'',
]
export function supportsAudioInputCapture() {
return (
typeof navigator !== 'undefined' &&
typeof window !== 'undefined' &&
typeof window.MediaRecorder !== 'undefined' &&
Boolean(navigator.mediaDevices?.getUserMedia) &&
Boolean(navigator.mediaDevices?.enumerateDevices)
)
}
export function getAudioInputConstraints(deviceId = '') {
const audio = {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
}
if (deviceId) {
audio.deviceId = { exact: deviceId }
}
return { audio }
}
export function stopMediaStream(stream) {
stream?.getTracks?.().forEach(track => track.stop())
}
export async function ensureAudioInputPermission() {
if (!supportsAudioInputCapture()) {
throw new Error('Microphone capture is not available in this environment.')
}
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
stopMediaStream(stream)
}
export async function listAudioInputDevices() {
if (!supportsAudioInputCapture()) {
return []
}
const devices = await navigator.mediaDevices.enumerateDevices()
return devices
.filter(device => device.kind === 'audioinput')
.map((device, index) => {
const label = String(device.label || '').trim()
return {
deviceId: device.deviceId || `audio-input-${index + 1}`,
label: label || `Microphone ${index + 1}`,
hasLabel: Boolean(label),
}
})
}
export function getPreferredAudioRecorderMimeType() {
if (typeof window === 'undefined' || typeof window.MediaRecorder === 'undefined') {
return ''
}
for (const mimeType of AUDIO_RECORDER_MIME_CANDIDATES) {
if (!mimeType) {
return ''
}
if (
typeof window.MediaRecorder.isTypeSupported !== 'function' ||
window.MediaRecorder.isTypeSupported(mimeType)
) {
return mimeType
}
}
return ''
}

34
src/backendApi.js Normal file
View File

@@ -0,0 +1,34 @@
export function isAbortError(error) {
return error?.name === 'AbortError'
}
export function getErrorText(error) {
if (error instanceof Error && error.message) return error.message
return String(error)
}
export async function readBackendErrorText(response) {
const bodyText = await response.text().catch(() => '')
if (bodyText) {
try {
const data = JSON.parse(bodyText)
if (typeof data?.detail === 'string' && data.detail.trim()) {
return data.detail.trim()
}
if (typeof data?.message === 'string' && data.message.trim()) {
return data.message.trim()
}
} catch {}
return bodyText.trim()
}
return `HTTP ${response.status}`
}
export async function expectBackendJson(response) {
const data = await response.json().catch(() => null)
if (response.ok) return data
const detail = typeof data?.detail === 'string'
? data.detail
: (typeof data?.message === 'string' ? data.message : '')
throw new Error(detail || `HTTP ${response.status}`)
}

141
src/chatApi.js Normal file
View File

@@ -0,0 +1,141 @@
import { expectBackendJson } from './backendApi'
export async function fetchModelCapabilities(apiBase, modelName, signal) {
const response = await fetch(
`${apiBase}/models/capabilities?name=${encodeURIComponent(modelName)}`,
{ signal }
)
return expectBackendJson(response)
}
export async function fetchStartupOllamaStatus(apiBase) {
const response = await fetch(`${apiBase}/ollama/startup-status`)
return expectBackendJson(response)
}
export async function prepareStartupModels(apiBase) {
const response = await fetch(`${apiBase}/startup/prepare-models`, { method: 'POST' })
return expectBackendJson(response)
}
export async function fetchLocalLibraryContext(apiBase, prompt, signal) {
const response = await fetch(`${apiBase}/knowledge/context`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal,
body: JSON.stringify({
prompt,
top_k: 5,
}),
})
const data = await response.json()
return {
contextBlock: typeof data?.context_block === 'string' && data.context_block.trim()
? data.context_block.trim()
: null,
sources: Array.isArray(data?.sources) ? data.sources : [],
}
}
export async function fetchWebSearchContext({
apiBase,
engines,
historyLimit = 8,
messages,
model,
prompt,
searxUrl,
signal,
}) {
const response = await fetch(`${apiBase}/websearch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal,
body: JSON.stringify({
prompt,
model,
messages,
history_limit: historyLimit,
searx_url: searxUrl || null,
engines: Array.isArray(engines) ? engines : null,
}),
})
const data = await response.json()
return {
contextBlock: typeof data?.context_block === 'string' && data.context_block.trim()
? data.context_block.trim()
: null,
sources: Array.isArray(data?.sources) ? data.sources : [],
}
}
export function postChatMessage({
apiBase,
attachments,
enrichedMessage,
message,
model,
sessionId,
signal,
sources,
stream,
transcriptionModel,
visionModel,
}) {
return fetch(`${apiBase}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal,
body: JSON.stringify({
session_id: sessionId,
model,
message,
enriched_message: enrichedMessage,
stream,
sources: sources || [],
attachments,
vision_model: visionModel || null,
transcription_model: transcriptionModel || null,
}),
})
}
export function postRegenerateMessage({
apiBase,
enrichedMessage,
index,
model,
sessionId,
signal,
sources,
stream,
transcriptionModel,
visionModel,
}) {
return fetch(`${apiBase}/sessions/${sessionId}/regenerate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal,
body: JSON.stringify({
index,
model,
stream,
enriched_message: enrichedMessage,
sources: sources || [],
vision_model: visionModel || null,
transcription_model: transcriptionModel || null,
}),
})
}
export function requestGeneratedTitle({ apiBase, message, model, sessionId }) {
return fetch(`${apiBase}/generate-title`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
session_id: sessionId,
message,
model,
}),
})
}

735
src/chatGeneration.js Normal file
View File

@@ -0,0 +1,735 @@
import { flushSync } from 'react-dom'
import { attachmentIsImage, getAttachmentDisplayName } from './attachments'
import { getErrorText, isAbortError, readBackendErrorText } from './backendApi'
import {
fetchWebSearchContext,
postChatMessage,
postRegenerateMessage,
requestGeneratedTitle,
} from './chatApi'
import { sanitizeChatTitle } from './chatText'
import { createWorkflowRun, streamWorkflowEvents } from './workflows/workflowApi'
function messageHasImageAttachments(message) {
return Array.isArray(message?.attachments) && message.attachments.some(attachmentIsImage)
}
function buildAttachmentTitleSeed(text, attachments = []) {
const trimmed = String(text || '').trim()
if (trimmed) {
return trimmed
}
const firstAttachment = Array.isArray(attachments) ? attachments[0] : null
const firstName = getAttachmentDisplayName(firstAttachment, '')
return firstName || 'Attachment'
}
function setAssistantMessageContent(setChatSessions, sessionId, messageId, content, options = {}) {
const { removeIfEmpty = false } = options
setChatSessions(prevSessions =>
prevSessions.map(session => {
if (session.session_id !== sessionId) return session
const nextMessages = []
for (const message of session.messages || []) {
if (message.id !== messageId) {
nextMessages.push(message)
continue
}
if (removeIfEmpty && !content) continue
nextMessages.push({ ...message, content })
}
return { ...session, messages: nextMessages }
})
)
}
export function createChatGenerationHandlers({
activeSessionId,
activeSessionIdRef,
backendApiUrl,
attachWorkflowRunToRequest,
beginCancelableRequest,
canAttachImages,
chatSessions,
composerAttachments,
createNewChat,
finishCancelableRequest,
getChatWorkflowForSession,
imageAttachmentUnavailableReason,
input,
isSending,
model,
onMessagesPersisted,
onWorkflowRunEvent,
restoredForRef,
scrollMessageToTop,
scrollToBottom,
searxEngines,
searxUrl,
setChatSessions,
setComposerAttachments,
setInput,
setIsAttachmentMenuOpen,
setNewMsgTip,
setPendingScrollToLastUser,
setUnreadSessions,
setUserScrolledUp,
streamOutput,
transcriptionModel,
userScrolledUpRef,
visionModel,
webSearchEnabled,
workflowRouterModel,
workflowSelectionMode,
}) {
function getEffectiveWorkflowSelection(sessionId) {
if (workflowSelectionMode !== 'manual') {
return { mode: 'automatic', workflowId: null }
}
const selection = getChatWorkflowForSession?.(sessionId)
if (selection?.mode === 'explicit') {
return selection
}
return { mode: 'direct', workflowId: null }
}
async function executeWorkflowRun({
sessionId,
userMessage,
attachments,
requestController,
selection,
workflowRevisionId = null,
regenerateIndex = null,
isNewChat = false,
}) {
const created = await createWorkflowRun(backendApiUrl, {
session_id: sessionId,
message: userMessage.content,
model,
selection_mode: selection.mode,
workflow_id: selection.workflowId || null,
workflow_revision_id: workflowRevisionId,
web_search_enabled: Boolean(webSearchEnabled),
searx_url: searxUrl || null,
searx_engines: searxEngines || [],
attachments,
vision_model: visionModel || null,
transcription_model: transcriptionModel || null,
router_model: workflowRouterModel || null,
regenerate_index: regenerateIndex,
stream: true,
}, requestController.signal)
attachWorkflowRunToRequest?.(requestController, created.run_id)
const assistantMsgId = `workflow-${created.run_id}`
let fullReply = ''
setChatSessions(previous => previous.map(session => session.session_id === sessionId
? { ...session, messages: [...(session.messages || []), {
role: 'assistant', content: '', id: assistantMsgId, sources: [],
workflow_id: created.workflow?.id,
workflow_revision_id: created.workflow?.revision_id,
workflow_run_id: created.run_id,
}] }
: session))
onWorkflowRunEvent?.(sessionId, {
type: 'client_run_started',
run_id: created.run_id,
payload: { workflow: created.workflow },
timestamp: new Date().toISOString(),
})
await streamWorkflowEvents(backendApiUrl, created.run_id, {
signal: requestController.signal,
onEvent: event => {
onWorkflowRunEvent?.(sessionId, event)
if (event.type === 'model_token') {
fullReply += event.payload?.text || ''
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, fullReply)
} else if (event.type === 'run_completed') {
const finalOutput = event.payload?.output || null
const content = finalOutput?.content || fullReply
setChatSessions(previous => previous.map(session => {
if (session.session_id !== sessionId) return session
return {
...session,
messages: (session.messages || []).map(message => message.id === assistantMsgId
? { ...message, content, sources: finalOutput?.sources || message.sources || [] }
: message),
}
}))
} else if (event.type === 'run_failed') {
const message = event.payload?.message || 'Workflow execution failed.'
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, `Error: ${message}`)
} else if (event.type === 'run_cancelled') {
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, fullReply, { removeIfEmpty: true })
} else if (event.type === 'run_interrupted') {
const message = event.payload?.message || 'Workflow run was interrupted.'
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, `Error: ${message}`)
}
},
})
if (onMessagesPersisted) await onMessagesPersisted(sessionId)
if (activeSessionIdRef.current !== sessionId) {
setUnreadSessions(previous => [...new Set([...previous, sessionId])])
} else if (!userScrolledUpRef.current[sessionId]) {
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', sessionId))
}
if (isNewChat) {
requestGeneratedTitle({
apiBase: backendApiUrl,
message: buildAttachmentTitleSeed(userMessage.content, attachments),
model,
sessionId,
})
.then(response => response.json())
.then(data => {
const sanitizedTitle = sanitizeChatTitle(data.title)
setChatSessions(previous => previous.map(session =>
session.session_id === sessionId ? { ...session, name: sanitizedTitle } : session
))
})
}
}
async function regenerateFromIndex(index, overrideUserText = null) {
const sessionId = activeSessionId
if (isSending || !sessionId || typeof index !== 'number') return
const msgs = (chatSessions.find(s => s.session_id === sessionId)?.messages) || []
let lastUserIdx = index
for (let i = index; i >= 0; i--) {
if (msgs[i]?.role === 'user') {
lastUserIdx = i
break
}
}
setChatSessions(prev =>
prev.map(s => s.session_id === sessionId
? { ...s, messages: (s.messages || []).slice(0, lastUserIdx + 1) }
: s
)
)
const conversationNeedsVision = msgs
.slice(0, lastUserIdx + 1)
.some(messageHasImageAttachments)
if (conversationNeedsVision && !canAttachImages) {
window.alert(imageAttachmentUnavailableReason)
return
}
const requestController = beginCancelableRequest(sessionId)
if (getChatWorkflowForSession) {
try {
const currentSelection = getEffectiveWorkflowSelection(sessionId)
const originalAssistant = msgs.slice(lastUserIdx + 1).find(message => message?.role === 'assistant')
const originalWorkflowId = originalAssistant?.workflow_id || null
const originalSelectionMode = originalAssistant?.agent_summary?.selection_mode || null
let selection = currentSelection
let workflowRevisionId = null
if (currentSelection.mode === 'automatic' && originalSelectionMode === 'automatic' && originalWorkflowId) {
selection = { mode: 'explicit', workflowId: originalWorkflowId }
workflowRevisionId = originalAssistant?.workflow_revision_id || null
} else if (
originalWorkflowId
&& (
(currentSelection.mode === 'explicit' && originalSelectionMode === 'explicit' && currentSelection.workflowId === originalWorkflowId)
|| (currentSelection.mode === 'direct' && originalSelectionMode === 'direct')
)
) {
workflowRevisionId = originalAssistant?.workflow_revision_id || null
}
await executeWorkflowRun({
sessionId,
userMessage: { ...msgs[lastUserIdx], content: overrideUserText ?? msgs[lastUserIdx]?.content ?? '' },
attachments: msgs[lastUserIdx]?.attachments || [],
requestController,
selection,
workflowRevisionId,
regenerateIndex: lastUserIdx,
})
} catch (error) {
if (!isAbortError(error)) console.error('Failed to regenerate workflow response:', error)
} finally {
finishCancelableRequest(requestController)
}
return
}
let enrichedPrompt = overrideUserText != null ? overrideUserText : (msgs[lastUserIdx]?.content || '')
let citationSources = []
const contextBlocks = []
try {
const promptText = overrideUserText != null ? overrideUserText : (msgs[lastUserIdx]?.content || '')
const hasPromptText = Boolean((promptText || '').trim())
if (hasPromptText && webSearchEnabled) {
try {
const historyForSearch = msgs
.slice(Math.max(0, lastUserIdx - 7), lastUserIdx + 1)
.map(m => ({ role: m.role, content: m.content || '' }))
if (historyForSearch.length > 0) {
historyForSearch[historyForSearch.length - 1] = { role: 'user', content: promptText }
}
const searchContext = await fetchWebSearchContext({
apiBase: backendApiUrl,
engines: searxEngines,
historyLimit: 8,
messages: historyForSearch,
model,
prompt: promptText,
searxUrl,
signal: requestController.signal,
})
if (searchContext.contextBlock) {
contextBlocks.push(searchContext.contextBlock)
}
if (Array.isArray(searchContext.sources)) {
citationSources.push(...searchContext.sources)
}
} catch (error) {
if (isAbortError(error)) throw error
console.warn('web search enrichment (regenerate) failed', error)
}
}
citationSources = [...new Set(citationSources)]
if (hasPromptText && contextBlocks.length > 0) {
enrichedPrompt = `${promptText}\n\n${contextBlocks.join('\n\n')}`
} else {
enrichedPrompt = null
}
if (streamOutput) {
const assistantMsgId = `msg-${Date.now()}-${Math.random()}`
let full = ''
setChatSessions(prev =>
prev.map(s => s.session_id === sessionId
? { ...s, messages: [...(s.messages || []), { id: assistantMsgId, role: 'assistant', content: '', sources: citationSources }] }
: s
)
)
try {
const res = await postRegenerateMessage({
apiBase: backendApiUrl,
enrichedMessage: enrichedPrompt,
index,
model,
sessionId,
signal: requestController.signal,
sources: citationSources || [],
stream: true,
transcriptionModel,
visionModel,
})
if (!res.ok) throw new Error(await readBackendErrorText(res))
const reader = res.body?.getReader()
if (!reader) throw new Error('Missing response body')
const decoder = new TextDecoder()
let unreadMarked = false
while (true) {
const { value, done } = await reader.read()
if (done) break
const chunk = decoder.decode(value, { stream: true })
full += chunk
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, full)
if (!unreadMarked && activeSessionIdRef.current !== sessionId) {
unreadMarked = true
setPendingScrollToLastUser(prev => ({ ...prev, [sessionId]: assistantMsgId }))
setUnreadSessions(prev => [...new Set([...prev, sessionId])])
}
}
if (activeSessionIdRef.current !== sessionId) {
setPendingScrollToLastUser(prev => ({ ...prev, [sessionId]: assistantMsgId }))
setUnreadSessions(prev => [...new Set([...prev, sessionId])])
} else if (!userScrolledUpRef.current[sessionId]) {
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', sessionId))
} else {
setNewMsgTip(prev => ({ ...prev, [sessionId]: assistantMsgId }))
}
} catch (error) {
if (isAbortError(error)) {
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, full, { removeIfEmpty: true })
return
}
console.error(error)
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, `Error: ${getErrorText(error)}`, { removeIfEmpty: true })
return
}
} else {
const res = await postRegenerateMessage({
apiBase: backendApiUrl,
enrichedMessage: enrichedPrompt,
index,
model,
sessionId,
signal: requestController.signal,
sources: citationSources || [],
stream: false,
transcriptionModel,
visionModel,
})
if (!res.ok) throw new Error(await readBackendErrorText(res))
const data = await res.json()
const assistantMsgId = `msg-${Date.now()}`
setChatSessions(prev =>
prev.map(s => s.session_id === sessionId
? { ...s, messages: [...(s.messages || []), { role: 'assistant', content: data.reply, id: assistantMsgId, sources: citationSources }] }
: s
)
)
if (activeSessionIdRef.current !== sessionId) {
setPendingScrollToLastUser(prev => ({ ...prev, [sessionId]: assistantMsgId }))
setUnreadSessions(prev => [...new Set([...prev, sessionId])])
} else if (!userScrolledUpRef.current[sessionId]) {
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', sessionId))
} else {
setNewMsgTip(prev => ({ ...prev, [sessionId]: assistantMsgId }))
}
}
if (onMessagesPersisted) void onMessagesPersisted(sessionId)
} catch (error) {
if (!isAbortError(error)) {
console.error(error)
}
} finally {
finishCancelableRequest(requestController)
}
}
async function sendMessage() {
const trimmedInput = input.trim()
if (isSending || (!trimmedInput && composerAttachments.length === 0) || !model) return
if (composerAttachments.some(attachmentIsImage) && !canAttachImages) {
window.alert(imageAttachmentUnavailableReason)
return
}
let targetSessionId = activeSessionId
let isNewChat = false
if (!targetSessionId) {
const newSession = await createNewChat()
await new Promise(resolve => setTimeout(resolve, 200))
targetSessionId = newSession.session_id
isNewChat = true
} else {
const currentSession = chatSessions.find(s => s.session_id === targetSessionId)
isNewChat = currentSession && currentSession.name === "New Chat" && currentSession.messages.length === 0
}
const existingMessages = (chatSessions.find(s => s.session_id === targetSessionId)?.messages) || []
const outgoingAttachments = composerAttachments.map(({ id, ...attachment }) => ({ ...attachment }))
const historyNeedsVision = existingMessages.some(messageHasImageAttachments)
if (historyNeedsVision && !canAttachImages) {
window.alert(imageAttachmentUnavailableReason)
return
}
const composerSnapshot = input
const attachmentSnapshot = composerAttachments.map(attachment => ({ ...attachment }))
const userMsg = {
role: 'user',
content: trimmedInput,
attachments: outgoingAttachments,
id: `msg-${Date.now()}-${Math.random()}`,
}
setIsAttachmentMenuOpen(false)
setUserScrolledUp(targetSessionId, false)
if (activeSessionIdRef.current === targetSessionId) {
restoredForRef.current = activeSessionIdRef.current
}
flushSync(() => {
setChatSessions(prevSessions =>
prevSessions.map(session =>
session.session_id === targetSessionId
? { ...session, messages: [...(session.messages || []), userMsg] }
: session
)
)
setInput('')
setComposerAttachments([])
})
requestAnimationFrame(() => scrollToBottom('auto', targetSessionId))
const requestController = beginCancelableRequest(targetSessionId)
try {
if (getChatWorkflowForSession) {
const selection = getEffectiveWorkflowSelection(targetSessionId)
await executeWorkflowRun({
sessionId: targetSessionId,
userMessage: userMsg,
attachments: outgoingAttachments,
requestController,
selection,
isNewChat,
})
return
}
let historyForSearch = []
if (userMsg.content) try {
const existing = (chatSessions.find(s => s.session_id === targetSessionId)?.messages) || []
const lastFew = existing.slice(-8).map(m => ({ role: m.role, content: m.content || '' }))
historyForSearch = [...lastFew, { role: 'user', content: userMsg.content }]
} catch {}
let enrichedPrompt = userMsg.content || null
let citationSources = []
const contextBlocks = []
if (userMsg.content && webSearchEnabled) {
try {
const searchContext = await fetchWebSearchContext({
apiBase: backendApiUrl,
engines: searxEngines,
historyLimit: 8,
messages: historyForSearch,
model,
prompt: userMsg.content,
searxUrl,
signal: requestController.signal,
})
if (searchContext.contextBlock) {
contextBlocks.push(searchContext.contextBlock)
}
if (Array.isArray(searchContext.sources)) {
citationSources.push(...searchContext.sources)
}
} catch (error) {
if (isAbortError(error)) throw error
console.warn('web search enrichment failed', error)
}
}
citationSources = [...new Set(citationSources)]
if (userMsg.content && contextBlocks.length > 0) {
enrichedPrompt = `${userMsg.content}\n\n${contextBlocks.join('\n\n')}`
}
if (streamOutput) {
const assistantMsgId = `msg-${Date.now()}-${Math.random()}`
let fullReply = ''
const assistantMsg = { role: 'assistant', content: '', id: assistantMsgId, sources: citationSources }
setChatSessions(prevSessions =>
prevSessions.map(session =>
session.session_id === targetSessionId
? { ...session, messages: [...(session.messages || []), assistantMsg] }
: session
)
)
try {
const res = await postChatMessage({
apiBase: backendApiUrl,
attachments: outgoingAttachments,
enrichedMessage: userMsg.content && contextBlocks.length > 0 ? enrichedPrompt : null,
message: userMsg.content,
model,
sessionId: targetSessionId,
signal: requestController.signal,
sources: citationSources || [],
stream: true,
transcriptionModel,
visionModel,
})
if (!res.ok) {
const error = new Error(await readBackendErrorText(res))
error.status = res.status
throw error
}
const reader = res.body?.getReader()
if (!reader) throw new Error('Missing response body')
const decoder = new TextDecoder()
let pendingMarked = false
while (true) {
const { value, done } = await reader.read()
if (done) {
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply)
if (activeSessionIdRef.current === targetSessionId) {
if (!userScrolledUpRef.current[targetSessionId]) {
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', targetSessionId))
} else {
setNewMsgTip(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
}
} else {
setPendingScrollToLastUser(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
setUnreadSessions(prev => [...new Set([...prev, targetSessionId])])
}
break
}
const chunk = decoder.decode(value, { stream: true })
fullReply += chunk
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply)
if (activeSessionIdRef.current === targetSessionId && !userScrolledUpRef.current[targetSessionId]) {
scrollToBottom('auto', targetSessionId)
}
if (activeSessionIdRef.current !== targetSessionId && !pendingMarked) {
setPendingScrollToLastUser(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
pendingMarked = true
}
}
} catch (error) {
if (isAbortError(error)) {
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply, { removeIfEmpty: true })
return
}
console.error('Failed to send message:', error)
if (Number(error?.status) >= 400 && Number(error?.status) < 500) {
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply, { removeIfEmpty: true })
setChatSessions(prevSessions =>
prevSessions.map(session =>
session.session_id === targetSessionId
? {
...session,
messages: (session.messages || []).filter(message => message.id !== userMsg.id),
}
: session
)
)
setInput(composerSnapshot)
setComposerAttachments(attachmentSnapshot)
window.alert(getErrorText(error))
return
}
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, 'Error: ' + getErrorText(error), { removeIfEmpty: true })
return
}
} else {
const res = await postChatMessage({
apiBase: backendApiUrl,
attachments: outgoingAttachments,
enrichedMessage: userMsg.content && contextBlocks.length > 0 ? enrichedPrompt : null,
message: userMsg.content,
model,
sessionId: targetSessionId,
signal: requestController.signal,
sources: citationSources || [],
stream: false,
transcriptionModel,
visionModel,
})
if (!res.ok) {
const error = new Error(await readBackendErrorText(res))
error.status = res.status
throw error
}
const data = await res.json()
const assistantMsgId = `msg-${Date.now()}`
const assistantMsg = {
role: 'assistant',
content: data.reply,
id: assistantMsgId,
sources: citationSources,
}
setChatSessions(prevSessions =>
prevSessions.map(session =>
session.session_id === targetSessionId
? { ...session, messages: [...(session.messages || []), assistantMsg] }
: session
)
)
if (assistantMsgId) {
if (activeSessionIdRef.current === targetSessionId) {
if (!userScrolledUpRef.current[targetSessionId]) {
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', targetSessionId))
} else {
setNewMsgTip(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
}
} else {
setPendingScrollToLastUser(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
}
}
}
if (activeSessionIdRef.current !== targetSessionId) {
setUnreadSessions(prev => [...new Set([...prev, targetSessionId])])
}
if (onMessagesPersisted) void onMessagesPersisted(targetSessionId)
if (isNewChat) {
requestGeneratedTitle({
apiBase: backendApiUrl,
message: buildAttachmentTitleSeed(userMsg.content, outgoingAttachments),
model,
sessionId: targetSessionId,
})
.then(r => r.json())
.then(data => {
const sanitizedTitle = sanitizeChatTitle(data.title)
setChatSessions(prevSessions =>
prevSessions.map(session =>
session.session_id === targetSessionId ? { ...session, name: sanitizedTitle } : session
)
)
})
}
} catch (error) {
if (isAbortError(error)) {
finishCancelableRequest(requestController)
return
}
console.error('Failed to send message:', error)
if (Number(error?.status) >= 400 && Number(error?.status) < 500) {
setChatSessions(prevSessions =>
prevSessions.map(session =>
session.session_id === targetSessionId
? {
...session,
messages: (session.messages || []).filter(message => message.id !== userMsg.id),
}
: session
)
)
setInput(composerSnapshot)
setComposerAttachments(attachmentSnapshot)
window.alert(getErrorText(error))
return
}
const errorMsg = { role: 'assistant', content: 'Error: ' + getErrorText(error), id: `msg-${Date.now()}-${Math.random()}` }
setChatSessions(prevSessions =>
prevSessions.map(session =>
session.session_id === targetSessionId
? { ...session, messages: [...session.messages, errorMsg] }
: session
)
)
} finally {
finishCancelableRequest(requestController)
}
}
return {
regenerateFromIndex,
sendMessage,
}
}

124
src/chatText.js Normal file
View File

@@ -0,0 +1,124 @@
export function sanitizeChatTitle(title) {
let cleanedTitle = String(title || '')
.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '')
.trim()
let previousTitle = null
while (cleanedTitle && cleanedTitle !== previousTitle) {
previousTitle = cleanedTitle
cleanedTitle = cleanedTitle
.replace(/^\s*#+\s*/, '')
.replace(/^\s*\*{1,2}\s*/, '')
.replace(/\s*\*{1,2}\s*$/, '')
.trim()
}
return cleanedTitle.replace(/\s+/g, ' ').trim()
}
function appendOllamaErrorHint(text, marker, block) {
if (text.includes(marker)) {
return text
}
return `${text}\n\n${block}`
}
export function enrichOllamaErrorText(text) {
const raw = String(text || '')
const trimmed = raw.trim()
if (!trimmed) {
return raw
}
const lower = trimmed.toLowerCase()
const looksLikeOllamaError = (
lower.startsWith('error:') ||
lower.startsWith('ollama error:') ||
lower.includes("client error '") ||
lower.includes("server error '") ||
(lower.includes('http') && lower.includes('error')) ||
lower.includes('unknown model architecture') ||
lower.includes('out of memory')
)
if (!looksLikeOllamaError) {
return raw
}
if (lower.includes('unknown model architecture')) {
return appendOllamaErrorHint(
raw,
'[ERROR - Unsupported Model]',
'[ERROR - Unsupported Model]\nThis Ollama version does not support the model.\nUpdate Ollama.'
)
}
if (lower.includes('out of memory')) {
return appendOllamaErrorHint(
raw,
'[ERROR - Out of Memory]',
'[ERROR - Out of Memory]\nThe model is too large for available memory.\nUse a smaller or quantized model.'
)
}
if (lower.includes('502')) {
return appendOllamaErrorHint(
raw,
'[ERROR 502 - Bad Gateway]',
'[ERROR 502 - Bad Gateway]\nOllama did not return a valid response.\nTry restarting or updating Ollama.'
)
}
if (lower.includes('500')) {
return appendOllamaErrorHint(
raw,
'[ERROR 500 - Internal Server Error]',
"[ERROR 500 - Internal Server Error]\nOllama crashed while processing the request.\nCheck 'ollama logs' and memory usage."
)
}
if (lower.includes('404')) {
return appendOllamaErrorHint(
raw,
'[ERROR 404 - Not Found]',
"[ERROR 404 - Not Found]\nThe model or endpoint was not found.\nCheck the model name or run 'ollama pull <model>'."
)
}
if (lower.includes('400')) {
return appendOllamaErrorHint(
raw,
'[ERROR 400 - Bad Request]',
'[ERROR 400 - Bad Request]\nThe request sent to Ollama was invalid.\nCheck parameters or payload format.'
)
}
return raw
}
export function splitThinkBlocks(text) {
if (!text) return { think: null, answer: '' }
const openTagRe = /<think(?:ing)?>/i
const closeTagRe = /<\/think(?:ing)?>/i
const openMatch = text.match(openTagRe)
if (!openMatch) {
return { think: null, answer: text }
}
const openTagIndex = openMatch.index
const openTagLength = openMatch[0].length
const answerPartBeforeThink = text.substring(0, openTagIndex).trim()
const contentAfterOpenTag = text.substring(openTagIndex + openTagLength)
const closeMatch = contentAfterOpenTag.match(closeTagRe)
let thinkInner = null
let finalAnswer = answerPartBeforeThink
if (closeMatch) {
thinkInner = contentAfterOpenTag.substring(0, closeMatch.index).trim()
finalAnswer += contentAfterOpenTag.substring(closeMatch.index + closeMatch[0].length)
} else {
thinkInner = contentAfterOpenTag.trim()
}
return { think: thinkInner || null, answer: finalAnswer.trim() }
}

176
src/desktop/desktopApi.js Normal file
View File

@@ -0,0 +1,176 @@
import { DEFAULT_BACKEND_API_URL } from '../appConfig'
const DEFAULT_SETTINGS = Object.freeze({
backendApiUrl: DEFAULT_BACKEND_API_URL,
ollamaApiUrl: 'http://127.0.0.1:11434',
chatModel: 'llama3',
visionModel: '',
embedModel: 'nomic-embed-text:latest',
rerankModel: 'nomic-embed-text:latest',
transcriptionModel: 'base',
workflowRouterModel: '',
autoDeepEnrichment: true,
colorScheme: 'Default',
uiScale: 1,
openDevToolsOnStartup: false,
audioInputEnabled: true,
audioInputDeviceId: '',
audioInputLanguage: '',
})
const DEFAULT_UPDATE_STATUS = Object.freeze({
state: 'unavailable',
message: 'Desktop update checks are not available in this runtime.',
checkedAt: null,
localCommit: null,
remoteCommit: null,
branch: null,
restartScheduled: false,
})
const DEFAULT_UI_SCALE = 1
const MIN_UI_SCALE = 0.7
const MAX_UI_SCALE = 1.3
const hasWindow = () => typeof window !== 'undefined'
const getTauriCore = () => (hasWindow() ? window.__TAURI__?.core : undefined)
const getTauriEvent = () => (hasWindow() ? window.__TAURI__?.event : undefined)
const tauriWindowFocusUnlisteners = new WeakMap()
function callTauriCommand(commandName, args = {}) {
const invoke = getTauriCore()?.invoke
if (typeof invoke !== 'function') {
return undefined
}
return invoke(commandName, args)
}
function fallbackPromise(value) {
return Promise.resolve(typeof value === 'function' ? value() : value)
}
function defaultSettings() {
return { ...DEFAULT_SETTINGS }
}
function normalizeUiScale(value) {
const numericValue = Number(value)
if (!Number.isFinite(numericValue)) {
return DEFAULT_UI_SCALE
}
return Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, Math.round(numericValue * 100) / 100))
}
function applyRendererUiScale(value) {
if (!hasWindow() || !window.document) {
return false
}
const scale = normalizeUiScale(value)
const root = window.document.documentElement
const body = window.document.body
root?.style?.setProperty('--heimgeist-ui-scale', String(scale))
if (body?.style) {
body.style.zoom = scale === DEFAULT_UI_SCALE ? '' : String(scale)
}
return true
}
function defaultUpdateStatus(message = DEFAULT_UPDATE_STATUS.message) {
return { ...DEFAULT_UPDATE_STATUS, message }
}
function defaultChangelogPage(page = 1) {
const normalizedPage = Number.isFinite(Number(page)) && Number(page) > 0 ? Number(page) : 1
return {
page: normalizedPage,
pageSize: 50,
hasMore: false,
entries: [],
}
}
function resultOrFallback(result, fallback) {
return result === undefined ? fallbackPromise(fallback) : result
}
function getExternalUrl(eventOrUrl) {
if (typeof eventOrUrl === 'string') {
return eventOrUrl
}
return eventOrUrl?.currentTarget?.href || eventOrUrl?.target?.href || ''
}
function listenForTauriWindowFocus(callback) {
const listen = getTauriEvent()?.listen
if (typeof listen !== 'function') {
return undefined
}
const unlistenPromise = listen('window-focused', () => callback())
tauriWindowFocusUnlisteners.set(callback, unlistenPromise)
return unlistenPromise
}
function unlistenForTauriWindowFocus(callback) {
const unlistenPromise = tauriWindowFocusUnlisteners.get(callback)
if (!unlistenPromise) {
return undefined
}
tauriWindowFocusUnlisteners.delete(callback)
Promise.resolve(unlistenPromise).then((unlisten) => {
if (typeof unlisten === 'function') {
unlisten()
}
})
return unlistenPromise
}
const desktopApi = {
getSettings: () => resultOrFallback(
callTauriCommand('get_settings'),
defaultSettings,
),
applyUiScale: (value) => applyRendererUiScale(value),
getUpdateStatus: () => resultOrFallback(
callTauriCommand('get_update_status'),
defaultUpdateStatus,
),
checkForUpdates: () => resultOrFallback(
callTauriCommand('check_for_updates'),
() => defaultUpdateStatus('Desktop update checks are not implemented in this runtime.'),
),
getChangelogPage: (page) => resultOrFallback(
callTauriCommand('get_changelog_page', { page }),
() => defaultChangelogPage(page),
),
setSetting: (key, value) => resultOrFallback(
callTauriCommand('set_setting', { key, value }),
false,
),
updateSettings: (settings) => resultOrFallback(
callTauriCommand('update_settings', { settings }),
false,
),
pickPaths: (options) => resultOrFallback(
callTauriCommand('pick_paths', { options }),
[],
),
openPath: (filePath) => resultOrFallback(
callTauriCommand('open_path', { filePath }),
false,
),
openExternalLink: (eventOrUrl) => {
eventOrUrl?.preventDefault?.()
const url = getExternalUrl(eventOrUrl)
return resultOrFallback(callTauriCommand('open_external_link', { url }), false)
},
onWindowFocus: (callback) => listenForTauriWindowFocus(callback),
offWindowFocus: (callback) => unlistenForTauriWindowFocus(callback),
}
export default desktopApi

View File

@@ -5,11 +5,13 @@ import { HashRouter as Router, Routes, Route } from 'react-router-dom'
import App from './App.jsx' import App from './App.jsx'
import './styles.css' import './styles.css'
import { applyColorScheme } from './colorSchemes' import { applyColorScheme } from './colorSchemes'
import desktopApi from './desktop/desktopApi'
function Main() { function Main() {
useEffect(() => { useEffect(() => {
window.electronAPI.getSettings().then(settings => { desktopApi.getSettings().then(settings => {
applyColorScheme(settings.colorScheme || 'Default') applyColorScheme(settings.colorScheme || 'Default')
desktopApi.applyUiScale(settings.uiScale)
}) })
}, []) }, [])

13
src/modelPicker.js Normal file
View File

@@ -0,0 +1,13 @@
export function buildModelPickerOptions(values, currentValue, missingLabel) {
const uniqueValues = [...new Set((Array.isArray(values) ? values : []).filter(Boolean))]
const options = uniqueValues.map(value => ({ value, label: value }))
if (currentValue && !uniqueValues.includes(currentValue)) {
options.unshift({
value: currentValue,
label: `${currentValue} (${missingLabel})`,
})
}
return options
}

File diff suppressed because it is too large Load Diff

327
src/useAudioInput.js Normal file
View File

@@ -0,0 +1,327 @@
import { useEffect, useRef, useState } from 'react'
import { readFileAsDataUrl } from './attachments'
import {
AUDIO_RECORDING_TICK_MS,
MAX_AUDIO_RECORDING_MS,
} from './appConfig'
import { expectBackendJson, getErrorText, isAbortError } from './backendApi'
import {
getAudioInputConstraints,
getPreferredAudioRecorderMimeType,
stopMediaStream,
supportsAudioInputCapture,
} from './audioInput'
function appendTranscriptToComposer(currentInput, transcript) {
const nextTranscript = String(transcript || '').trim()
if (!nextTranscript) {
return currentInput || ''
}
const existing = String(currentInput || '')
if (!existing.trim()) {
return nextTranscript
}
const separator = /[\s\n]$/.test(existing) ? '' : '\n'
return `${existing}${separator}${nextTranscript}`
}
export function formatRecordingDuration(milliseconds) {
const totalSeconds = Math.max(0, Math.floor(Number(milliseconds || 0) / 1000))
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
}
export function useAudioInput({
activeSidebarMode,
audioInputDeviceId,
audioInputEnabled,
audioInputLanguage,
backendApiUrl,
isSending,
setInput,
textareaRef,
transcriptionModel,
}) {
const [audioInputRuntimeReady, setAudioInputRuntimeReady] = useState(true)
const [audioInputRuntimeMessage, setAudioInputRuntimeMessage] = useState('')
const [isRecordingAudio, setIsRecordingAudio] = useState(false)
const [isTranscribingAudio, setIsTranscribingAudio] = useState(false)
const [audioRecordingMs, setAudioRecordingMs] = useState(0)
const audioRecorderRef = useRef(null)
const audioStreamRef = useRef(null)
const audioChunksRef = useRef([])
const audioStopPromiseRef = useRef(null)
const audioRecorderMimeTypeRef = useRef('')
const audioTickTimerRef = useRef(null)
const audioAutoStopTimerRef = useRef(null)
const audioStartedAtRef = useRef(0)
const audioTranscriptionAbortRef = useRef(null)
function syncAudioInputRuntimeFromStartupStatus(status) {
const whisperReady = Boolean(status?.whisper_model_available)
if (whisperReady) {
setAudioInputRuntimeReady(true)
setAudioInputRuntimeMessage('')
return
}
const modelName = status?.whisper_model || 'base'
const reason = String(status?.whisper_error || '').trim()
setAudioInputRuntimeReady(false)
setAudioInputRuntimeMessage(reason || `Whisper ${modelName} is not available.`)
}
function clearAudioTimers() {
if (audioTickTimerRef.current) {
window.clearInterval(audioTickTimerRef.current)
audioTickTimerRef.current = null
}
if (audioAutoStopTimerRef.current) {
window.clearTimeout(audioAutoStopTimerRef.current)
audioAutoStopTimerRef.current = null
}
}
function cleanupAudioRecorder(stream = audioStreamRef.current) {
clearAudioTimers()
stopMediaStream(stream)
if (audioStreamRef.current === stream) {
audioStreamRef.current = null
}
audioRecorderRef.current = null
}
async function transcribeRecordedAudio(blob, mimeType) {
if (!backendApiUrl) {
throw new Error('The Heimgeist backend is not configured.')
}
const controller = new AbortController()
audioTranscriptionAbortRef.current = controller
setIsTranscribingAudio(true)
try {
const dataUrl = await readFileAsDataUrl(blob)
const commaIndex = dataUrl.indexOf(',')
if (commaIndex <= 5) {
throw new Error('Recorded audio could not be encoded for upload.')
}
const header = dataUrl.slice(0, commaIndex)
const payload = dataUrl.slice(commaIndex + 1)
if (!/^data:[^,]+;base64$/i.test(header) || !payload) {
throw new Error('Recorded audio could not be encoded for upload.')
}
const detectedMimeType = header
.slice(5)
.replace(/;base64$/i, '')
.trim()
const response = await fetch(`${backendApiUrl}/audio/transcribe`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: controller.signal,
body: JSON.stringify({
mime_type: mimeType || detectedMimeType || 'audio/webm',
audio_base64: payload,
model: transcriptionModel || null,
language: audioInputLanguage || null,
}),
})
const data = await expectBackendJson(response)
const transcript = String(data?.text || '').trim()
if (!transcript) {
window.alert('No speech was detected. Try again and speak closer to the selected microphone.')
return
}
setInput(prev => appendTranscriptToComposer(prev, transcript))
requestAnimationFrame(() => textareaRef.current?.focus())
} catch (error) {
if (isAbortError(error)) {
return
}
throw error
} finally {
if (audioTranscriptionAbortRef.current === controller) {
audioTranscriptionAbortRef.current = null
}
setIsTranscribingAudio(false)
}
}
async function stopAudioRecording(options = {}) {
const { shouldTranscribe = true } = options
const recorder = audioRecorderRef.current
const stopPromise = audioStopPromiseRef.current
const mimeType = audioRecorderMimeTypeRef.current || recorder?.mimeType || 'audio/webm'
if (!recorder || !stopPromise) {
return
}
setIsRecordingAudio(false)
clearAudioTimers()
try {
if (recorder.state !== 'inactive') {
recorder.stop()
}
const blob = await stopPromise
if (!shouldTranscribe) {
return
}
if (!blob || blob.size <= 0) {
throw new Error('Recorded audio was empty.')
}
await transcribeRecordedAudio(blob, mimeType)
} catch (error) {
if (shouldTranscribe) {
console.error('Failed to stop microphone recording', error)
window.alert(`Microphone transcription failed: ${getErrorText(error)}`)
}
} finally {
audioStopPromiseRef.current = null
audioChunksRef.current = []
audioRecorderMimeTypeRef.current = ''
audioStartedAtRef.current = 0
setAudioRecordingMs(0)
}
}
async function startAudioRecording() {
if (!audioInputEnabled || !audioInputRuntimeReady || isRecordingAudio || isTranscribingAudio || isSending) {
return
}
if (!supportsAudioInputCapture()) {
window.alert('Microphone capture is not available in this environment.')
return
}
let stream = null
try {
stream = await navigator.mediaDevices.getUserMedia(getAudioInputConstraints(audioInputDeviceId))
} catch (error) {
console.error('Failed to access microphone', error)
window.alert(`Microphone access failed: ${getErrorText(error)}`)
return
}
const preferredMimeType = getPreferredAudioRecorderMimeType()
let recorder = null
try {
recorder = preferredMimeType
? new MediaRecorder(stream, { mimeType: preferredMimeType })
: new MediaRecorder(stream)
} catch (error) {
cleanupAudioRecorder(stream)
console.error('Failed to create audio recorder', error)
window.alert(`Microphone recording is not available: ${getErrorText(error)}`)
return
}
audioStreamRef.current = stream
audioRecorderRef.current = recorder
audioChunksRef.current = []
audioRecorderMimeTypeRef.current = recorder.mimeType || preferredMimeType || 'audio/webm'
audioStartedAtRef.current = Date.now()
setAudioRecordingMs(0)
setIsRecordingAudio(true)
recorder.ondataavailable = (event) => {
if (event.data && event.data.size > 0) {
audioChunksRef.current.push(event.data)
}
}
audioStopPromiseRef.current = new Promise((resolve, reject) => {
recorder.onstop = () => {
const blob = new Blob(audioChunksRef.current, {
type: recorder.mimeType || audioRecorderMimeTypeRef.current || 'audio/webm',
})
cleanupAudioRecorder(stream)
resolve(blob)
}
recorder.onerror = (event) => {
cleanupAudioRecorder(stream)
reject(event?.error || new Error('Audio recording failed.'))
}
})
audioTickTimerRef.current = window.setInterval(() => {
setAudioRecordingMs(Date.now() - audioStartedAtRef.current)
}, AUDIO_RECORDING_TICK_MS)
audioAutoStopTimerRef.current = window.setTimeout(() => {
stopAudioRecording()
}, MAX_AUDIO_RECORDING_MS)
recorder.start()
}
async function toggleAudioRecording() {
if (isTranscribingAudio) {
return
}
if (isRecordingAudio) {
await stopAudioRecording()
return
}
await startAudioRecording()
}
useEffect(() => {
if (audioInputEnabled || !isRecordingAudio) {
return
}
stopAudioRecording({ shouldTranscribe: false })
}, [audioInputEnabled, isRecordingAudio])
useEffect(() => {
if (audioInputRuntimeReady || !isRecordingAudio) {
return
}
stopAudioRecording({ shouldTranscribe: false })
}, [audioInputRuntimeReady, isRecordingAudio])
useEffect(() => {
if (activeSidebarMode === 'chats' || !isRecordingAudio) {
return
}
stopAudioRecording()
}, [activeSidebarMode, isRecordingAudio])
useEffect(() => {
return () => {
audioTranscriptionAbortRef.current?.abort()
clearAudioTimers()
const recorder = audioRecorderRef.current
if (recorder) {
recorder.ondataavailable = null
recorder.onstop = null
recorder.onerror = null
try {
if (recorder.state !== 'inactive') {
recorder.stop()
}
} catch {}
}
stopMediaStream(audioStreamRef.current)
}
}, [])
return {
audioInputRuntimeMessage,
audioInputRuntimeReady,
audioRecordingMs,
isRecordingAudio,
isTranscribingAudio,
setAudioInputRuntimeMessage,
setAudioInputRuntimeReady,
syncAudioInputRuntimeFromStartupStatus,
toggleAudioRecording,
}
}

249
src/useChatScroll.js Normal file
View File

@@ -0,0 +1,249 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { BOTTOM_EPSILON, TOP_ALIGN_OFFSET } from './appConfig'
import desktopApi from './desktop/desktopApi'
export function useChatScroll({
activeSessionId,
activeSidebarMode,
chatRef,
messagesLength,
}) {
const [scrollPositions, setScrollPositions] = useState({})
const [userScrolledUpState, setUserScrolledUpState] = useState({})
const userScrolledUpRef = useRef({})
const [pendingScrollToLastUser, setPendingScrollToLastUser] = useState({})
const scrollTopsRef = useRef({})
const prevScrollTopsRef = useRef({})
const [newMsgTip, setNewMsgTip] = useState({})
const restoredForRef = useRef(null)
const activeSessionIdRef = useRef(activeSessionId)
useEffect(() => {
activeSessionIdRef.current = activeSessionId
}, [activeSessionId])
const setUserScrolledUp = useCallback((sessionId, value) => {
setUserScrolledUpState(prev => {
const next = { ...prev, [sessionId]: value }
userScrolledUpRef.current = next
return next
})
}, [])
useEffect(() => {
const leavingSessionId = activeSessionId
const leavingMode = activeSidebarMode
return () => {
if (leavingMode === 'chats' && leavingSessionId) {
const top = typeof scrollTopsRef.current[leavingSessionId] === 'number'
? scrollTopsRef.current[leavingSessionId]
: (chatRef.current ? chatRef.current.scrollTop : 0)
setScrollPositions(prev => {
const updated = { ...prev, [leavingSessionId]: top }
desktopApi.updateSettings({ scrollPositions: updated })
return updated
})
}
}
}, [activeSessionId, activeSidebarMode, chatRef])
useEffect(() => {
const chatDiv = chatRef.current
if (!chatDiv) return
const handleScroll = () => {
const { scrollTop, scrollHeight, clientHeight } = chatDiv
const isAtBottom = (scrollHeight - scrollTop - clientHeight) <= BOTTOM_EPSILON
if (activeSessionId) {
const prevScrollTop = prevScrollTopsRef.current[activeSessionId]
const scrolledUp = typeof prevScrollTop === 'number' && scrollTop < prevScrollTop
scrollTopsRef.current[activeSessionId] = scrollTop
if (isAtBottom) {
setUserScrolledUp(activeSessionId, false)
} else if (scrolledUp) {
setUserScrolledUp(activeSessionId, true)
}
prevScrollTopsRef.current[activeSessionId] = scrollTop
}
}
chatDiv.addEventListener('scroll', handleScroll)
return () => chatDiv.removeEventListener('scroll', handleScroll)
}, [activeSessionId, chatRef, setUserScrolledUp])
useEffect(() => {
const sid = activeSessionId
if (!sid) return
if (userScrolledUpState[sid] === false) {
setNewMsgTip(prev => {
if (!(sid in prev)) return prev
const rest = { ...prev }
delete rest[sid]
return rest
})
}
}, [activeSessionId, userScrolledUpState])
useLayoutEffect(() => {
if (activeSidebarMode !== 'chats' || !activeSessionId) return
const div = chatRef.current
if (!div) return
restoredForRef.current = null
const applyRestore = () => {
if (restoredForRef.current === activeSessionId) return
const liveSaved = typeof scrollTopsRef.current[activeSessionId] === 'number'
? scrollTopsRef.current[activeSessionId]
: undefined
const saved = typeof liveSaved === 'number'
? liveSaved
: scrollPositions[activeSessionId]
if (typeof saved === 'number') {
div.scrollTop = saved
restoredForRef.current = activeSessionId
return
}
if (messagesLength > 0) {
div.scrollTop = div.scrollHeight
restoredForRef.current = activeSessionId
}
}
applyRestore()
const r0 = requestAnimationFrame(applyRestore)
const onDomChange = () => {
if (restoredForRef.current !== activeSessionId) {
requestAnimationFrame(applyRestore)
}
}
const mo = new MutationObserver(onDomChange)
mo.observe(div, { childList: true, subtree: true })
const ro = new ResizeObserver(onDomChange)
ro.observe(div)
return () => {
cancelAnimationFrame(r0)
mo.disconnect()
ro.disconnect()
}
}, [activeSessionId, activeSidebarMode, chatRef, messagesLength, scrollPositions])
useEffect(() => {
if (activeSidebarMode !== 'chats' || !activeSessionId) return
if (restoredForRef.current === activeSessionId) return
const liveSaved = typeof scrollTopsRef.current[activeSessionId] === 'number'
? scrollTopsRef.current[activeSessionId]
: undefined
const savedScrollTop = typeof liveSaved === 'number'
? liveSaved
: scrollPositions[activeSessionId]
if (typeof savedScrollTop !== 'number' && messagesLength > 0) {
requestAnimationFrame(() => {
const div = chatRef.current
if (!div) return
div.scrollTop = div.scrollHeight
restoredForRef.current = activeSessionId
})
}
}, [messagesLength, activeSessionId, activeSidebarMode, chatRef, scrollPositions])
const scrollToBottom = useCallback((behavior = 'smooth', sessionId = null) => {
const chatDiv = chatRef.current
if (!chatDiv) return
const target = sessionId ?? activeSessionIdRef.current
if (activeSessionIdRef.current !== target) return
chatDiv.scrollTo({ top: chatDiv.scrollHeight, behavior })
setUserScrolledUp(target, false)
}, [chatRef, setUserScrolledUp])
const scrollMessageToTop = useCallback((msgId, behavior = 'auto', sessionId = null) => {
const chatDiv = chatRef.current
if (!chatDiv) return
const target = sessionId ?? activeSessionIdRef.current
if (activeSessionIdRef.current !== target) return
const el = document.getElementById(msgId)
if (el) {
const top = Math.max(0, el.offsetTop - TOP_ALIGN_OFFSET)
chatDiv.scrollTo({ top, behavior })
}
}, [chatRef])
const handleNewMsgTipClick = useCallback(() => {
const sid = activeSessionIdRef.current
const msgId = newMsgTip[sid]
if (msgId) {
scrollMessageToTop(msgId, 'smooth', sid)
setNewMsgTip(prev => {
const { [sid]: _omit, ...rest } = prev
return rest
})
}
}, [newMsgTip, scrollMessageToTop])
const scrollPendingMessageForSession = useCallback((sessionId, chatSessions) => {
const pendingId = pendingScrollToLastUser[sessionId]
if (!pendingId) return
requestAnimationFrame(() => {
let tries = 12
const attempt = () => {
const chatDiv = chatRef.current
if (!chatDiv) return
let el = document.getElementById(pendingId)
if (!el) {
const sess = chatSessions.find(s => s.session_id === sessionId)
if (sess && Array.isArray(sess.messages)) {
for (let i = sess.messages.length - 1; i >= 0; i--) {
const m = sess.messages[i]
if (m.role === 'assistant' && m.id) {
el = document.getElementById(m.id)
break
}
}
}
}
if (el) {
scrollMessageToTop(el.id, 'smooth', sessionId)
setPendingScrollToLastUser(prev => {
const { [sessionId]: _omit, ...rest } = prev
return rest
})
} else if (tries-- > 0) {
requestAnimationFrame(attempt)
}
}
requestAnimationFrame(attempt)
})
}, [chatRef, pendingScrollToLastUser, scrollMessageToTop])
return {
activeSessionIdRef,
handleNewMsgTipClick,
newMsgTip,
restoredForRef,
scrollMessageToTop,
scrollPendingMessageForSession,
scrollToBottom,
setNewMsgTip,
setPendingScrollToLastUser,
setScrollPositions,
setUserScrolledUp,
userScrolledUpRef,
}
}

View File

@@ -0,0 +1,75 @@
import { useEffect, useMemo, useState } from 'react'
import { CHAT_WORKFLOW_MAP_KEY } from './appConfig'
const DIRECT_SELECTION = Object.freeze({ mode: 'direct', workflowId: null })
function normalizeSelection(selection, validIds = null) {
if (selection?.mode === 'explicit' && (!validIds || validIds.has(selection.workflowId))) {
return selection
}
return DIRECT_SELECTION
}
function loadMap() {
try {
const raw = JSON.parse(localStorage.getItem(CHAT_WORKFLOW_MAP_KEY) || '{}')
return Object.fromEntries(Object.entries(raw).map(([sessionId, selection]) => [sessionId, normalizeSelection(selection)]))
} catch {
return {}
}
}
export function useChatWorkflowSelection({ activeSessionId, workflows }) {
const [selectionBySession, setSelectionBySession] = useState(loadMap)
useEffect(() => {
try {
localStorage.setItem(CHAT_WORKFLOW_MAP_KEY, JSON.stringify(selectionBySession))
} catch {}
}, [selectionBySession])
useEffect(() => {
const validIds = new Set(workflows.filter(item => item.enabled).map(item => item.id))
setSelectionBySession(previous => {
let changed = false
const next = { ...previous }
Object.entries(next).forEach(([sessionId, selection]) => {
const normalized = normalizeSelection(selection, validIds)
if (normalized !== selection) {
next[sessionId] = DIRECT_SELECTION
changed = true
}
})
return changed ? next : previous
})
}, [workflows])
const selection = activeSessionId
? normalizeSelection(selectionBySession[activeSessionId])
: DIRECT_SELECTION
const selectedWorkflow = useMemo(() => {
if (selection.mode === 'direct') return workflows.find(item => item.slug === 'input-output') || null
if (selection.mode === 'automatic') return null
return workflows.find(item => item.id === selection.workflowId) || null
}, [selection, workflows])
function getSelectionForSession(sessionId) {
return normalizeSelection(selectionBySession[sessionId])
}
function setSelectionForSession(sessionId, nextSelection) {
if (!sessionId) return
setSelectionBySession(previous => ({
...previous,
[sessionId]: normalizeSelection(nextSelection),
}))
}
return {
getSelectionForSession,
selectedWorkflow,
selection,
setSelectionForSession,
}
}

View File

@@ -0,0 +1,65 @@
import React from 'react'
const CONDITION_OPERATIONS = ['equals', 'not_equals', 'exists', 'greater_than', 'less_than', 'contains', 'array_not_empty', 'score_at_least']
export default function NodeInspector({ node, tools, onChange, onDelete, readOnly }) {
const [configText, setConfigText] = React.useState('{}')
const [configError, setConfigError] = React.useState('')
React.useEffect(() => {
setConfigText(JSON.stringify(node?.data?.config || {}, null, 2))
setConfigError('')
}, [node])
if (!node) return <div className="workflow-inspector empty">Select a node to edit it.</div>
const nodeType = node.data.nodeType
const patchConfig = (config) => onChange({ ...node, data: { ...node.data, config, tool: config.tool || '' } })
return (
<div className="workflow-inspector">
<div className="workflow-inspector-heading">
<strong>{node.id}</strong>
{!readOnly && <button type="button" className="button danger ghost" onClick={onDelete}>Delete</button>}
</div>
<label>Label
<input disabled={readOnly} value={node.data.label || ''} onChange={(event) => onChange({ ...node, data: { ...node.data, label: event.target.value } })} />
</label>
{nodeType === 'tool' && (
<label>Registered tool
<select
disabled={readOnly}
value={node.data.config?.tool || ''}
onChange={(event) => patchConfig({ ...node.data.config, tool: event.target.value, arguments: node.data.config?.arguments || {} })}
>
<option value="">Select a tool</option>
{tools.map(tool => <option key={tool.name} value={tool.name}>{tool.name}</option>)}
</select>
</label>
)}
{nodeType === 'condition' && (
<label>Operation
<select disabled={readOnly} value={node.data.config?.operation || 'equals'} onChange={(event) => patchConfig({ ...node.data.config, operation: event.target.value })}>
{CONDITION_OPERATIONS.map(operation => <option key={operation}>{operation}</option>)}
</select>
</label>
)}
<label>Configuration JSON
<textarea
rows={18}
disabled={readOnly}
value={configText}
onChange={(event) => {
const text = event.target.value
setConfigText(text)
try {
patchConfig(JSON.parse(text))
setConfigError('')
} catch (error) {
setConfigError(error.message)
}
}}
/>
</label>
{configError && <p className="workflow-validation-error">{configError}</p>}
</div>
)
}

View File

@@ -0,0 +1,22 @@
import React from 'react'
export const NODE_TYPES = ['input', 'output', 'tool', 'prompt', 'agent', 'condition', 'merge', 'template', 'select', 'limit']
export default function NodePalette({ onAdd }) {
return (
<div className="workflow-palette">
<strong>Nodes</strong>
{NODE_TYPES.map(type => (
<button
key={type}
type="button"
draggable
onDragStart={(event) => event.dataTransfer.setData('application/heimgeist-workflow-node', type)}
onClick={() => onAdd(type)}
>
{type}
</button>
))}
</div>
)
}

View File

@@ -0,0 +1,45 @@
import React from 'react'
import {
Background,
Controls,
MiniMap,
ReactFlow,
addEdge,
applyEdgeChanges,
applyNodeChanges,
} from '@xyflow/react'
import '@xyflow/react/dist/style.css'
import WorkflowNode from './WorkflowNode'
const nodeTypes = { workflow: WorkflowNode }
export default function WorkflowCanvas({ edges, nodes, onEdgesChange, onNodesChange, onSelectNode, onDropNode }) {
const [instance, setInstance] = React.useState(null)
return (
<div className="workflow-canvas">
<ReactFlow
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
onInit={setInstance}
onNodesChange={(changes) => onNodesChange(applyNodeChanges(changes, nodes))}
onEdgesChange={(changes) => onEdgesChange(applyEdgeChanges(changes, edges))}
onConnect={(connection) => onEdgesChange(addEdge({ ...connection, id: `${connection.source}-${connection.target}-${Date.now()}` }, edges))}
onNodeClick={(_event, node) => onSelectNode(node.id)}
onPaneClick={() => onSelectNode(null)}
onDragOver={(event) => { event.preventDefault(); event.dataTransfer.dropEffect = 'move' }}
onDrop={(event) => {
event.preventDefault()
const type = event.dataTransfer.getData('application/heimgeist-workflow-node')
if (!type || !instance) return
onDropNode(type, instance.screenToFlowPosition({ x: event.clientX, y: event.clientY }))
}}
fitView
>
<Background gap={20} />
<MiniMap pannable zoomable />
<Controls />
</ReactFlow>
</div>
)
}

View File

@@ -0,0 +1,22 @@
import React from 'react'
export default function WorkflowConfirmationDialog({ confirmation, onRespond }) {
if (!confirmation) return null
const args = confirmation.payload?.arguments || {}
return (
<div className="workflow-confirmation-overlay" role="dialog" aria-modal="true">
<div className="workflow-confirmation-dialog">
<h3>Confirm workflow action</h3>
<p>This workflow wants to run <code>{confirmation.payload?.tool}</code>.</p>
{args.library_slug && <p><strong>Destination:</strong> Knowledge</p>}
{args.title && <p><strong>Title:</strong> {args.title}</p>}
{args.message_id && <p><strong>Message:</strong> {args.message_id}</p>}
{args.url && <p><strong>URL:</strong> {args.url}</p>}
<div className="workflow-confirmation-actions">
<button className="button ghost" type="button" onClick={() => onRespond(false)}>Reject</button>
<button className="button" type="button" onClick={() => onRespond(true)}>Approve</button>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,197 @@
import React from 'react'
import NodePalette from './NodePalette'
import NodeInspector from './NodeInspector'
import WorkflowCanvas from './WorkflowCanvas'
import WorkflowRunInspector from './WorkflowRunInspector'
import WorkflowValidationPanel from './WorkflowValidationPanel'
import {
createWorkflowRun,
getWorkflowRun,
saveWorkflowRevision,
streamWorkflowEvents,
updateWorkflow,
validateWorkflow,
} from './workflowApi'
function toCanvasNode(node) {
return {
id: node.id,
type: 'workflow',
position: node.position || { x: 0, y: 0 },
data: {
nodeType: node.type,
label: node.config?.label || node.id,
config: node.config || {},
tool: node.config?.tool || '',
},
}
}
function toGraphNode(node) {
const config = { ...(node.data.config || {}) }
if (node.data.label && node.data.label !== node.id) config.label = node.data.label
return { id: node.id, type: node.data.nodeType, position: node.position, config }
}
function nextNodeConfig(type) {
if (type === 'tool') return { tool: '', arguments: {} }
if (type === 'prompt') return { model_source: 'chat_model', system_template: '', user_template: '{{input.prompt}}', output_mode: 'text', temperature: 0.2 }
if (type === 'agent') return { model: { $ref: 'run.chat_model' }, messages: { $ref: 'run.messages' }, allowed_tool_names: [], maximum_rounds: 4 }
if (type === 'condition') return { value: { $ref: 'input.prompt' }, operation: 'exists', compare_to: null }
if (type === 'merge') return { values: [], deduplicate_by: 'url' }
if (type === 'template') return { template: '{{input.prompt}}', values: {} }
if (type === 'select') return { value: { $ref: 'input.prompt' } }
if (type === 'limit') return { value: { $ref: 'input.prompt' }, maximum_chars: 12000 }
if (type === 'output') return { value: { content: { $ref: 'input.prompt' }, sources: [], usage: {} } }
return {}
}
export default function WorkflowEditor({ apiBase, model, onChanged, tools, workflow }) {
const [nodes, setNodes] = React.useState([])
const [edges, setEdges] = React.useState([])
const [selectedNodeId, setSelectedNodeId] = React.useState(null)
const [inputsText, setInputsText] = React.useState('{}')
const [outputsText, setOutputsText] = React.useState('{}')
const [limits, setLimits] = React.useState({})
const [metadata, setMetadata] = React.useState({ name: '', description: '', routing_description: '', routing_examples: [], enabled: true })
const [validation, setValidation] = React.useState(null)
const [status, setStatus] = React.useState('')
const [testPrompt, setTestPrompt] = React.useState('Summarize this sample request.')
const [testRun, setTestRun] = React.useState(null)
const [testEvents, setTestEvents] = React.useState([])
React.useEffect(() => {
const graph = workflow?.graph || {}
setNodes((graph.nodes || []).map(toCanvasNode))
setEdges((graph.edges || []).map(edge => ({
...edge,
sourceHandle: edge.sourceHandle || edge.source_handle || 'output',
targetHandle: edge.targetHandle || edge.target_handle || 'input',
})))
setInputsText(JSON.stringify(graph.inputs || {}, null, 2))
setOutputsText(JSON.stringify(graph.outputs || {}, null, 2))
setLimits(graph.limits || {})
setMetadata({
name: workflow?.name || '', description: workflow?.description || '',
routing_description: workflow?.routing_description || '', routing_examples: workflow?.routing_examples || [],
enabled: workflow?.enabled !== false,
})
setSelectedNodeId(null)
setValidation(null)
setTestRun(null)
setTestEvents([])
}, [workflow])
const readOnly = Boolean(workflow?.built_in)
const selectedNode = nodes.find(node => node.id === selectedNodeId) || null
const buildGraph = () => ({
schema_version: 1,
inputs: JSON.parse(inputsText || '{}'),
outputs: JSON.parse(outputsText || '{}'),
nodes: nodes.map(toGraphNode),
edges: edges.map(edge => ({
id: edge.id, source: edge.source, source_handle: edge.sourceHandle || edge.source_handle || 'output',
target: edge.target, target_handle: edge.targetHandle || edge.target_handle || 'input',
})),
limits,
})
const addNode = (type, position = { x: 120 + nodes.length * 35, y: 120 + nodes.length * 20 }) => {
if (readOnly) return
const id = `${type}-${Date.now().toString(36)}`
setNodes(previous => [...previous, toCanvasNode({ id, type, position, config: nextNodeConfig(type) })])
setSelectedNodeId(id)
}
const runValidation = async () => {
try {
const result = await validateWorkflow(apiBase, buildGraph())
setValidation(result)
return result
} catch (error) {
setValidation({ valid: false, errors: [{ code: 'editor', message: error.message }] })
return null
}
}
const save = async () => {
const result = await runValidation()
if (!result?.valid) return
setStatus('Saving…')
try {
await updateWorkflow(apiBase, workflow.id, metadata)
await saveWorkflowRevision(apiBase, workflow.id, buildGraph())
setStatus('Saved as a new revision.')
await onChanged(workflow.id)
} catch (error) {
setStatus(error.message)
}
}
const test = async () => {
const result = await runValidation()
if (!result?.valid) return
setTestRun({ status: 'starting', node_runs: [] })
setTestEvents([])
try {
const created = await createWorkflowRun(apiBase, {
message: testPrompt, model, selection_mode: 'explicit', workflow_id: workflow.id,
sample_inputs: { prompt: testPrompt }, stream: true, explicit_user_action: true,
})
await streamWorkflowEvents(apiBase, created.run_id, {
onEvent: event => setTestEvents(previous => [...previous, event]),
})
setTestRun(await getWorkflowRun(apiBase, created.run_id))
} catch (error) {
setTestRun({ status: 'failed', error: { message: error.message }, node_runs: [] })
}
}
if (!workflow) return <div className="workflow-empty">Select a workflow.</div>
return (
<div className="workflow-editor">
<div className="workflow-editor-toolbar">
<input value={metadata.name} disabled={readOnly} onChange={(event) => setMetadata(value => ({ ...value, name: event.target.value }))} />
<button className="button ghost" type="button" onClick={runValidation}>Validate</button>
{!readOnly && <button className="button" type="button" onClick={save}>Save revision</button>}
{readOnly && <span className="header-subtle">Built-in revisions are read-only.</span>}
{status && <span className="header-subtle">{status}</span>}
</div>
<div className="workflow-editor-meta">
<label>Description<textarea disabled={readOnly} value={metadata.description} onChange={(event) => setMetadata(value => ({ ...value, description: event.target.value }))} /></label>
<label>Routing description<textarea disabled={readOnly} value={metadata.routing_description} onChange={(event) => setMetadata(value => ({ ...value, routing_description: event.target.value }))} /></label>
<label>Routing examples<input disabled={readOnly} value={metadata.routing_examples.join(' | ')} onChange={(event) => setMetadata(value => ({ ...value, routing_examples: event.target.value.split('|').map(item => item.trim()).filter(Boolean) }))} /></label>
<label className="workflow-enabled"><input type="checkbox" disabled={readOnly} checked={metadata.enabled} onChange={(event) => setMetadata(value => ({ ...value, enabled: event.target.checked }))} /> Enabled for routing</label>
</div>
<div className="workflow-editor-grid">
<NodePalette onAdd={addNode} />
<WorkflowCanvas nodes={nodes} edges={edges} onNodesChange={setNodes} onEdgesChange={setEdges} onSelectNode={setSelectedNodeId} onDropNode={addNode} />
<NodeInspector
node={selectedNode}
tools={tools}
readOnly={readOnly}
onChange={(next) => setNodes(previous => previous.map(node => node.id === next.id ? next : node))}
onDelete={() => {
setNodes(previous => previous.filter(node => node.id !== selectedNodeId))
setEdges(previous => previous.filter(edge => edge.source !== selectedNodeId && edge.target !== selectedNodeId))
setSelectedNodeId(null)
}}
/>
</div>
<details className="workflow-schema-editor">
<summary>Workflow input/output schemas and limits</summary>
<div>
<label>Inputs JSON<textarea disabled={readOnly} rows={10} value={inputsText} onChange={(event) => setInputsText(event.target.value)} /></label>
<label>Outputs JSON<textarea disabled={readOnly} rows={10} value={outputsText} onChange={(event) => setOutputsText(event.target.value)} /></label>
<label>Limits JSON<textarea disabled={readOnly} rows={10} value={JSON.stringify(limits, null, 2)} onChange={(event) => { try { setLimits(JSON.parse(event.target.value)) } catch {} }} /></label>
</div>
</details>
<WorkflowValidationPanel result={validation} />
<div className="workflow-test-panel">
<input value={testPrompt} onChange={(event) => setTestPrompt(event.target.value)} />
<button className="button ghost" type="button" onClick={test} disabled={!model}>Run test</button>
</div>
<WorkflowRunInspector run={testRun} events={testEvents} />
</div>
)
}

View File

@@ -0,0 +1,37 @@
import React from 'react'
const ACTIVE_TYPES = new Set(['node_started', 'tool_started', 'model_token', 'confirmation_required'])
export default function WorkflowExecutionPanel({ execution }) {
const [open, setOpen] = React.useState(false)
if (!execution) return null
const events = execution.events || []
const current = [...events].reverse().find(event => ACTIVE_TYPES.has(event.type))
const duration = execution.startedAt
? Math.max(0, ((execution.finishedAt || Date.now()) - execution.startedAt) / 1000).toFixed(1)
: '0.0'
return (
<div className={`workflow-execution ${execution.status || ''}`}>
<button type="button" className="workflow-execution-summary" onClick={() => setOpen(value => !value)}>
<span>{open ? '▾' : '▸'}</span>
<strong>{execution.workflowName || 'Workflow'}</strong>
<span>{execution.status || 'running'}</span>
<span>{duration}s</span>
</button>
{open && (
<div className="workflow-execution-body">
{current && <div className="workflow-current-node">Current: {current.node_id || current.payload?.tool || current.type}</div>}
<div className="workflow-event-list">
{events.filter(event => event.type !== 'model_token').slice(-40).map(event => (
<div key={event.sequence} className={`workflow-event ${event.type}`}>
<span>{event.type.replaceAll('_', ' ')}</span>
<code>{event.node_id || event.payload?.tool || ''}</code>
{event.payload?.error && <small>{String(event.payload.error)}</small>}
</div>
))}
</div>
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,24 @@
import React from 'react'
export default function WorkflowList({ activeId, onCreate, onDelete, onDuplicate, onSelect, workflows }) {
return (
<div className="workflow-list">
<div className="workflow-list-heading">
<strong>Workflows</strong>
<button className="button" type="button" onClick={onCreate}>New</button>
</div>
{workflows.map(workflow => (
<div key={workflow.id} className={`workflow-list-item${workflow.id === activeId ? ' active' : ''}`} onClick={() => onSelect(workflow.id)}>
<div>
<strong>{workflow.name}</strong>
<small>{workflow.built_in ? 'Built-in' : `Revision ${workflow.current_version || 1}`}{workflow.enabled ? '' : ' · Disabled'}</small>
</div>
<div className="workflow-list-actions">
<button type="button" className="icon-button" title="Duplicate" onClick={(event) => { event.stopPropagation(); onDuplicate(workflow.id) }}>⧉</button>
{!workflow.built_in && <button type="button" className="icon-button" title="Delete" onClick={(event) => { event.stopPropagation(); onDelete(workflow.id) }}>×</button>}
</div>
</div>
))}
</div>
)
}

View File

@@ -0,0 +1,19 @@
import React from 'react'
import { Handle, Position } from '@xyflow/react'
export default function WorkflowNode({ data, selected }) {
return (
<div className={`workflow-node workflow-node-${data.nodeType}${selected ? ' selected' : ''}`}>
{data.nodeType !== 'input' && <Handle type="target" position={Position.Left} id="input" />}
<div className="workflow-node-type">{data.nodeType}</div>
<strong>{data.label}</strong>
{data.tool && <small>{data.tool}</small>}
{data.nodeType === 'condition' ? (
<>
<Handle type="source" position={Position.Right} id="true" style={{ top: '38%' }} />
<Handle type="source" position={Position.Right} id="false" style={{ top: '72%' }} />
</>
) : data.nodeType !== 'output' && <Handle type="source" position={Position.Right} id="output" />}
</div>
)
}

View File

@@ -0,0 +1,19 @@
import React from 'react'
export default function WorkflowRunInspector({ run, events }) {
if (!run && !(events || []).length) return null
return (
<div className="workflow-run-inspector">
<strong>Test run {run?.status || 'running'}</strong>
{(run?.node_runs || []).map(node => (
<details key={node.id || node.node_id}>
<summary>{node.node_id}: {node.status} {node.metrics?.duration_seconds != null ? `(${node.metrics.duration_seconds.toFixed(2)}s)` : ''}</summary>
{node.resolved_inputs && <pre>{JSON.stringify(node.resolved_inputs, null, 2)}</pre>}
{node.outputs && <pre>{JSON.stringify(node.outputs, null, 2)}</pre>}
{node.error && <pre className="workflow-validation-error">{JSON.stringify(node.error, null, 2)}</pre>}
</details>
))}
{run?.error && <pre className="workflow-validation-error">{JSON.stringify(run.error, null, 2)}</pre>}
</div>
)
}

View File

@@ -0,0 +1,24 @@
import React from 'react'
export default function WorkflowSelector({ disabled, onChange, selection, workflows }) {
const value = selection.mode === 'explicit' ? `workflow:${selection.workflowId}` : 'direct'
return (
<label className="workflow-selector" title="Choose how this chat prompt is executed">
<span>Flow</span>
<select
value={value}
disabled={disabled}
onChange={(event) => {
const next = event.target.value
if (next === 'direct') onChange({ mode: next, workflowId: null })
else onChange({ mode: 'explicit', workflowId: next.replace(/^workflow:/, '') })
}}
>
<option value="direct">Direct</option>
{workflows.filter(item => item.enabled && item.slug !== 'input-output').map(item => (
<option key={item.id} value={`workflow:${item.id}`}>{item.name}</option>
))}
</select>
</label>
)
}

View File

@@ -0,0 +1,15 @@
import React from 'react'
export default function WorkflowValidationPanel({ result }) {
if (!result) return null
return (
<div className={`workflow-validation ${result.valid ? 'valid' : 'invalid'}`}>
<strong>{result.valid ? 'Workflow is valid' : `${result.errors?.length || 0} validation error(s)`}</strong>
{(result.errors || []).map((error, index) => (
<div key={`${error.code}-${index}`}>
<code>{error.node_id || error.field_path || error.code}</code> {error.message}
</div>
))}
</div>
)
}

Some files were not shown because too many files have changed in this diff Show More