Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6137f7cb7e | ||
|
|
832d0181b6 | ||
|
|
d1dd449f63 | ||
|
|
2751a0f0b6 | ||
|
|
a9e9fe7899 | ||
|
|
702906aee7 | ||
|
|
fe837d80e7 | ||
|
|
860a0b414e | ||
|
|
9c9a18d6d4 | ||
|
|
67893b9a57 | ||
|
|
2e8c4da17b | ||
|
|
ff9f761d65 | ||
|
|
6863ca482c | ||
|
|
5645d5bccc | ||
|
|
201b93bfcc | ||
|
|
0c2e4270bc | ||
|
|
80ad5fd2d0 | ||
|
|
9904566513 | ||
|
|
2054ee0b73 | ||
|
|
93bab8d822 | ||
|
|
259d5ca596 | ||
|
|
597883a179 | ||
|
|
387225eb8b | ||
|
|
c83a42198d | ||
|
|
2cacc2e649 | ||
|
|
c9a78e5476 | ||
|
|
2cbba2a28a | ||
|
|
62ab30f593 | ||
|
|
0fff2fbcab | ||
|
|
fcff9c3afd | ||
|
|
d415edcfcd | ||
|
|
5f304e57d2 | ||
|
|
0b851cf55a | ||
|
|
ff86283be0 | ||
|
|
e9011113b4 | ||
|
|
1b89bee098 | ||
|
|
c436e0366c | ||
|
|
1db36b5eda | ||
|
|
3569280c0b | ||
|
|
a0d6c209c3 | ||
|
|
73617ec7fa | ||
|
|
391a4878e6 | ||
|
|
6d7f21b57b | ||
|
|
fe604a8a9b | ||
|
|
a9d8348cf9 | ||
|
|
c37c0e3490 | ||
|
|
ddedceb7ad | ||
|
|
18865a9fef | ||
|
|
769ef856bc | ||
|
|
ed1b959bc6 | ||
|
|
d2b38127d0 | ||
|
|
3d535db304 | ||
|
|
234306ff57 | ||
|
|
ae28e7d245 | ||
|
|
39b87d9683 | ||
|
|
e83f668107 | ||
|
|
7dda8025fc | ||
|
|
1357dc6737 | ||
|
|
43c30428a6 | ||
|
|
668bd44485 | ||
|
|
a3de0bcc58 | ||
|
|
aed2f69efe | ||
|
|
30ae519226 | ||
|
|
499ca282e5 | ||
|
|
40d90286b6 | ||
|
|
2d27ef4ece | ||
|
|
e9b5eb6ed3 | ||
|
|
6b462ff121 | ||
|
|
c3bac9aa62 | ||
|
|
f7226333c3 | ||
|
|
fc5f399573 | ||
|
|
ff8cf80fb5 | ||
|
|
54cefedf53 | ||
|
|
9440d09114 | ||
|
|
5bb1c42fa8 | ||
|
|
242b3f0c01 | ||
|
|
144c0f3d76 | ||
|
|
18401de254 | ||
|
|
c71beb0a7d | ||
|
|
f5bf2a2ed7 | ||
|
|
ab3f03bbd5 | ||
|
|
5ac502e93f | ||
|
|
c60b0fa0e3 | ||
|
|
9544a80aa0 | ||
|
|
83b17e2ac8 | ||
|
|
3a6c88ade9 | ||
|
|
3be06132db | ||
|
|
bbbcf27dd5 | ||
|
|
cfa16e1a37 | ||
|
|
f60d386b74 | ||
|
|
0324a1bbdd | ||
|
|
a677b212d9 | ||
|
|
179a4ad9ea | ||
|
|
2d82d260cc | ||
|
|
e7a9988893 | ||
|
|
6b01f96eac | ||
|
|
965f242d16 | ||
|
|
758d8fcf31 | ||
|
|
0f8b339f6d | ||
|
|
5d821d21f3 | ||
|
|
d6d9d1c535 | ||
|
|
44ab77b4f5 | ||
|
|
646b64a318 | ||
|
|
bbab64b53e | ||
|
|
4731ccb73c | ||
|
|
4737e1f118 | ||
|
|
7ea6afdf95 | ||
|
|
4654ecbf1b | ||
|
|
527d36e13a | ||
|
|
d7d05a4717 | ||
|
|
419ea1c346 | ||
|
|
59214538bb | ||
|
|
eca9b405eb | ||
|
|
58d685eea4 | ||
|
|
44ed941a5d | ||
|
|
46229a93ce | ||
|
|
50eff6a672 | ||
|
|
1cb74b0bf7 | ||
|
|
c303388296 | ||
|
|
5a08084899 | ||
|
|
b1f292965c | ||
|
|
819ea0d9be | ||
|
|
1f77691b01 | ||
|
|
50e6a19957 | ||
|
|
cb0165827f | ||
|
|
c5225039ab | ||
|
|
f2c3fff278 | ||
|
|
3271a5277c | ||
|
|
8b2160f2f7 | ||
|
|
bee13f72ad | ||
|
|
64ff15a536 | ||
|
|
345f3e3559 | ||
|
|
636ab99ad8 | ||
|
|
f0c71e5a6d | ||
|
|
87d33f6e18 | ||
|
|
fd91fa433a | ||
|
|
484ba91b07 | ||
|
|
acb2147024 | ||
|
|
ace69bba75 | ||
|
|
5beb37c57c | ||
|
|
50f95a4f1a | ||
|
|
39e3f8fb81 | ||
|
|
b2413f914a | ||
|
|
9dff497abf | ||
|
|
e3f21d6c3b | ||
|
|
184e921930 | ||
|
|
5ee5093259 | ||
|
|
81781e6495 | ||
|
|
82959cec88 | ||
|
|
9478c5e7ac | ||
|
|
62e7e0bc09 | ||
|
|
7a16e495dd | ||
|
|
958fbdd5c0 | ||
|
|
5c403fb829 | ||
|
|
538501c88d | ||
|
|
0b6c92baa7 | ||
|
|
64ec73635b | ||
|
|
b36e55cf1f | ||
|
|
2461121637 | ||
|
|
e6fe3ba8ef | ||
|
|
0b867590a8 | ||
|
|
3c8d658160 | ||
|
|
176f9a7816 | ||
|
|
3d99de6771 | ||
|
|
a52e6c2d57 | ||
|
|
1808d7fd2f | ||
|
|
f4a1d99f00 | ||
|
|
8f49725aa5 | ||
|
|
febc66ef2b | ||
|
|
3761b3ac28 | ||
|
|
140ab270af | ||
|
|
6ab452a452 | ||
|
|
8962afd586 | ||
|
|
22f074cf59 | ||
|
|
ec4fe4f390 | ||
|
|
32c68e000b |
@@ -95,6 +95,7 @@ jobs:
|
||||
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
||||
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
||||
sbom: true
|
||||
build-args: |
|
||||
BUILD_HASH=${{ github.sha }}
|
||||
|
||||
@@ -199,6 +200,7 @@ jobs:
|
||||
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
||||
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
||||
sbom: true
|
||||
build-args: |
|
||||
BUILD_HASH=${{ github.sha }}
|
||||
USE_CUDA=true
|
||||
@@ -304,6 +306,7 @@ jobs:
|
||||
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
||||
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
||||
sbom: true
|
||||
build-args: |
|
||||
BUILD_HASH=${{ github.sha }}
|
||||
USE_CUDA=true
|
||||
@@ -407,6 +410,7 @@ jobs:
|
||||
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
||||
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
||||
sbom: true
|
||||
build-args: |
|
||||
BUILD_HASH=${{ github.sha }}
|
||||
USE_OLLAMA=true
|
||||
@@ -509,6 +513,7 @@ jobs:
|
||||
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
||||
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
||||
sbom: true
|
||||
build-args: |
|
||||
BUILD_HASH=${{ github.sha }}
|
||||
USE_SLIM=true
|
||||
|
||||
@@ -5,6 +5,82 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.8.7] - 2026-03-01
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🔒 **Connection access control privacy.** Tool server and terminal connections without explicit access grants are now private (admin-only) by default, fixing a bug where connections configured with no access grants were visible to all users instead of being restricted. [Commit](https://github.com/open-webui/open-webui/commit/2751a0f0b)
|
||||
- 🧠 **ChatControls memory leak.** The ChatControls panel no longer leaks event listeners, ResizeObserver instances, and media query handlers when navigating between chats, fixing memory accumulation that could degrade performance during extended use. [#22112](https://github.com/open-webui/open-webui/pull/22112)
|
||||
- 💾 **Temporary chat params preservation.** Model parameters are now correctly saved when creating a temporary chat, ensuring custom settings like temperature and top_p persist across the session. [Commit](https://github.com/open-webui/open-webui/commit/fe837d80e)
|
||||
- ⚡ **Faster artifact content updates.** Artifact content extraction during streaming is now debounced via requestAnimationFrame, reducing redundant DOM reads and improving CPU efficiency when tokens arrive faster than the browser can paint. [Commit](https://github.com/open-webui/open-webui/commit/6863ca482)
|
||||
|
||||
## [0.8.6] - 2026-03-01
|
||||
|
||||
### Added
|
||||
|
||||
- 🖥️ **Open Terminal integration.** Users can now connect to [Open Terminal](https://github.com/open-webui/open-terminal) instances to browse, read, and upload files directly in chat, with the terminal acting as an always-on tool. File navigation includes folder browsing, image and PDF previews, drag-and-drop uploads, directory creation, and file deletion. The current working directory is automatically injected into tool descriptions for context-aware commands. [Commit](https://github.com/open-webui/open-webui/commit/636ab99ad8e5b71b32dd37ba7c62c32368585b2a), [Commit](https://github.com/open-webui/open-webui/commit/64ff15a5365e2c4122fccab582782669f06ec58d), [Commit](https://github.com/open-webui/open-webui/commit/4737e1f11847d057859ec78892fa89e24cbcd83b)
|
||||
- 📄 **Terminal file creation.** Users can now create new empty files directly in the Open Terminal file browser, in addition to the existing folder creation functionality. [Commit](https://github.com/open-webui/open-webui/commit/234306ff57c9e24314ff805a60de919632465319)
|
||||
- ✏️ **Terminal file editing.** Users can now edit text files directly in the Open Terminal file browser, with the ability to save changes back to the terminal. [Commit](https://github.com/open-webui/open-webui/commit/3d535db304bfc6fa09e655f737de8a36c0482868)
|
||||
- 🛠️ **Terminal file preview toolbar.** The Open Terminal file browser now displays contextual toolbar buttons based on file type, including preview/source toggle for Markdown and CSV files, reset view for images, and improved editing controls for text files. [Commit](https://github.com/open-webui/open-webui/commit/d2b38127d0572006577b85c770607b04782de4f9)
|
||||
- 🔄 **Terminal file write refresh.** The file browser now automatically refreshes when files are written or modified via the write_file or replace_file_content tools, eliminating the need to manually refresh. [Commit](https://github.com/open-webui/open-webui/commit/18865a9fef1bb154603b7b8af0116a10560e03ac)
|
||||
- 🛡️ **Docker image SBOM attestation.** Docker images now include a Software Bill of Materials (SBOM) for vulnerability scanning and supply chain security compliance. [#21779](https://github.com/open-webui/open-webui/issues/21779), [Commit](https://github.com/open-webui/open-webui/commit/febc66ef2bb05606b59719e737ac5ad839002977)
|
||||
- 📡 **Reporting-Endpoints security header.** Administrators can now configure a Reporting-Endpoints header via the REPORTING_ENDPOINTS environment variable to receive CSP violation reports directly, aiding in security policy debugging and hardening. [#21830](https://github.com/open-webui/open-webui/issues/21830)
|
||||
- 🎯 **Action button priority sorting.** Action buttons under assistant messages now appear in a consistent order based on the priority field from function Valves, allowing developers to control button placement. [#21790](https://github.com/open-webui/open-webui/pull/21790)
|
||||
- 🏷️ **Public/Private model filtering.** The Admin Settings Model listing now displays Public/Private badges and includes filter options to easily view public or private models. [#21732](https://github.com/open-webui/open-webui/issues/21732), [#21797](https://github.com/open-webui/open-webui/pull/21797)
|
||||
- 👁️ **Show/Hide all models bulk action.** Administrators can now show or hide all models at once from the Admin Settings Models page Actions menu, making it faster to manage model visibility. Bulk actions now display a single toast notification on success for better user feedback. [#21838](https://github.com/open-webui/open-webui/pull/21838), [#21958](https://github.com/open-webui/open-webui/pull/21958)
|
||||
- 🔐 **Individual user sharing control.** Administrators can now disable individual user sharing via the USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_USERS environment variable, allowing only group-based sharing when set to false. [#21793](https://github.com/open-webui/open-webui/issues/21793), [Commit](https://github.com/open-webui/open-webui/commit/3d99de67716774af2f95f2e3c8e7cc4879464c71), [Commit](https://github.com/open-webui/open-webui/commit/176f9a781619d836be003d28d53904639cad4128)
|
||||
- 🔄 **OAuth profile sync on login.** Administrators can now enable automatic synchronization of user profile name and email from OAuth providers on login via the OAUTH_UPDATE_NAME_ON_LOGIN and OAUTH_UPDATE_EMAIL_ON_LOGIN environment variables. [#21787](https://github.com/open-webui/open-webui/pull/21787), [Commit](https://github.com/open-webui/open-webui/commit/9478c5e7ac8254b5f522c006da0c1c49bb282727)
|
||||
- 👥 **Default group share permission.** Administrators can now configure the default sharing permission for new groups via the DEFAULT_GROUP_SHARE_PERMISSION environment variable, controlling whether anyone, no one, or only members can share to new groups. [Commit](https://github.com/open-webui/open-webui/commit/538501c88da034434bcd1969f15341dbbaf154e4)
|
||||
- 💨 **Streaming performance.** Chat responses now render more efficiently during streaming, reducing CPU usage and improving responsiveness. [Commit](https://github.com/open-webui/open-webui/commit/484ba91b0777042eb848134f206ef3921f968dea)
|
||||
- 🧮 **Streaming message comparison.** Chat message updates during streaming are now faster thanks to an optimization that skips expensive comparisons when content changes. [#21884](https://github.com/open-webui/open-webui/pull/21884)
|
||||
- 🚀 **Streaming scroll optimization.** Chat auto-scroll during streaming is now more efficient by batching scroll operations via requestAnimationFrame, reducing unnecessary layout reflows when tokens arrive faster than the browser can paint. [#21946](https://github.com/open-webui/open-webui/pull/21946)
|
||||
- 📋 **Message cloning performance.** Chat message cloning during streaming is now more efficient thanks to the use of structuredClone() instead of JSON.parse(JSON.stringify(...)). [#21948](https://github.com/open-webui/open-webui/pull/21948)
|
||||
- 🎯 **Faster code block rendering.** Chat message updates during streaming are now faster. [#22101](https://github.com/open-webui/open-webui/pull/22101)
|
||||
- 📊 **Faster status history display.** Chat message updates during streaming are now faster. [#22103](https://github.com/open-webui/open-webui/pull/22103)
|
||||
- 🛠️ **Faster tool result handling.** Tool execution results are now handled more efficiently, improving streaming performance. [#22104](https://github.com/open-webui/open-webui/pull/22104)
|
||||
- 💾 **Faster model and file operations.** Model selection, file preparation, and history saving are now faster. [#22102](https://github.com/open-webui/open-webui/pull/22102)
|
||||
- 🛠️ **Tool server advanced options toggle.** Advanced OpenAPI configuration options in the tool server modal are now hidden by default behind a toggle, simplifying the interface for basic setups. The admin settings tab was also renamed from "Tools" to "Integrations" for clearer organization. [Commit](https://github.com/open-webui/open-webui/commit/f0c71e5a6d971af7322d4245313e5e04620253f0), [Commit](https://github.com/open-webui/open-webui/commit/4731ccb73c4b4bab78fd86fec7b2c231af8cca8b)
|
||||
- 🔧 **Faster tool loading.** Tool access control now skips an unnecessary database query when no tools are attached to the request, slightly improving performance. [#21873](https://github.com/open-webui/open-webui/pull/21873)
|
||||
- ➗ **Faster math rendering.** Mathematical notation now renders more efficiently, improving responsiveness when displaying equations in chat. [#21880](https://github.com/open-webui/open-webui/pull/21880)
|
||||
- 🏎️ **Faster message list updates.** The chat message list now rebuilds at most once per animation frame during streaming, reducing CPU overhead. [#21885](https://github.com/open-webui/open-webui/pull/21885)
|
||||
- 📋 **Faster message rendering.** Chat message rendering is now more efficient during streaming. [#22086](https://github.com/open-webui/open-webui/pull/22086)
|
||||
- 🗄️ **Faster real-time chat updates.** Chat responses now process faster with improved handling for concurrent users. [#22087](https://github.com/open-webui/open-webui/pull/22087)
|
||||
- 📝 **Faster status persistence.** Only final status updates are now saved to the database during streaming, reducing unnecessary writes. [#22085](https://github.com/open-webui/open-webui/pull/22085)
|
||||
- 🔄 **Faster event matching.** Event handling in the socket handler is now more efficient. [Commit](https://github.com/open-webui/open-webui/commit/ff86283be0479ccb86b639926b2b67ccbbe78746)
|
||||
- 🔀 **General improvements.** Various improvements were implemented across the application to enhance performance, stability, and security.
|
||||
- 🌐 **Translation updates.** Translations for German, Portuguese (Brazil), Simplified Chinese, Traditional Chinese, Catalan, and Spanish were enhanced and expanded.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🗄️ **Database migration execution.** Database migrations now run correctly on startup, fixing a circular import issue that caused schema updates to fail silently. [#21848](https://github.com/open-webui/open-webui/pull/21848), [Commit](https://github.com/open-webui/open-webui/commit/87d33f6e18196876603eee7d1bf8e4977c7fa9c1)
|
||||
- 🔔 **Notification HTML escaping.** Notification messages now properly escape HTML content, matching the behavior in chat messages and ensuring consistent rendering across the interface. [#21860](https://github.com/open-webui/open-webui/issues/21860), [Commit](https://github.com/open-webui/open-webui/commit/e83f668107723fa90ba0efa76c340c8338f45431)
|
||||
- 🛠️ **Tool call JSON error handling.** Chat no longer crashes when models generate malformed JSON in tool call arguments; instead, a descriptive error message is returned to the model for retry. [#21984](https://github.com/open-webui/open-webui/pull/21984), [Commit](https://github.com/open-webui/open-webui/commit/668bd44485bdf88e9083c6f09c3c47ab97a128a4)
|
||||
- 🧠 **Reasoning model KV cache preservation.** Reasoning model thinking tags are no longer stored as HTML in the database, preserving KV cache efficiency for backends like llama.cpp and ensuring faster subsequent conversation turns. [#21815](https://github.com/open-webui/open-webui/issues/21815), [Commit](https://github.com/open-webui/open-webui/commit/81781e6495dcc788c863bbf6b4aa4cf0ddd9fdcc)
|
||||
- ⚡ **Duplicate model execution prevention.** Models are no longer called twice when no tools are configured, eliminating unnecessary API requests and reducing latency. [#21802](https://github.com/open-webui/open-webui/issues/21802), [Commit](https://github.com/open-webui/open-webui/commit/3c8d658160809f6d651837cf93d89dddc1d17caf)
|
||||
- 🔐 **OAuth session database error.** OAuth login no longer fails with a database error when creating sessions, fixing the "'NoneType' object has no attribute 'id'" and "can't adapt type 'dict'" errors that occurred during OAuth group creation. [#21788](https://github.com/open-webui/open-webui/issues/21788)
|
||||
- 👤 **User sharing permission enforcement.** The user sharing option now correctly respects the USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_USERS setting, fixing an issue where sharing to individual users was incorrectly allowed even when disabled. [#21856](https://github.com/open-webui/open-webui/pull/21856), [Commit](https://github.com/open-webui/open-webui/commit/acb21470241ed6fd3eb3f659f196f697c418d9e8), [Commit](https://github.com/open-webui/open-webui/commit/ace69bba7512dc0a653695f9e6311712dfabb640)
|
||||
- 🔑 **Password manager autofill.** Password manager autofill (like iCloud Passwords, 1Password, Bitwarden) now correctly captures filled-in passwords, fixing login failures where the password appeared filled but was sent as empty. [#21869](https://github.com/open-webui/open-webui/pull/21869), [Commit](https://github.com/open-webui/open-webui/commit/9dff497abf821dfba6eb8ea65e48a657ee91fd71)
|
||||
- 📝 **RAG template duplication.** RAG templates are no longer duplicated in chat messages when models make multiple tool calls, preventing hallucinations and incorrect tool usage. [#21780](https://github.com/open-webui/open-webui/issues/21780), [Commit](https://github.com/open-webui/open-webui/commit/8f49725aa5f2d9b87e559e7d3f02f037335b7914)
|
||||
- 📋 **Audit log stdout.** Audit logs now correctly appear on stdout when the ENABLE_AUDIT_STDOUT environment variable is set to true, aligning runtime behavior with the intended configuration. [#21777](https://github.com/open-webui/open-webui/pull/21777)
|
||||
- 🎯 **Function valve priority resolution.** Function priorities defined in code are now correctly applied when no custom value has been saved in the database, ensuring consistent action button and filter ordering. [#21841](https://github.com/open-webui/open-webui/pull/21841)
|
||||
- 📄 **Web content knowledge base append.** Processing web URLs with overwrite=false now correctly appends content to existing knowledge bases instead of silently doing nothing, fixing a regression where no content was being added. [#21786](https://github.com/open-webui/open-webui/pull/21786), [Commit](https://github.com/open-webui/open-webui/commit/5ee509325970f01524348b0f91081110340f2e7e)
|
||||
- 🔍 **Web search domain filter config.** The WEB_SEARCH_DOMAIN_FILTER_LIST environment variable is now correctly read and applied, fixing an issue where domain filtering for web searches always used an empty default value. [#21964](https://github.com/open-webui/open-webui/pull/21964), [#20186](https://github.com/open-webui/open-webui/issues/20186)
|
||||
- 🧹 **Tooltip memory leak.** Tooltip instances are now properly destroyed when elements change, fixing a memory leak that could cause performance issues over time. [#21969](https://github.com/open-webui/open-webui/pull/21969)
|
||||
- ⌨️ **MessageInput memory leak.** Event listeners in the message input component are now properly cleaned up, preventing a memory leak that could cause page crashes during extended use. [#21968](https://github.com/open-webui/open-webui/pull/21968)
|
||||
- 📝 **Notes memory leak.** Event listeners in the Notes component are now properly cleaned up, fixing a memory leak that could cause page crashes during extended use. [#21963](https://github.com/open-webui/open-webui/pull/21963)
|
||||
- 🏗️ **Model create memory leak.** Event listeners in the model creation page are now properly cleaned up, fixing a memory leak that could cause page crashes during extended use. [#21966](https://github.com/open-webui/open-webui/pull/21966)
|
||||
- 💬 **MentionList memory leak.** Event listeners in the MentionList component are now properly cleaned up, fixing a memory leak that could cause page crashes during extended use. [#21965](https://github.com/open-webui/open-webui/pull/21965)
|
||||
- 📐 **Sidebar memory leak.** Event listeners in the Sidebar component are now properly cleaned up, fixing a memory leak that could cause page crashes during extended use. [#22082](https://github.com/open-webui/open-webui/pull/22082)
|
||||
- 🎨 **Sidebar user menu positioning.** The sidebar user menu no longer drifts rightward when the sidebar is resized, keeping the menu properly aligned with its trigger. [#21853](https://github.com/open-webui/open-webui/pull/21853)
|
||||
- 💻 **Code block UI.** Code block headers are now sticky and properly positioned, with language labels now showing tooltips for truncated text. [Commit](https://github.com/open-webui/open-webui/commit/6b462ff121d28cd2d335db7763052622d374e3a5)
|
||||
- 📊 **Multi-model responses horizontal scroll.** The model list in multi-model responses tabs now has horizontal scroll support, making all models accessible on desktop screens. [#21800](https://github.com/open-webui/open-webui/issues/21800), [Commit](https://github.com/open-webui/open-webui/commit/a3de0bcc586ddd14dde6ae915067f082d628eaeb)
|
||||
- 🎭 **TailwindCSS gray color theme.** Custom gray color palette is now correctly applied to the CSS root theme layer, fixing an issue where --color-gray-x variables were missing. [#21900](https://github.com/open-webui/open-webui/pull/21900), [#21899](https://github.com/open-webui/open-webui/issues/21899)
|
||||
- 📎 **Broken documentation links.** Fixed broken links in the backend config and admin settings that pointed to outdated documentation locations. [#21904](https://github.com/open-webui/open-webui/pull/21904)
|
||||
- 🔓 **OAuth session token decryption.** OAuth sessions are now properly detached from the database context before token decryption, preventing potential database session conflicts when reading encrypted tokens. [#21794](https://github.com/open-webui/open-webui/pull/21794)
|
||||
- 🕐 **Chat timestamp i18n fix.** Chat timestamps in the sidebar now display correctly, fixing an issue where the time ago format (e.g., "5m", "2h", "3d") was not being localized properly due to incorrect variable casing in the translation function. [Commit](https://github.com/open-webui/open-webui/commit/ae28e7d24530eb9f7909b293bcd0f33048a022a9)
|
||||
- 🍞 **Model toast notification fix.** Hiding or showing a single model now displays only one toast notification instead of two, removing the redundant generic "model updated" message when a specific action toast is shown. [#22079](https://github.com/open-webui/open-webui/pull/22079)
|
||||
- 📡 **Offline mode embedding model fix.** Open WebUI no longer attempts to download embedding models when in offline mode, fixing error logs that occurred when trying to fetch models that weren't cached locally. [#22106](https://github.com/open-webui/open-webui/pull/22106), [#21405](https://github.com/open-webui/open-webui/issues/21405)
|
||||
|
||||
## [0.8.5] - 2026-02-23
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Open WebUI Contributor License Agreement
|
||||
# Contributor License Agreement
|
||||
|
||||
By submitting my contributions to Open WebUI, I grant Open WebUI full freedom to use my work in any way they choose, under any terms they like, both now and in the future. This approach helps ensure the project remains unified, flexible, and easy to maintain, while empowering Open WebUI to respond quickly to the needs of its users and the wider community.
|
||||
By submitting my contributions to this repository in any form, I grant Open WebUI Inc. a perpetual, worldwide, irrevocable, royalty-free license, under copyright and patent, to use, modify, distribute, sublicense, and commercialize my work under any terms they choose, both now and in the future.
|
||||
|
||||
Taking part in this process means my work can be seamlessly integrated and combined with others, ensuring longevity and adaptability for everyone who benefits from the Open WebUI project. This collaborative approach strengthens the project’s future and helps guarantee that improvements can always be shared and distributed in the most effective way possible.
|
||||
I represent that my contributions are my original work (or that I have sufficient rights to grant this license) and that I have the authority to enter into this agreement.
|
||||
|
||||
**_To the fullest extent permitted by law, my contributions are provided on an “as is” basis, with no warranties or guarantees of any kind, and I disclaim any liability for any issues or damages arising from their use or incorporation into the project, regardless of the type of legal claim._**
|
||||
@@ -322,7 +322,7 @@ JWT_EXPIRES_IN = PersistentConfig(
|
||||
if JWT_EXPIRES_IN.value == "-1":
|
||||
log.warning(
|
||||
"⚠️ SECURITY WARNING: JWT_EXPIRES_IN is set to '-1'\n"
|
||||
" See: https://docs.openwebui.com/getting-started/env-configuration\n"
|
||||
" See: https://docs.openwebui.com/reference/env-configuration\n"
|
||||
)
|
||||
|
||||
####################################
|
||||
@@ -642,6 +642,18 @@ OAUTH_UPDATE_PICTURE_ON_LOGIN = PersistentConfig(
|
||||
os.environ.get("OAUTH_UPDATE_PICTURE_ON_LOGIN", "False").lower() == "true",
|
||||
)
|
||||
|
||||
OAUTH_UPDATE_NAME_ON_LOGIN = PersistentConfig(
|
||||
"OAUTH_UPDATE_NAME_ON_LOGIN",
|
||||
"oauth.update_name_on_login",
|
||||
os.environ.get("OAUTH_UPDATE_NAME_ON_LOGIN", "False").lower() == "true",
|
||||
)
|
||||
|
||||
OAUTH_UPDATE_EMAIL_ON_LOGIN = PersistentConfig(
|
||||
"OAUTH_UPDATE_EMAIL_ON_LOGIN",
|
||||
"oauth.update_email_on_login",
|
||||
os.environ.get("OAUTH_UPDATE_EMAIL_ON_LOGIN", "False").lower() == "true",
|
||||
)
|
||||
|
||||
OAUTH_ACCESS_TOKEN_REQUEST_INCLUDE_CLIENT_ID = (
|
||||
os.environ.get("OAUTH_ACCESS_TOKEN_REQUEST_INCLUDE_CLIENT_ID", "False").lower()
|
||||
== "true"
|
||||
@@ -1171,6 +1183,20 @@ TOOL_SERVER_CONNECTIONS = PersistentConfig(
|
||||
tool_server_connections,
|
||||
)
|
||||
|
||||
####################################
|
||||
# TERMINAL_SERVER
|
||||
####################################
|
||||
|
||||
terminal_server_connections = json.loads(
|
||||
os.environ.get("TERMINAL_SERVER_CONNECTIONS", "[]")
|
||||
)
|
||||
|
||||
TERMINAL_SERVER_CONNECTIONS = PersistentConfig(
|
||||
"TERMINAL_SERVER_CONNECTIONS",
|
||||
"terminal_server.connections",
|
||||
terminal_server_connections,
|
||||
)
|
||||
|
||||
####################################
|
||||
# WEBUI
|
||||
####################################
|
||||
@@ -1433,6 +1459,11 @@ USER_PERMISSIONS_NOTES_ALLOW_PUBLIC_SHARING = (
|
||||
== "true"
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_USERS = (
|
||||
os.environ.get("USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_USERS", "True").lower()
|
||||
== "true"
|
||||
)
|
||||
|
||||
|
||||
USER_PERMISSIONS_CHAT_CONTROLS = (
|
||||
os.environ.get("USER_PERMISSIONS_CHAT_CONTROLS", "True").lower() == "true"
|
||||
@@ -1590,6 +1621,9 @@ DEFAULT_USER_PERMISSIONS = {
|
||||
"notes": USER_PERMISSIONS_NOTES_ALLOW_SHARING,
|
||||
"public_notes": USER_PERMISSIONS_NOTES_ALLOW_PUBLIC_SHARING,
|
||||
},
|
||||
"access_grants": {
|
||||
"allow_users": USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_USERS,
|
||||
},
|
||||
"chat": {
|
||||
"controls": USER_PERMISSIONS_CHAT_CONTROLS,
|
||||
"valves": USER_PERMISSIONS_CHAT_VALVES,
|
||||
@@ -3177,17 +3211,24 @@ WEB_SEARCH_RESULT_COUNT = PersistentConfig(
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
web_search_domain_filter_list = json.loads(
|
||||
os.getenv("WEB_SEARCH_DOMAIN_FILTER_LIST", "[]")
|
||||
)
|
||||
except Exception as e:
|
||||
web_search_domain_filter_list = [
|
||||
# "wikipedia.com",
|
||||
# "wikimedia.org",
|
||||
# "wikidata.org",
|
||||
# "!stackoverflow.com",
|
||||
]
|
||||
|
||||
# You can provide a list of your own websites to filter after performing a web search.
|
||||
# This ensures the highest level of safety and reliability of the information sources.
|
||||
WEB_SEARCH_DOMAIN_FILTER_LIST = PersistentConfig(
|
||||
"WEB_SEARCH_DOMAIN_FILTER_LIST",
|
||||
"rag.web.search.domain.filter_list",
|
||||
[
|
||||
# "wikipedia.com",
|
||||
# "wikimedia.org",
|
||||
# "wikidata.org",
|
||||
# "!stackoverflow.com",
|
||||
],
|
||||
web_search_domain_filter_list,
|
||||
)
|
||||
|
||||
WEB_SEARCH_CONCURRENT_REQUESTS = PersistentConfig(
|
||||
|
||||
@@ -1041,3 +1041,16 @@ PIP_PACKAGE_INDEX_OPTIONS = os.getenv("PIP_PACKAGE_INDEX_OPTIONS", "").split()
|
||||
####################################
|
||||
|
||||
EXTERNAL_PWA_MANIFEST_URL = os.environ.get("EXTERNAL_PWA_MANIFEST_URL")
|
||||
|
||||
####################################
|
||||
# GROUP DEFAULTS
|
||||
####################################
|
||||
|
||||
# Controls the default "Who can share to this group" setting for new groups.
|
||||
# Env var values: "true" (anyone), "false" (no one), "members" (only group members).
|
||||
_default_group_share = (
|
||||
os.environ.get("DEFAULT_GROUP_SHARE_PERMISSION", "members").strip().lower()
|
||||
)
|
||||
DEFAULT_GROUP_SHARE_PERMISSION = (
|
||||
"members" if _default_group_share == "members" else _default_group_share == "true"
|
||||
)
|
||||
|
||||
@@ -96,6 +96,7 @@ from open_webui.routers import (
|
||||
users,
|
||||
utils,
|
||||
scim,
|
||||
terminals,
|
||||
)
|
||||
|
||||
from open_webui.routers.retrieval import (
|
||||
@@ -132,6 +133,8 @@ from open_webui.config import (
|
||||
THREAD_POOL_SIZE,
|
||||
# Tool Server Configs
|
||||
TOOL_SERVER_CONNECTIONS,
|
||||
# Terminal Server
|
||||
TERMINAL_SERVER_CONNECTIONS,
|
||||
# Code Execution
|
||||
ENABLE_CODE_EXECUTION,
|
||||
CODE_EXECUTION_ENGINE,
|
||||
@@ -524,7 +527,7 @@ from open_webui.utils.middleware import (
|
||||
process_chat_payload,
|
||||
process_chat_response,
|
||||
)
|
||||
from open_webui.utils.tools import set_tool_servers
|
||||
from open_webui.utils.tools import set_tool_servers, set_terminal_servers
|
||||
|
||||
from open_webui.utils.auth import (
|
||||
get_license_data,
|
||||
@@ -690,8 +693,13 @@ async def lifespan(app: FastAPI):
|
||||
)
|
||||
await set_tool_servers(mock_request)
|
||||
log.info(f"Initialized {len(app.state.TOOL_SERVERS)} tool server(s)")
|
||||
|
||||
await set_terminal_servers(mock_request)
|
||||
log.info(
|
||||
f"Initialized {len(app.state.TERMINAL_SERVERS)} terminal server(s)"
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to initialize tool servers at startup: {e}")
|
||||
log.warning(f"Failed to initialize tool/terminal servers at startup: {e}")
|
||||
|
||||
yield
|
||||
|
||||
@@ -775,6 +783,15 @@ app.state.OPENAI_MODELS = {}
|
||||
app.state.config.TOOL_SERVER_CONNECTIONS = TOOL_SERVER_CONNECTIONS
|
||||
app.state.TOOL_SERVERS = []
|
||||
|
||||
########################################
|
||||
#
|
||||
# TERMINAL SERVER
|
||||
#
|
||||
########################################
|
||||
|
||||
app.state.config.TERMINAL_SERVER_CONNECTIONS = TERMINAL_SERVER_CONNECTIONS
|
||||
app.state.TERMINAL_SERVERS = []
|
||||
|
||||
########################################
|
||||
#
|
||||
# DIRECT CONNECTIONS
|
||||
@@ -1540,6 +1557,7 @@ app.include_router(
|
||||
if ENABLE_ADMIN_ANALYTICS:
|
||||
app.include_router(analytics.router, prefix="/api/v1/analytics", tags=["analytics"])
|
||||
app.include_router(utils.router, prefix="/api/v1/utils", tags=["utils"])
|
||||
app.include_router(terminals.router, prefix="/api/v1/terminals", tags=["terminals"])
|
||||
|
||||
# SCIM 2.0 API for identity management
|
||||
if ENABLE_SCIM:
|
||||
|
||||
@@ -127,6 +127,11 @@ def upgrade() -> None:
|
||||
|
||||
timestamp = message.get("timestamp", now)
|
||||
|
||||
try:
|
||||
timestamp = int(float(timestamp))
|
||||
except Exception as e:
|
||||
timestamp = now
|
||||
|
||||
# Normalize timestamp: convert ms to seconds, validate range
|
||||
if timestamp > 10_000_000_000:
|
||||
timestamp = timestamp // 1000
|
||||
|
||||
@@ -204,6 +204,43 @@ def has_public_read_access_grant(access_grants: Optional[list]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def has_user_access_grant(access_grants: Optional[list]) -> bool:
|
||||
"""
|
||||
Returns True when a direct grant list includes any non-wildcard user grant.
|
||||
"""
|
||||
for grant in normalize_access_grants(access_grants):
|
||||
if grant["principal_type"] == "user" and grant["principal_id"] != "*":
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def strip_user_access_grants(access_grants: Optional[list]) -> list:
|
||||
"""
|
||||
Remove all non-wildcard user grants from the list.
|
||||
Keeps group grants and the public wildcard (user:*) intact.
|
||||
"""
|
||||
if not access_grants:
|
||||
return []
|
||||
return [
|
||||
grant
|
||||
for grant in access_grants
|
||||
if not (
|
||||
(
|
||||
grant.get("principal_type")
|
||||
if isinstance(grant, dict)
|
||||
else getattr(grant, "principal_type", None)
|
||||
)
|
||||
== "user"
|
||||
and (
|
||||
grant.get("principal_id")
|
||||
if isinstance(grant, dict)
|
||||
else getattr(grant, "principal_id", None)
|
||||
)
|
||||
!= "*"
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def grants_to_access_control(grants: list) -> Optional[dict]:
|
||||
"""
|
||||
Convert a list of grant objects (AccessGrantModel or AccessGrantResponse)
|
||||
|
||||
@@ -146,7 +146,7 @@ class AuthsTable:
|
||||
def authenticate_user_by_api_key(
|
||||
self, api_key: str, db: Optional[Session] = None
|
||||
) -> Optional[UserModel]:
|
||||
log.info(f"authenticate_user_by_api_key: {api_key}")
|
||||
log.info(f"authenticate_user_by_api_key")
|
||||
# if no api_key, return None
|
||||
if not api_key:
|
||||
return None
|
||||
@@ -197,7 +197,10 @@ class AuthsTable:
|
||||
with get_db_context(db) as db:
|
||||
result = db.query(Auth).filter_by(id=id).update({"email": email})
|
||||
db.commit()
|
||||
return True if result == 1 else False
|
||||
if result == 1:
|
||||
Users.update_user_by_id(id, {"email": email}, db=db)
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import uuid
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from open_webui.internal.db import Base, JSONField, get_db, get_db_context
|
||||
from open_webui.env import DEFAULT_GROUP_SHARE_PERMISSION
|
||||
|
||||
from open_webui.models.files import FileMetadataResponse
|
||||
|
||||
@@ -130,13 +131,26 @@ class GroupListResponse(BaseModel):
|
||||
|
||||
|
||||
class GroupTable:
|
||||
def _ensure_default_share_config(self, group_data: dict) -> dict:
|
||||
"""Ensure the group data dict has a default share config if not already set."""
|
||||
if "data" not in group_data or group_data["data"] is None:
|
||||
group_data["data"] = {}
|
||||
if "config" not in group_data["data"]:
|
||||
group_data["data"]["config"] = {}
|
||||
if "share" not in group_data["data"]["config"]:
|
||||
group_data["data"]["config"]["share"] = DEFAULT_GROUP_SHARE_PERMISSION
|
||||
return group_data
|
||||
|
||||
def insert_new_group(
|
||||
self, user_id: str, form_data: GroupForm, db: Optional[Session] = None
|
||||
) -> Optional[GroupModel]:
|
||||
with get_db_context(db) as db:
|
||||
group_data = self._ensure_default_share_config(
|
||||
form_data.model_dump(exclude_none=True)
|
||||
)
|
||||
group = GroupModel(
|
||||
**{
|
||||
**form_data.model_dump(exclude_none=True),
|
||||
**group_data,
|
||||
"id": str(uuid.uuid4()),
|
||||
"user_id": user_id,
|
||||
"created_at": int(time.time()),
|
||||
@@ -504,6 +518,11 @@ class GroupTable:
|
||||
user_id=user_id,
|
||||
name=group_name,
|
||||
description="",
|
||||
data={
|
||||
"config": {
|
||||
"share": DEFAULT_GROUP_SHARE_PERMISSION,
|
||||
}
|
||||
},
|
||||
created_at=int(time.time()),
|
||||
updated_at=int(time.time()),
|
||||
)
|
||||
|
||||
@@ -613,6 +613,21 @@ class KnowledgeTable:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def has_file(
|
||||
self, knowledge_id: str, file_id: str, db: Optional[Session] = None
|
||||
) -> bool:
|
||||
"""Check whether a file belongs to a knowledge base."""
|
||||
try:
|
||||
with get_db_context(db) as db:
|
||||
return (
|
||||
db.query(KnowledgeFile)
|
||||
.filter_by(knowledge_id=knowledge_id, file_id=file_id)
|
||||
.first()
|
||||
is not None
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def remove_file_from_knowledge_by_id(
|
||||
self, knowledge_id: str, file_id: str, db: Optional[Session] = None
|
||||
) -> bool:
|
||||
|
||||
@@ -135,6 +135,7 @@ class OAuthSessionTable:
|
||||
db.refresh(result)
|
||||
|
||||
if result:
|
||||
db.expunge(result) # Detach so dict swap is never flushed
|
||||
result.token = token # Return decrypted token
|
||||
return OAuthSessionModel.model_validate(result)
|
||||
else:
|
||||
@@ -151,6 +152,7 @@ class OAuthSessionTable:
|
||||
with get_db_context(db) as db:
|
||||
session = db.query(OAuthSession).filter_by(id=session_id).first()
|
||||
if session:
|
||||
db.expunge(session)
|
||||
session.token = self._decrypt_token(session.token)
|
||||
return OAuthSessionModel.model_validate(session)
|
||||
|
||||
@@ -171,6 +173,7 @@ class OAuthSessionTable:
|
||||
.first()
|
||||
)
|
||||
if session:
|
||||
db.expunge(session)
|
||||
session.token = self._decrypt_token(session.token)
|
||||
return OAuthSessionModel.model_validate(session)
|
||||
|
||||
@@ -192,6 +195,7 @@ class OAuthSessionTable:
|
||||
.first()
|
||||
)
|
||||
if session:
|
||||
db.expunge(session)
|
||||
session.token = self._decrypt_token(session.token)
|
||||
return OAuthSessionModel.model_validate(session)
|
||||
|
||||
@@ -211,6 +215,7 @@ class OAuthSessionTable:
|
||||
results = []
|
||||
for session in sessions:
|
||||
try:
|
||||
db.expunge(session)
|
||||
session.token = self._decrypt_token(session.token)
|
||||
results.append(OAuthSessionModel.model_validate(session))
|
||||
except Exception as e:
|
||||
@@ -245,6 +250,7 @@ class OAuthSessionTable:
|
||||
session = db.query(OAuthSession).filter_by(id=session_id).first()
|
||||
|
||||
if session:
|
||||
db.expunge(session)
|
||||
session.token = self._decrypt_token(session.token)
|
||||
return OAuthSessionModel.model_validate(session)
|
||||
|
||||
|
||||
@@ -1306,6 +1306,8 @@ def get_model_path(model: str, update_model: bool = False):
|
||||
return model_repo_path
|
||||
except Exception as e:
|
||||
log.exception(f"Cannot determine model snapshot path: {e}")
|
||||
if OFFLINE_MODE:
|
||||
raise
|
||||
return model
|
||||
|
||||
|
||||
|
||||
@@ -1194,7 +1194,9 @@ def transcription(
|
||||
)
|
||||
|
||||
try:
|
||||
ext = file.filename.split(".")[-1]
|
||||
safe_name = os.path.basename(file.filename) if file.filename else ""
|
||||
ext = safe_name.rsplit(".", 1)[-1] if "." in safe_name else ""
|
||||
|
||||
id = uuid.uuid4()
|
||||
|
||||
filename = f"{id}.{ext}"
|
||||
@@ -1204,6 +1206,10 @@ def transcription(
|
||||
os.makedirs(file_dir, exist_ok=True)
|
||||
file_path = f"{file_dir}/{filename}"
|
||||
|
||||
# Defense-in-depth: ensure resolved path stays within intended directory
|
||||
if not os.path.realpath(file_path).startswith(os.path.realpath(file_dir)):
|
||||
raise ValueError("Invalid file path detected")
|
||||
|
||||
with open(file_path, "wb") as f:
|
||||
f.write(contents)
|
||||
|
||||
@@ -1225,7 +1231,7 @@ def transcription(
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=ERROR_MESSAGES.DEFAULT(e),
|
||||
detail="Transcription failed.",
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -1233,7 +1239,7 @@ def transcription(
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=ERROR_MESSAGES.DEFAULT(e),
|
||||
detail="Transcription failed.",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1578,7 +1578,9 @@ async def update_message_by_id(
|
||||
if (
|
||||
user.role != "admin"
|
||||
and message.user_id != user.id
|
||||
and not channel_has_access(user.id, channel, permission="read", db=db)
|
||||
and not channel_has_access(
|
||||
user.id, channel, permission="write", strict=False, db=db
|
||||
)
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
|
||||
|
||||
@@ -15,6 +15,7 @@ from open_webui.utils.tools import (
|
||||
get_tool_server_data,
|
||||
get_tool_server_url,
|
||||
set_tool_servers,
|
||||
set_terminal_servers,
|
||||
)
|
||||
from open_webui.utils.mcp.client import MCPClient
|
||||
from open_webui.models.oauth_sessions import OAuthSessions
|
||||
@@ -214,6 +215,51 @@ async def set_tool_servers_config(
|
||||
}
|
||||
|
||||
|
||||
class TerminalServerConnection(BaseModel):
|
||||
id: Optional[str] = ""
|
||||
name: Optional[str] = ""
|
||||
|
||||
enabled: Optional[bool] = True
|
||||
|
||||
url: str
|
||||
path: Optional[str] = "/openapi.json"
|
||||
|
||||
key: Optional[str] = ""
|
||||
auth_type: Optional[str] = "bearer"
|
||||
|
||||
config: Optional[dict] = None
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
class TerminalServersConfigForm(BaseModel):
|
||||
TERMINAL_SERVER_CONNECTIONS: list[TerminalServerConnection]
|
||||
|
||||
|
||||
@router.get("/terminal_servers")
|
||||
async def get_terminal_servers_config(request: Request, user=Depends(get_admin_user)):
|
||||
return {
|
||||
"TERMINAL_SERVER_CONNECTIONS": request.app.state.config.TERMINAL_SERVER_CONNECTIONS,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/terminal_servers")
|
||||
async def set_terminal_servers_config(
|
||||
request: Request,
|
||||
form_data: TerminalServersConfigForm,
|
||||
user=Depends(get_admin_user),
|
||||
):
|
||||
request.app.state.config.TERMINAL_SERVER_CONNECTIONS = [
|
||||
connection.model_dump() for connection in form_data.TERMINAL_SERVER_CONNECTIONS
|
||||
]
|
||||
|
||||
await set_terminal_servers(request)
|
||||
|
||||
return {
|
||||
"TERMINAL_SERVER_CONNECTIONS": request.app.state.config.TERMINAL_SERVER_CONNECTIONS,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/tool_servers/verify")
|
||||
async def verify_tool_servers_config(
|
||||
request: Request, form_data: ToolServerConnection, user=Depends(get_admin_user)
|
||||
|
||||
@@ -57,64 +57,7 @@ log = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
############################
|
||||
# Check if the current user has access to a file through any knowledge bases the user may be in.
|
||||
############################
|
||||
|
||||
|
||||
# TODO: Optimize this function to use the knowledge_file table for faster lookups.
|
||||
def has_access_to_file(
|
||||
file_id: Optional[str],
|
||||
access_type: str,
|
||||
user=Depends(get_verified_user),
|
||||
db: Optional[Session] = None,
|
||||
) -> bool:
|
||||
file = Files.get_file_by_id(file_id, db=db)
|
||||
log.debug(f"Checking if user has {access_type} access to file")
|
||||
if not file:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
# Check if the file is associated with any knowledge bases the user has access to
|
||||
knowledge_bases = Knowledges.get_knowledges_by_file_id(file_id, db=db)
|
||||
user_group_ids = {
|
||||
group.id for group in Groups.get_groups_by_member_id(user.id, db=db)
|
||||
}
|
||||
for knowledge_base in knowledge_bases:
|
||||
if knowledge_base.user_id == user.id or AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type="knowledge",
|
||||
resource_id=knowledge_base.id,
|
||||
permission=access_type,
|
||||
user_group_ids=user_group_ids,
|
||||
db=db,
|
||||
):
|
||||
return True
|
||||
|
||||
knowledge_base_id = file.meta.get("collection_name") if file.meta else None
|
||||
if knowledge_base_id:
|
||||
knowledge_bases = Knowledges.get_knowledge_bases_by_user_id(
|
||||
user.id, access_type, db=db
|
||||
)
|
||||
for knowledge_base in knowledge_bases:
|
||||
if knowledge_base.id == knowledge_base_id:
|
||||
return True
|
||||
|
||||
# Check if the file is associated with any channels the user has access to
|
||||
channels = Channels.get_channels_by_file_id_and_user_id(file_id, user.id, db=db)
|
||||
if access_type == "read" and channels:
|
||||
return True
|
||||
|
||||
# Check if the file is associated with any chats the user has access to
|
||||
# TODO: Granular access control for chats
|
||||
chats = Chats.get_shared_chats_by_file_id(file_id, db=db)
|
||||
if chats:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
from open_webui.utils.access_control.files import has_access_to_file
|
||||
|
||||
############################
|
||||
# Upload File
|
||||
|
||||
@@ -29,8 +29,8 @@ from open_webui.storage.provider import Storage
|
||||
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.utils.auth import get_verified_user, get_admin_user
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.models.access_grants import AccessGrants, has_public_read_access_grant
|
||||
from open_webui.utils.access_control import has_permission, filter_allowed_access_grants
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
|
||||
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
@@ -251,7 +251,7 @@ async def create_new_knowledge(
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
# NOTE: We intentionally do NOT use Depends(get_session) here.
|
||||
# Database operations (has_permission, insert_new_knowledge) manage their own sessions.
|
||||
# Database operations (has_permission, filter_allowed_access_grants, insert_new_knowledge) manage their own sessions.
|
||||
# This prevents holding a connection during embed_knowledge_base_metadata()
|
||||
# which makes external embedding API calls (1-5+ seconds).
|
||||
if user.role != "admin" and not has_permission(
|
||||
@@ -262,17 +262,13 @@ async def create_new_knowledge(
|
||||
detail=ERROR_MESSAGES.UNAUTHORIZED,
|
||||
)
|
||||
|
||||
# Check if user can share publicly
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_knowledge",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = []
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_knowledge",
|
||||
)
|
||||
|
||||
knowledge = Knowledges.insert_new_knowledge(user.id, form_data)
|
||||
|
||||
@@ -482,17 +478,13 @@ async def update_knowledge_by_id(
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
# Check if user can share publicly
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_knowledge",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = []
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_knowledge",
|
||||
)
|
||||
|
||||
knowledge = Knowledges.update_knowledge_by_id(id=id, form_data=form_data)
|
||||
if knowledge:
|
||||
@@ -554,24 +546,13 @@ async def update_knowledge_access_by_id(
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
# Strip public sharing if user lacks permission
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_knowledge",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = [
|
||||
grant
|
||||
for grant in form_data.access_grants
|
||||
if not (
|
||||
grant.get("principal_type") == "user"
|
||||
and grant.get("principal_id") == "*"
|
||||
)
|
||||
]
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_knowledge",
|
||||
)
|
||||
|
||||
AccessGrants.set_access_grants("knowledge", id, form_data.access_grants, db=db)
|
||||
|
||||
@@ -764,6 +745,13 @@ def update_file_from_knowledge_by_id(
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
# Validate the file actually belongs to this knowledge base
|
||||
if not Knowledges.has_file(knowledge_id=id, file_id=form_data.file_id, db=db):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
# Remove content from the vector database
|
||||
VECTOR_DB_CLIENT.delete(
|
||||
collection_name=knowledge.id, filter={"file_id": form_data.file_id}
|
||||
@@ -838,6 +826,13 @@ def remove_file_from_knowledge_by_id(
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
# Validate the file actually belongs to this knowledge base
|
||||
if not Knowledges.has_file(knowledge_id=id, file_id=form_data.file_id, db=db):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
Knowledges.remove_file_from_knowledge_by_id(
|
||||
knowledge_id=id, file_id=form_data.file_id, db=db
|
||||
)
|
||||
|
||||
@@ -17,7 +17,7 @@ from open_webui.models.models import (
|
||||
ModelAccessResponse,
|
||||
Models,
|
||||
)
|
||||
from open_webui.models.access_grants import AccessGrants, has_public_read_access_grant
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
|
||||
from pydantic import BaseModel
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
@@ -33,7 +33,7 @@ from fastapi.responses import FileResponse, StreamingResponse
|
||||
|
||||
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.access_control import has_permission, filter_allowed_access_grants
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL, STATIC_DIR
|
||||
from open_webui.internal.db import get_session
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -565,24 +565,13 @@ async def update_model_access_by_id(
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
# Strip public sharing if user lacks permission
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_models",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = [
|
||||
grant
|
||||
for grant in form_data.access_grants
|
||||
if not (
|
||||
grant.get("principal_type") == "user"
|
||||
and grant.get("principal_id") == "*"
|
||||
)
|
||||
]
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_models",
|
||||
)
|
||||
|
||||
AccessGrants.set_access_grants(
|
||||
"model", form_data.id, form_data.access_grants, db=db
|
||||
|
||||
@@ -27,8 +27,8 @@ from open_webui.constants import ERROR_MESSAGES
|
||||
|
||||
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.models.access_grants import AccessGrants, has_public_read_access_grant
|
||||
from open_webui.utils.access_control import has_permission, filter_allowed_access_grants
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.internal.db import get_session
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -283,18 +283,14 @@ async def update_note_by_id(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
|
||||
)
|
||||
|
||||
# Check if user can share publicly
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_notes",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
db=db,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = []
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_notes",
|
||||
db=db,
|
||||
)
|
||||
|
||||
try:
|
||||
note = Notes.update_note_by_id(id, form_data, db=db)
|
||||
@@ -357,24 +353,13 @@ async def update_note_access_by_id(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
|
||||
)
|
||||
|
||||
# Strip public sharing if user lacks permission
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_notes",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = [
|
||||
grant
|
||||
for grant in form_data.access_grants
|
||||
if not (
|
||||
grant.get("principal_type") == "user"
|
||||
and grant.get("principal_id") == "*"
|
||||
)
|
||||
]
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_notes",
|
||||
)
|
||||
|
||||
AccessGrants.set_access_grants("note", id, form_data.access_grants, db=db)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from open_webui.models.prompts import (
|
||||
PromptModel,
|
||||
Prompts,
|
||||
)
|
||||
from open_webui.models.access_grants import AccessGrants, has_public_read_access_grant
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.prompt_history import (
|
||||
PromptHistories,
|
||||
@@ -18,7 +18,7 @@ from open_webui.models.prompt_history import (
|
||||
)
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.access_control import has_permission, filter_allowed_access_grants
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
from open_webui.internal.db import get_session
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -473,24 +473,13 @@ async def update_prompt_access_by_id(
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
# Strip public sharing if user lacks permission
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_prompts",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = [
|
||||
grant
|
||||
for grant in form_data.access_grants
|
||||
if not (
|
||||
grant.get("principal_type") == "user"
|
||||
and grant.get("principal_id") == "*"
|
||||
)
|
||||
]
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_prompts",
|
||||
)
|
||||
|
||||
AccessGrants.set_access_grants("prompt", prompt_id, form_data.access_grants, db=db)
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ from langchain_text_splitters import (
|
||||
from langchain_core.documents import Document
|
||||
|
||||
from open_webui.models.files import FileModel, FileUpdateForm, Files
|
||||
from open_webui.utils.access_control.files import has_access_to_file
|
||||
from open_webui.models.knowledge import Knowledges
|
||||
from open_webui.storage.provider import Storage
|
||||
from open_webui.internal.db import get_session, get_db
|
||||
@@ -1971,6 +1972,7 @@ async def process_web(
|
||||
docs,
|
||||
collection_name,
|
||||
overwrite=overwrite,
|
||||
add=(not overwrite),
|
||||
user=user,
|
||||
)
|
||||
else:
|
||||
@@ -2489,6 +2491,34 @@ async def process_web_search(
|
||||
)
|
||||
|
||||
|
||||
def _validate_collection_access(collection_names: list[str], user) -> None:
|
||||
"""
|
||||
Prevent users from querying collections they don't own.
|
||||
Enforces ownership on user-memory-* and file-* collections.
|
||||
Admins bypass this check.
|
||||
"""
|
||||
if user.role == "admin":
|
||||
return
|
||||
|
||||
for name in collection_names:
|
||||
if name.startswith("user-memory-") and name != f"user-memory-{user.id}":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
elif name.startswith("file-"):
|
||||
file_id = name[len("file-") :]
|
||||
if not has_access_to_file(
|
||||
file_id=file_id,
|
||||
access_type="read",
|
||||
user=user,
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
|
||||
class QueryDocForm(BaseModel):
|
||||
collection_name: str
|
||||
query: str
|
||||
@@ -2504,6 +2534,8 @@ async def query_doc_handler(
|
||||
form_data: QueryDocForm,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
_validate_collection_access([form_data.collection_name], user)
|
||||
|
||||
try:
|
||||
if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH and (
|
||||
form_data.hybrid is None or form_data.hybrid
|
||||
@@ -2578,6 +2610,8 @@ async def query_collection_handler(
|
||||
form_data: QueryCollectionsForm,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
_validate_collection_access(form_data.collection_names, user)
|
||||
|
||||
try:
|
||||
if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH and (
|
||||
form_data.hybrid is None or form_data.hybrid
|
||||
@@ -2756,6 +2790,27 @@ async def process_files_batch(
|
||||
|
||||
for file in form_data.files:
|
||||
try:
|
||||
# Ownership check: verify the requesting user owns the file or is an admin
|
||||
db_file = Files.get_file_by_id(file.id)
|
||||
if not db_file:
|
||||
file_errors.append(
|
||||
BatchProcessFilesResult(
|
||||
file_id=file.id,
|
||||
status="failed",
|
||||
error="File not found",
|
||||
)
|
||||
)
|
||||
continue
|
||||
if db_file.user_id != user.id and user.role != "admin":
|
||||
file_errors.append(
|
||||
BatchProcessFilesResult(
|
||||
file_id=file.id,
|
||||
status="failed",
|
||||
error="Permission denied: not file owner",
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
text_content = file.data.get("content", "")
|
||||
docs: List[Document] = [
|
||||
Document(
|
||||
|
||||
@@ -17,7 +17,7 @@ from open_webui.models.skills import (
|
||||
SkillAccessListResponse,
|
||||
Skills,
|
||||
)
|
||||
from open_webui.models.access_grants import AccessGrants, has_public_read_access_grant
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_access, has_permission
|
||||
|
||||
@@ -341,24 +341,13 @@ async def update_skill_access_by_id(
|
||||
detail=ERROR_MESSAGES.UNAUTHORIZED,
|
||||
)
|
||||
|
||||
# Strip public sharing if user lacks permission
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_skills",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = [
|
||||
grant
|
||||
for grant in form_data.access_grants
|
||||
if not (
|
||||
grant.get("principal_type") == "user"
|
||||
and grant.get("principal_id") == "*"
|
||||
)
|
||||
]
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_skills",
|
||||
)
|
||||
|
||||
AccessGrants.set_access_grants("skill", id, form_data.access_grants, db=db)
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Reverse proxy for admin-configured terminal servers.
|
||||
|
||||
Routes:
|
||||
GET / — list terminals the user has access to
|
||||
* /{server_id}/{path:path} — proxy request to terminal server
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import aiohttp
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from open_webui.utils.auth import get_verified_user
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
from open_webui.models.groups import Groups
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
STREAMING_CONTENT_TYPES = ("application/octet-stream", "image/", "application/pdf")
|
||||
STRIPPED_RESPONSE_HEADERS = frozenset(
|
||||
("transfer-encoding", "connection", "content-encoding", "content-length")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def list_terminal_servers(request: Request, user=Depends(get_verified_user)):
|
||||
"""Return terminal servers the authenticated user has access to."""
|
||||
connections = request.app.state.config.TERMINAL_SERVER_CONNECTIONS or []
|
||||
user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user.id)}
|
||||
|
||||
return [
|
||||
{
|
||||
"id": connection.get("id", ""),
|
||||
"url": connection.get("url", ""),
|
||||
"name": connection.get("name", ""),
|
||||
}
|
||||
for connection in connections
|
||||
if connection.get("enabled", True)
|
||||
and has_connection_access(user, connection, user_group_ids)
|
||||
]
|
||||
|
||||
|
||||
PROXY_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
||||
|
||||
|
||||
@router.api_route("/{server_id}/{path:path}", methods=PROXY_METHODS)
|
||||
async def proxy_terminal(
|
||||
server_id: str,
|
||||
path: str,
|
||||
request: Request,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
"""Proxy a request to the admin terminal server identified by *server_id*."""
|
||||
connections = request.app.state.config.TERMINAL_SERVER_CONNECTIONS or []
|
||||
connection = next((c for c in connections if c.get("id") == server_id), None)
|
||||
|
||||
if connection is None:
|
||||
return JSONResponse(
|
||||
{"error": f"Terminal server '{server_id}' not found"}, status_code=404
|
||||
)
|
||||
|
||||
user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user.id)}
|
||||
if not has_connection_access(user, connection, user_group_ids):
|
||||
return JSONResponse({"error": "Access denied"}, status_code=403)
|
||||
|
||||
base_url = (connection.get("url") or "").rstrip("/")
|
||||
if not base_url:
|
||||
return JSONResponse(
|
||||
{"error": "Terminal server URL not configured"}, status_code=503
|
||||
)
|
||||
|
||||
target_url = f"{base_url}/{path}"
|
||||
if request.query_params:
|
||||
target_url += f"?{request.query_params}"
|
||||
|
||||
headers = {"X-User-Id": user.id}
|
||||
cookies = {}
|
||||
auth_type = connection.get("auth_type", "bearer")
|
||||
|
||||
if auth_type == "bearer":
|
||||
headers["Authorization"] = f"Bearer {connection.get('key', '')}"
|
||||
elif auth_type == "session":
|
||||
cookies = request.cookies
|
||||
headers["Authorization"] = f"Bearer {request.state.token.credentials}"
|
||||
elif auth_type == "system_oauth":
|
||||
cookies = request.cookies
|
||||
oauth_token = request.headers.get("x-oauth-access-token", "")
|
||||
if oauth_token:
|
||||
headers["Authorization"] = f"Bearer {oauth_token}"
|
||||
# auth_type == "none": no Authorization header
|
||||
|
||||
content_type = request.headers.get("content-type")
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
|
||||
body = await request.body()
|
||||
session = aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=300, connect=10),
|
||||
trust_env=True,
|
||||
)
|
||||
|
||||
try:
|
||||
upstream_response = await session.request(
|
||||
method=request.method,
|
||||
url=target_url,
|
||||
headers=headers,
|
||||
cookies=cookies,
|
||||
data=body or None,
|
||||
)
|
||||
|
||||
upstream_content_type = upstream_response.headers.get("content-type", "")
|
||||
filtered_headers = {
|
||||
key: value
|
||||
for key, value in upstream_response.headers.items()
|
||||
if key.lower() not in STRIPPED_RESPONSE_HEADERS
|
||||
}
|
||||
|
||||
# Stream binary responses directly
|
||||
if any(t in upstream_content_type for t in STREAMING_CONTENT_TYPES):
|
||||
|
||||
async def cleanup():
|
||||
await upstream_response.release()
|
||||
await session.close()
|
||||
|
||||
return StreamingResponse(
|
||||
content=upstream_response.content.iter_any(),
|
||||
status_code=upstream_response.status,
|
||||
headers=filtered_headers,
|
||||
background=BackgroundTask(cleanup),
|
||||
)
|
||||
|
||||
# Buffer text/JSON responses
|
||||
response_body = await upstream_response.read()
|
||||
status_code = upstream_response.status
|
||||
await upstream_response.release()
|
||||
await session.close()
|
||||
|
||||
return Response(
|
||||
content=response_body, status_code=status_code, headers=filtered_headers
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
await session.close()
|
||||
log.exception("Terminal proxy error: %s", error)
|
||||
return JSONResponse(
|
||||
{"error": f"Terminal proxy error: {error}"}, status_code=502
|
||||
)
|
||||
@@ -21,7 +21,7 @@ from open_webui.models.tools import (
|
||||
ToolAccessResponse,
|
||||
Tools,
|
||||
)
|
||||
from open_webui.models.access_grants import AccessGrants, has_public_read_access_grant
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.utils.plugin import (
|
||||
load_tool_module_by_id,
|
||||
replace_imports,
|
||||
@@ -576,24 +576,13 @@ async def update_tool_access_by_id(
|
||||
detail=ERROR_MESSAGES.UNAUTHORIZED,
|
||||
)
|
||||
|
||||
# Strip public sharing if user lacks permission
|
||||
if (
|
||||
user.role != "admin"
|
||||
and has_public_read_access_grant(form_data.access_grants)
|
||||
and not has_permission(
|
||||
user.id,
|
||||
"sharing.public_tools",
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
):
|
||||
form_data.access_grants = [
|
||||
grant
|
||||
for grant in form_data.access_grants
|
||||
if not (
|
||||
grant.get("principal_type") == "user"
|
||||
and grant.get("principal_id") == "*"
|
||||
)
|
||||
]
|
||||
form_data.access_grants = filter_allowed_access_grants(
|
||||
request.app.state.config.USER_PERMISSIONS,
|
||||
user.id,
|
||||
user.role,
|
||||
form_data.access_grants,
|
||||
"sharing.public_tools",
|
||||
)
|
||||
|
||||
AccessGrants.set_access_grants("tool", id, form_data.access_grants, db=db)
|
||||
|
||||
|
||||
@@ -196,6 +196,10 @@ class SharingPermissions(BaseModel):
|
||||
public_notes: bool = True
|
||||
|
||||
|
||||
class AccessGrantsPermissions(BaseModel):
|
||||
allow_users: bool = True
|
||||
|
||||
|
||||
class ChatPermissions(BaseModel):
|
||||
controls: bool = True
|
||||
valves: bool = True
|
||||
@@ -239,6 +243,7 @@ class SettingsPermissions(BaseModel):
|
||||
class UserPermissions(BaseModel):
|
||||
workspace: WorkspacePermissions
|
||||
sharing: SharingPermissions
|
||||
access_grants: AccessGrantsPermissions
|
||||
chat: ChatPermissions
|
||||
features: FeaturesPermissions
|
||||
settings: SettingsPermissions
|
||||
@@ -253,6 +258,9 @@ async def get_default_user_permissions(request: Request, user=Depends(get_admin_
|
||||
"sharing": SharingPermissions(
|
||||
**request.app.state.config.USER_PERMISSIONS.get("sharing", {})
|
||||
),
|
||||
"access_grants": AccessGrantsPermissions(
|
||||
**request.app.state.config.USER_PERMISSIONS.get("access_grants", {})
|
||||
),
|
||||
"chat": ChatPermissions(
|
||||
**request.app.state.config.USER_PERMISSIONS.get("chat", {})
|
||||
),
|
||||
|
||||
@@ -790,21 +790,26 @@ def get_event_emitter(request_info, update_db=True):
|
||||
},
|
||||
room=f"user:{user_id}",
|
||||
)
|
||||
|
||||
if (
|
||||
update_db
|
||||
and message_id
|
||||
and not request_info.get("chat_id", "").startswith("local:")
|
||||
):
|
||||
|
||||
if "type" in event_data and event_data["type"] == "status":
|
||||
Chats.add_message_status_to_chat_by_id_and_message_id(
|
||||
event_type = event_data.get("type")
|
||||
|
||||
if event_type == "status":
|
||||
await asyncio.to_thread(
|
||||
Chats.add_message_status_to_chat_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
event_data.get("data", {}),
|
||||
)
|
||||
|
||||
if "type" in event_data and event_data["type"] == "message":
|
||||
message = Chats.get_message_by_id_and_message_id(
|
||||
elif event_type == "message":
|
||||
message = await asyncio.to_thread(
|
||||
Chats.get_message_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
)
|
||||
@@ -813,7 +818,8 @@ def get_event_emitter(request_info, update_db=True):
|
||||
content = message.get("content", "")
|
||||
content += event_data.get("data", {}).get("content", "")
|
||||
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
await asyncio.to_thread(
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
{
|
||||
@@ -821,10 +827,11 @@ def get_event_emitter(request_info, update_db=True):
|
||||
},
|
||||
)
|
||||
|
||||
if "type" in event_data and event_data["type"] == "replace":
|
||||
elif event_type == "replace":
|
||||
content = event_data.get("data", {}).get("content", "")
|
||||
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
await asyncio.to_thread(
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
{
|
||||
@@ -832,8 +839,9 @@ def get_event_emitter(request_info, update_db=True):
|
||||
},
|
||||
)
|
||||
|
||||
if "type" in event_data and event_data["type"] == "embeds":
|
||||
message = Chats.get_message_by_id_and_message_id(
|
||||
elif event_type == "embeds":
|
||||
message = await asyncio.to_thread(
|
||||
Chats.get_message_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
)
|
||||
@@ -841,7 +849,8 @@ def get_event_emitter(request_info, update_db=True):
|
||||
embeds = event_data.get("data", {}).get("embeds", [])
|
||||
embeds.extend(message.get("embeds", []))
|
||||
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
await asyncio.to_thread(
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
{
|
||||
@@ -849,8 +858,9 @@ def get_event_emitter(request_info, update_db=True):
|
||||
},
|
||||
)
|
||||
|
||||
if "type" in event_data and event_data["type"] == "files":
|
||||
message = Chats.get_message_by_id_and_message_id(
|
||||
elif event_type == "files":
|
||||
message = await asyncio.to_thread(
|
||||
Chats.get_message_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
)
|
||||
@@ -858,7 +868,8 @@ def get_event_emitter(request_info, update_db=True):
|
||||
files = event_data.get("data", {}).get("files", [])
|
||||
files.extend(message.get("files", []))
|
||||
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
await asyncio.to_thread(
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
{
|
||||
@@ -866,10 +877,11 @@ def get_event_emitter(request_info, update_db=True):
|
||||
},
|
||||
)
|
||||
|
||||
if event_data.get("type") in ["source", "citation"]:
|
||||
elif event_type in ("source", "citation"):
|
||||
data = event_data.get("data", {})
|
||||
if data.get("type") == None:
|
||||
message = Chats.get_message_by_id_and_message_id(
|
||||
if data.get("type") is None:
|
||||
message = await asyncio.to_thread(
|
||||
Chats.get_message_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
)
|
||||
@@ -877,7 +889,8 @@ def get_event_emitter(request_info, update_db=True):
|
||||
sources = message.get("sources", [])
|
||||
sources.append(data)
|
||||
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
await asyncio.to_thread(
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id,
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
{
|
||||
|
||||
@@ -1627,7 +1627,7 @@ async def view_file(
|
||||
|
||||
try:
|
||||
from open_webui.models.files import Files
|
||||
from open_webui.routers.files import has_access_to_file
|
||||
from open_webui.utils.access_control.files import has_access_to_file
|
||||
|
||||
user_id = __user__.get("id")
|
||||
user_role = __user__.get("role", "user")
|
||||
|
||||
+85
@@ -153,6 +153,31 @@ def has_access(
|
||||
return False
|
||||
|
||||
|
||||
def has_connection_access(
|
||||
user: UserModel,
|
||||
connection: dict,
|
||||
user_group_ids: Optional[Set[str]] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Check if a user can access a server connection (tool server, terminal, etc.)
|
||||
based on ``config.access_grants`` within the connection dict.
|
||||
|
||||
- Admin with BYPASS_ADMIN_ACCESS_CONTROL → always allowed
|
||||
- Missing, None, or empty access_grants → private, admin-only
|
||||
- access_grants has entries → delegates to ``has_access``
|
||||
"""
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
return True
|
||||
|
||||
if user_group_ids is None:
|
||||
user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user.id)}
|
||||
|
||||
access_grants = (connection.get("config") or {}).get("access_grants", [])
|
||||
return has_access(user.id, "read", access_grants, user_group_ids)
|
||||
|
||||
|
||||
def migrate_access_control(
|
||||
data: dict, ac_key: str = "access_control", grants_key: str = "access_grants"
|
||||
) -> None:
|
||||
@@ -194,3 +219,63 @@ def migrate_access_control(
|
||||
|
||||
data[grants_key] = grants
|
||||
data.pop(ac_key, None)
|
||||
|
||||
|
||||
from open_webui.models.access_grants import (
|
||||
has_public_read_access_grant,
|
||||
has_user_access_grant,
|
||||
strip_user_access_grants,
|
||||
)
|
||||
|
||||
|
||||
def filter_allowed_access_grants(
|
||||
default_permissions: Dict[str, Any],
|
||||
user_id: str,
|
||||
user_role: str,
|
||||
access_grants: list,
|
||||
public_permission_key: str,
|
||||
db: Optional[Any] = None,
|
||||
) -> list:
|
||||
"""
|
||||
Checks if the user has the required permissions to grant access to a resource.
|
||||
Returns the filtered list of access grants if permissions are missing.
|
||||
"""
|
||||
if user_role == "admin" or not access_grants:
|
||||
return access_grants
|
||||
|
||||
# Check if user can share publicly
|
||||
if has_public_read_access_grant(access_grants) and not has_permission(
|
||||
user_id,
|
||||
public_permission_key,
|
||||
default_permissions,
|
||||
db=db,
|
||||
):
|
||||
access_grants = [
|
||||
grant
|
||||
for grant in access_grants
|
||||
if not (
|
||||
(
|
||||
grant.get("principal_type")
|
||||
if isinstance(grant, dict)
|
||||
else getattr(grant, "principal_type", None)
|
||||
)
|
||||
== "user"
|
||||
and (
|
||||
grant.get("principal_id")
|
||||
if isinstance(grant, dict)
|
||||
else getattr(grant, "principal_id", None)
|
||||
)
|
||||
== "*"
|
||||
)
|
||||
]
|
||||
|
||||
# Strip individual user sharing if user lacks permission
|
||||
if has_user_access_grant(access_grants) and not has_permission(
|
||||
user_id,
|
||||
"access_grants.allow_users",
|
||||
default_permissions,
|
||||
db=db,
|
||||
):
|
||||
access_grants = strip_user_access_grants(access_grants)
|
||||
|
||||
return access_grants
|
||||
@@ -0,0 +1,75 @@
|
||||
import logging
|
||||
from typing import Optional, Any
|
||||
|
||||
from open_webui.models.users import UserModel
|
||||
from open_webui.models.files import Files
|
||||
from open_webui.models.knowledge import Knowledges
|
||||
from open_webui.models.channels import Channels
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def has_access_to_file(
|
||||
file_id: Optional[str],
|
||||
access_type: str,
|
||||
user: UserModel,
|
||||
db: Optional[Any] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Check if a user has the specified access to a file through any of:
|
||||
- Knowledge bases (ownership or access grants)
|
||||
- Channels the user is a member of
|
||||
- Shared chats
|
||||
|
||||
NOTE: This does NOT check direct file ownership — callers should check
|
||||
file.user_id == user.id separately before calling this.
|
||||
"""
|
||||
file = Files.get_file_by_id(file_id, db=db)
|
||||
log.debug(f"Checking if user has {access_type} access to file")
|
||||
if not file:
|
||||
return False
|
||||
|
||||
# Direct ownership
|
||||
if file.user_id == user.id:
|
||||
return True
|
||||
|
||||
# Check if the file is associated with any knowledge bases the user has access to
|
||||
knowledge_bases = Knowledges.get_knowledges_by_file_id(file_id, db=db)
|
||||
user_group_ids = {
|
||||
group.id for group in Groups.get_groups_by_member_id(user.id, db=db)
|
||||
}
|
||||
for knowledge_base in knowledge_bases:
|
||||
if knowledge_base.user_id == user.id or AccessGrants.has_access(
|
||||
user_id=user.id,
|
||||
resource_type="knowledge",
|
||||
resource_id=knowledge_base.id,
|
||||
permission=access_type,
|
||||
user_group_ids=user_group_ids,
|
||||
db=db,
|
||||
):
|
||||
return True
|
||||
|
||||
knowledge_base_id = file.meta.get("collection_name") if file.meta else None
|
||||
if knowledge_base_id:
|
||||
knowledge_bases = Knowledges.get_knowledge_bases_by_user_id(
|
||||
user.id, access_type, db=db
|
||||
)
|
||||
for knowledge_base in knowledge_bases:
|
||||
if knowledge_base.id == knowledge_base_id:
|
||||
return True
|
||||
|
||||
# Check if the file is associated with any channels the user has access to
|
||||
channels = Channels.get_channels_by_file_id_and_user_id(file_id, user.id, db=db)
|
||||
if access_type == "read" and channels:
|
||||
return True
|
||||
|
||||
# Check if the file is associated with any chats the user has access to
|
||||
# TODO: Granular access control for chats
|
||||
chats = Chats.get_shared_chats_by_file_id(file_id, db=db)
|
||||
if chats:
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -22,10 +22,14 @@ def get_function_module(request, function_id, load_from_db=True):
|
||||
|
||||
def get_sorted_filter_ids(request, model: dict, enabled_filter_ids: list = None):
|
||||
def get_priority(function_id):
|
||||
function = Functions.get_function_by_id(function_id)
|
||||
if function is not None:
|
||||
valves = Functions.get_function_valves_by_id(function_id)
|
||||
return valves.get("priority", 0) if valves else 0
|
||||
try:
|
||||
function_module = get_function_module(request, function_id)
|
||||
if function_module and hasattr(function_module, "Valves"):
|
||||
valves_db = Functions.get_function_valves_by_id(function_id)
|
||||
valves = function_module.Valves(**(valves_db if valves_db else {}))
|
||||
return getattr(valves, "priority", 0)
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
filter_ids = [function.id for function in Functions.get_global_filter_functions()]
|
||||
@@ -50,7 +54,7 @@ def get_sorted_filter_ids(request, model: dict, enabled_filter_ids: list = None)
|
||||
]
|
||||
|
||||
filter_ids = [fid for fid in filter_ids if fid in active_filter_ids]
|
||||
filter_ids.sort(key=get_priority)
|
||||
filter_ids.sort(key=lambda fid: (get_priority(fid), fid))
|
||||
|
||||
return filter_ids
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ def start_logger():
|
||||
logger.remove()
|
||||
|
||||
audit_filter = lambda record: (
|
||||
"auditable" not in record["extra"] if ENABLE_AUDIT_STDOUT else True
|
||||
True if ENABLE_AUDIT_STDOUT else "auditable" not in record["extra"]
|
||||
)
|
||||
if LOG_FORMAT == "json":
|
||||
logger.add(
|
||||
|
||||
@@ -86,6 +86,7 @@ from open_webui.utils.misc import (
|
||||
get_message_list,
|
||||
add_or_update_system_message,
|
||||
add_or_update_user_message,
|
||||
set_last_user_message_content,
|
||||
get_last_user_message,
|
||||
get_last_user_message_item,
|
||||
get_last_assistant_message,
|
||||
@@ -98,8 +99,9 @@ from open_webui.utils.misc import (
|
||||
from open_webui.utils.tools import (
|
||||
get_tools,
|
||||
get_updated_tool_function,
|
||||
has_tool_server_access,
|
||||
get_terminal_tools,
|
||||
)
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
from open_webui.utils.plugin import load_function_module_by_id
|
||||
from open_webui.utils.filter import (
|
||||
get_sorted_filter_ids,
|
||||
@@ -373,9 +375,14 @@ def serialize_output(output: list) -> str:
|
||||
result_item = tool_outputs.get(call_id)
|
||||
if result_item:
|
||||
result_text = ""
|
||||
for out in result_item.get("output", []):
|
||||
if "text" in out:
|
||||
result_text += out.get("text", "")
|
||||
for output in result_item.get("output", []):
|
||||
if "text" in output:
|
||||
output_text = output.get("text", "")
|
||||
result_text += (
|
||||
str(output_text)
|
||||
if not isinstance(output_text, str)
|
||||
else output_text
|
||||
)
|
||||
files = result_item.get("files")
|
||||
embeds = result_item.get("embeds", "")
|
||||
|
||||
@@ -888,6 +895,7 @@ def process_tool_result(
|
||||
user=None,
|
||||
):
|
||||
tool_result_embeds = []
|
||||
EXTERNAL_TOOL_TYPES = ("external", "action", "terminal")
|
||||
|
||||
if isinstance(tool_result, HTMLResponse):
|
||||
content_disposition = tool_result.headers.get("Content-Disposition", "")
|
||||
@@ -922,7 +930,7 @@ def process_tool_result(
|
||||
else:
|
||||
tool_result = tool_result.body.decode("utf-8", "replace")
|
||||
|
||||
elif (tool_type in ("external", "action") and isinstance(tool_result, tuple)) or (
|
||||
elif (tool_type in EXTERNAL_TOOL_TYPES and isinstance(tool_result, tuple)) or (
|
||||
direct_tool and isinstance(tool_result, list) and len(tool_result) == 2
|
||||
):
|
||||
tool_result, tool_response_headers = tool_result
|
||||
@@ -1018,9 +1026,67 @@ def process_tool_result(
|
||||
if isinstance(tool_result, dict) or isinstance(tool_result, list):
|
||||
tool_result = json.dumps(tool_result, indent=2, ensure_ascii=False)
|
||||
|
||||
# Safety: ensure tool_result is always a string (or None) to prevent
|
||||
# downstream TypeError when concatenating (e.g. if an upstream callable
|
||||
# returned a tuple that was not unpacked by the branches above).
|
||||
if tool_result is not None and not isinstance(tool_result, str):
|
||||
if isinstance(tool_result, tuple):
|
||||
# execute_tool_server returns (data, headers); unpack the data part
|
||||
tool_result = (
|
||||
json.dumps(tool_result[0], indent=2, ensure_ascii=False)
|
||||
if len(tool_result) > 0
|
||||
else ""
|
||||
)
|
||||
else:
|
||||
tool_result = str(tool_result)
|
||||
|
||||
return tool_result, tool_result_files, tool_result_embeds
|
||||
|
||||
|
||||
async def terminal_event_handler(
|
||||
tool_function_name: str,
|
||||
tool_function_params: dict,
|
||||
tool_result,
|
||||
event_emitter,
|
||||
):
|
||||
"""Emit terminal:* events for Open Terminal tools.
|
||||
|
||||
- display_file → emits 'terminal:display_file' to open the file preview.
|
||||
- write_file → emits 'terminal:write_file' to silently refresh the file browser.
|
||||
"""
|
||||
if not event_emitter:
|
||||
return
|
||||
|
||||
path = tool_function_params.get("path", "")
|
||||
if not path:
|
||||
return
|
||||
|
||||
if tool_function_name == "display_file":
|
||||
# Only emit if the file actually exists
|
||||
parsed = tool_result
|
||||
if isinstance(parsed, str):
|
||||
try:
|
||||
parsed = json.loads(parsed)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
if isinstance(parsed, dict) and parsed.get("exists") is False:
|
||||
return
|
||||
|
||||
await event_emitter(
|
||||
{
|
||||
"type": f"terminal:{tool_function_name}",
|
||||
"data": {"path": path},
|
||||
}
|
||||
)
|
||||
elif tool_function_name == "write_file":
|
||||
await event_emitter(
|
||||
{
|
||||
"type": f"terminal:{tool_function_name}",
|
||||
"data": {"path": path},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def chat_completion_tools_handler(
|
||||
request: Request, body: dict, extra_params: dict, user: UserModel, models, tools
|
||||
) -> tuple[dict, dict]:
|
||||
@@ -1175,6 +1241,13 @@ async def chat_completion_tools_handler(
|
||||
)
|
||||
|
||||
if event_emitter:
|
||||
await terminal_event_handler(
|
||||
tool_function_name,
|
||||
tool_function_params,
|
||||
tool_result,
|
||||
event_emitter,
|
||||
)
|
||||
|
||||
if tool_result_files:
|
||||
await event_emitter(
|
||||
{
|
||||
@@ -1977,7 +2050,7 @@ def process_messages_with_output(messages: list[dict]) -> list[dict]:
|
||||
for message in messages:
|
||||
if message.get("role") == "assistant" and message.get("output"):
|
||||
# Use output items for clean OpenAI-format messages
|
||||
output_messages = convert_output_to_messages(message["output"])
|
||||
output_messages = convert_output_to_messages(message["output"], raw=True)
|
||||
if output_messages:
|
||||
processed.extend(output_messages)
|
||||
continue
|
||||
@@ -2224,6 +2297,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
)
|
||||
|
||||
tool_ids = form_data.pop("tool_ids", None)
|
||||
terminal_id = form_data.pop("terminal_id", None)
|
||||
files = form_data.pop("files", None)
|
||||
|
||||
# Caller-provided OpenAI-style tools take precedence over server-side
|
||||
@@ -2297,6 +2371,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
metadata = {
|
||||
**metadata,
|
||||
"tool_ids": tool_ids,
|
||||
"terminal_id": terminal_id,
|
||||
"files": files,
|
||||
}
|
||||
form_data["metadata"] = metadata
|
||||
@@ -2341,7 +2416,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
continue
|
||||
|
||||
# Check access control for MCP server
|
||||
if not has_tool_server_access(user, mcp_server_connection):
|
||||
if not has_connection_access(user, mcp_server_connection):
|
||||
log.warning(
|
||||
f"Access denied to MCP server {server_id} for user {user.id}"
|
||||
)
|
||||
@@ -2478,6 +2553,21 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
if mcp_tools_dict:
|
||||
tools_dict = {**tools_dict, **mcp_tools_dict}
|
||||
|
||||
# Resolve terminal tools if terminal_id is set (outside tool_ids check
|
||||
# so system terminals work even when no other tools are selected)
|
||||
if terminal_id:
|
||||
try:
|
||||
terminal_tools = await get_terminal_tools(
|
||||
request,
|
||||
terminal_id,
|
||||
user,
|
||||
extra_params,
|
||||
)
|
||||
if terminal_tools:
|
||||
tools_dict = {**tools_dict, **terminal_tools}
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
|
||||
if direct_tool_servers:
|
||||
for tool_server in direct_tool_servers:
|
||||
tool_specs = tool_server.pop("specs", [])
|
||||
@@ -2530,16 +2620,15 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
{"type": "function", "function": tool.get("spec", {})}
|
||||
for tool in tools_dict.values()
|
||||
]
|
||||
|
||||
else:
|
||||
# If the function calling is not native, then call the tools function calling handler
|
||||
try:
|
||||
form_data, flags = await chat_completion_tools_handler(
|
||||
request, form_data, extra_params, user, models, tools_dict
|
||||
)
|
||||
sources.extend(flags.get("sources", []))
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
else:
|
||||
# If the function calling is not native, then call the tools function calling handler
|
||||
try:
|
||||
form_data, flags = await chat_completion_tools_handler(
|
||||
request, form_data, extra_params, user, models, tools_dict
|
||||
)
|
||||
sources.extend(flags.get("sources", []))
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
|
||||
# Check if file context extraction is enabled for this model (default True)
|
||||
file_context_enabled = (
|
||||
@@ -4059,6 +4148,13 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
log.error(
|
||||
f"Error parsing tool call arguments: {tool_args}"
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"tool_call_id": tool_call_id,
|
||||
"content": f"Error: Tool call arguments could not be parsed. The model generated malformed or incomplete JSON for `{tool_function_name}`. Please try again.",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# Ensure arguments are valid JSON for downstream LLM integrations
|
||||
log.debug(
|
||||
@@ -4139,6 +4235,13 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
)
|
||||
)
|
||||
|
||||
await terminal_event_handler(
|
||||
tool_function_name,
|
||||
tool_function_params,
|
||||
tool_result,
|
||||
event_emitter,
|
||||
)
|
||||
|
||||
# Extract citation sources from tool results
|
||||
if (
|
||||
tool_function_name
|
||||
@@ -4164,7 +4267,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
results.append(
|
||||
{
|
||||
"tool_call_id": tool_call_id,
|
||||
"content": tool_result or "",
|
||||
"content": str(tool_result) if tool_result else "",
|
||||
**(
|
||||
{"files": tool_result_files}
|
||||
if tool_result_files
|
||||
@@ -4241,8 +4344,8 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
all_tool_call_sources.extend(tool_call_sources)
|
||||
if all_tool_call_sources and user_message:
|
||||
# Restore original user message before re-applying to avoid recursive nesting
|
||||
form_data["messages"] = add_or_update_user_message(
|
||||
user_message, form_data["messages"], append=False
|
||||
set_last_user_message_content(
|
||||
user_message, form_data["messages"]
|
||||
)
|
||||
form_data["messages"] = apply_source_context_to_messages(
|
||||
request,
|
||||
|
||||
@@ -210,7 +210,12 @@ def convert_output_to_messages(output: list, raw: bool = False) -> list[dict]:
|
||||
content = ""
|
||||
for part in output_parts:
|
||||
if part.get("type") == "input_text":
|
||||
content += part.get("text", "")
|
||||
output_text = part.get("text", "")
|
||||
content += (
|
||||
str(output_text)
|
||||
if not isinstance(output_text, str)
|
||||
else output_text
|
||||
)
|
||||
|
||||
messages.append(
|
||||
{
|
||||
@@ -277,6 +282,24 @@ def get_last_user_message(messages: list[dict]) -> Optional[str]:
|
||||
return get_content_from_message(message)
|
||||
|
||||
|
||||
def set_last_user_message_content(content: str, messages: list[dict]) -> list[dict]:
|
||||
"""
|
||||
Replace the text content of the last user message in-place.
|
||||
Handles both plain-string and list-of-parts content formats.
|
||||
"""
|
||||
for message in reversed(messages):
|
||||
if message.get("role") == "user":
|
||||
if isinstance(message.get("content"), list):
|
||||
for item in message["content"]:
|
||||
if item.get("type") == "text":
|
||||
item["text"] = content
|
||||
break
|
||||
else:
|
||||
message["content"] = content
|
||||
break
|
||||
return messages
|
||||
|
||||
|
||||
def get_last_assistant_message_item(messages: list[dict]) -> Optional[dict]:
|
||||
for message in reversed(messages):
|
||||
if message["role"] == "assistant":
|
||||
|
||||
@@ -331,12 +331,25 @@ async def get_all_models(request, refresh: bool = False, user: UserModel = None)
|
||||
elif meta.get(key) is None:
|
||||
meta[key] = copy.deepcopy(value)
|
||||
|
||||
def get_action_priority(action_id):
|
||||
try:
|
||||
function_module = request.app.state.FUNCTIONS.get(action_id)
|
||||
if function_module and hasattr(function_module, "Valves"):
|
||||
valves_db = Functions.get_function_valves_by_id(action_id)
|
||||
valves = function_module.Valves(**(valves_db if valves_db else {}))
|
||||
return getattr(valves, "priority", 0)
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
for model in models:
|
||||
action_ids = [
|
||||
action_id
|
||||
for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
|
||||
if action_id in enabled_action_ids
|
||||
]
|
||||
action_ids.sort(key=lambda aid: (get_action_priority(aid), aid))
|
||||
|
||||
filter_ids = [
|
||||
filter_id
|
||||
for filter_id in list(set(model.pop("filter_ids", []) + global_filter_ids))
|
||||
|
||||
@@ -55,6 +55,8 @@ from open_webui.config import (
|
||||
OAUTH_ADMIN_ROLES,
|
||||
OAUTH_ALLOWED_DOMAINS,
|
||||
OAUTH_UPDATE_PICTURE_ON_LOGIN,
|
||||
OAUTH_UPDATE_NAME_ON_LOGIN,
|
||||
OAUTH_UPDATE_EMAIL_ON_LOGIN,
|
||||
OAUTH_ACCESS_TOKEN_REQUEST_INCLUDE_CLIENT_ID,
|
||||
OAUTH_AUDIENCE,
|
||||
WEBHOOK_URL,
|
||||
@@ -129,6 +131,8 @@ auth_manager_config.OAUTH_ALLOWED_DOMAINS = OAUTH_ALLOWED_DOMAINS
|
||||
auth_manager_config.WEBHOOK_URL = WEBHOOK_URL
|
||||
auth_manager_config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
|
||||
auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN = OAUTH_UPDATE_PICTURE_ON_LOGIN
|
||||
auth_manager_config.OAUTH_UPDATE_NAME_ON_LOGIN = OAUTH_UPDATE_NAME_ON_LOGIN
|
||||
auth_manager_config.OAUTH_UPDATE_EMAIL_ON_LOGIN = OAUTH_UPDATE_EMAIL_ON_LOGIN
|
||||
auth_manager_config.OAUTH_AUDIENCE = OAUTH_AUDIENCE
|
||||
|
||||
|
||||
@@ -1548,6 +1552,33 @@ class OAuthManager:
|
||||
# Update the user object in memory as well,
|
||||
# to avoid problems with the ENABLE_OAUTH_GROUP_MANAGEMENT check below
|
||||
user.role = determined_role
|
||||
|
||||
if auth_manager_config.OAUTH_UPDATE_NAME_ON_LOGIN:
|
||||
username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
|
||||
if username_claim:
|
||||
new_name = user_data.get(username_claim)
|
||||
if new_name and new_name != user.name:
|
||||
Users.update_user_by_id(user.id, {"name": new_name}, db=db)
|
||||
user.name = new_name
|
||||
log.debug(f"Updated name for user {user.email}")
|
||||
|
||||
if auth_manager_config.OAUTH_UPDATE_EMAIL_ON_LOGIN:
|
||||
email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
|
||||
if email_claim:
|
||||
new_email = user_data.get(email_claim)
|
||||
if new_email and new_email.lower() != user.email.lower():
|
||||
existing_user = Users.get_user_by_email(new_email, db=db)
|
||||
if existing_user:
|
||||
log.error(
|
||||
f"Cannot update email to {new_email} for user {user.id} because it is already taken."
|
||||
)
|
||||
else:
|
||||
Auths.update_email_by_id(
|
||||
user.id, new_email.lower(), db=db
|
||||
)
|
||||
user.email = new_email.lower()
|
||||
log.debug(f"Updated email for user {user.id}")
|
||||
|
||||
# Update profile picture if enabled and different from current
|
||||
if auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN:
|
||||
picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
|
||||
@@ -1706,17 +1737,22 @@ class OAuthManager:
|
||||
db=db,
|
||||
)
|
||||
|
||||
response.set_cookie(
|
||||
key="oauth_session_id",
|
||||
value=session.id,
|
||||
httponly=True,
|
||||
samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
|
||||
secure=WEBUI_AUTH_COOKIE_SECURE,
|
||||
)
|
||||
if session:
|
||||
response.set_cookie(
|
||||
key="oauth_session_id",
|
||||
value=session.id,
|
||||
httponly=True,
|
||||
samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
|
||||
secure=WEBUI_AUTH_COOKIE_SECURE,
|
||||
)
|
||||
|
||||
log.info(
|
||||
f"Stored OAuth session server-side for user {user.id}, provider {provider}"
|
||||
)
|
||||
log.info(
|
||||
f"Stored OAuth session server-side for user {user.id}, provider {provider}"
|
||||
)
|
||||
else:
|
||||
log.warning(
|
||||
f"Failed to create OAuth session for user {user.id}, provider {provider}"
|
||||
)
|
||||
except Exception as e:
|
||||
log.error(f"Failed to store OAuth session server-side: {e}")
|
||||
|
||||
|
||||
@@ -144,6 +144,7 @@ def convert_response_ollama_to_openai(ollama_response: dict) -> dict:
|
||||
|
||||
|
||||
async def convert_streaming_response_ollama_to_openai(ollama_streaming_response):
|
||||
has_tool_calls = False
|
||||
async for data in ollama_streaming_response.body_iterator:
|
||||
data = json.loads(data)
|
||||
|
||||
@@ -155,6 +156,7 @@ async def convert_streaming_response_ollama_to_openai(ollama_streaming_response)
|
||||
|
||||
if tool_calls:
|
||||
openai_tool_calls = convert_ollama_tool_call_to_openai(tool_calls)
|
||||
has_tool_calls = True
|
||||
|
||||
done = data.get("done", False)
|
||||
|
||||
@@ -166,7 +168,7 @@ async def convert_streaming_response_ollama_to_openai(ollama_streaming_response)
|
||||
model, message_content, reasoning_content, openai_tool_calls, usage
|
||||
)
|
||||
|
||||
if done and openai_tool_calls:
|
||||
if done and has_tool_calls:
|
||||
data["choices"][0]["finish_reason"] = "tool_calls"
|
||||
|
||||
line = f"data: {json.dumps(data)}\n\n"
|
||||
|
||||
@@ -28,6 +28,7 @@ def set_security_headers() -> Dict[str, str]:
|
||||
- x-frame-options
|
||||
- x-permitted-cross-domain-policies
|
||||
- content-security-policy
|
||||
- reporting-endpoints
|
||||
|
||||
Each environment variable is associated with a specific setter function
|
||||
that constructs the header. If the environment variable is set, the
|
||||
@@ -47,6 +48,7 @@ def set_security_headers() -> Dict[str, str]:
|
||||
"XFRAME_OPTIONS": set_xframe,
|
||||
"XPERMITTED_CROSS_DOMAIN_POLICIES": set_xpermitted_cross_domain_policies,
|
||||
"CONTENT_SECURITY_POLICY": set_content_security_policy,
|
||||
"REPORTING_ENDPOINTS": set_reporting_endpoints,
|
||||
}
|
||||
|
||||
for env_var, setter in header_setters.items():
|
||||
@@ -131,3 +133,8 @@ def set_xpermitted_cross_domain_policies(value: str):
|
||||
# Set Content-Security-Policy response header
|
||||
def set_content_security_policy(value: str):
|
||||
return {"Content-Security-Policy": value}
|
||||
|
||||
|
||||
# Set Reporting-Endpoints response header
|
||||
def set_reporting_endpoints(value: str):
|
||||
return {"Reporting-Endpoints": value}
|
||||
|
||||
@@ -40,7 +40,7 @@ from open_webui.models.users import UserModel
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.utils.plugin import load_tool_module_by_id
|
||||
from open_webui.utils.access_control import has_access
|
||||
from open_webui.utils.access_control import has_access, has_connection_access
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
from open_webui.env import (
|
||||
AIOHTTP_CLIENT_TIMEOUT,
|
||||
@@ -144,25 +144,13 @@ def get_updated_tool_function(function: Callable, extra_params: dict):
|
||||
return function
|
||||
|
||||
|
||||
def has_tool_server_access(
|
||||
user: UserModel, server_connection: dict, user_group_ids: set = None
|
||||
) -> bool:
|
||||
"""Check if user has access to a tool server (MCP or OpenAPI)."""
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
return True
|
||||
|
||||
if user_group_ids is None:
|
||||
user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user.id)}
|
||||
|
||||
server_config = server_connection.get("config", {})
|
||||
access_grants = server_config.get("access_grants", [])
|
||||
return has_access(user.id, "read", access_grants, user_group_ids)
|
||||
|
||||
|
||||
async def get_tools(
|
||||
request: Request, tool_ids: list[str], user: UserModel, extra_params: dict
|
||||
) -> dict[str, dict]:
|
||||
"""Load tools for the given tool_ids, checking access control."""
|
||||
if not tool_ids:
|
||||
return {}
|
||||
|
||||
tools_dict = {}
|
||||
|
||||
# Get user's group memberships for access control checks
|
||||
@@ -294,7 +282,7 @@ async def get_tools(
|
||||
)
|
||||
|
||||
# Check access control for tool server
|
||||
if not has_tool_server_access(
|
||||
if not has_connection_access(
|
||||
user, tool_server_connection, user_group_ids
|
||||
):
|
||||
log.warning(
|
||||
@@ -391,7 +379,7 @@ async def get_tools(
|
||||
tool_dict = {
|
||||
"tool_id": tool_id,
|
||||
"callable": callable,
|
||||
"spec": spec,
|
||||
"spec": clean_openai_tool_schema(spec),
|
||||
# Misc info
|
||||
"type": "external",
|
||||
}
|
||||
@@ -560,6 +548,7 @@ def get_builtin_tools(
|
||||
# Generate spec from function
|
||||
pydantic_model = convert_function_to_pydantic_model(func)
|
||||
spec = convert_pydantic_model_to_openai_function_spec(pydantic_model)
|
||||
spec = clean_openai_tool_schema(spec)
|
||||
|
||||
tools_dict[func.__name__] = {
|
||||
"tool_id": f"builtin:{func.__name__}",
|
||||
@@ -668,6 +657,44 @@ def convert_function_to_pydantic_model(func: Callable) -> type[BaseModel]:
|
||||
return model
|
||||
|
||||
|
||||
def clean_properties(schema: dict):
|
||||
if not isinstance(schema, dict):
|
||||
return
|
||||
|
||||
if "anyOf" in schema:
|
||||
non_null_types = [t for t in schema["anyOf"] if t.get("type") != "null"]
|
||||
if len(non_null_types) == 1:
|
||||
schema.update(non_null_types[0])
|
||||
del schema["anyOf"]
|
||||
else:
|
||||
schema["anyOf"] = non_null_types
|
||||
|
||||
if "default" in schema and schema["default"] is None:
|
||||
del schema["default"]
|
||||
|
||||
# fix missing type
|
||||
if "type" not in schema and "anyOf" not in schema and "properties" not in schema:
|
||||
schema["type"] = "string"
|
||||
|
||||
if "properties" in schema:
|
||||
for prop_name, prop_schema in schema["properties"].items():
|
||||
clean_properties(prop_schema)
|
||||
|
||||
if "items" in schema:
|
||||
clean_properties(schema["items"])
|
||||
|
||||
|
||||
def clean_openai_tool_schema(spec: dict) -> dict:
|
||||
import copy
|
||||
|
||||
cleaned_spec = copy.deepcopy(spec)
|
||||
|
||||
if "parameters" in cleaned_spec:
|
||||
clean_properties(cleaned_spec["parameters"])
|
||||
|
||||
return cleaned_spec
|
||||
|
||||
|
||||
def get_functions_from_tool(tool: object) -> list[Callable]:
|
||||
return [
|
||||
getattr(tool, func)
|
||||
@@ -690,7 +717,9 @@ def get_tool_specs(tool_module: object) -> list[dict]:
|
||||
)
|
||||
|
||||
specs = [
|
||||
convert_pydantic_model_to_openai_function_spec(function_model)
|
||||
clean_openai_tool_schema(
|
||||
convert_pydantic_model_to_openai_function_spec(function_model)
|
||||
)
|
||||
for function_model in function_models
|
||||
]
|
||||
|
||||
@@ -766,7 +795,7 @@ def convert_openapi_to_tool_payload(openapi_spec):
|
||||
f". Possible values: {', '.join(param_schema.get('enum'))}"
|
||||
)
|
||||
param_property = {
|
||||
"type": param_schema.get("type"),
|
||||
"type": param_schema.get("type") or "string",
|
||||
"description": description,
|
||||
}
|
||||
|
||||
@@ -774,6 +803,11 @@ def convert_openapi_to_tool_payload(openapi_spec):
|
||||
if param_schema.get("type") == "array" and "items" in param_schema:
|
||||
param_property["items"] = param_schema["items"]
|
||||
|
||||
# Filter out None values to prevent schema validation errors
|
||||
param_property = {
|
||||
k: v for k, v in param_property.items() if v is not None
|
||||
}
|
||||
|
||||
tool["parameters"]["properties"][param_name] = param_property
|
||||
if param.get("required"):
|
||||
tool["parameters"]["required"].append(param_name)
|
||||
@@ -837,6 +871,180 @@ async def get_tool_servers(request: Request):
|
||||
return tool_servers
|
||||
|
||||
|
||||
async def get_terminal_cwd(
|
||||
base_url: str,
|
||||
headers: dict,
|
||||
cookies: Optional[dict] = None,
|
||||
) -> Optional[str]:
|
||||
"""Fetch the current working directory from a terminal server."""
|
||||
try:
|
||||
cwd_url = f"{base_url.rstrip('/')}/files/cwd"
|
||||
async with aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=5),
|
||||
trust_env=True,
|
||||
) as session:
|
||||
async with session.get(
|
||||
cwd_url, headers=headers, cookies=cookies or {}
|
||||
) as resp:
|
||||
if resp.status == 200:
|
||||
data = await resp.json()
|
||||
return data.get("cwd")
|
||||
except Exception as e:
|
||||
log.debug(f"Failed to fetch terminal CWD: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def set_terminal_servers(request: Request):
|
||||
"""Load and cache OpenAPI specs from all TERMINAL_SERVER_CONNECTIONS."""
|
||||
connections = request.app.state.config.TERMINAL_SERVER_CONNECTIONS or []
|
||||
|
||||
# Build server configs compatible with get_tool_servers_data
|
||||
# Terminal connections store id/name at top level; translate to info dict
|
||||
server_configs = []
|
||||
for connection in connections:
|
||||
if not connection.get("url"):
|
||||
continue
|
||||
|
||||
enabled = connection.get("enabled", True)
|
||||
|
||||
server_configs.append(
|
||||
{
|
||||
"url": connection.get("url", ""),
|
||||
"key": connection.get("key", ""),
|
||||
"auth_type": connection.get("auth_type", "bearer"),
|
||||
"path": connection.get("path", "/openapi.json"),
|
||||
"spec_type": "url",
|
||||
# get_tool_servers_data reads config.enable to filter active servers
|
||||
"config": {"enable": enabled},
|
||||
"info": {
|
||||
"id": connection.get("id", ""),
|
||||
"name": connection.get("name", ""),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
request.app.state.TERMINAL_SERVERS = await get_tool_servers_data(server_configs)
|
||||
|
||||
if request.app.state.redis is not None:
|
||||
await request.app.state.redis.set(
|
||||
"terminal_servers", json.dumps(request.app.state.TERMINAL_SERVERS)
|
||||
)
|
||||
|
||||
return request.app.state.TERMINAL_SERVERS
|
||||
|
||||
|
||||
async def get_terminal_servers(request: Request):
|
||||
"""Return cached terminal server specs, loading if needed."""
|
||||
terminal_servers = []
|
||||
if request.app.state.redis is not None:
|
||||
try:
|
||||
terminal_servers = json.loads(
|
||||
await request.app.state.redis.get("terminal_servers")
|
||||
)
|
||||
request.app.state.TERMINAL_SERVERS = terminal_servers
|
||||
except Exception as e:
|
||||
log.error(f"Error fetching terminal_servers from Redis: {e}")
|
||||
|
||||
if not terminal_servers:
|
||||
terminal_servers = await set_terminal_servers(request)
|
||||
|
||||
return terminal_servers
|
||||
|
||||
|
||||
async def get_terminal_tools(
|
||||
request: Request,
|
||||
terminal_id: str,
|
||||
user: UserModel,
|
||||
extra_params: dict,
|
||||
) -> dict[str, dict]:
|
||||
"""Resolve tools for a terminal server identified by terminal_id.
|
||||
|
||||
- Finds the connection in TERMINAL_SERVER_CONNECTIONS
|
||||
- Checks access_grants
|
||||
- Loads specs from cache
|
||||
- Builds callables that route through the terminal proxy
|
||||
"""
|
||||
connections = request.app.state.config.TERMINAL_SERVER_CONNECTIONS or []
|
||||
connection = next((c for c in connections if c.get("id") == terminal_id), None)
|
||||
if connection is None:
|
||||
log.warning(f"Terminal server not found: {terminal_id}")
|
||||
return {}
|
||||
|
||||
user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user.id)}
|
||||
if not has_connection_access(user, connection, user_group_ids):
|
||||
log.warning(f"Access denied to terminal {terminal_id} for user {user.id}")
|
||||
return {}
|
||||
|
||||
# Find the cached spec data for this terminal
|
||||
terminal_servers = await get_terminal_servers(request)
|
||||
server_data = next(
|
||||
(s for s in terminal_servers if s.get("id") == terminal_id), None
|
||||
)
|
||||
if server_data is None:
|
||||
log.warning(f"Terminal server spec not found for {terminal_id}")
|
||||
return {}
|
||||
|
||||
specs = server_data.get("specs", [])
|
||||
if not specs:
|
||||
return {}
|
||||
|
||||
# Build auth headers
|
||||
auth_type = connection.get("auth_type", "bearer")
|
||||
cookies = {}
|
||||
headers = {"Content-Type": "application/json", "X-User-Id": user.id}
|
||||
|
||||
if auth_type == "bearer":
|
||||
headers["Authorization"] = f"Bearer {connection.get('key', '')}"
|
||||
elif auth_type == "session":
|
||||
cookies = request.cookies
|
||||
headers["Authorization"] = f"Bearer {request.state.token.credentials}"
|
||||
elif auth_type == "system_oauth":
|
||||
cookies = request.cookies
|
||||
oauth_token = extra_params.get("__oauth_token__", None)
|
||||
if oauth_token:
|
||||
headers["Authorization"] = f"Bearer {oauth_token.get('access_token', '')}"
|
||||
# auth_type == "none": no Authorization header
|
||||
|
||||
terminal_cwd = await get_terminal_cwd(connection.get("url", ""), headers, cookies)
|
||||
|
||||
tools_dict = {}
|
||||
for spec in specs:
|
||||
function_name = spec["name"]
|
||||
|
||||
# Inject CWD into run_command description
|
||||
tool_spec = clean_openai_tool_schema(spec)
|
||||
if function_name == "run_command" and terminal_cwd:
|
||||
tool_spec["description"] = (
|
||||
tool_spec.get("description", "")
|
||||
+ f"\n\nThe current working directory is: {terminal_cwd}"
|
||||
)
|
||||
|
||||
def make_tool_function(fn_name, srv_data, hdrs, cks):
|
||||
async def tool_function(**kwargs):
|
||||
return await execute_tool_server(
|
||||
url=srv_data["url"],
|
||||
headers=hdrs,
|
||||
cookies=cks,
|
||||
name=fn_name,
|
||||
params=kwargs,
|
||||
server_data=srv_data,
|
||||
)
|
||||
|
||||
return tool_function
|
||||
|
||||
tool_function = make_tool_function(function_name, server_data, headers, cookies)
|
||||
callable = get_async_tool_function_and_apply_extra_params(tool_function, {})
|
||||
|
||||
tools_dict[function_name] = {
|
||||
"tool_id": f"terminal:{terminal_id}",
|
||||
"callable": callable,
|
||||
"spec": tool_spec,
|
||||
"type": "terminal",
|
||||
}
|
||||
|
||||
return tools_dict
|
||||
|
||||
|
||||
async def get_tool_server_data(url: str, headers: Optional[dict]) -> Dict[str, Any]:
|
||||
_headers = {
|
||||
"Accept": "application/json",
|
||||
@@ -953,6 +1161,11 @@ async def get_tool_servers_data(servers: List[Dict[str, Any]]) -> List[Dict[str,
|
||||
log.error(f"Failed to connect to {url} OpenAPI tool server")
|
||||
continue
|
||||
|
||||
# Guard against invalid or non-OpenAPI specs (e.g., MCP-style configs)
|
||||
if not isinstance(response, dict) or "paths" not in response:
|
||||
log.warning(f"Invalid OpenAPI spec from {url}: missing 'paths'")
|
||||
continue
|
||||
|
||||
response = {
|
||||
"openapi": response,
|
||||
"info": response.get("info", {}),
|
||||
|
||||
+29
-22
@@ -26,33 +26,40 @@ We appreciate the community's interest in identifying potential vulnerabilities.
|
||||
|
||||
2. **No Vague Reports**: Submissions such as "I found a vulnerability" without any details will be treated as spam and will not be accepted.
|
||||
|
||||
3. **In-Depth Understanding Required**: Reports must reflect a clear understanding of the codebase and provide specific details about the vulnerability, including the affected components and potential impacts.
|
||||
3. **In-Depth Understanding**: Reports must reflect a clear understanding of the codebase, how Open WebUI is used and provide specific details about the vulnerability, including the affected components and potential impacts.
|
||||
|
||||
4. **Proof of Concept (PoC) is Mandatory**: Each submission must include a well-documented proof of concept (PoC) that demonstrates the vulnerability. If confidentiality is a concern, reporters are encouraged to create a private fork of the repository and share access with the maintainers. Reports lacking valid evidence may be disregarded.
|
||||
|
||||
> [!NOTE]
|
||||
> A PoC (Proof of Concept) is a **demonstration of exploitation of a vulnerability**. Your PoC must show:
|
||||
>
|
||||
> 1. What security boundary was crossed (Confidentiality, Integrity, Availability, Authenticity, Non-repudiation)
|
||||
> 2. How this vulnerability was abused
|
||||
> 1. Exactly what security boundary was crossed (Confidentiality, Integrity, Availability, Authenticity, Non-repudiation)
|
||||
> 2. How this vulnerability is triggered/abused (inputs, endpoints, UI actions, etc.)
|
||||
> 3. What actions the attacker can now perform
|
||||
>
|
||||
> **Examples of valid PoCs:**
|
||||
>
|
||||
> - Step-by-step reproduction instructions with exact commands
|
||||
> - Complete exploit code with detailed execution instructions
|
||||
> - Screenshots/videos demonstrating the exploit (supplementary to written steps)
|
||||
> 4. What data/action becomes possible that should not be possible
|
||||
> 5. Exact steps and commands to reproduce (copy/paste runnable where possible), expected result vs. actual result
|
||||
>
|
||||
> **Failure to provide a reproducible PoC may lead to closure of the report**
|
||||
>
|
||||
> We will notify you, if we struggle to reproduce the exploit using your PoC to allow you to improve your PoC.
|
||||
> If we cannot reproduce the issue from your PoC, we may ask for clarification or improvements
|
||||
> However, if we repeatedly cannot reproduce the exploit using the PoC, the report may be closed.
|
||||
|
||||
5. **Required Patch or Actionable Remediation Plan Submission**: Along with the PoC, reporters must provide a patch or some actionable steps to remediate the identified vulnerability. This helps us evaluate and implement fixes rapidly.
|
||||
5. **Remediation is required**:
|
||||
|
||||
6. **Streamlined Merging Process**: When vulnerability reports meet the above criteria, we can consider provided patches for immediate merging, similar to regular pull requests. Well-structured and thorough submissions will expedite the process of enhancing our security.
|
||||
Along with the PoC, you must provide **either**:
|
||||
|
||||
7. **Default Configuration Testing**: All vulnerability reports MUST be tested and reproducible using Open WebUI's out-of-the-box default configuration. Claims of vulnerabilities that only manifest with explicitly weakened security settings may be discarded, unless they are covered by the following exception:
|
||||
1. **A patch/PR**, **or**
|
||||
2. **a remediation plan** ("actionable steps") that a maintainer can apply without guesswork.
|
||||
|
||||
Your remediation guidance can include, for example:
|
||||
|
||||
- The **likely root cause** (what's wrong and where)
|
||||
- The **location(s)** to change (file/module/function names if known)
|
||||
- The **recommended fix approach** (validation/sanitization rules, auth checks, safe defaults, etc.)
|
||||
- Any **security tradeoffs** or potential regressions to watch for
|
||||
|
||||
6. **Default Configuration Testing**: All vulnerability reports must be tested and reproducible using Open WebUI's out-of-the-box default configuration. Claims of vulnerabilities that only manifest with explicitly weakened security settings may be discarded, unless they are covered by the following exception:
|
||||
|
||||
> [!NOTE]
|
||||
> **Note**: If you believe you have found a security issue that
|
||||
@@ -61,26 +68,26 @@ We appreciate the community's interest in identifying potential vulnerabilities.
|
||||
> 2. represents a genuine bypass of intended security controls, **or**
|
||||
> 3. works only with non-default configurations, **but the configuration in question is likely to be used by production deployments**, **then we absolutely want to hear about it.** This policy is intended to filter configuration issues and deployment problems, not to discourage legitimate security research.
|
||||
|
||||
8. **Threat Model Understanding Required**: Reports must demonstrate understanding of Open WebUI's self-hosted, authenticated, role-based access control architecture. Comparing Open WebUI to services with fundamentally different security models without acknowledging the architectural differences may result in report rejection.
|
||||
7. **Threat Model Understanding Required**: Reports must demonstrate understanding of Open WebUI's self-hosted, authenticated, extensible, role-based access control architecture. Comparing Open WebUI to services with fundamentally different security models without acknowledging the architectural differences may result in report rejection.
|
||||
|
||||
9. **CVSS Scoring Accuracy:** If you include a CVSS score with your report, it must accurately reflect the vulnerability according to CVSS methodology. Common errors include 1) rating PR:N (None) when authentication is required, 2) scoring hypothetical attack chains instead of the actual vulnerability, or 3) inflating severity without evidence. **We will adjust inaccurate CVSS scores.** Intentionally inflated scores may result in report rejection.
|
||||
8. **CVSS Scoring Accuracy:** If you include a CVSS score with your report, it must accurately reflect the vulnerability according to CVSS methodology. Common errors include 1) rating PR:N (None) when authentication is required, 2) scoring hypothetical attack chains instead of the actual vulnerability, or 3) inflating severity without evidence. **We will adjust inaccurate CVSS scores.** Intentionally inflated scores may result in report rejection.
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> **Using CVE Precedents:** If you cite other CVEs to support your report, ensure they are **genuinely comparable** in vulnerability type, threat model, and attack vector. Citing CVEs from different product categories, different vulnerability classes or different deployment models will lead us to suspect the use of AI in your report.
|
||||
|
||||
10. **Admin Actions Are Out of Scope:** Vulnerabilities that require an administrator to actively perform unsafe actions are **not considered valid vulnerabilities**. Admins have full system control and are expected to understand the security implications of their actions and configurations. This includes but is not limited to: adding malicious external servers (models, tools, webhooks), pasting untrusted code into Functions/Tools, or intentionally weakening security settings. **Reports requiring admin negligence or social engineering of admins may be rejected.**
|
||||
9. **Admin Actions Are Out of Scope:** Vulnerabilities that require an administrator to actively perform unsafe actions are **not considered valid vulnerabilities**. **Admins have full system control and are expected to understand the security implications of their actions and configurations**. This includes but is not limited to: adding malicious external servers (models, tools, webhooks), pasting untrusted code into Functions/Tools, or intentionally weakening security settings. **Reports requiring admin negligence or social engineering of admins may be rejected.**
|
||||
|
||||
> [!NOTE]
|
||||
> Similar to rule "Default Configuration Testing": If you believe you have found a vulnerability that affects admins and is NOT caused by admin negligence or intentionally malicious actions,
|
||||
> **then we absolutely want to hear about it.** This policy is intended to filter social engineering attacks on admins, malicious plugins being deployed by admins and similar malicious actions, not to discourage legitimate security research.
|
||||
|
||||
11. **AI report transparency:** Due to an extreme spike in AI-aided vulnerability reports **YOU MUST DISCLOSE if AI was used in any capacity** - whether for writing the report, generating the PoC, or identifying the vulnerability. If AI helped you in any way shape or form in the creation of the report, PoC or finding the vulnerability, you MUST disclose it.
|
||||
10. **AI report transparency:** Due to an extreme spike in AI-aided vulnerability reports **you MUST DISCLOSE if AI was used in any capacity** - whether for writing the report, generating the PoC, or identifying the vulnerability. If AI helped you in any way shape or form in the creation of the report, PoC or finding the vulnerability, you MUST disclose it.
|
||||
|
||||
> [!NOTE]
|
||||
> AI-aided vulnerability reports **will not be rejected by us by default**. But:
|
||||
>
|
||||
> - If we suspect you used AI (but you did not disclose it to us), we will be asking tough follow-up questions to validate your understanding of the reported vulnerability and Open WebUI itself.
|
||||
> - If we suspect you used AI (but you did not disclose it to us), we will be asking thorough follow-up questions to validate your understanding of the reported vulnerability and Open WebUI itself.
|
||||
> - If we suspect you used AI (but you did not disclose it to us) **and** your report ends up being invalid/not a vulnerability/not reproducible, then you **may be banned** from reporting future vulnerabilities.
|
||||
>
|
||||
> This measure was necessary due to the extreme rise in clearly AI written vulnerability reports, where the vast majority of them
|
||||
@@ -91,9 +98,9 @@ We appreciate the community's interest in identifying potential vulnerabilities.
|
||||
> - violated any of the rules outlined here
|
||||
> - had a clear lack of understanding of Open WebUI
|
||||
> - wrote comments with conflicting information
|
||||
> - used illogical arguments
|
||||
> - used illogical and conflicting arguments
|
||||
|
||||
**Non-compliant submissions will be closed, and repeat extreme violators may be banned.** Our goal is to foster a constructive reporting environment where quality submissions promote better security for all users.
|
||||
**Non-compliant submissions will be closed, and repeat or extreme violators may be banned.** Our goal is to foster a constructive reporting environment where quality submissions promote better security for all users.
|
||||
|
||||
## Where to report the vulnerability
|
||||
|
||||
@@ -119,12 +126,12 @@ If your concern does not meet the vulnerability requirements outlined above, is
|
||||
- Feature requests for optional security enhancements (2FA, audit logging, etc.)
|
||||
- General security questions about production deployment
|
||||
|
||||
Please use the adequate channel for your specific issue - e.g. best-practice guidance or additional documentation needs into the Documentation Repository, and feature requests into the Main Repository as an issue or discussion.
|
||||
Please use the adequate channel for your specific issue - e.g. best-practice guidance or **dditional documentation needs into the [Documentation Repository](https://github.com/open-webui/docs)**, and **feature requests into the Main Repository as an issue or discussion**.
|
||||
|
||||
We regularly audit our internal processes and system architecture for vulnerabilities using a combination of automated and manual testing techniques. We are also planning to implement SAST and SCA scans in our project soon.
|
||||
|
||||
For any other immediate concerns, please create an issue in our [issue tracker](https://github.com/open-webui/open-webui/issues) or contact our team on [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
For any other immediate concerns and questions, please create an issue in our [issue tracker](https://github.com/open-webui/open-webui/issues) or contact our team on [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
---
|
||||
|
||||
_Last updated on **2025-11-06**._
|
||||
_Last updated on **2026-02-25**._
|
||||
|
||||
Generated
+12
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "open-webui",
|
||||
"version": "0.8.5",
|
||||
"version": "0.8.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "open-webui",
|
||||
"version": "0.8.5",
|
||||
"version": "0.8.7",
|
||||
"dependencies": {
|
||||
"@azure/msal-browser": "^4.5.0",
|
||||
"@codemirror/lang-javascript": "^6.2.2",
|
||||
@@ -38,6 +38,7 @@
|
||||
"@tiptap/pm": "^3.0.7",
|
||||
"@tiptap/starter-kit": "^3.0.7",
|
||||
"@tiptap/suggestion": "^3.4.2",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"@xyflow/svelte": "^0.1.19",
|
||||
"alpinejs": "^3.15.0",
|
||||
"async": "^3.2.5",
|
||||
@@ -4619,6 +4620,15 @@
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@xterm/xterm": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz",
|
||||
"integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"addons/*"
|
||||
]
|
||||
},
|
||||
"node_modules/@xyflow/svelte": {
|
||||
"version": "0.1.19",
|
||||
"resolved": "https://registry.npmjs.org/@xyflow/svelte/-/svelte-0.1.19.tgz",
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "open-webui",
|
||||
"version": "0.8.5",
|
||||
"version": "0.8.7",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "npm run pyodide:fetch && vite dev --host",
|
||||
@@ -82,6 +82,7 @@
|
||||
"@tiptap/pm": "^3.0.7",
|
||||
"@tiptap/starter-kit": "^3.0.7",
|
||||
"@tiptap/suggestion": "^3.4.2",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"@xyflow/svelte": "^0.1.19",
|
||||
"alpinejs": "^3.15.0",
|
||||
"async": "^3.2.5",
|
||||
|
||||
+6
-12
@@ -332,12 +332,9 @@ input[type='number'] {
|
||||
}
|
||||
|
||||
.codespan {
|
||||
color: #eb5757;
|
||||
border-width: 0px;
|
||||
padding: 3px 8px;
|
||||
font-size: 0.8em;
|
||||
font-weight: 600;
|
||||
@apply rounded-md dark:bg-gray-800 bg-gray-100 mx-0.5;
|
||||
padding: 0.15rem 0.3rem;
|
||||
font-size: 0.85em;
|
||||
@apply font-mono rounded-md text-gray-800 bg-gray-100 dark:text-gray-200 dark:bg-gray-800 mx-0.5;
|
||||
}
|
||||
|
||||
.svelte-flow {
|
||||
@@ -566,12 +563,9 @@ input[type='number'] {
|
||||
}
|
||||
|
||||
.tiptap p code {
|
||||
color: #eb5757;
|
||||
border-width: 0px;
|
||||
padding: 3px 8px;
|
||||
font-size: 0.8em;
|
||||
font-weight: 600;
|
||||
@apply rounded-md dark:bg-gray-800 bg-gray-50 mx-0.5;
|
||||
padding: 0.15rem 0.3rem;
|
||||
font-size: 0.85em;
|
||||
@apply font-mono rounded-md text-gray-800 bg-gray-50 dark:text-gray-200 dark:bg-gray-800 mx-0.5;
|
||||
}
|
||||
|
||||
/* Code styling */
|
||||
|
||||
@@ -172,6 +172,63 @@ export const setToolServerConnections = async (token: string, connections: objec
|
||||
return res;
|
||||
};
|
||||
|
||||
export const getTerminalServerConnections = async (token: string) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/configs/terminal_servers`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
error = err.detail;
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const setTerminalServerConnections = async (token: string, connections: object) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/configs/terminal_servers`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...connections
|
||||
})
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
error = err.detail;
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const verifyToolServerConnection = async (token: string, connection: object) => {
|
||||
let error = null;
|
||||
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
export type FileEntry = {
|
||||
name: string;
|
||||
type: 'file' | 'directory';
|
||||
size?: number;
|
||||
modified?: number;
|
||||
};
|
||||
|
||||
import { WEBUI_API_BASE_URL } from '$lib/constants';
|
||||
|
||||
export type TerminalServer = {
|
||||
id: string;
|
||||
url: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export const getTerminalServers = async (token: string): Promise<TerminalServer[]> => {
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/terminals/`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
}).catch(() => null);
|
||||
if (!res || !res.ok) return [];
|
||||
return res.json().catch(() => []);
|
||||
};
|
||||
|
||||
export const getCwd = async (baseUrl: string, apiKey: string): Promise<string | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/cwd`;
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${apiKey}` }
|
||||
}).catch(() => null);
|
||||
if (!res || !res.ok) return null;
|
||||
const json = await res.json().catch(() => null);
|
||||
return json?.cwd ?? null;
|
||||
};
|
||||
|
||||
export const listFiles = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
path: string = '/'
|
||||
): Promise<FileEntry[] | null> => {
|
||||
// The endpoint uses `directory` as the query param name
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/list?directory=${encodeURIComponent(path)}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${apiKey}` }
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('open-terminal listFiles error:', err);
|
||||
return null;
|
||||
});
|
||||
return res?.entries ?? null;
|
||||
};
|
||||
|
||||
export const readFile = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
path: string
|
||||
): Promise<string | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/read?path=${encodeURIComponent(path)}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${apiKey}` }
|
||||
}).catch((err) => {
|
||||
console.error('open-terminal readFile error:', err);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (!res || !res.ok) return null;
|
||||
|
||||
const contentType = res.headers.get('content-type') ?? '';
|
||||
if (contentType.startsWith('image/') || contentType.startsWith('application/octet')) {
|
||||
// Binary — return a placeholder
|
||||
return `[Binary file: ${contentType}]`;
|
||||
}
|
||||
|
||||
// Text files: endpoint returns JSON { path, total_lines, content }
|
||||
// Binary image files: endpoint returns raw bytes (handled above)
|
||||
const json = await res.json().catch(() => null);
|
||||
return json?.content ?? null;
|
||||
};
|
||||
|
||||
export const downloadFileBlob = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
path: string
|
||||
): Promise<{ blob: Blob; filename: string } | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${apiKey}` }
|
||||
}).catch(() => null);
|
||||
|
||||
if (!res || !res.ok) return null;
|
||||
|
||||
const filename = path.split('/').pop() ?? 'file';
|
||||
const blob = await res.blob();
|
||||
return { blob, filename };
|
||||
};
|
||||
|
||||
export const uploadToTerminal = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
directory: string,
|
||||
file: File
|
||||
): Promise<{ path: string; size: number } | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/upload?directory=${encodeURIComponent(directory)}`;
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
body
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('open-terminal uploadToTerminal error:', err);
|
||||
return null;
|
||||
});
|
||||
return res;
|
||||
};
|
||||
|
||||
export const createDirectory = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
path: string
|
||||
): Promise<{ path: string } | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/mkdir`;
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ path })
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('open-terminal createDirectory error:', err);
|
||||
return null;
|
||||
});
|
||||
return res;
|
||||
};
|
||||
|
||||
export const deleteEntry = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
path: string
|
||||
): Promise<{ path: string; type: string } | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/delete?path=${encodeURIComponent(path)}`;
|
||||
const res = await fetch(url, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${apiKey}` }
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('open-terminal deleteEntry error:', err);
|
||||
return null;
|
||||
});
|
||||
return res;
|
||||
};
|
||||
|
||||
export const setCwd = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
path: string
|
||||
): Promise<{ cwd: string } | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/cwd`;
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ path })
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('open-terminal setCwd error:', err);
|
||||
return null;
|
||||
});
|
||||
return res;
|
||||
};
|
||||
@@ -0,0 +1,353 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { getContext, onMount } from 'svelte';
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import { settings } from '$lib/stores';
|
||||
|
||||
import Modal from '$lib/components/common/Modal.svelte';
|
||||
import SensitiveInput from '$lib/components/common/SensitiveInput.svelte';
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
import AccessControlModal from '$lib/components/workspace/common/AccessControlModal.svelte';
|
||||
import LockClosed from '$lib/components/icons/LockClosed.svelte';
|
||||
|
||||
export let show = false;
|
||||
export let edit = false;
|
||||
export let admin = false;
|
||||
export let connection = null;
|
||||
|
||||
export let onSubmit: Function = () => {};
|
||||
export let onDelete: () => void = () => {};
|
||||
|
||||
let url = '';
|
||||
let key = '';
|
||||
let name = '';
|
||||
let id = '';
|
||||
let auth_type = 'bearer';
|
||||
let path = '/openapi.json';
|
||||
let enabled = true;
|
||||
let showAdvanced = false;
|
||||
let showAccessControlModal = false;
|
||||
let accessGrants: any[] = [];
|
||||
|
||||
const init = () => {
|
||||
if (connection) {
|
||||
id = connection?.id ?? '';
|
||||
url = connection.url;
|
||||
key = connection?.key ?? '';
|
||||
name = connection?.name ?? '';
|
||||
auth_type = connection?.auth_type ?? 'bearer';
|
||||
path = connection?.path ?? '/openapi.json';
|
||||
enabled = connection?.enabled ?? true;
|
||||
accessGrants = connection?.config?.access_grants ?? [];
|
||||
} else {
|
||||
id = '';
|
||||
url = '';
|
||||
key = '';
|
||||
name = '';
|
||||
auth_type = 'bearer';
|
||||
path = '/openapi.json';
|
||||
enabled = true;
|
||||
accessGrants = [];
|
||||
}
|
||||
};
|
||||
|
||||
$: if (show) {
|
||||
init();
|
||||
}
|
||||
|
||||
const submitHandler = () => {
|
||||
if (url === '') {
|
||||
toast.error($i18n.t('Please enter a valid URL'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove trailing slash
|
||||
url = url.replace(/\/$/, '');
|
||||
|
||||
const result = {
|
||||
...(admin && id.trim() ? { id: id.trim() } : {}),
|
||||
url,
|
||||
key,
|
||||
name,
|
||||
path,
|
||||
auth_type,
|
||||
enabled: enabled,
|
||||
config: {
|
||||
...(admin ? { access_grants: accessGrants } : {})
|
||||
}
|
||||
};
|
||||
|
||||
onSubmit(result);
|
||||
show = false;
|
||||
};
|
||||
</script>
|
||||
|
||||
<Modal size="sm" bind:show>
|
||||
<div>
|
||||
<div class="flex justify-between dark:text-gray-100 px-5 pt-4 pb-2">
|
||||
<h1 class="text-lg font-medium self-center font-primary">
|
||||
{#if edit}
|
||||
{$i18n.t('Edit Terminal Connection')}
|
||||
{:else}
|
||||
{$i18n.t('Add Terminal Connection')}
|
||||
{/if}
|
||||
</h1>
|
||||
|
||||
<button
|
||||
class="self-center"
|
||||
aria-label={$i18n.t('Close')}
|
||||
on:click={() => {
|
||||
show = false;
|
||||
}}
|
||||
>
|
||||
<XMark className={'size-5'} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col md:flex-row w-full px-4 pb-4 md:space-x-4 dark:text-gray-200">
|
||||
<div class="flex flex-col w-full sm:flex-row sm:justify-center sm:space-x-6">
|
||||
<form class="flex flex-col w-full" on:submit|preventDefault={submitHandler}>
|
||||
<div class="px-1">
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-col flex-1">
|
||||
<div class="flex justify-between mb-0.5">
|
||||
<label
|
||||
for="terminal-name"
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('Name')}</label
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center">
|
||||
<input
|
||||
id="terminal-name"
|
||||
class={`w-full flex-1 text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={name}
|
||||
placeholder={$i18n.t('My Terminal')}
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if admin}
|
||||
<div class="flex flex-col flex-1">
|
||||
<div class="flex justify-between mb-0.5">
|
||||
<label
|
||||
for="terminal-id"
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('ID')}
|
||||
<span class="opacity-50">({$i18n.t('optional')})</span></label
|
||||
>
|
||||
</div>
|
||||
<div class="flex flex-1 items-center">
|
||||
<input
|
||||
id="terminal-id"
|
||||
class={`w-full flex-1 text-sm bg-transparent font-mono ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={id}
|
||||
placeholder="auto"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<div class="flex justify-between mb-0.5">
|
||||
<label
|
||||
for="terminal-url"
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('URL')}</label
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center">
|
||||
<input
|
||||
id="terminal-url"
|
||||
class={`w-full flex-1 text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={url}
|
||||
placeholder="http://localhost:9900"
|
||||
required
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition mt-2"
|
||||
on:click={() => (showAdvanced = !showAdvanced)}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="w-3 h-3 transition-transform {showAdvanced ? 'rotate-90' : ''}"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{$i18n.t('Advanced')}
|
||||
</button>
|
||||
|
||||
{#if admin}
|
||||
<button
|
||||
class="bg-gray-50 hover:bg-gray-100 text-black dark:bg-gray-850 dark:hover:bg-gray-800 dark:text-white transition px-2 py-1 object-cover rounded-full flex gap-1 items-center mt-2"
|
||||
type="button"
|
||||
on:click={() => {
|
||||
showAccessControlModal = true;
|
||||
}}
|
||||
>
|
||||
<LockClosed strokeWidth="2.5" className="size-3.5 shrink-0" />
|
||||
|
||||
<div class="text-xs font-medium shrink-0">
|
||||
{$i18n.t('Access')}
|
||||
</div>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if showAdvanced}
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<div class="flex justify-between items-center mb-0.5">
|
||||
<div class="flex gap-2 items-center">
|
||||
<div
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('OpenAPI Spec')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-1 items-center">
|
||||
<div class="flex-1 flex items-center">
|
||||
<label for="openapi-path" class="sr-only"
|
||||
>{$i18n.t('openapi.json URL or Path')}</label
|
||||
>
|
||||
<input
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
id="openapi-path"
|
||||
bind:value={path}
|
||||
placeholder={$i18n.t('openapi.json URL or Path')}
|
||||
autocomplete="off"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class={`text-xs mt-1 ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t(`WebUI will make requests to "{{url}}"`, {
|
||||
url: path.includes('://')
|
||||
? path
|
||||
: `${url}${path.startsWith('/') ? '' : '/'}${path}`
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<div class="flex justify-between items-center">
|
||||
<div class="flex gap-2 items-center">
|
||||
<div
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('Auth')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex-shrink-0 self-start">
|
||||
<select
|
||||
class={`dark:bg-gray-900 w-full text-sm bg-transparent pr-5 ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
bind:value={auth_type}
|
||||
>
|
||||
<option value="none">{$i18n.t('None')}</option>
|
||||
<option value="bearer">{$i18n.t('Bearer')}</option>
|
||||
{#if admin}
|
||||
<option value="session">{$i18n.t('Session')}</option>
|
||||
<option value="system_oauth">{$i18n.t('OAuth')}</option>
|
||||
{/if}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center">
|
||||
{#if auth_type === 'bearer'}
|
||||
<SensitiveInput
|
||||
bind:value={key}
|
||||
placeholder={$i18n.t('API Key')}
|
||||
required={false}
|
||||
/>
|
||||
{:else if auth_type === 'none'}
|
||||
<div
|
||||
class={`text-xs self-center translate-y-[1px] ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('No authentication')}
|
||||
</div>
|
||||
{:else if auth_type === 'session'}
|
||||
<div
|
||||
class={`text-xs self-center translate-y-[1px] ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('Forwards system user session credentials to authenticate')}
|
||||
</div>
|
||||
{:else if auth_type === 'system_oauth'}
|
||||
<div
|
||||
class={`text-xs self-center translate-y-[1px] ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('Forwards system user OAuth access token to authenticate')}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-between pt-3 text-sm font-medium gap-1.5">
|
||||
<div></div>
|
||||
<div class="flex gap-1.5">
|
||||
{#if edit}
|
||||
<button
|
||||
class="px-3.5 py-1.5 text-sm font-medium dark:bg-black dark:hover:bg-gray-900 dark:text-white bg-white text-black hover:bg-gray-100 transition rounded-full flex flex-row space-x-1 items-center"
|
||||
type="button"
|
||||
on:click={() => {
|
||||
onDelete();
|
||||
show = false;
|
||||
}}
|
||||
>
|
||||
{$i18n.t('Delete')}
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<button
|
||||
class="px-3.5 py-1.5 text-sm font-medium bg-black hover:bg-gray-900 text-white dark:bg-white dark:text-black dark:hover:bg-gray-100 transition rounded-full flex flex-row space-x-1 items-center"
|
||||
type="submit"
|
||||
>
|
||||
{$i18n.t('Save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<AccessControlModal bind:show={showAccessControlModal} bind:accessGrants />
|
||||
@@ -19,7 +19,8 @@
|
||||
import Tags from './common/Tags.svelte';
|
||||
import { getToolServerData } from '$lib/apis';
|
||||
import { verifyToolServerConnection, registerOAuthClient } from '$lib/apis/configs';
|
||||
import AccessControl from './workspace/common/AccessControl.svelte';
|
||||
import AccessControlModal from '$lib/components/workspace/common/AccessControlModal.svelte';
|
||||
import LockClosed from '$lib/components/icons/LockClosed.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
import Textarea from './common/Textarea.svelte';
|
||||
@@ -58,6 +59,8 @@
|
||||
|
||||
let enable = true;
|
||||
let loading = false;
|
||||
let showAdvanced = false;
|
||||
let showAccessControlModal = false;
|
||||
|
||||
const registerOAuthClientHandler = async () => {
|
||||
if (url === '') {
|
||||
@@ -439,30 +442,94 @@
|
||||
}}
|
||||
>
|
||||
<div class="px-1">
|
||||
{#if !direct}
|
||||
<div class="flex gap-2 mb-1.5">
|
||||
<div class="flex w-full justify-between items-center">
|
||||
<div class=" text-xs text-gray-500">{$i18n.t('Type')}</div>
|
||||
<div class="flex gap-2 mb-1.5">
|
||||
<div class="flex w-full justify-between items-center">
|
||||
<div class=" text-xs text-gray-500">{$i18n.t('Type')}</div>
|
||||
|
||||
<div class="">
|
||||
<button
|
||||
on:click={() => {
|
||||
type = ['', 'openapi'].includes(type) ? 'mcp' : 'openapi';
|
||||
}}
|
||||
type="button"
|
||||
class=" text-xs text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
{#if ['', 'openapi'].includes(type)}
|
||||
{$i18n.t('OpenAPI')}
|
||||
{:else if type === 'mcp'}
|
||||
{$i18n.t('MCP')}
|
||||
<span class="text-gray-500">{$i18n.t('Streamable HTTP')}</span>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
<div class="">
|
||||
<button
|
||||
on:click={() => {
|
||||
type = ['', 'openapi'].includes(type) ? 'mcp' : 'openapi';
|
||||
}}
|
||||
type="button"
|
||||
class=" text-xs text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
{#if ['', 'openapi'].includes(type)}
|
||||
{$i18n.t('OpenAPI')}
|
||||
{:else if type === 'mcp'}
|
||||
{$i18n.t('MCP')}
|
||||
<span class="text-gray-500">{$i18n.t('Streamable HTTP')}</span>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-col flex-1">
|
||||
<div class="flex justify-between mb-0.5">
|
||||
<label
|
||||
for="enter-name"
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('Name')}</label
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center">
|
||||
<input
|
||||
id="enter-name"
|
||||
class={`w-full flex-1 text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={name}
|
||||
placeholder={$i18n.t('Enter name')}
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if !direct}
|
||||
<div class="flex flex-col flex-1">
|
||||
<div class="flex justify-between mb-0.5">
|
||||
<label
|
||||
for="enter-id"
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('ID')}
|
||||
{#if type !== 'mcp'}<span class="opacity-50">({$i18n.t('optional')})</span
|
||||
>{/if}</label
|
||||
>
|
||||
</div>
|
||||
<div class="flex flex-1 items-center">
|
||||
<input
|
||||
id="enter-id"
|
||||
class={`w-full flex-1 text-sm bg-transparent font-mono ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={id}
|
||||
placeholder="auto"
|
||||
autocomplete="off"
|
||||
required={type === 'mcp'}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col w-full mt-1 mb-1.5">
|
||||
<label
|
||||
for="description"
|
||||
class={`mb-0.5 text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('Description')}</label
|
||||
>
|
||||
|
||||
<div class="flex-1">
|
||||
<input
|
||||
id="description"
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={description}
|
||||
placeholder={$i18n.t('Enter description')}
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-col w-full">
|
||||
@@ -520,81 +587,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if ['', 'openapi'].includes(type)}
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<div class="flex justify-between items-center mb-0.5">
|
||||
<div class="flex gap-2 items-center">
|
||||
<div
|
||||
for="select-bearer-or-session"
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('OpenAPI Spec')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex-shrink-0 self-start">
|
||||
<select
|
||||
id="select-bearer-or-session"
|
||||
class={`dark:bg-gray-900 w-full text-sm bg-transparent pr-5 ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
bind:value={spec_type}
|
||||
>
|
||||
<option value="url">{$i18n.t('URL')}</option>
|
||||
<option value="json">{$i18n.t('JSON')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center">
|
||||
{#if spec_type === 'url'}
|
||||
<div class="flex-1 flex items-center">
|
||||
<label for="url-or-path" class="sr-only"
|
||||
>{$i18n.t('openapi.json URL or Path')}</label
|
||||
>
|
||||
<input
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
id="url-or-path"
|
||||
bind:value={path}
|
||||
placeholder={$i18n.t('openapi.json URL or Path')}
|
||||
autocomplete="off"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{:else if spec_type === 'json'}
|
||||
<div
|
||||
class={`text-xs w-full self-center translate-y-[1px] ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
<label for="url-or-path" class="sr-only">{$i18n.t('JSON Spec')}</label>
|
||||
<textarea
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700 text-black dark:text-white'}`}
|
||||
bind:value={spec}
|
||||
placeholder={$i18n.t('JSON Spec')}
|
||||
autocomplete="off"
|
||||
required
|
||||
rows="5"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if ['', 'url'].includes(spec_type)}
|
||||
<div
|
||||
class={`text-xs mt-1 ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t(`WebUI will make requests to "{{url}}"`, {
|
||||
url: path.includes('://')
|
||||
? path
|
||||
: `${url}${path.startsWith('/') ? '' : '/'}${path}`
|
||||
})}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<div class="flex justify-between items-center">
|
||||
@@ -702,104 +694,152 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if !direct}
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<label
|
||||
for="headers-input"
|
||||
class={`mb-0.5 text-xs text-gray-500
|
||||
${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : ''}`}
|
||||
>{$i18n.t('Headers')}</label
|
||||
>
|
||||
|
||||
<div class="flex-1">
|
||||
<Tooltip
|
||||
content={$i18n.t(
|
||||
'Enter additional headers in JSON format (e.g. {"X-Custom-Header": "value"}'
|
||||
)}
|
||||
>
|
||||
<Textarea
|
||||
className="w-full text-sm outline-hidden"
|
||||
bind:value={headers}
|
||||
placeholder={$i18n.t('Enter additional headers in JSON format')}
|
||||
required={false}
|
||||
minSize={30}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class=" border-gray-100 dark:border-gray-700/10 my-2.5 w-full" />
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<label
|
||||
for="enter-id"
|
||||
class={`mb-0.5 text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('ID')}
|
||||
|
||||
{#if type !== 'mcp'}
|
||||
<span class="text-xs text-gray-200 dark:text-gray-800 ml-0.5"
|
||||
>{$i18n.t('Optional')}</span
|
||||
>
|
||||
{/if}
|
||||
</label>
|
||||
|
||||
<div class="flex-1">
|
||||
<input
|
||||
id="enter-id"
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={id}
|
||||
placeholder={$i18n.t('Enter ID')}
|
||||
autocomplete="off"
|
||||
required={type === 'mcp'}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<label
|
||||
for="enter-name"
|
||||
class={`mb-0.5 text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('Name')}
|
||||
</label>
|
||||
|
||||
<div class="flex-1">
|
||||
<input
|
||||
id="enter-name"
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={name}
|
||||
placeholder={$i18n.t('Enter name')}
|
||||
autocomplete="off"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col w-full mt-2">
|
||||
<label
|
||||
for="description"
|
||||
class={`mb-1 text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100 placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700 text-gray-500'}`}
|
||||
>{$i18n.t('Description')}</label
|
||||
<div class="flex items-center justify-between">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition mt-2"
|
||||
on:click={() => (showAdvanced = !showAdvanced)}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="w-3 h-3 transition-transform {showAdvanced ? 'rotate-90' : ''}"
|
||||
>
|
||||
|
||||
<div class="flex-1">
|
||||
<input
|
||||
id="description"
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={description}
|
||||
placeholder={$i18n.t('Enter description')}
|
||||
autocomplete="off"
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{$i18n.t('Advanced')}
|
||||
</button>
|
||||
|
||||
{#if !direct}
|
||||
<button
|
||||
class="bg-gray-50 hover:bg-gray-100 text-black dark:bg-gray-850 dark:hover:bg-gray-800 dark:text-white transition px-2 py-1 object-cover rounded-full flex gap-1 items-center mt-2"
|
||||
type="button"
|
||||
on:click={() => {
|
||||
showAccessControlModal = true;
|
||||
}}
|
||||
>
|
||||
<LockClosed strokeWidth="2.5" className="size-3.5 shrink-0" />
|
||||
|
||||
<div class="text-xs font-medium shrink-0">
|
||||
{$i18n.t('Access')}
|
||||
</div>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if showAdvanced}
|
||||
{#if ['', 'openapi'].includes(type)}
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<div class="flex justify-between items-center mb-0.5">
|
||||
<div class="flex gap-2 items-center">
|
||||
<div
|
||||
for="select-bearer-or-session"
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('OpenAPI Spec')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex-shrink-0 self-start">
|
||||
<select
|
||||
id="select-bearer-or-session"
|
||||
class={`dark:bg-gray-900 w-full text-sm bg-transparent pr-5 ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
bind:value={spec_type}
|
||||
>
|
||||
<option value="url">{$i18n.t('URL')}</option>
|
||||
<option value="json">{$i18n.t('JSON')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center">
|
||||
{#if spec_type === 'url'}
|
||||
<div class="flex-1 flex items-center">
|
||||
<label for="url-or-path" class="sr-only"
|
||||
>{$i18n.t('openapi.json URL or Path')}</label
|
||||
>
|
||||
<input
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
id="url-or-path"
|
||||
bind:value={path}
|
||||
placeholder={$i18n.t('openapi.json URL or Path')}
|
||||
autocomplete="off"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{:else if spec_type === 'json'}
|
||||
<div
|
||||
class={`text-xs w-full self-center translate-y-[1px] ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
<label for="url-or-path" class="sr-only">{$i18n.t('JSON Spec')}</label>
|
||||
<textarea
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700 text-black dark:text-white'}`}
|
||||
bind:value={spec}
|
||||
placeholder={$i18n.t('JSON Spec')}
|
||||
autocomplete="off"
|
||||
required
|
||||
rows="5"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if ['', 'url'].includes(spec_type)}
|
||||
<div
|
||||
class={`text-xs mt-1 ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t(`WebUI will make requests to "{{url}}"`, {
|
||||
url: path.includes('://')
|
||||
? path
|
||||
: `${url}${path.startsWith('/') ? '' : '/'}${path}`
|
||||
})}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !direct}
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<label
|
||||
for="headers-input"
|
||||
class={`mb-0.5 text-xs text-gray-500
|
||||
${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : ''}`}
|
||||
>{$i18n.t('Headers')}</label
|
||||
>
|
||||
|
||||
<div class="flex-1">
|
||||
<Tooltip
|
||||
content={$i18n.t(
|
||||
'Enter additional headers in JSON format (e.g. {"X-Custom-Header": "value"}'
|
||||
)}
|
||||
>
|
||||
<Textarea
|
||||
className="w-full text-sm outline-hidden"
|
||||
bind:value={headers}
|
||||
placeholder={$i18n.t('Enter additional headers in JSON format')}
|
||||
required={false}
|
||||
minSize={30}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if !direct}
|
||||
<hr class=" border-gray-100 dark:border-gray-700/10 my-2.5 w-full" />
|
||||
|
||||
<div class="flex flex-col w-full mt-2">
|
||||
<label
|
||||
@@ -819,12 +859,6 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class=" border-gray-100 dark:border-gray-700/10 my-2.5 w-full" />
|
||||
|
||||
<div class="my-2">
|
||||
<AccessControl bind:accessGrants />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -885,3 +919,5 @@
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<AccessControlModal bind:show={showAccessControlModal} bind:accessGrants />
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
import { WEBUI_BASE_URL } from '$lib/constants';
|
||||
import { settings, playingNotificationSound, isLastActiveTab } from '$lib/stores';
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
import { marked } from 'marked';
|
||||
|
||||
import { createEventDispatcher, onMount } from 'svelte';
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
{/if}
|
||||
|
||||
<div class=" line-clamp-2 text-xs self-center dark:text-gray-300 font-normal">
|
||||
{@html DOMPurify.sanitize(marked(content))}
|
||||
{@html DOMPurify.sanitize(marked(DOMPurify.sanitize(content, { ALLOWED_TAGS: [] })))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -24,12 +24,12 @@
|
||||
// Time period - persist in localStorage
|
||||
let selectedPeriod =
|
||||
(typeof localStorage !== 'undefined' && localStorage.getItem('analyticsPeriod')) || '7d';
|
||||
const periods = [
|
||||
{ value: '24h', label: 'Last 24 hours' },
|
||||
{ value: '7d', label: 'Last 7 days' },
|
||||
{ value: '30d', label: 'Last 30 days' },
|
||||
{ value: '90d', label: 'Last 90 days' },
|
||||
{ value: 'all', label: 'All time' }
|
||||
$: periods = [
|
||||
{ value: '24h', label: $i18n.t('Last 24 hours') },
|
||||
{ value: '7d', label: $i18n.t('Last 7 days') },
|
||||
{ value: '30d', label: $i18n.t('Last 30 days') },
|
||||
{ value: '90d', label: $i18n.t('Last 90 days') },
|
||||
{ value: 'all', label: $i18n.t('All time') }
|
||||
];
|
||||
|
||||
// User group filter
|
||||
@@ -214,7 +214,7 @@
|
||||
class="w-fit pr-8 rounded-sm px-2 text-xs bg-transparent outline-none text-right"
|
||||
>
|
||||
{#each periods as period}
|
||||
<option value={period.value}>{$i18n.t(period.label)}</option>
|
||||
<option value={period.value}>{period.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
@@ -274,7 +274,7 @@
|
||||
{@const periodMap = { '24h': 'hour', '7d': 'week', '30d': 'month', '90d': 'year', all: 'all' }}
|
||||
<div class="mb-4">
|
||||
<div class="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2 px-0.5">
|
||||
{$i18n.t(selectedPeriod === '24h' ? 'Hourly Messages' : 'Daily Messages')}
|
||||
{selectedPeriod === '24h' ? $i18n.t('Hourly Messages') : $i18n.t('Daily Messages')}
|
||||
</div>
|
||||
<ChartLine
|
||||
data={dailyStats}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
import Evaluations from './Settings/Evaluations.svelte';
|
||||
import CodeExecution from './Settings/CodeExecution.svelte';
|
||||
import Tools from './Settings/Tools.svelte';
|
||||
import Integrations from './Settings/Integrations.svelte';
|
||||
|
||||
import ChartBar from '../icons/ChartBar.svelte';
|
||||
import DocumentChartBar from '../icons/DocumentChartBar.svelte';
|
||||
@@ -40,7 +40,7 @@
|
||||
'connections',
|
||||
'models',
|
||||
'evaluations',
|
||||
'tools',
|
||||
'integrations',
|
||||
'documents',
|
||||
'web',
|
||||
'code-execution',
|
||||
@@ -132,10 +132,10 @@
|
||||
keywords: ['evaluations', 'feedback', 'rating', 'arena', 'leaderboard', 'preference']
|
||||
},
|
||||
{
|
||||
id: 'tools',
|
||||
title: 'External Tools',
|
||||
route: '/admin/settings/tools',
|
||||
keywords: ['tools', 'plugins', 'extensions', 'functions', 'openapi', 'server']
|
||||
id: 'integrations',
|
||||
title: 'Integrations',
|
||||
route: '/admin/settings/integrations',
|
||||
keywords: ['tools', 'integrations', 'plugins', 'extensions', 'functions', 'openapi', 'server']
|
||||
},
|
||||
{
|
||||
id: 'documents',
|
||||
@@ -311,7 +311,7 @@
|
||||
<!-- {$i18n.t('Connections')} -->
|
||||
<!-- {$i18n.t('Models')} -->
|
||||
<!-- {$i18n.t('Evaluations')} -->
|
||||
<!-- {$i18n.t('External Tools')} -->
|
||||
<!-- {$i18n.t('Integrations')} -->
|
||||
<!-- {$i18n.t('Documents')} -->
|
||||
<!-- {$i18n.t('Web Search')} -->
|
||||
<!-- {$i18n.t('Code Execution')} -->
|
||||
@@ -370,7 +370,7 @@
|
||||
</svg>
|
||||
{:else if tab.id === 'evaluations'}
|
||||
<DocumentChartBar />
|
||||
{:else if tab.id === 'tools'}
|
||||
{:else if tab.id === 'integrations'}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
@@ -525,8 +525,8 @@
|
||||
<Models />
|
||||
{:else if selectedTab === 'evaluations'}
|
||||
<Evaluations />
|
||||
{:else if selectedTab === 'tools'}
|
||||
<Tools />
|
||||
{:else if selectedTab === 'integrations'}
|
||||
<Integrations />
|
||||
{:else if selectedTab === 'documents'}
|
||||
<Documents
|
||||
on:save={async () => {
|
||||
|
||||
@@ -420,9 +420,8 @@
|
||||
/>
|
||||
|
||||
<div class="mt-2 text-xs text-gray-400 dark:text-gray-500">
|
||||
<!-- https://docs.openwebui.com/getting-started/advanced-topics/api-endpoints -->
|
||||
<a
|
||||
href="https://docs.openwebui.com/getting-started/api-endpoints"
|
||||
href="https://docs.openwebui.com/reference/api-endpoints"
|
||||
target="_blank"
|
||||
class=" text-gray-300 font-medium underline"
|
||||
>
|
||||
@@ -463,7 +462,7 @@
|
||||
<span class=" font-medium">{$i18n.t('Warning')}:</span>
|
||||
<span
|
||||
><a
|
||||
href="https://docs.openwebui.com/getting-started/env-configuration#jwt_expires_in"
|
||||
href="https://docs.openwebui.com/reference/env-configuration#jwt_expires_in"
|
||||
target="_blank"
|
||||
class=" underline"
|
||||
>{$i18n.t('No expiration can pose security risks.')}
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { createEventDispatcher, onMount, getContext, tick } from 'svelte';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { getModels as _getModels } from '$lib/apis';
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import { models, settings, user, terminalServers } from '$lib/stores';
|
||||
import { getTerminalServers } from '$lib/apis/terminal';
|
||||
import { WEBUI_API_BASE_URL } from '$lib/constants';
|
||||
|
||||
import Switch from '$lib/components/common/Switch.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import Cog6 from '$lib/components/icons/Cog6.svelte';
|
||||
import Cloud from '$lib/components/icons/Cloud.svelte';
|
||||
import Connection from '$lib/components/chat/Settings/Tools/Connection.svelte';
|
||||
import SensitiveInput from '$lib/components/common/SensitiveInput.svelte';
|
||||
|
||||
import AddToolServerModal from '$lib/components/AddToolServerModal.svelte';
|
||||
import AddTerminalServerModal from '$lib/components/AddTerminalServerModal.svelte';
|
||||
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
||||
|
||||
import {
|
||||
getToolServerConnections,
|
||||
setToolServerConnections,
|
||||
getTerminalServerConnections,
|
||||
setTerminalServerConnections
|
||||
} from '$lib/apis/configs';
|
||||
|
||||
export let saveSettings: Function;
|
||||
|
||||
let servers = null;
|
||||
let showConnectionModal = false;
|
||||
|
||||
// Terminal server admin connections
|
||||
let terminalConnections = [];
|
||||
let showAddTerminalModal = false;
|
||||
let editTerminalIdx: number | null = null;
|
||||
let showDeleteTerminalConfirm = false;
|
||||
let deleteTerminalIdx: number | null = null;
|
||||
|
||||
const addConnectionHandler = async (server) => {
|
||||
servers = [...servers, server];
|
||||
await updateHandler();
|
||||
};
|
||||
|
||||
const updateHandler = async () => {
|
||||
const res = await setToolServerConnections(localStorage.token, {
|
||||
TOOL_SERVER_CONNECTIONS: servers
|
||||
}).catch((err) => {
|
||||
toast.error($i18n.t('Failed to save connections'));
|
||||
return null;
|
||||
});
|
||||
|
||||
if (res) {
|
||||
toast.success($i18n.t('Connections saved successfully'));
|
||||
}
|
||||
};
|
||||
|
||||
const saveTerminalServers = async () => {
|
||||
const res = await setTerminalServerConnections(localStorage.token, {
|
||||
TERMINAL_SERVER_CONNECTIONS: terminalConnections
|
||||
}).catch((err) => {
|
||||
toast.error($i18n.t('Failed to save terminal servers'));
|
||||
return null;
|
||||
});
|
||||
|
||||
if (res) {
|
||||
toast.success($i18n.t('Terminal servers saved'));
|
||||
|
||||
// Refresh the terminalServers store so changes are reflected immediately
|
||||
// Preserve user direct terminals, refresh system terminals from backend
|
||||
const existingDirectTerminals = ($terminalServers ?? []).filter((t) => !t.id);
|
||||
const systemTerminals = await getTerminalServers(localStorage.token);
|
||||
const systemEntries = systemTerminals.map((t) => ({
|
||||
id: t.id,
|
||||
url: `${WEBUI_API_BASE_URL}/terminals/${t.id}`,
|
||||
name: t.name,
|
||||
key: localStorage.token
|
||||
}));
|
||||
terminalServers.set([...existingDirectTerminals, ...systemEntries]);
|
||||
}
|
||||
};
|
||||
|
||||
const addTerminalConnection = (server) => {
|
||||
terminalConnections = [...terminalConnections, { ...server, id: server.id ?? uuidv4() }];
|
||||
saveTerminalServers();
|
||||
};
|
||||
|
||||
const updateTerminalConnection = (idx: number, updated) => {
|
||||
terminalConnections = terminalConnections.map((c, i) =>
|
||||
i === idx ? { ...c, ...updated, id: updated.id ?? c.id } : c
|
||||
);
|
||||
saveTerminalServers();
|
||||
};
|
||||
|
||||
const removeTerminalConnection = (idx: number) => {
|
||||
terminalConnections = terminalConnections.filter((_, i) => i !== idx);
|
||||
saveTerminalServers();
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
const res = await getToolServerConnections(localStorage.token);
|
||||
servers = res.TOOL_SERVER_CONNECTIONS;
|
||||
|
||||
// Load terminal server connections
|
||||
try {
|
||||
const terminalRes = await getTerminalServerConnections(localStorage.token);
|
||||
if (terminalRes?.TERMINAL_SERVER_CONNECTIONS) {
|
||||
terminalConnections = terminalRes.TERMINAL_SERVER_CONNECTIONS;
|
||||
}
|
||||
} catch {
|
||||
// Not configured yet
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<AddToolServerModal bind:show={showConnectionModal} onSubmit={addConnectionHandler} />
|
||||
|
||||
<AddTerminalServerModal
|
||||
admin
|
||||
bind:show={showAddTerminalModal}
|
||||
edit={editTerminalIdx !== null}
|
||||
connection={editTerminalIdx !== null ? terminalConnections[editTerminalIdx] : null}
|
||||
onSubmit={(c) => {
|
||||
if (editTerminalIdx !== null) {
|
||||
updateTerminalConnection(editTerminalIdx, c);
|
||||
editTerminalIdx = null;
|
||||
} else {
|
||||
addTerminalConnection(c);
|
||||
}
|
||||
}}
|
||||
onDelete={() => {
|
||||
if (editTerminalIdx !== null) {
|
||||
deleteTerminalIdx = editTerminalIdx;
|
||||
showDeleteTerminalConfirm = true;
|
||||
editTerminalIdx = null;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:show={showDeleteTerminalConfirm}
|
||||
on:confirm={() => {
|
||||
if (deleteTerminalIdx !== null) {
|
||||
removeTerminalConnection(deleteTerminalIdx);
|
||||
deleteTerminalIdx = null;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<form
|
||||
class="flex flex-col h-full justify-between text-sm"
|
||||
on:submit|preventDefault={() => {
|
||||
updateHandler();
|
||||
}}
|
||||
>
|
||||
<div class=" overflow-y-scroll scrollbar-hidden h-full">
|
||||
{#if servers !== null}
|
||||
<div class="">
|
||||
<div class="mb-3">
|
||||
<div class=" mt-0.5 mb-2.5 text-base font-medium">{$i18n.t('General')}</div>
|
||||
|
||||
<hr class=" border-gray-100/30 dark:border-gray-850/30 my-2" />
|
||||
|
||||
<div class="mb-2.5 flex flex-col w-full justify-between">
|
||||
<div class="flex justify-between items-center mb-0.5">
|
||||
<div class="font-medium">{$i18n.t('Manage Tool Servers')}</div>
|
||||
|
||||
<Tooltip content={$i18n.t(`Add Connection`)}>
|
||||
<button
|
||||
class="px-1"
|
||||
on:click={() => {
|
||||
showConnectionModal = true;
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<Plus />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
{#each servers as server, idx}
|
||||
<Connection
|
||||
bind:connection={server}
|
||||
onSubmit={() => {
|
||||
updateHandler();
|
||||
}}
|
||||
onDelete={() => {
|
||||
servers = servers.filter((_, i) => i !== idx);
|
||||
updateHandler();
|
||||
}}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if servers.length === 0}
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('No tool server connections configured.')}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="my-1.5">
|
||||
<div class="text-xs text-gray-500">
|
||||
{$i18n.t('Connect to your own OpenAPI compatible external tool servers.')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class=" border-gray-100/30 dark:border-gray-850/30 my-4" />
|
||||
|
||||
<div class="mb-2.5 flex flex-col w-full">
|
||||
<div class="flex justify-between items-center mb-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="font-medium">{$i18n.t('Open Terminal')}</div>
|
||||
<span
|
||||
class="text-[0.65rem] font-medium uppercase px-1.5 py-0.5 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400"
|
||||
>{$i18n.t('Experimental')}</span
|
||||
>
|
||||
</div>
|
||||
|
||||
<Tooltip content={$i18n.t('Add Connection')}>
|
||||
<button
|
||||
class="px-1"
|
||||
on:click={() => {
|
||||
editTerminalIdx = null;
|
||||
showAddTerminalModal = true;
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<Plus />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1.5">
|
||||
{#each terminalConnections as connection, idx}
|
||||
<div class="flex w-full gap-2 items-center">
|
||||
<Tooltip className="w-full relative" content={''} placement="top-start">
|
||||
<div class="flex w-full">
|
||||
<div
|
||||
class="flex-1 relative flex gap-1.5 items-center {connection?.enabled ===
|
||||
false
|
||||
? 'opacity-50'
|
||||
: ''}"
|
||||
>
|
||||
<Tooltip content={$i18n.t('Terminal')}>
|
||||
<Cloud className="size-4" strokeWidth="1.5" />
|
||||
</Tooltip>
|
||||
|
||||
<div class="outline-hidden w-full bg-transparent text-sm">
|
||||
{connection.name || connection.url || $i18n.t('New Terminal')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
|
||||
<div class="flex gap-1 items-center">
|
||||
<Tooltip content={$i18n.t('Configure')}>
|
||||
<button
|
||||
class="self-center p-1 bg-transparent hover:bg-gray-100 dark:hover:bg-gray-850 rounded-lg transition"
|
||||
on:click={() => {
|
||||
editTerminalIdx = idx;
|
||||
showAddTerminalModal = true;
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<Cog6 />
|
||||
</button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip
|
||||
content={connection?.enabled !== false
|
||||
? $i18n.t('Enabled')
|
||||
: $i18n.t('Disabled')}
|
||||
>
|
||||
<Switch
|
||||
state={connection?.enabled !== false}
|
||||
on:change={() => {
|
||||
terminalConnections = terminalConnections.map((c, i) =>
|
||||
i === idx ? { ...c, enabled: !(c?.enabled !== false) } : c
|
||||
);
|
||||
saveTerminalServers();
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if terminalConnections.length === 0}
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('No terminal connections configured.')}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-1.5">
|
||||
<div class="text-xs text-gray-500">
|
||||
{$i18n.t(
|
||||
'Connect to Open Terminal instances. All users will have access to file browsing and terminal tools through these servers.'
|
||||
)}
|
||||
</div>
|
||||
<div class="text-xs text-gray-600 dark:text-gray-300 mt-1">
|
||||
<a
|
||||
class="underline"
|
||||
href="https://github.com/open-webui/open-terminal"
|
||||
target="_blank">{$i18n.t('Learn more about Open Terminal')} ↗</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex h-full justify-center">
|
||||
<div class="my-auto">
|
||||
<Spinner className="size-6" />
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end pt-3 text-sm font-medium">
|
||||
<button
|
||||
class="px-3.5 py-1.5 text-sm font-medium bg-black hover:bg-gray-900 text-white dark:bg-white dark:text-black dark:hover:bg-gray-100 transition rounded-full"
|
||||
type="submit"
|
||||
>
|
||||
{$i18n.t('Save')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -39,6 +39,8 @@
|
||||
import EllipsisHorizontal from '$lib/components/icons/EllipsisHorizontal.svelte';
|
||||
import EyeSlash from '$lib/components/icons/EyeSlash.svelte';
|
||||
import Eye from '$lib/components/icons/Eye.svelte';
|
||||
import CheckCircle from '$lib/components/icons/CheckCircle.svelte';
|
||||
import Minus from '$lib/components/icons/Minus.svelte';
|
||||
import { WEBUI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';
|
||||
import { goto } from '$app/navigation';
|
||||
import { DropdownMenu } from 'bits-ui';
|
||||
@@ -69,6 +71,12 @@
|
||||
const perPage = 30;
|
||||
let currentPage = 1;
|
||||
|
||||
const isPublicModel = (model) => {
|
||||
return (model?.access_grants ?? []).some(
|
||||
(g) => g.principal_type === 'user' && g.principal_id === '*' && g.permission === 'read'
|
||||
);
|
||||
};
|
||||
|
||||
$: if (models) {
|
||||
filteredModels = models
|
||||
.filter((m) => searchValue === '' || m.name.toLowerCase().includes(searchValue.toLowerCase()))
|
||||
@@ -77,6 +85,8 @@
|
||||
if (viewOption === 'disabled') return !(m?.is_active ?? true);
|
||||
if (viewOption === 'visible') return !(m?.meta?.hidden ?? false);
|
||||
if (viewOption === 'hidden') return m?.meta?.hidden === true;
|
||||
if (viewOption === 'public') return isPublicModel(m);
|
||||
if (viewOption === 'private') return !isPublicModel(m);
|
||||
return true; // All
|
||||
})
|
||||
.sort((a, b) => {
|
||||
@@ -110,6 +120,30 @@
|
||||
);
|
||||
};
|
||||
|
||||
const showAllHandler = async () => {
|
||||
const modelsToShow = filteredModels.filter((m) => m?.meta?.hidden === true);
|
||||
// Optimistic UI update
|
||||
modelsToShow.forEach((m) => {
|
||||
m.meta = { ...m.meta, hidden: false };
|
||||
});
|
||||
models = models;
|
||||
// Sync with server
|
||||
await Promise.all(modelsToShow.map((model) => upsertModelHandler(model, false)));
|
||||
toast.success($i18n.t('All models are now visible'));
|
||||
};
|
||||
|
||||
const hideAllHandler = async () => {
|
||||
const modelsToHide = filteredModels.filter((m) => !(m?.meta?.hidden ?? false));
|
||||
// Optimistic UI update
|
||||
modelsToHide.forEach((m) => {
|
||||
m.meta = { ...m.meta, hidden: true };
|
||||
});
|
||||
models = models;
|
||||
// Sync with server
|
||||
await Promise.all(modelsToHide.map((model) => upsertModelHandler(model, false)));
|
||||
toast.success($i18n.t('All models are now hidden'));
|
||||
};
|
||||
|
||||
const downloadModels = async (models) => {
|
||||
let blob = new Blob([JSON.stringify(models)], {
|
||||
type: 'application/json'
|
||||
@@ -143,7 +177,7 @@
|
||||
});
|
||||
};
|
||||
|
||||
const upsertModelHandler = async (model) => {
|
||||
const upsertModelHandler = async (model, showToast = true) => {
|
||||
model.base_model_id = null;
|
||||
|
||||
if (workspaceModels.find((m) => m.id === model.id)) {
|
||||
@@ -151,7 +185,7 @@
|
||||
return null;
|
||||
});
|
||||
|
||||
if (res) {
|
||||
if (res && showToast) {
|
||||
toast.success($i18n.t('Model updated successfully'));
|
||||
}
|
||||
} else {
|
||||
@@ -167,7 +201,7 @@
|
||||
return null;
|
||||
});
|
||||
|
||||
if (res) {
|
||||
if (res && !silent) {
|
||||
toast.success($i18n.t('Model updated successfully'));
|
||||
}
|
||||
}
|
||||
@@ -215,6 +249,8 @@
|
||||
|
||||
console.debug(model);
|
||||
|
||||
upsertModelHandler(model, false);
|
||||
|
||||
toast.success(
|
||||
model.meta.hidden
|
||||
? $i18n.t(`Model {{name}} is now hidden`, {
|
||||
@@ -224,8 +260,6 @@
|
||||
name: model.id
|
||||
})
|
||||
);
|
||||
|
||||
upsertModelHandler(model);
|
||||
};
|
||||
|
||||
const copyLinkHandler = async (model) => {
|
||||
@@ -474,7 +508,7 @@
|
||||
enableAllHandler();
|
||||
}}
|
||||
>
|
||||
<Eye className="size-4" />
|
||||
<CheckCircle className="size-4" />
|
||||
<div class="flex items-center">{$i18n.t('Enable All')}</div>
|
||||
</DropdownMenu.Item>
|
||||
|
||||
@@ -484,9 +518,31 @@
|
||||
disableAllHandler();
|
||||
}}
|
||||
>
|
||||
<EyeSlash className="size-4" />
|
||||
<Minus className="size-4" />
|
||||
<div class="flex items-center">{$i18n.t('Disable All')}</div>
|
||||
</DropdownMenu.Item>
|
||||
|
||||
<hr class="border-gray-100 dark:border-gray-800 my-1" />
|
||||
|
||||
<DropdownMenu.Item
|
||||
class="select-none flex gap-2 items-center px-3 py-1.5 text-sm font-medium cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-md"
|
||||
on:click={() => {
|
||||
showAllHandler();
|
||||
}}
|
||||
>
|
||||
<Eye className="size-4" />
|
||||
<div class="flex items-center">{$i18n.t('Show All')}</div>
|
||||
</DropdownMenu.Item>
|
||||
|
||||
<DropdownMenu.Item
|
||||
class="select-none flex gap-2 items-center px-3 py-1.5 text-sm font-medium cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-md"
|
||||
on:click={() => {
|
||||
hideAllHandler();
|
||||
}}
|
||||
>
|
||||
<EyeSlash className="size-4" />
|
||||
<div class="flex items-center">{$i18n.t('Hide All')}</div>
|
||||
</DropdownMenu.Item>
|
||||
</DropdownMenu.Content>
|
||||
</div>
|
||||
</Dropdown>
|
||||
|
||||
@@ -16,7 +16,9 @@
|
||||
{ value: 'enabled', label: $i18n.t('Enabled') },
|
||||
{ value: 'disabled', label: $i18n.t('Disabled') },
|
||||
{ value: 'visible', label: $i18n.t('Visible') },
|
||||
{ value: 'hidden', label: $i18n.t('Hidden') }
|
||||
{ value: 'hidden', label: $i18n.t('Hidden') },
|
||||
{ value: 'public', label: $i18n.t('Public') },
|
||||
{ value: 'private', label: $i18n.t('Private') }
|
||||
];
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import Sortable from 'sortablejs';
|
||||
|
||||
import { createEventDispatcher, getContext, onMount } from 'svelte';
|
||||
import { createEventDispatcher, getContext, onDestroy, onMount, tick } from 'svelte';
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import { models } from '$lib/stores';
|
||||
@@ -14,20 +14,27 @@
|
||||
let modelListElement = null;
|
||||
|
||||
const positionChangeHandler = () => {
|
||||
const modelList = Array.from(modelListElement.children).map((child) =>
|
||||
// Read new order from DOM
|
||||
const newOrder = Array.from(modelListElement.children).map((child) =>
|
||||
child.id.replace('model-item-', '')
|
||||
);
|
||||
|
||||
modelIds = modelList;
|
||||
// Revert SortableJS DOM manipulation so Svelte stays in control of the DOM
|
||||
if (sortable) {
|
||||
sortable.sort(
|
||||
modelIds.map((id) => `model-item-${id}`),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
// Update reactive data — Svelte will re-render with the new order
|
||||
modelIds = newOrder;
|
||||
};
|
||||
|
||||
$: if (modelIds) {
|
||||
init();
|
||||
}
|
||||
|
||||
const init = () => {
|
||||
const initSortable = () => {
|
||||
if (sortable) {
|
||||
sortable.destroy();
|
||||
sortable = null;
|
||||
}
|
||||
|
||||
if (modelListElement) {
|
||||
@@ -40,11 +47,24 @@
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
// Wait a tick for the {#if} block to render and bind modelListElement
|
||||
tick().then(() => {
|
||||
initSortable();
|
||||
});
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (sortable) {
|
||||
sortable.destroy();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if modelIds.length > 0}
|
||||
<div class="flex flex-col -translate-x-1" bind:this={modelListElement}>
|
||||
{#each modelIds as modelId, modelIdx (`${modelId}-${modelIdx}`)}
|
||||
{#each modelIds as modelId (modelId)}
|
||||
<div class=" flex gap-2 w-full justify-between items-center" id="model-item-{modelId}">
|
||||
<Tooltip content={modelId} placement="top-start">
|
||||
<div class="flex items-center gap-1">
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { createEventDispatcher, onMount, getContext, tick } from 'svelte';
|
||||
import { getModels as _getModels } from '$lib/apis';
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import { models, settings, user } from '$lib/stores';
|
||||
|
||||
import Switch from '$lib/components/common/Switch.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import Connection from '$lib/components/chat/Settings/Tools/Connection.svelte';
|
||||
|
||||
import AddToolServerModal from '$lib/components/AddToolServerModal.svelte';
|
||||
import { getToolServerConnections, setToolServerConnections } from '$lib/apis/configs';
|
||||
|
||||
export let saveSettings: Function;
|
||||
|
||||
let servers = null;
|
||||
let showConnectionModal = false;
|
||||
|
||||
const addConnectionHandler = async (server) => {
|
||||
servers = [...servers, server];
|
||||
await updateHandler();
|
||||
};
|
||||
|
||||
const updateHandler = async () => {
|
||||
const res = await setToolServerConnections(localStorage.token, {
|
||||
TOOL_SERVER_CONNECTIONS: servers
|
||||
}).catch((err) => {
|
||||
toast.error($i18n.t('Failed to save connections'));
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
if (res) {
|
||||
toast.success($i18n.t('Connections saved successfully'));
|
||||
}
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
const res = await getToolServerConnections(localStorage.token);
|
||||
servers = res.TOOL_SERVER_CONNECTIONS;
|
||||
});
|
||||
</script>
|
||||
|
||||
<AddToolServerModal bind:show={showConnectionModal} onSubmit={addConnectionHandler} />
|
||||
|
||||
<form
|
||||
class="flex flex-col h-full justify-between text-sm"
|
||||
on:submit|preventDefault={() => {
|
||||
updateHandler();
|
||||
}}
|
||||
>
|
||||
<div class=" overflow-y-scroll scrollbar-hidden h-full">
|
||||
{#if servers !== null}
|
||||
<div class="">
|
||||
<div class="mb-3">
|
||||
<div class=" mt-0.5 mb-2.5 text-base font-medium">{$i18n.t('General')}</div>
|
||||
|
||||
<hr class=" border-gray-100/30 dark:border-gray-850/30 my-2" />
|
||||
|
||||
<div class="mb-2.5 flex flex-col w-full justify-between">
|
||||
<!-- {$i18n.t(`Failed to connect to {{URL}} OpenAPI tool server`, {
|
||||
URL: 'server?.url'
|
||||
})} -->
|
||||
<div class="flex justify-between items-center mb-0.5">
|
||||
<div class="font-medium">{$i18n.t('Manage Tool Servers')}</div>
|
||||
|
||||
<Tooltip content={$i18n.t(`Add Connection`)}>
|
||||
<button
|
||||
class="px-1"
|
||||
on:click={() => {
|
||||
showConnectionModal = true;
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<Plus />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
{#each servers as server, idx}
|
||||
<Connection
|
||||
bind:connection={server}
|
||||
onSubmit={() => {
|
||||
updateHandler();
|
||||
}}
|
||||
onDelete={() => {
|
||||
servers = servers.filter((_, i) => i !== idx);
|
||||
updateHandler();
|
||||
}}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="my-1.5">
|
||||
<div class="text-xs text-gray-500">
|
||||
{$i18n.t('Connect to your own OpenAPI compatible external tool servers.')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- <div class="mb-2.5 flex w-full justify-between">
|
||||
<div class=" text-xs font-medium">{$i18n.t('Arena Models')}</div>
|
||||
|
||||
<Tooltip content={$i18n.t(`Message rating should be enabled to use this feature`)}>
|
||||
<Switch bind:state={evaluationConfig.ENABLE_EVALUATION_ARENA_MODELS} />
|
||||
</Tooltip>
|
||||
</div> -->
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex h-full justify-center">
|
||||
<div class="my-auto">
|
||||
<Spinner className="size-6" />
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end pt-3 text-sm font-medium">
|
||||
<button
|
||||
class="px-3.5 py-1.5 text-sm font-medium bg-black hover:bg-gray-900 text-white dark:bg-white dark:text-black dark:hover:bg-gray-100 transition rounded-full"
|
||||
type="submit"
|
||||
>
|
||||
{$i18n.t('Save')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -64,6 +64,7 @@
|
||||
permissions = {
|
||||
workspace: { ...DEFAULT_PERMISSIONS.workspace, ...loadedPermissions.workspace },
|
||||
sharing: { ...DEFAULT_PERMISSIONS.sharing, ...loadedPermissions.sharing },
|
||||
access_grants: { ...DEFAULT_PERMISSIONS.access_grants, ...loadedPermissions.access_grants },
|
||||
chat: { ...DEFAULT_PERMISSIONS.chat, ...loadedPermissions.chat },
|
||||
features: { ...DEFAULT_PERMISSIONS.features, ...loadedPermissions.features },
|
||||
settings: { ...DEFAULT_PERMISSIONS.settings, ...loadedPermissions.settings }
|
||||
|
||||
@@ -78,7 +78,7 @@
|
||||
<div class="flex items-center gap-2 p-1">
|
||||
<select
|
||||
class="text-sm bg-transparent outline-hidden rounded-lg px-2"
|
||||
value={data?.config?.share ?? true}
|
||||
value={data?.config?.share ?? 'members'}
|
||||
on:change={(e) => {
|
||||
const value = e.target.value;
|
||||
let shareValue;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
...obj,
|
||||
workspace: { ...defaults.workspace, ...obj.workspace },
|
||||
sharing: { ...defaults.sharing, ...obj.sharing },
|
||||
access_grants: { ...defaults.access_grants, ...obj.access_grants },
|
||||
chat: { ...defaults.chat, ...obj.chat },
|
||||
features: { ...defaults.features, ...obj.features },
|
||||
settings: { ...defaults.settings, ...obj.settings }
|
||||
@@ -395,6 +396,28 @@
|
||||
|
||||
<hr class=" border-gray-100/30 dark:border-gray-850/30" />
|
||||
|
||||
<div>
|
||||
<div class=" mb-2 text-sm font-medium">{$i18n.t('Access Grants')}</div>
|
||||
|
||||
<div class="flex flex-col w-full">
|
||||
<div class="flex w-full justify-between my-1">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Allow Sharing With Users')}
|
||||
</div>
|
||||
<Switch bind:state={permissions.access_grants.allow_users} />
|
||||
</div>
|
||||
{#if defaultPermissions?.access_grants?.allow_users && !permissions.access_grants.allow_users}
|
||||
<div>
|
||||
<div class="text-xs text-gray-500">
|
||||
{$i18n.t('This is a default user permission and will remain enabled.')}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class=" border-gray-100/30 dark:border-gray-850/30" />
|
||||
|
||||
<div>
|
||||
<div class=" mb-2 text-sm font-medium">{$i18n.t('Chat Permissions')}</div>
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { tick, getContext, onMount, onDestroy } from 'svelte';
|
||||
import { tick, getContext, onMount } from 'svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
@@ -510,7 +510,7 @@
|
||||
}
|
||||
};
|
||||
|
||||
const onDragOver = (e) => {
|
||||
const onDragOver = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Check if a file is being draggedOver.
|
||||
@@ -525,7 +525,7 @@
|
||||
draggedOver = false;
|
||||
};
|
||||
|
||||
const onDrop = async (e) => {
|
||||
const onDrop = async (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (e.dataTransfer?.files && acceptFiles) {
|
||||
@@ -567,7 +567,7 @@
|
||||
onChange();
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
onMount(() => {
|
||||
suggestions = [
|
||||
{
|
||||
char: '@',
|
||||
@@ -633,25 +633,33 @@
|
||||
}, 100);
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
await tick();
|
||||
|
||||
const dropzoneElement = document.getElementById('channel-container');
|
||||
let isDestroyed = false;
|
||||
let dropzoneElement: HTMLElement | null = null;
|
||||
const initialize = async () => {
|
||||
await tick();
|
||||
if (isDestroyed) return;
|
||||
|
||||
dropzoneElement?.addEventListener('dragover', onDragOver);
|
||||
dropzoneElement?.addEventListener('drop', onDrop);
|
||||
dropzoneElement?.addEventListener('dragleave', onDragLeave);
|
||||
});
|
||||
dropzoneElement = document.getElementById('channel-container');
|
||||
if (dropzoneElement) {
|
||||
dropzoneElement.addEventListener('dragover', onDragOver);
|
||||
dropzoneElement.addEventListener('drop', onDrop);
|
||||
dropzoneElement.addEventListener('dragleave', onDragLeave);
|
||||
}
|
||||
};
|
||||
initialize();
|
||||
|
||||
onDestroy(() => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
isDestroyed = true;
|
||||
|
||||
const dropzoneElement = document.getElementById('channel-container');
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
|
||||
if (dropzoneElement) {
|
||||
dropzoneElement?.removeEventListener('dragover', onDragOver);
|
||||
dropzoneElement?.removeEventListener('drop', onDrop);
|
||||
dropzoneElement?.removeEventListener('dragleave', onDragLeave);
|
||||
}
|
||||
if (dropzoneElement) {
|
||||
dropzoneElement.removeEventListener('dragover', onDragOver);
|
||||
dropzoneElement.removeEventListener('drop', onDrop);
|
||||
dropzoneElement.removeEventListener('dragleave', onDragLeave);
|
||||
}
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -98,16 +98,17 @@
|
||||
return onKeyDown(event);
|
||||
}
|
||||
|
||||
const keydownListener = (e) => {
|
||||
// required to prevent the default enter behavior
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
select(selectedIndex);
|
||||
}
|
||||
};
|
||||
onMount(() => {
|
||||
const keydownListener = (e: KeyboardEvent) => {
|
||||
// required to prevent the default enter behavior
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
select(selectedIndex);
|
||||
}
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
window.addEventListener('keydown', keydownListener);
|
||||
|
||||
if (channelSuggestions) {
|
||||
// Add a dummy channel item
|
||||
_channels = [
|
||||
@@ -117,17 +118,17 @@
|
||||
];
|
||||
} else {
|
||||
if (userSuggestions) {
|
||||
await getUserList();
|
||||
getUserList();
|
||||
}
|
||||
|
||||
if (modelSuggestions) {
|
||||
_models = [...$models.map((m) => ({ type: 'model', id: m.id, label: m.name, data: m }))];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
window.removeEventListener('keydown', keydownListener);
|
||||
return () => {
|
||||
window.removeEventListener('keydown', keydownListener);
|
||||
};
|
||||
});
|
||||
|
||||
const hasPublicReadGrant = (grants: any) =>
|
||||
|
||||
@@ -33,18 +33,23 @@
|
||||
currentChatPage,
|
||||
temporaryChatEnabled,
|
||||
mobile,
|
||||
showOverview,
|
||||
chatTitle,
|
||||
showArtifacts,
|
||||
artifactContents,
|
||||
tools,
|
||||
toolServers,
|
||||
terminalServers,
|
||||
functions,
|
||||
selectedFolder,
|
||||
pinnedChats,
|
||||
showEmbeds
|
||||
showEmbeds,
|
||||
selectedTerminalId,
|
||||
showFileNavPath,
|
||||
showFileNavDir
|
||||
} from '$lib/stores';
|
||||
|
||||
import { WEBUI_API_BASE_URL } from '$lib/constants';
|
||||
|
||||
import {
|
||||
convertMessagesToHistory,
|
||||
copyToClipboard,
|
||||
@@ -54,7 +59,8 @@
|
||||
processDetails,
|
||||
removeAllDetails,
|
||||
getCodeBlockContents,
|
||||
isYoutubeUrl
|
||||
isYoutubeUrl,
|
||||
displayFileHandler
|
||||
} from '$lib/utils';
|
||||
import { AudioQueue } from '$lib/utils/audio';
|
||||
|
||||
@@ -92,6 +98,7 @@
|
||||
import ChatControls from './ChatControls.svelte';
|
||||
import EventConfirmDialog from '../common/ConfirmDialog.svelte';
|
||||
import Placeholder from './Placeholder.svelte';
|
||||
import FilesOverlay from './MessageInput/FilesOverlay.svelte';
|
||||
import NotificationToast from '../NotificationToast.svelte';
|
||||
import Spinner from '../common/Spinner.svelte';
|
||||
import Tooltip from '../common/Tooltip.svelte';
|
||||
@@ -103,10 +110,10 @@
|
||||
let loading = true;
|
||||
|
||||
const eventTarget = new EventTarget();
|
||||
let controlPane;
|
||||
let controlPaneComponent;
|
||||
let controlPane: Pane | undefined;
|
||||
let controlPaneComponent: ChatControls | undefined;
|
||||
|
||||
let messageInput;
|
||||
let messageInput: MessageInput | undefined;
|
||||
|
||||
let autoScroll = true;
|
||||
let processing = '';
|
||||
@@ -123,8 +130,6 @@
|
||||
let eventConfirmationInputType = '';
|
||||
let eventCallback = null;
|
||||
|
||||
let chatIdUnsubscriber: Unsubscriber | undefined;
|
||||
|
||||
let selectedModels = [''];
|
||||
let atSelectedModel: Model | undefined;
|
||||
let selectedModelIds = [];
|
||||
@@ -136,13 +141,43 @@
|
||||
|
||||
let selectedToolIds = [];
|
||||
let selectedFilterIds = [];
|
||||
|
||||
let imageGenerationEnabled = false;
|
||||
let webSearchEnabled = false;
|
||||
let codeInterpreterEnabled = false;
|
||||
|
||||
// Auto-inject direct terminal servers into selected tool IDs so they act like toggled-on tools
|
||||
// System terminals (with id field) are handled server-side via terminal_id, not as direct tool servers
|
||||
$: if ($terminalServers && $terminalServers.length > 0) {
|
||||
const directTerminalServers = $terminalServers.filter((t) => !t.id);
|
||||
const terminalIds = directTerminalServers.map(
|
||||
(_, i) => `direct_server:terminal_${$terminalServers.indexOf(directTerminalServers[i])}`
|
||||
);
|
||||
const missingIds = terminalIds.filter((id) => !selectedToolIds.includes(id));
|
||||
if (missingIds.length > 0) {
|
||||
selectedToolIds = [...selectedToolIds, ...missingIds];
|
||||
}
|
||||
}
|
||||
|
||||
// Remove disabled terminal servers from selectedToolIds automatically
|
||||
$: if (selectedToolIds.length > 0) {
|
||||
const directTerminalServers = ($terminalServers ?? []).filter((t) => !t.id);
|
||||
const terminalIds = directTerminalServers.map(
|
||||
(_, i) =>
|
||||
`direct_server:terminal_${($terminalServers ?? []).indexOf(directTerminalServers[i])}`
|
||||
);
|
||||
const invalidTerminalIds = selectedToolIds.filter(
|
||||
(id) => id.startsWith('direct_server:terminal_') && !terminalIds.includes(id)
|
||||
);
|
||||
if (invalidTerminalIds.length > 0) {
|
||||
selectedToolIds = selectedToolIds.filter((id) => !invalidTerminalIds.includes(id));
|
||||
}
|
||||
}
|
||||
|
||||
let showCommands = false;
|
||||
|
||||
let generating = false;
|
||||
let dragged = false;
|
||||
let generationController = null;
|
||||
|
||||
let chat = null;
|
||||
@@ -284,7 +319,7 @@
|
||||
|
||||
const onSelectedModelIdsChange = () => {
|
||||
resetInput();
|
||||
oldSelectedModelIds = JSON.parse(JSON.stringify(selectedModelIds));
|
||||
oldSelectedModelIds = structuredClone(selectedModelIds);
|
||||
};
|
||||
|
||||
const resetInput = () => {
|
||||
@@ -319,6 +354,23 @@
|
||||
[...(model?.info?.meta?.toolIds ?? [])].filter((id) => $tools.find((t) => t.id === id))
|
||||
)
|
||||
];
|
||||
} else if (
|
||||
$settings?.tools &&
|
||||
$settings.tools.some((id) => !id.startsWith('direct_server:terminal_'))
|
||||
) {
|
||||
selectedToolIds = $settings.tools;
|
||||
} else {
|
||||
// Don't wipe existing terminal servers if no default tool IDs
|
||||
selectedToolIds = selectedToolIds.filter((id) => !id.startsWith('direct_server:'));
|
||||
}
|
||||
|
||||
// Auto-inject direct terminal servers (system ones are handled via terminal_id)
|
||||
if ($terminalServers && $terminalServers.length > 0) {
|
||||
const directTerminalServers = $terminalServers.filter((t) => !t.id);
|
||||
const terminalIds = directTerminalServers.map(
|
||||
(_, i) => `direct_server:terminal_${$terminalServers.indexOf(directTerminalServers[i])}`
|
||||
);
|
||||
selectedToolIds = [...new Set([...selectedToolIds, ...terminalIds])];
|
||||
}
|
||||
|
||||
// Set Default Filters (Toggleable only)
|
||||
@@ -393,6 +445,15 @@
|
||||
saveChatHandler(_chatId, history);
|
||||
};
|
||||
|
||||
const terminalEventHandler = (type: string, data: any) => {
|
||||
if (!data?.path) return;
|
||||
if (type === 'terminal:display_file') {
|
||||
displayFileHandler(data.path, { showControls, showFileNavPath });
|
||||
} else if (type === 'terminal:write_file') {
|
||||
showFileNavDir.set(data.path);
|
||||
}
|
||||
};
|
||||
|
||||
const chatEventHandler = async (event, cb) => {
|
||||
console.log(event);
|
||||
|
||||
@@ -526,6 +587,8 @@
|
||||
eventConfirmationInputPlaceholder = data.placeholder;
|
||||
eventConfirmationInputValue = data?.value ?? '';
|
||||
eventConfirmationInputType = data?.type ?? '';
|
||||
} else if (type.startsWith('terminal:')) {
|
||||
terminalEventHandler(type, data);
|
||||
} else {
|
||||
console.log('Unknown message type', data);
|
||||
}
|
||||
@@ -592,26 +655,33 @@
|
||||
savedModelIds();
|
||||
}
|
||||
|
||||
let pageSubscribe = null;
|
||||
let showControlsSubscribe = null;
|
||||
let selectedFolderSubscribe = null;
|
||||
|
||||
const stopAudio = () => {
|
||||
try {
|
||||
speechSynthesis.cancel();
|
||||
$audioQueue.stop();
|
||||
$audioQueue?.stop();
|
||||
} catch {}
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
onMount(() => {
|
||||
loading = true;
|
||||
console.log('mounted');
|
||||
window.addEventListener('message', onMessageHandler);
|
||||
$socket?.on('events', chatEventHandler);
|
||||
|
||||
audioQueue.set(new AudioQueue(document.getElementById('audioElement')));
|
||||
$audioQueue?.destroy();
|
||||
|
||||
pageSubscribe = page.subscribe(async (p) => {
|
||||
const audioQueueInstance = new AudioQueue(document.getElementById('audioElement'));
|
||||
audioQueue.set(audioQueueInstance);
|
||||
|
||||
// Reset direct terminal enabled states — selectedTerminalId starts null on every page load
|
||||
if ($settings?.terminalServers?.some((s) => s.enabled)) {
|
||||
settings.set({
|
||||
...$settings,
|
||||
terminalServers: ($settings.terminalServers ?? []).map((s) => ({ ...s, enabled: false }))
|
||||
});
|
||||
}
|
||||
|
||||
const pageSubscribe = page.subscribe(async (p) => {
|
||||
if (p.url.pathname === '/') {
|
||||
await tick();
|
||||
initNewChat();
|
||||
@@ -620,46 +690,12 @@
|
||||
stopAudio();
|
||||
});
|
||||
|
||||
const storageChatInput = sessionStorage.getItem(
|
||||
`chat-input${chatIdProp ? `-${chatIdProp}` : ''}`
|
||||
);
|
||||
|
||||
if (!chatIdProp) {
|
||||
loading = false;
|
||||
const showControlsSubscribe = showControls.subscribe(async (value) => {
|
||||
await tick();
|
||||
}
|
||||
|
||||
if (storageChatInput) {
|
||||
prompt = '';
|
||||
messageInput?.setText('');
|
||||
|
||||
files = [];
|
||||
selectedToolIds = [];
|
||||
selectedFilterIds = [];
|
||||
webSearchEnabled = false;
|
||||
imageGenerationEnabled = false;
|
||||
codeInterpreterEnabled = false;
|
||||
|
||||
try {
|
||||
const input = JSON.parse(storageChatInput);
|
||||
|
||||
if (!$temporaryChatEnabled) {
|
||||
messageInput?.setText(input.prompt);
|
||||
files = input.files;
|
||||
selectedToolIds = input.selectedToolIds;
|
||||
selectedFilterIds = input.selectedFilterIds;
|
||||
webSearchEnabled = input.webSearchEnabled;
|
||||
imageGenerationEnabled = input.imageGenerationEnabled;
|
||||
codeInterpreterEnabled = input.codeInterpreterEnabled;
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
showControlsSubscribe = showControls.subscribe(async (value) => {
|
||||
if (controlPane && !$mobile) {
|
||||
try {
|
||||
if (value) {
|
||||
controlPaneComponent.openPane();
|
||||
controlPaneComponent?.openPane();
|
||||
} else {
|
||||
controlPane.collapse();
|
||||
}
|
||||
@@ -670,13 +706,13 @@
|
||||
|
||||
if (!value) {
|
||||
showCallOverlay.set(false);
|
||||
showOverview.set(false);
|
||||
showArtifacts.set(false);
|
||||
showEmbeds.set(false);
|
||||
}
|
||||
});
|
||||
|
||||
selectedFolderSubscribe = selectedFolder.subscribe(async (folder) => {
|
||||
const selectedFolderSubscribe = selectedFolder.subscribe(async (folder) => {
|
||||
await tick();
|
||||
if (
|
||||
folder?.data?.model_ids &&
|
||||
JSON.stringify(selectedModels) !== JSON.stringify(folder.data.model_ids)
|
||||
@@ -687,22 +723,60 @@
|
||||
}
|
||||
});
|
||||
|
||||
const chatInput = document.getElementById('chat-input');
|
||||
chatInput?.focus();
|
||||
});
|
||||
const storageChatInput = sessionStorage.getItem(
|
||||
`chat-input${chatIdProp ? `-${chatIdProp}` : ''}`
|
||||
);
|
||||
|
||||
onDestroy(() => {
|
||||
try {
|
||||
pageSubscribe();
|
||||
showControlsSubscribe();
|
||||
selectedFolderSubscribe();
|
||||
chatIdUnsubscriber?.();
|
||||
window.removeEventListener('message', onMessageHandler);
|
||||
$socket?.off('events', chatEventHandler);
|
||||
$audioQueue?.destroy();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
const init = async () => {
|
||||
if (!chatIdProp) {
|
||||
loading = false;
|
||||
await tick();
|
||||
}
|
||||
|
||||
if (storageChatInput) {
|
||||
prompt = '';
|
||||
messageInput?.setText('');
|
||||
|
||||
files = [];
|
||||
selectedToolIds = [];
|
||||
selectedFilterIds = [];
|
||||
webSearchEnabled = false;
|
||||
imageGenerationEnabled = false;
|
||||
codeInterpreterEnabled = false;
|
||||
|
||||
try {
|
||||
const input = JSON.parse(storageChatInput);
|
||||
|
||||
if (!$temporaryChatEnabled) {
|
||||
messageInput?.setText(input.prompt);
|
||||
files = input.files;
|
||||
selectedToolIds = input.selectedToolIds;
|
||||
selectedFilterIds = input.selectedFilterIds;
|
||||
webSearchEnabled = input.webSearchEnabled;
|
||||
imageGenerationEnabled = input.imageGenerationEnabled;
|
||||
codeInterpreterEnabled = input.codeInterpreterEnabled;
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
const chatInput = document.getElementById('chat-input');
|
||||
chatInput?.focus();
|
||||
};
|
||||
init();
|
||||
|
||||
return () => {
|
||||
try {
|
||||
pageSubscribe();
|
||||
showControlsSubscribe();
|
||||
selectedFolderSubscribe();
|
||||
window.removeEventListener('message', onMessageHandler);
|
||||
$socket?.off('events', chatEventHandler);
|
||||
audioQueueInstance?.destroy();
|
||||
audioQueue.set(null);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// File upload functions
|
||||
@@ -890,7 +964,11 @@
|
||||
};
|
||||
|
||||
$: if (history) {
|
||||
getContents();
|
||||
cancelAnimationFrame(contentsRAF);
|
||||
contentsRAF = requestAnimationFrame(() => {
|
||||
getContents();
|
||||
contentsRAF = null;
|
||||
});
|
||||
} else {
|
||||
artifactContents.set([]);
|
||||
}
|
||||
@@ -1053,9 +1131,10 @@
|
||||
}
|
||||
}
|
||||
|
||||
await showControls.set(false);
|
||||
if ($mobile) {
|
||||
await showControls.set(false);
|
||||
}
|
||||
await showCallOverlay.set(false);
|
||||
await showOverview.set(false);
|
||||
await showArtifacts.set(false);
|
||||
|
||||
if ($page.url.pathname.includes('/c/')) {
|
||||
@@ -1168,7 +1247,7 @@
|
||||
selectedModels = selectedModels.length > 0 ? [selectedModels[0]] : [''];
|
||||
}
|
||||
|
||||
oldSelectedModelIds = JSON.parse(JSON.stringify(selectedModels));
|
||||
oldSelectedModelIds = structuredClone(selectedModels);
|
||||
|
||||
history =
|
||||
(chatContent?.history ?? undefined) !== undefined
|
||||
@@ -1217,6 +1296,17 @@
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let scrollRAF = null;
|
||||
let contentsRAF = null;
|
||||
const scheduleScrollToBottom = () => {
|
||||
if (!scrollRAF) {
|
||||
scrollRAF = requestAnimationFrame(async () => {
|
||||
scrollRAF = null;
|
||||
await scrollToBottom();
|
||||
});
|
||||
}
|
||||
};
|
||||
const chatCompletedHandler = async (_chatId, modelId, responseMessageId, messages) => {
|
||||
const res = await chatCompleted(localStorage.token, {
|
||||
model: modelId,
|
||||
@@ -1634,7 +1724,7 @@
|
||||
await tick();
|
||||
|
||||
if (autoScroll) {
|
||||
scrollToBottom();
|
||||
scheduleScrollToBottom();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1688,7 +1778,7 @@
|
||||
if (taskIds !== null && taskIds.length > 0) {
|
||||
if ($settings?.enableMessageQueue ?? true) {
|
||||
// Queue the message
|
||||
const _files = JSON.parse(JSON.stringify(files));
|
||||
const _files = structuredClone(files);
|
||||
messageQueue = [
|
||||
...messageQueue,
|
||||
{
|
||||
@@ -1723,7 +1813,7 @@
|
||||
prompt = '';
|
||||
|
||||
const messages = createMessagesList(history, history.currentId);
|
||||
const _files = JSON.parse(JSON.stringify(files));
|
||||
const _files = structuredClone(files);
|
||||
|
||||
chatFiles.push(
|
||||
..._files.filter(
|
||||
@@ -1792,7 +1882,7 @@
|
||||
}
|
||||
|
||||
let _chatId = JSON.parse(JSON.stringify($chatId));
|
||||
_history = JSON.parse(JSON.stringify(_history));
|
||||
_history = structuredClone(_history);
|
||||
|
||||
const responseMessageIds: Record<PropertyKey, string> = {};
|
||||
// If modelId is provided, use it, else use selected model
|
||||
@@ -1845,7 +1935,7 @@
|
||||
|
||||
await tick();
|
||||
|
||||
_history = JSON.parse(JSON.stringify(history));
|
||||
_history = structuredClone(history);
|
||||
// Save chat after all messages have been created
|
||||
await saveChatHandler(_chatId, _history);
|
||||
|
||||
@@ -1956,7 +2046,7 @@
|
||||
return fileExists;
|
||||
});
|
||||
|
||||
let files = JSON.parse(JSON.stringify(chatFiles));
|
||||
let files = structuredClone(chatFiles);
|
||||
files.push(
|
||||
...(userMessage?.files ?? []).filter(
|
||||
(item) =>
|
||||
@@ -2091,6 +2181,9 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Use the user-selected terminal from the dropdown
|
||||
const activeTerminalId = $selectedTerminalId ?? null;
|
||||
|
||||
const res = await generateOpenAIChatCompletion(
|
||||
localStorage.token,
|
||||
{
|
||||
@@ -2113,9 +2206,12 @@
|
||||
filter_ids: selectedFilterIds.length > 0 ? selectedFilterIds : undefined,
|
||||
tool_ids: toolIds.length > 0 ? toolIds : undefined,
|
||||
skill_ids: skillIds.length > 0 ? skillIds : undefined,
|
||||
tool_servers: ($toolServers ?? []).filter(
|
||||
(server, idx) => toolServerIds.includes(idx) || toolServerIds.includes(server?.id)
|
||||
),
|
||||
terminal_id: activeTerminalId ?? undefined,
|
||||
tool_servers: [
|
||||
...($toolServers ?? []).filter(
|
||||
(server, idx) => toolServerIds.includes(idx) || toolServerIds.includes(server?.id)
|
||||
)
|
||||
],
|
||||
features: getFeatures(),
|
||||
variables: {
|
||||
...getPromptVariables(
|
||||
@@ -2412,7 +2508,7 @@
|
||||
}
|
||||
|
||||
if (autoScroll) {
|
||||
scrollToBottom();
|
||||
scheduleScrollToBottom();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2591,6 +2687,7 @@
|
||||
|
||||
<PaneGroup direction="horizontal" class="w-full h-full">
|
||||
<Pane defaultSize={50} minSize={30} class="h-full flex relative max-w-full flex-col">
|
||||
<FilesOverlay show={dragged} />
|
||||
<Navbar
|
||||
bind:this={navbarElement}
|
||||
chat={{
|
||||
@@ -2627,6 +2724,7 @@
|
||||
id: uuidv4(),
|
||||
title: title.length > 50 ? `${title.slice(0, 50)}...` : title,
|
||||
models: selectedModels,
|
||||
params: params,
|
||||
history: history,
|
||||
messages: messages,
|
||||
timestamp: Date.now()
|
||||
@@ -2649,7 +2747,7 @@
|
||||
}}
|
||||
/>
|
||||
|
||||
<div class="flex flex-col flex-auto z-10 w-full @container overflow-auto">
|
||||
<div id="chat-pane" class="flex flex-col flex-auto z-10 w-full @container overflow-auto">
|
||||
{#if ($settings?.landingPageMode === 'chat' && !$selectedFolder) || createMessagesList(history, history.currentId).length > 0}
|
||||
<div
|
||||
class=" pb-2.5 flex flex-col justify-between w-full flex-auto overflow-auto h-0 max-w-full z-10 scrollbar-hidden"
|
||||
@@ -2703,6 +2801,7 @@
|
||||
bind:webSearchEnabled
|
||||
bind:atSelectedModel
|
||||
bind:showCommands
|
||||
bind:dragged
|
||||
toolServers={$toolServers}
|
||||
{generating}
|
||||
{stopResponse}
|
||||
@@ -2773,6 +2872,7 @@
|
||||
bind:webSearchEnabled
|
||||
bind:atSelectedModel
|
||||
bind:showCommands
|
||||
bind:dragged
|
||||
toolServers={$toolServers}
|
||||
{stopResponse}
|
||||
{createMessagePair}
|
||||
|
||||
@@ -1,23 +1,39 @@
|
||||
<script context="module">
|
||||
let savedTab: 'controls' | 'files' | 'overview' = 'controls';
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { SvelteFlowProvider } from '@xyflow/svelte';
|
||||
import { slide } from 'svelte/transition';
|
||||
import { Pane, PaneResizer } from 'paneforge';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { onDestroy, onMount, tick } from 'svelte';
|
||||
import { onDestroy, onMount, tick, getContext } from 'svelte';
|
||||
import {
|
||||
terminalServers,
|
||||
mobile,
|
||||
showControls,
|
||||
showCallOverlay,
|
||||
showOverview,
|
||||
showArtifacts,
|
||||
showEmbeds
|
||||
showEmbeds,
|
||||
settings,
|
||||
showFileNavPath,
|
||||
selectedTerminalId,
|
||||
user
|
||||
} from '$lib/stores';
|
||||
|
||||
import { uploadFile } from '$lib/apis/files';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
import Controls from './Controls/Controls.svelte';
|
||||
import CallOverlay from './MessageInput/CallOverlay.svelte';
|
||||
import Drawer from '../common/Drawer.svelte';
|
||||
import Artifacts from './Artifacts.svelte';
|
||||
import Embeds from './ChatControls/Embeds.svelte';
|
||||
import FileNav from './FileNav.svelte';
|
||||
import Overview from './Overview.svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let history;
|
||||
export let models = [];
|
||||
@@ -34,13 +50,88 @@
|
||||
export let files;
|
||||
export let modelId;
|
||||
|
||||
export let pane;
|
||||
export let pane: Pane | null = null;
|
||||
|
||||
let mediaQuery;
|
||||
let largeScreen = false;
|
||||
let dragged = false;
|
||||
|
||||
let minSize = 0;
|
||||
let paneReady = false;
|
||||
|
||||
// Tab state for Controls+Files panel
|
||||
let activeTab: 'controls' | 'files' | 'overview' = savedTab;
|
||||
$: savedTab = activeTab;
|
||||
$: hasMessages = history?.messages && Object.keys(history.messages).length > 0;
|
||||
|
||||
$: showControlsTab = $user?.role === 'admin' || ($user?.permissions?.chat?.controls ?? true);
|
||||
$: showFilesTab = !!$selectedTerminalId;
|
||||
$: showOverviewTab = hasMessages;
|
||||
|
||||
// Tab fallback: if active tab becomes hidden, switch to next available
|
||||
$: if (!showOverviewTab && activeTab === 'overview') activeTab = 'controls';
|
||||
$: if (!showFilesTab && activeTab === 'files') activeTab = 'controls';
|
||||
$: if (!showControlsTab && activeTab === 'controls') {
|
||||
if (showFilesTab) activeTab = 'files';
|
||||
else if (showOverviewTab) activeTab = 'overview';
|
||||
}
|
||||
|
||||
// Auto-close if there are no visible tabs
|
||||
$: if (!showControlsTab && !showFilesTab && !showOverviewTab) {
|
||||
showControls.set(false);
|
||||
}
|
||||
|
||||
// Auto-switch to Files tab when display_file is triggered
|
||||
$: if ($showFileNavPath) {
|
||||
activeTab = 'files';
|
||||
showControls.set(true);
|
||||
}
|
||||
|
||||
// Auto-open Files tab when a terminal is selected
|
||||
$: if ($selectedTerminalId) {
|
||||
activeTab = 'files';
|
||||
showControls.set(true);
|
||||
}
|
||||
|
||||
// Attach a terminal file to the chat input
|
||||
const handleTerminalAttach = async (blob: Blob, name: string, contentType: string) => {
|
||||
const tempItemId = uuidv4();
|
||||
const fileItem = {
|
||||
type: 'file',
|
||||
file: '',
|
||||
id: null,
|
||||
url: '',
|
||||
name,
|
||||
collection_name: '',
|
||||
status: 'uploading',
|
||||
error: '',
|
||||
itemId: tempItemId,
|
||||
size: blob.size
|
||||
};
|
||||
|
||||
files = [...files, fileItem];
|
||||
|
||||
try {
|
||||
const file = new File([blob], name, { type: contentType || 'application/octet-stream' });
|
||||
const uploaded = await uploadFile(localStorage.token, file);
|
||||
if (!uploaded) throw new Error('Upload failed');
|
||||
|
||||
const idx = files.findIndex((f) => f.itemId === tempItemId);
|
||||
if (idx !== -1) {
|
||||
files[idx] = {
|
||||
...fileItem,
|
||||
status: 'uploaded',
|
||||
file: uploaded,
|
||||
id: uploaded.id,
|
||||
url: `${uploaded.id}`,
|
||||
collection_name: uploaded?.meta?.collection_name
|
||||
};
|
||||
files = files;
|
||||
}
|
||||
toast.success($i18n.t('File attached to chat'));
|
||||
} catch (e) {
|
||||
files = files.filter((f) => f.itemId !== tempItemId);
|
||||
toast.error($i18n.t('Failed to attach file'));
|
||||
}
|
||||
};
|
||||
|
||||
export const openPane = () => {
|
||||
if (parseInt(localStorage?.chatControlsSize)) {
|
||||
@@ -57,7 +148,6 @@
|
||||
const handleMediaQuery = async (e) => {
|
||||
if (e.matches) {
|
||||
largeScreen = true;
|
||||
|
||||
if ($showCallOverlay) {
|
||||
showCallOverlay.set(false);
|
||||
await tick();
|
||||
@@ -65,7 +155,6 @@
|
||||
}
|
||||
} else {
|
||||
largeScreen = false;
|
||||
|
||||
if ($showCallOverlay) {
|
||||
showCallOverlay.set(false);
|
||||
await tick();
|
||||
@@ -75,98 +164,102 @@
|
||||
}
|
||||
};
|
||||
|
||||
const onMouseDown = (event) => {
|
||||
const onMouseDown = () => {
|
||||
dragged = true;
|
||||
};
|
||||
|
||||
const onMouseUp = (event) => {
|
||||
const onMouseUp = () => {
|
||||
dragged = false;
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
// listen to resize 1024px
|
||||
mediaQuery = window.matchMedia('(min-width: 1024px)');
|
||||
|
||||
const mediaQuery = window.matchMedia('(min-width: 1024px)');
|
||||
mediaQuery.addEventListener('change', handleMediaQuery);
|
||||
handleMediaQuery(mediaQuery);
|
||||
|
||||
// Select the container element you want to observe
|
||||
const container = document.getElementById('chat-container');
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let isDestroyed = false;
|
||||
|
||||
// initialize the minSize based on the container width
|
||||
minSize = Math.floor((350 / container.clientWidth) * 100);
|
||||
// Wait for Svelte to render the Pane after largeScreen changed
|
||||
const init = async () => {
|
||||
await tick();
|
||||
|
||||
// Create a new ResizeObserver instance
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
for (let entry of entries) {
|
||||
const width = entry.contentRect.width;
|
||||
// calculate the percentage of 350px
|
||||
const percentage = (350 / width) * 100;
|
||||
// set the minSize to the percentage, must be an integer
|
||||
minSize = Math.floor(percentage);
|
||||
if (isDestroyed) return;
|
||||
|
||||
if ($showControls) {
|
||||
if (pane && pane.isExpanded() && pane.getSize() < minSize) {
|
||||
pane.resize(minSize);
|
||||
} else {
|
||||
let size = Math.floor(
|
||||
(parseInt(localStorage?.chatControlsSize) / container.clientWidth) * 100
|
||||
);
|
||||
if (size < minSize) {
|
||||
// If controls were persisted as open, set the pane to the saved size
|
||||
if ($showControls && pane) {
|
||||
openPane();
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
paneReady = true;
|
||||
}, 0);
|
||||
|
||||
const container = document.getElementById('chat-container') as HTMLElement;
|
||||
if (!container) return;
|
||||
|
||||
minSize = Math.floor((350 / container.clientWidth) * 100);
|
||||
resizeObserver = new ResizeObserver((entries) => {
|
||||
for (let entry of entries) {
|
||||
const width = entry.contentRect.width;
|
||||
minSize = Math.floor((350 / width) * 100);
|
||||
if ($showControls) {
|
||||
if (pane && pane.isExpanded() && pane.getSize() < minSize) {
|
||||
pane.resize(minSize);
|
||||
} else {
|
||||
let size = Math.floor(
|
||||
(parseInt(localStorage?.chatControlsSize) / container.clientWidth) * 100
|
||||
);
|
||||
if (size < minSize && pane) pane.resize(minSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Start observing the container's size changes
|
||||
resizeObserver.observe(container);
|
||||
});
|
||||
resizeObserver.observe(container);
|
||||
};
|
||||
init();
|
||||
|
||||
document.addEventListener('mousedown', onMouseDown);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
showControls.set(false);
|
||||
|
||||
mediaQuery.removeEventListener('change', handleMediaQuery);
|
||||
document.removeEventListener('mousedown', onMouseDown);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
return () => {
|
||||
isDestroyed = true;
|
||||
paneReady = false;
|
||||
resizeObserver?.disconnect();
|
||||
if (!largeScreen) {
|
||||
showControls.set(false);
|
||||
}
|
||||
mediaQuery.removeEventListener('change', handleMediaQuery);
|
||||
document.removeEventListener('mousedown', onMouseDown);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
};
|
||||
});
|
||||
|
||||
const closeHandler = () => {
|
||||
showControls.set(false);
|
||||
showOverview.set(false);
|
||||
if (!largeScreen) {
|
||||
showControls.set(false);
|
||||
}
|
||||
showArtifacts.set(false);
|
||||
showEmbeds.set(false);
|
||||
|
||||
if ($showCallOverlay) {
|
||||
showCallOverlay.set(false);
|
||||
}
|
||||
if ($showCallOverlay) showCallOverlay.set(false);
|
||||
};
|
||||
|
||||
$: if (!chatId) {
|
||||
closeHandler();
|
||||
}
|
||||
$: if (paneReady && !chatId) closeHandler();
|
||||
|
||||
// Helper: is a "special" full-screen panel active?
|
||||
$: specialPanel = $showCallOverlay || $showArtifacts || $showEmbeds;
|
||||
</script>
|
||||
|
||||
{#if !largeScreen}
|
||||
{#if $showControls}
|
||||
<Drawer
|
||||
show={$showControls}
|
||||
onClose={() => {
|
||||
showControls.set(false);
|
||||
}}
|
||||
onClose={() => showControls.set(false)}
|
||||
className="min-h-[100dvh] !bg-white dark:!bg-gray-850"
|
||||
>
|
||||
<div
|
||||
class=" {$showCallOverlay || $showOverview || $showArtifacts || $showEmbeds
|
||||
? ' h-screen w-full'
|
||||
: 'px-4 py-3'} h-full"
|
||||
>
|
||||
<div class="h-[100dvh] flex flex-col">
|
||||
{#if $showCallOverlay}
|
||||
<div
|
||||
class=" h-full max-h-[100dvh] bg-white text-gray-700 dark:bg-black dark:text-gray-300 flex justify-center"
|
||||
class="h-full max-h-[100dvh] bg-white text-gray-700 dark:bg-black dark:text-gray-300 flex justify-center"
|
||||
>
|
||||
<CallOverlay
|
||||
bind:files
|
||||
@@ -175,51 +268,103 @@
|
||||
{modelId}
|
||||
{chatId}
|
||||
{eventTarget}
|
||||
on:close={() => {
|
||||
showControls.set(false);
|
||||
}}
|
||||
on:close={() => showControls.set(false)}
|
||||
/>
|
||||
</div>
|
||||
{:else if $showEmbeds}
|
||||
<Embeds />
|
||||
{:else if $showArtifacts}
|
||||
<Artifacts {history} />
|
||||
{:else if $showOverview}
|
||||
{#await import('./Overview.svelte') then { default: Overview }}
|
||||
<Overview
|
||||
{history}
|
||||
onNodeClick={(e) => {
|
||||
const node = e.node;
|
||||
showMessage(node.data.message, true);
|
||||
}}
|
||||
onClose={() => {
|
||||
showControls.set(false);
|
||||
}}
|
||||
/>
|
||||
{/await}
|
||||
{:else}
|
||||
<Controls
|
||||
on:close={() => {
|
||||
showControls.set(false);
|
||||
}}
|
||||
{models}
|
||||
bind:chatFiles
|
||||
bind:params
|
||||
/>
|
||||
<!-- Controls + Files tabs -->
|
||||
<div class="flex flex-col h-full min-h-0">
|
||||
<!-- Tab bar -->
|
||||
<div class="flex items-center justify-between px-2 pt-2.5 pb-2 shrink-0">
|
||||
<div class="flex gap-1">
|
||||
{#if showControlsTab}
|
||||
<button
|
||||
class="px-2.5 py-1 text-sm rounded-lg transition {activeTab === 'controls'
|
||||
? 'bg-gray-100 dark:bg-gray-800 font-medium text-gray-900 dark:text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
on:click={() => (activeTab = 'controls')}
|
||||
>
|
||||
{$i18n.t('Controls')}
|
||||
</button>
|
||||
{/if}
|
||||
{#if showFilesTab}
|
||||
<button
|
||||
class="px-2.5 py-1 text-sm rounded-lg transition {activeTab === 'files'
|
||||
? 'bg-gray-100 dark:bg-gray-800 font-medium text-gray-900 dark:text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
on:click={() => (activeTab = 'files')}
|
||||
>
|
||||
{$i18n.t('Files')}
|
||||
</button>
|
||||
{/if}
|
||||
{#if showOverviewTab}
|
||||
<button
|
||||
class="px-2.5 py-1 text-sm rounded-lg transition {activeTab === 'overview'
|
||||
? 'bg-gray-100 dark:bg-gray-800 font-medium text-gray-900 dark:text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
on:click={() => (activeTab = 'overview')}
|
||||
>
|
||||
{$i18n.t('Overview')}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
class="p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-500 dark:text-gray-400"
|
||||
on:click={() => showControls.set(false)}
|
||||
aria-label={$i18n.t('Close')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-4"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex-1 min-h-0 {activeTab === 'overview'
|
||||
? 'h-full'
|
||||
: activeTab === 'controls'
|
||||
? 'overflow-y-auto px-3 pt-1'
|
||||
: 'overflow-y-auto'}"
|
||||
>
|
||||
{#if activeTab === 'overview'}
|
||||
<Overview
|
||||
{history}
|
||||
onNodeClick={(e) => {
|
||||
const node = e.node;
|
||||
showMessage(node.data.message, true);
|
||||
}}
|
||||
onClose={() => showControls.set(false)}
|
||||
/>
|
||||
{:else if activeTab === 'files' && $selectedTerminalId}
|
||||
<FileNav onAttach={handleTerminalAttach} />
|
||||
{:else}
|
||||
<Controls embed={true} {models} bind:chatFiles bind:params />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Drawer>
|
||||
{/if}
|
||||
{:else}
|
||||
<!-- if $showControls -->
|
||||
|
||||
{#if $showControls}
|
||||
<PaneResizer
|
||||
class="relative flex items-center justify-center group border-l border-gray-50 dark:border-gray-850/30 hover:border-gray-200 dark:hover:border-gray-800 transition z-20"
|
||||
class="relative flex items-center justify-center group border-l border-gray-50 dark:border-gray-850/30 hover:border-gray-200 dark:hover:border-gray-800 transition z-20"
|
||||
id="controls-resizer"
|
||||
>
|
||||
<div
|
||||
class=" absolute -left-1.5 -right-1.5 -top-0 -bottom-0 z-20 cursor-col-resize bg-transparent"
|
||||
class="absolute -left-1.5 -right-1.5 -top-0 -bottom-0 z-20 cursor-col-resize bg-transparent"
|
||||
/>
|
||||
</PaneResizer>
|
||||
{/if}
|
||||
@@ -229,31 +374,27 @@
|
||||
defaultSize={0}
|
||||
onResize={(size) => {
|
||||
if ($showControls && pane.isExpanded()) {
|
||||
if (size < minSize) {
|
||||
pane.resize(minSize);
|
||||
}
|
||||
|
||||
if (size < minSize) pane.resize(minSize);
|
||||
if (size < minSize) {
|
||||
localStorage.chatControlsSize = 0;
|
||||
} else {
|
||||
// save the size in pixels to localStorage
|
||||
const container = document.getElementById('chat-container');
|
||||
localStorage.chatControlsSize = Math.floor((size / 100) * container.clientWidth);
|
||||
}
|
||||
}
|
||||
}}
|
||||
onCollapse={() => {
|
||||
showControls.set(false);
|
||||
if (paneReady) showControls.set(false);
|
||||
}}
|
||||
collapsible={true}
|
||||
class=" z-10 bg-white dark:bg-gray-850"
|
||||
class="z-10 bg-white dark:bg-gray-850"
|
||||
>
|
||||
{#if $showControls}
|
||||
<div class="flex max-h-full min-h-full">
|
||||
<div
|
||||
class="w-full {($showOverview || $showArtifacts || $showEmbeds) && !$showCallOverlay
|
||||
class="w-full {specialPanel && !$showCallOverlay
|
||||
? ' '
|
||||
: 'px-4 py-3 bg-white dark:shadow-lg dark:bg-gray-850 '} z-40 pointer-events-auto overflow-y-auto scrollbar-hidden"
|
||||
: 'bg-white dark:shadow-lg dark:bg-gray-850'} z-40 pointer-events-auto overflow-y-auto scrollbar-hidden"
|
||||
id="controls-container"
|
||||
>
|
||||
{#if $showCallOverlay}
|
||||
@@ -265,43 +406,96 @@
|
||||
{modelId}
|
||||
{chatId}
|
||||
{eventTarget}
|
||||
on:close={() => {
|
||||
showControls.set(false);
|
||||
}}
|
||||
on:close={() => showControls.set(false)}
|
||||
/>
|
||||
</div>
|
||||
{:else if $showEmbeds}
|
||||
<Embeds overlay={dragged} />
|
||||
{:else if $showArtifacts}
|
||||
<Artifacts {history} overlay={dragged} />
|
||||
{:else if $showOverview}
|
||||
{#await import('./Overview.svelte') then { default: Overview }}
|
||||
<Overview
|
||||
{history}
|
||||
onNodeClick={(e) => {
|
||||
const node = e.node;
|
||||
if (node?.data?.message?.favorite) {
|
||||
history.messages[node.data.message.id].favorite = true;
|
||||
} else {
|
||||
history.messages[node.data.message.id].favorite = null;
|
||||
}
|
||||
|
||||
showMessage(node.data.message, true);
|
||||
}}
|
||||
onClose={() => {
|
||||
showControls.set(false);
|
||||
}}
|
||||
/>
|
||||
{/await}
|
||||
{:else}
|
||||
<Controls
|
||||
on:close={() => {
|
||||
showControls.set(false);
|
||||
}}
|
||||
{models}
|
||||
bind:chatFiles
|
||||
bind:params
|
||||
/>
|
||||
<!-- Controls + Files tabs -->
|
||||
<div class="flex flex-col h-full min-h-0">
|
||||
<!-- Tab bar -->
|
||||
<div class="flex items-center justify-between px-2 pt-2.5 pb-2 shrink-0">
|
||||
<div class="flex gap-1">
|
||||
{#if showControlsTab}
|
||||
<button
|
||||
class="px-2.5 py-1 text-sm rounded-lg transition {activeTab === 'controls'
|
||||
? 'bg-gray-100 dark:bg-gray-800 font-medium text-gray-900 dark:text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
on:click={() => (activeTab = 'controls')}
|
||||
>
|
||||
{$i18n.t('Controls')}
|
||||
</button>
|
||||
{/if}
|
||||
{#if showFilesTab}
|
||||
<button
|
||||
class="px-2.5 py-1 text-sm rounded-lg transition {activeTab === 'files'
|
||||
? 'bg-gray-100 dark:bg-gray-800 font-medium text-gray-900 dark:text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
on:click={() => (activeTab = 'files')}
|
||||
>
|
||||
{$i18n.t('Files')}
|
||||
</button>
|
||||
{/if}
|
||||
{#if showOverviewTab}
|
||||
<button
|
||||
class="px-2.5 py-1 text-sm rounded-lg transition {activeTab === 'overview'
|
||||
? 'bg-gray-100 dark:bg-gray-800 font-medium text-gray-900 dark:text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
on:click={() => (activeTab = 'overview')}
|
||||
>
|
||||
{$i18n.t('Overview')}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
class="p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-500 dark:text-gray-400"
|
||||
on:click={() => showControls.set(false)}
|
||||
aria-label={$i18n.t('Close')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-4"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex-1 min-h-0 {activeTab === 'overview'
|
||||
? 'h-full'
|
||||
: activeTab === 'controls'
|
||||
? 'overflow-y-auto px-3 pt-1'
|
||||
: 'overflow-y-auto'}"
|
||||
>
|
||||
{#if activeTab === 'overview'}
|
||||
<Overview
|
||||
{history}
|
||||
onNodeClick={(e) => {
|
||||
const node = e.node;
|
||||
if (node?.data?.message?.favorite) {
|
||||
history.messages[node.data.message.id].favorite = true;
|
||||
} else {
|
||||
history.messages[node.data.message.id].favorite = null;
|
||||
}
|
||||
showMessage(node.data.message, true);
|
||||
}}
|
||||
onClose={() => showControls.set(false)}
|
||||
/>
|
||||
{:else if activeTab === 'files' && $selectedTerminalId}
|
||||
<FileNav onAttach={handleTerminalAttach} />
|
||||
{:else}
|
||||
<Controls embed={true} {models} bind:chatFiles bind:params />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -40,9 +40,9 @@
|
||||
</script>
|
||||
|
||||
{#if $embed}
|
||||
<div class="h-full w-full">
|
||||
<div class="h-full w-full flex flex-col">
|
||||
<div
|
||||
class="pointer-events-auto z-20 flex justify-between items-center py-3 px-2 font-primar text-gray-900 dark:text-white"
|
||||
class="pointer-events-auto z-20 flex justify-between items-center py-3 px-2 font-primar text-gray-900 dark:text-white flex-shrink-0"
|
||||
>
|
||||
<div class="flex-1 flex items-center justify-between pl-2">
|
||||
<a
|
||||
@@ -68,7 +68,7 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class=" w-full h-full relative">
|
||||
<div class="w-full flex-1 min-h-0 relative">
|
||||
{#if overlay}
|
||||
<div class=" absolute top-0 left-0 right-0 bottom-0 z-10"></div>
|
||||
{/if}
|
||||
|
||||
@@ -13,28 +13,48 @@
|
||||
export let models = [];
|
||||
export let chatFiles = [];
|
||||
export let params = {};
|
||||
export let embed = false;
|
||||
|
||||
let showValves = false;
|
||||
// Persist collapsible section open/close state
|
||||
const getOpen = (key: string, fallback = true): boolean => {
|
||||
const v = localStorage.getItem(`chatControls.${key}`);
|
||||
return v !== null ? v === 'true' : fallback;
|
||||
};
|
||||
const setOpen = (key: string) => (open: boolean) => {
|
||||
localStorage.setItem(`chatControls.${key}`, String(open));
|
||||
};
|
||||
|
||||
let showFiles = getOpen('files');
|
||||
let showValves = getOpen('valves', false);
|
||||
let showSystemPrompt = getOpen('systemPrompt');
|
||||
let showAdvancedParams = getOpen('advancedParams');
|
||||
</script>
|
||||
|
||||
<div class=" dark:text-white">
|
||||
<div class=" flex items-center justify-between dark:text-gray-100 mb-2">
|
||||
<div class=" text-lg font-medium self-center font-primary">{$i18n.t('Chat Controls')}</div>
|
||||
<button
|
||||
class="self-center"
|
||||
aria-label={$i18n.t('Close chat controls')}
|
||||
on:click={() => {
|
||||
dispatch('close');
|
||||
}}
|
||||
>
|
||||
<XMark className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{#if !embed}
|
||||
<div class=" flex items-center justify-between dark:text-gray-100 mb-2">
|
||||
<div class=" text-md self-center font-primary">{$i18n.t('Controls')}</div>
|
||||
<button
|
||||
class="self-center"
|
||||
aria-label={$i18n.t('Close chat controls')}
|
||||
on:click={() => {
|
||||
dispatch('close');
|
||||
}}
|
||||
>
|
||||
<XMark className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if $user?.role === 'admin' || ($user?.permissions.chat?.controls ?? true)}
|
||||
<div class=" dark:text-gray-200 text-sm font-primary py-0.5 px-0.5">
|
||||
<div class=" dark:text-gray-200 text-sm py-0.5 px-0.5">
|
||||
{#if chatFiles.length > 0}
|
||||
<Collapsible title={$i18n.t('Files')} open={true} buttonClassName="w-full">
|
||||
<Collapsible
|
||||
title={$i18n.t('Files')}
|
||||
bind:open={showFiles}
|
||||
onChange={setOpen('files')}
|
||||
buttonClassName="w-full"
|
||||
>
|
||||
<div class="flex flex-col gap-1 mt-1.5" slot="content">
|
||||
{#each chatFiles as file, fileIdx}
|
||||
<FileItem
|
||||
@@ -65,7 +85,12 @@
|
||||
{/if}
|
||||
|
||||
{#if $user?.role === 'admin' || ($user?.permissions.chat?.valves ?? true)}
|
||||
<Collapsible bind:open={showValves} title={$i18n.t('Valves')} buttonClassName="w-full">
|
||||
<Collapsible
|
||||
bind:open={showValves}
|
||||
onChange={setOpen('valves')}
|
||||
title={$i18n.t('Valves')}
|
||||
buttonClassName="w-full"
|
||||
>
|
||||
<div class="text-sm" slot="content">
|
||||
<Valves show={showValves} />
|
||||
</div>
|
||||
@@ -75,7 +100,12 @@
|
||||
{/if}
|
||||
|
||||
{#if $user?.role === 'admin' || ($user?.permissions.chat?.system_prompt ?? true)}
|
||||
<Collapsible title={$i18n.t('System Prompt')} open={true} buttonClassName="w-full">
|
||||
<Collapsible
|
||||
title={$i18n.t('System Prompt')}
|
||||
bind:open={showSystemPrompt}
|
||||
onChange={setOpen('systemPrompt')}
|
||||
buttonClassName="w-full"
|
||||
>
|
||||
<div class="" slot="content">
|
||||
<textarea
|
||||
bind:value={params.system}
|
||||
@@ -92,7 +122,12 @@
|
||||
{/if}
|
||||
|
||||
{#if $user?.role === 'admin' || ($user?.permissions.chat?.params ?? true)}
|
||||
<Collapsible title={$i18n.t('Advanced Params')} open={true} buttonClassName="w-full">
|
||||
<Collapsible
|
||||
title={$i18n.t('Advanced Params')}
|
||||
bind:open={showAdvancedParams}
|
||||
onChange={setOpen('advancedParams')}
|
||||
buttonClassName="w-full"
|
||||
>
|
||||
<div class="text-sm mt-1.5" slot="content">
|
||||
<div>
|
||||
<AdvancedParams admin={$user?.role === 'admin'} custom={true} bind:params />
|
||||
|
||||
@@ -0,0 +1,728 @@
|
||||
<script context="module">
|
||||
// Persists across mount/unmount cycles (module-level, not per-instance)
|
||||
let savedPath = '/';
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { getContext, onMount, onDestroy, tick } from 'svelte';
|
||||
import {
|
||||
terminalServers,
|
||||
settings,
|
||||
showFileNavPath,
|
||||
showFileNavDir,
|
||||
selectedTerminalId
|
||||
} from '$lib/stores';
|
||||
import {
|
||||
getCwd,
|
||||
listFiles,
|
||||
readFile,
|
||||
downloadFileBlob,
|
||||
uploadToTerminal,
|
||||
createDirectory,
|
||||
deleteEntry,
|
||||
setCwd,
|
||||
type FileEntry
|
||||
} from '$lib/apis/terminal';
|
||||
import Folder from '../icons/Folder.svelte';
|
||||
import Document from '../icons/Document.svelte';
|
||||
import PenAlt from '../icons/PenAlt.svelte';
|
||||
import Reset from '../icons/Reset.svelte';
|
||||
import Spinner from '../common/Spinner.svelte';
|
||||
import Tooltip from '../common/Tooltip.svelte';
|
||||
import ConfirmDialog from '../common/ConfirmDialog.svelte';
|
||||
|
||||
import FileNavToolbar from './FileNav/FileNavToolbar.svelte';
|
||||
import FilePreview from './FileNav/FilePreview.svelte';
|
||||
import FileEntryRow from './FileNav/FileEntryRow.svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let onAttach: ((blob: Blob, name: string, contentType: string) => void) | null = null;
|
||||
|
||||
// ── Directory state ──────────────────────────────────────────────────
|
||||
let currentPath = savedPath;
|
||||
let entries: FileEntry[] = [];
|
||||
let loading = false;
|
||||
let error: string | null = null;
|
||||
|
||||
// ── File preview state ───────────────────────────────────────────────
|
||||
let selectedFile: string | null = null;
|
||||
let fileContent: string | null = null;
|
||||
let fileImageUrl: string | null = null;
|
||||
let filePdfData: ArrayBuffer | null = null;
|
||||
let fileLoading = false;
|
||||
let filePreviewRef: FilePreview;
|
||||
|
||||
// ── File preview toolbar state (bound from FilePreview) ─────────────
|
||||
let editing = false;
|
||||
let showRaw = false;
|
||||
let saving = false;
|
||||
|
||||
const MD_EXTS = new Set(['md', 'markdown', 'mdx']);
|
||||
const CSV_EXTS = new Set(['csv', 'tsv']);
|
||||
const getFileExt = (path: string | null) => path?.split('.').pop()?.toLowerCase() ?? '';
|
||||
|
||||
$: isMarkdown = MD_EXTS.has(getFileExt(selectedFile));
|
||||
$: isCsv = CSV_EXTS.has(getFileExt(selectedFile));
|
||||
$: isTextFile = fileContent !== null && fileImageUrl === null && filePdfData === null;
|
||||
|
||||
// ── Upload / folder creation ─────────────────────────────────────────
|
||||
let isDragOver = false;
|
||||
let uploading = false;
|
||||
let creatingFolder = false;
|
||||
let newFolderName = '';
|
||||
let newFolderInput: HTMLInputElement;
|
||||
let creatingFile = false;
|
||||
let newFileName = '';
|
||||
let newFileInput: HTMLInputElement;
|
||||
|
||||
// ── Delete confirmation ──────────────────────────────────────────────
|
||||
let deleteTarget: { path: string; name: string } | null = null;
|
||||
let showDeleteConfirm = false;
|
||||
let shiftKey = false;
|
||||
|
||||
// ── Terminal resolution ──────────────────────────────────────────────
|
||||
let selectedTerminal: { url: string; key: string } | null = null;
|
||||
|
||||
const getTerminal = (): { url: string; key: string } | null => {
|
||||
const systemTerminal = $selectedTerminalId
|
||||
? (($terminalServers ?? []).find((t) => t.id === $selectedTerminalId) ?? null)
|
||||
: ($terminalServers?.[0] ?? null);
|
||||
|
||||
const userTerminal = ($settings?.terminalServers ?? []).find(
|
||||
(s) => s.url === $selectedTerminalId
|
||||
);
|
||||
|
||||
const isSystem = !!systemTerminal;
|
||||
const url = systemTerminal?.url ?? userTerminal?.url ?? '';
|
||||
const key = isSystem ? localStorage.token : (userTerminal?.key ?? '');
|
||||
|
||||
return url ? { url, key } : null;
|
||||
};
|
||||
|
||||
// Detect terminal changes — the explicit store references ensure
|
||||
// Svelte re-runs this block when any of them update.
|
||||
let prevTerminalUrl = '';
|
||||
$: {
|
||||
$selectedTerminalId, $terminalServers, $settings;
|
||||
const terminal = getTerminal();
|
||||
selectedTerminal = terminal;
|
||||
|
||||
if (terminal && terminal.url !== prevTerminalUrl) {
|
||||
prevTerminalUrl = terminal.url;
|
||||
(async () => {
|
||||
const cwd = await getCwd(terminal.url, terminal.key);
|
||||
const dir = cwd ? (cwd.endsWith('/') ? cwd : cwd + '/') : '/';
|
||||
savedPath = dir;
|
||||
loadDir(dir);
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
|
||||
const isImage = (path: string) => IMAGE_EXTS.has(path.split('.').pop()?.toLowerCase() ?? '');
|
||||
const isPdf = (path: string) => path.split('.').pop()?.toLowerCase() === 'pdf';
|
||||
|
||||
const buildBreadcrumbs = (path: string) =>
|
||||
path
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.reduce(
|
||||
(acc, part) => {
|
||||
const prev = acc[acc.length - 1];
|
||||
acc.push({ label: part, path: `${prev.path}${part}/` });
|
||||
return acc;
|
||||
},
|
||||
[{ label: '/', path: '/' }]
|
||||
);
|
||||
|
||||
// ── File preview management ──────────────────────────────────────────
|
||||
const clearFilePreview = () => {
|
||||
fileContent = null;
|
||||
filePreviewRef?.disposePanzoom();
|
||||
if (fileImageUrl) {
|
||||
URL.revokeObjectURL(fileImageUrl);
|
||||
fileImageUrl = null;
|
||||
}
|
||||
filePdfData = null;
|
||||
};
|
||||
|
||||
// ── Directory operations ─────────────────────────────────────────────
|
||||
const loadDir = async (path: string) => {
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal) return;
|
||||
|
||||
loading = true;
|
||||
error = null;
|
||||
selectedFile = null;
|
||||
clearFilePreview();
|
||||
currentPath = path;
|
||||
savedPath = path;
|
||||
|
||||
const result = await listFiles(terminal.url, terminal.key, path);
|
||||
loading = false;
|
||||
|
||||
// Set working directory on the terminal server (fire-and-forget)
|
||||
setCwd(terminal.url, terminal.key, path);
|
||||
|
||||
if (result === null) {
|
||||
error =
|
||||
'Failed to load directory. Check your Terminal connection in Settings → Integrations.';
|
||||
entries = [];
|
||||
} else {
|
||||
entries = result.sort((a, b) => {
|
||||
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const openEntry = async (entry: FileEntry) => {
|
||||
if (entry.type === 'directory') {
|
||||
await loadDir(`${currentPath}${entry.name}/`);
|
||||
return;
|
||||
}
|
||||
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal) return;
|
||||
|
||||
const filePath = `${currentPath}${entry.name}`;
|
||||
selectedFile = filePath;
|
||||
fileLoading = true;
|
||||
clearFilePreview();
|
||||
|
||||
if (isImage(filePath)) {
|
||||
const result = await downloadFileBlob(terminal.url, terminal.key, filePath);
|
||||
if (result) fileImageUrl = URL.createObjectURL(result.blob);
|
||||
} else if (isPdf(filePath)) {
|
||||
const result = await downloadFileBlob(terminal.url, terminal.key, filePath);
|
||||
if (result) filePdfData = await result.blob.arrayBuffer();
|
||||
} else {
|
||||
fileContent = await readFile(terminal.url, terminal.key, filePath);
|
||||
}
|
||||
fileLoading = false;
|
||||
};
|
||||
|
||||
const downloadFile = async (path: string) => {
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal) return;
|
||||
|
||||
const result = await downloadFileBlob(terminal.url, terminal.key, path);
|
||||
if (!result) return;
|
||||
const url = URL.createObjectURL(result.blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = result.filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
// ── Drag-and-drop upload ─────────────────────────────────────────────
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
if (selectedFile) return;
|
||||
if (!e.dataTransfer?.types.includes('Files')) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
isDragOver = true;
|
||||
};
|
||||
|
||||
const handleDrop = async (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
isDragOver = false;
|
||||
|
||||
const terminal = selectedTerminal;
|
||||
if (selectedFile || !terminal) return;
|
||||
|
||||
const droppedFiles = Array.from(e.dataTransfer?.files ?? []);
|
||||
if (!droppedFiles.length) return;
|
||||
|
||||
uploading = true;
|
||||
for (const file of droppedFiles) {
|
||||
await uploadToTerminal(terminal.url, terminal.key, currentPath, file);
|
||||
}
|
||||
uploading = false;
|
||||
await loadDir(currentPath);
|
||||
};
|
||||
|
||||
const handleUploadFiles = async (files: File[]) => {
|
||||
const terminal = selectedTerminal;
|
||||
if (!files.length || !terminal) return;
|
||||
|
||||
uploading = true;
|
||||
for (const file of files) {
|
||||
await uploadToTerminal(terminal.url, terminal.key, currentPath, file);
|
||||
}
|
||||
uploading = false;
|
||||
await loadDir(currentPath);
|
||||
};
|
||||
|
||||
// ── Folder creation ──────────────────────────────────────────────────
|
||||
const startNewFolder = async () => {
|
||||
creatingFolder = true;
|
||||
newFolderName = '';
|
||||
await tick();
|
||||
newFolderInput?.focus();
|
||||
};
|
||||
|
||||
const submitNewFolder = async () => {
|
||||
const name = newFolderName.trim();
|
||||
creatingFolder = false;
|
||||
newFolderName = '';
|
||||
if (!name) return;
|
||||
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal) return;
|
||||
|
||||
const result = await createDirectory(terminal.url, terminal.key, `${currentPath}${name}`);
|
||||
toast[result ? 'success' : 'error'](
|
||||
$i18n.t(result ? 'Folder created' : 'Failed to create folder')
|
||||
);
|
||||
await loadDir(currentPath);
|
||||
};
|
||||
|
||||
// ── File creation ────────────────────────────────────────────────────
|
||||
const startNewFile = async () => {
|
||||
creatingFile = true;
|
||||
newFileName = '';
|
||||
await tick();
|
||||
newFileInput?.focus();
|
||||
};
|
||||
|
||||
const submitNewFile = async () => {
|
||||
const name = newFileName.trim();
|
||||
creatingFile = false;
|
||||
newFileName = '';
|
||||
if (!name) return;
|
||||
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal) return;
|
||||
|
||||
const emptyFile = new File([''], name, { type: 'application/octet-stream' });
|
||||
const result = await uploadToTerminal(terminal.url, terminal.key, currentPath, emptyFile);
|
||||
toast[result ? 'success' : 'error']($i18n.t(result ? 'File created' : 'Failed to create file'));
|
||||
await loadDir(currentPath);
|
||||
};
|
||||
|
||||
// ── Delete ───────────────────────────────────────────────────────────
|
||||
const handleDelete = async (path: string, name: string) => {
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal) return;
|
||||
|
||||
const result = await deleteEntry(terminal.url, terminal.key, path);
|
||||
toast[result ? 'success' : 'error'](
|
||||
$i18n.t(result ? '{{name}} deleted' : 'Failed to delete {{name}}', { name })
|
||||
);
|
||||
await loadDir(currentPath);
|
||||
};
|
||||
|
||||
const requestDelete = (path: string, name: string) => {
|
||||
deleteTarget = { path, name };
|
||||
showDeleteConfirm = true;
|
||||
};
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────────────
|
||||
onMount(async () => {
|
||||
const terminal = getTerminal();
|
||||
if (!terminal) return;
|
||||
|
||||
let handledDisplayFile = false;
|
||||
|
||||
const unsubFileNav = showFileNavPath.subscribe(async (filePath) => {
|
||||
if (!filePath || !selectedTerminal) return;
|
||||
handledDisplayFile = true;
|
||||
showFileNavPath.set(null);
|
||||
|
||||
const lastSlash = filePath.lastIndexOf('/');
|
||||
const dir = lastSlash > 0 ? filePath.substring(0, lastSlash + 1) : '/';
|
||||
const fileName = filePath.substring(lastSlash + 1);
|
||||
|
||||
if (dir !== currentPath) {
|
||||
await loadDir(dir);
|
||||
}
|
||||
|
||||
await tick();
|
||||
const entry = entries.find((e) => e.name === fileName);
|
||||
if (entry) await openEntry(entry);
|
||||
});
|
||||
|
||||
const unsubFileNavDir = showFileNavDir.subscribe(async (filePath) => {
|
||||
if (!filePath || !selectedTerminal) return;
|
||||
showFileNavDir.set(null);
|
||||
|
||||
const lastSlash = filePath.lastIndexOf('/');
|
||||
const dir = lastSlash > 0 ? filePath.substring(0, lastSlash + 1) : '/';
|
||||
|
||||
if (dir === currentPath) {
|
||||
await loadDir(currentPath);
|
||||
}
|
||||
if (filePath === selectedFile) {
|
||||
const fileName = filePath.substring(lastSlash + 1);
|
||||
const entry = entries.find((e) => e.name === fileName);
|
||||
if (entry) await openEntry(entry);
|
||||
}
|
||||
});
|
||||
|
||||
if (!handledDisplayFile) {
|
||||
if (savedPath === '/') {
|
||||
const cwd = await getCwd(terminal.url, terminal.key);
|
||||
if (cwd) savedPath = cwd.endsWith('/') ? cwd : cwd + '/';
|
||||
}
|
||||
loadDir(savedPath);
|
||||
}
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Shift') shiftKey = true;
|
||||
};
|
||||
const onKeyUp = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Shift') shiftKey = false;
|
||||
};
|
||||
const onBlur = () => (shiftKey = false);
|
||||
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible' && !selectedFile && selectedTerminal && !loading) {
|
||||
loadDir(currentPath);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
window.addEventListener('keyup', onKeyUp);
|
||||
window.addEventListener('blur', onBlur);
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKeyDown);
|
||||
window.removeEventListener('keyup', onKeyUp);
|
||||
window.removeEventListener('blur', onBlur);
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
};
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (fileImageUrl) URL.revokeObjectURL(fileImageUrl);
|
||||
});
|
||||
</script>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:show={showDeleteConfirm}
|
||||
on:confirm={() => {
|
||||
if (deleteTarget) {
|
||||
handleDelete(deleteTarget.path, deleteTarget.name);
|
||||
deleteTarget = null;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
{#if !selectedTerminal}
|
||||
<div class="flex-1 flex flex-col items-center justify-center p-6 text-center">
|
||||
<Folder className="size-6 text-gray-300 dark:text-gray-600 mb-2" />
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">
|
||||
{$i18n.t('No Terminal connection configured.')}
|
||||
</div>
|
||||
<div class="text-[10px] text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('Add your Open Terminal URL and API key in Settings → Integrations.')}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div
|
||||
class="flex flex-col h-full min-h-0 relative"
|
||||
on:dragover={handleDragOver}
|
||||
on:dragleave={() => (isDragOver = false)}
|
||||
on:drop={handleDrop}
|
||||
role="region"
|
||||
aria-label={$i18n.t('File browser')}
|
||||
>
|
||||
{#if isDragOver}
|
||||
<div
|
||||
class="absolute inset-0 z-10 flex flex-col items-center justify-center bg-white/80 dark:bg-gray-850/80 backdrop-blur-sm pointer-events-none gap-1.5"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-5 text-gray-400 dark:text-gray-500"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-xs text-gray-400 dark:text-gray-500">{currentPath}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<FileNavToolbar
|
||||
breadcrumbs={buildBreadcrumbs(currentPath)}
|
||||
{selectedFile}
|
||||
{loading}
|
||||
onNavigate={loadDir}
|
||||
onRefresh={() => loadDir(currentPath)}
|
||||
onNewFolder={startNewFolder}
|
||||
onNewFile={startNewFile}
|
||||
onUploadFiles={handleUploadFiles}
|
||||
>
|
||||
{#if fileImageUrl !== null}
|
||||
<Tooltip content={$i18n.t('Reset view')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => filePreviewRef?.resetImageView()}
|
||||
aria-label={$i18n.t('Reset view')}
|
||||
>
|
||||
<Reset className="size-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
{#if filePdfData !== null}
|
||||
<Tooltip content={$i18n.t('Reset view')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => filePreviewRef?.resetPdfView()}
|
||||
aria-label={$i18n.t('Reset view')}
|
||||
>
|
||||
<Reset className="size-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
{#if (isMarkdown || isCsv) && fileContent !== null && !editing}
|
||||
<Tooltip content={showRaw ? $i18n.t('Preview') : $i18n.t('Source')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => {
|
||||
if (editing) filePreviewRef?.cancelEdit();
|
||||
showRaw = !showRaw;
|
||||
}}
|
||||
aria-label={showRaw ? $i18n.t('Preview') : $i18n.t('Source')}
|
||||
>
|
||||
{#if showRaw}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"
|
||||
/>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"
|
||||
/>
|
||||
</svg>
|
||||
{:else}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M17.25 6.75 22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3-4.5 16.5"
|
||||
/>
|
||||
</svg>
|
||||
{/if}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
{#if isTextFile}
|
||||
{#if editing}
|
||||
<Tooltip content={$i18n.t('Cancel')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => filePreviewRef?.cancelEdit()}
|
||||
aria-label={$i18n.t('Cancel')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip content={$i18n.t('Save')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => filePreviewRef?.saveEdit()}
|
||||
disabled={saving}
|
||||
aria-label={$i18n.t('Save')}
|
||||
>
|
||||
{#if saving}
|
||||
<Spinner className="size-3.5" />
|
||||
{:else}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{/if}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{:else}
|
||||
<Tooltip content={$i18n.t('Edit')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => filePreviewRef?.startEdit()}
|
||||
aria-label={$i18n.t('Edit')}
|
||||
>
|
||||
<PenAlt className="size-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
{/if}
|
||||
<Tooltip content={$i18n.t('Download')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => downloadFile(selectedFile)}
|
||||
aria-label={$i18n.t('Download')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</FileNavToolbar>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="flex-1 overflow-y-auto min-h-0">
|
||||
{#if selectedFile !== null}
|
||||
<FilePreview
|
||||
bind:this={filePreviewRef}
|
||||
bind:editing
|
||||
bind:showRaw
|
||||
bind:saving
|
||||
{selectedFile}
|
||||
{fileLoading}
|
||||
{fileImageUrl}
|
||||
{filePdfData}
|
||||
{fileContent}
|
||||
onSave={async (content) => {
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal || !selectedFile) return;
|
||||
const fileName = selectedFile.split('/').pop() ?? 'file';
|
||||
const dir = selectedFile.substring(0, selectedFile.lastIndexOf('/') + 1) || '/';
|
||||
const file = new File([content], fileName, { type: 'text/plain' });
|
||||
const result = await uploadToTerminal(terminal.url, terminal.key, dir, file);
|
||||
toast[result ? 'success' : 'error'](
|
||||
$i18n.t(result ? 'File saved' : 'Failed to save file')
|
||||
);
|
||||
if (result) fileContent = content;
|
||||
}}
|
||||
/>
|
||||
{:else}
|
||||
{#if uploading}
|
||||
<div class="flex items-center justify-center gap-2 p-4 text-xs text-gray-500">
|
||||
<Spinner className="size-4" />
|
||||
{$i18n.t('Uploading...')}
|
||||
</div>
|
||||
{:else if loading}
|
||||
<div class="flex justify-center pt-8"><Spinner className="size-4" /></div>
|
||||
{:else if error}
|
||||
<div class="p-4 text-xs">{error}</div>
|
||||
{:else if entries.length === 0 && !creatingFolder && !creatingFile}
|
||||
<div class="flex flex-col items-center justify-center gap-1.5 py-12 text-center">
|
||||
<Folder className="size-6 text-gray-200 dark:text-gray-700" />
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('This folder is empty')}
|
||||
</div>
|
||||
<div class="text-[11px] text-gray-300 dark:text-gray-600">
|
||||
{$i18n.t('Drop files here to upload')}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !loading && !error && !uploading}
|
||||
{#if creatingFolder}
|
||||
<div class="flex items-center gap-2 px-3 py-1.5">
|
||||
<Folder className="size-4 shrink-0 text-blue-400 dark:text-blue-300" />
|
||||
<input
|
||||
bind:this={newFolderInput}
|
||||
bind:value={newFolderName}
|
||||
class="flex-1 text-xs bg-transparent border border-gray-200 dark:border-gray-700 rounded px-1.5 py-0.5 outline-none focus:border-blue-400 dark:focus:border-blue-500"
|
||||
placeholder={$i18n.t('Folder name')}
|
||||
on:keydown={(e) => {
|
||||
if (e.key === 'Enter') submitNewFolder();
|
||||
if (e.key === 'Escape') {
|
||||
creatingFolder = false;
|
||||
newFolderName = '';
|
||||
}
|
||||
}}
|
||||
on:blur={submitNewFolder}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{#if creatingFile}
|
||||
<div class="flex items-center gap-2 px-3 py-1.5">
|
||||
<Document className="size-4 shrink-0 text-gray-400 dark:text-gray-500" />
|
||||
<input
|
||||
bind:this={newFileInput}
|
||||
bind:value={newFileName}
|
||||
class="flex-1 text-xs bg-transparent border border-gray-200 dark:border-gray-700 rounded px-1.5 py-0.5 outline-none focus:border-blue-400 dark:focus:border-blue-500"
|
||||
placeholder={$i18n.t('File name')}
|
||||
on:keydown={(e) => {
|
||||
if (e.key === 'Enter') submitNewFile();
|
||||
if (e.key === 'Escape') {
|
||||
creatingFile = false;
|
||||
newFileName = '';
|
||||
}
|
||||
}}
|
||||
on:blur={submitNewFile}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if entries.length > 0 || creatingFolder || creatingFile}
|
||||
<ul>
|
||||
{#each entries as entry}
|
||||
<FileEntryRow
|
||||
{entry}
|
||||
{currentPath}
|
||||
terminalUrl={selectedTerminal.url}
|
||||
terminalKey={selectedTerminal.key}
|
||||
onOpen={openEntry}
|
||||
onDownload={downloadFile}
|
||||
onDelete={requestDelete}
|
||||
/>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,127 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import { DropdownMenu } from 'bits-ui';
|
||||
import { flyAndScale } from '$lib/utils/transitions';
|
||||
import { formatFileSize } from '$lib/utils';
|
||||
import type { FileEntry } from '$lib/apis/terminal';
|
||||
import Folder from '../../icons/Folder.svelte';
|
||||
import EllipsisHorizontal from '../../icons/EllipsisHorizontal.svelte';
|
||||
import GarbageBin from '../../icons/GarbageBin.svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let entry: FileEntry;
|
||||
export let currentPath: string;
|
||||
export let terminalUrl: string;
|
||||
export let terminalKey: string;
|
||||
|
||||
export let onOpen: (entry: FileEntry) => void = () => {};
|
||||
export let onDownload: (path: string) => void = () => {};
|
||||
export let onDelete: (path: string, name: string) => void = () => {};
|
||||
</script>
|
||||
|
||||
<li class="group">
|
||||
<div class="w-full flex items-center hover:bg-gray-50 dark:hover:bg-gray-800 transition">
|
||||
<button
|
||||
class="flex-1 flex items-center gap-2 px-3 py-1.5 text-left min-w-0"
|
||||
draggable={entry.type === 'file'}
|
||||
on:dragstart={(e) => {
|
||||
if (entry.type !== 'file') return;
|
||||
e.dataTransfer?.setData(
|
||||
'application/x-terminal-file',
|
||||
JSON.stringify({
|
||||
path: `${currentPath}${entry.name}`,
|
||||
name: entry.name,
|
||||
url: terminalUrl,
|
||||
key: terminalKey
|
||||
})
|
||||
);
|
||||
}}
|
||||
on:click={() => onOpen(entry)}
|
||||
>
|
||||
{#if entry.type === 'directory'}
|
||||
<Folder className="size-4 shrink-0 text-blue-400 dark:text-blue-300" />
|
||||
{:else}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-4 shrink-0 text-gray-400"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"
|
||||
/>
|
||||
</svg>
|
||||
{/if}
|
||||
<span class="flex-1 text-xs text-gray-800 dark:text-gray-200 truncate">
|
||||
{entry.name}
|
||||
</span>
|
||||
{#if entry.type === 'file' && entry.size !== undefined}
|
||||
<span class="text-xs text-gray-400 shrink-0">{formatFileSize(entry.size)}</span>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<DropdownMenu.Root>
|
||||
<DropdownMenu.Trigger
|
||||
class="shrink-0 p-0.5 mr-1 rounded-lg transition
|
||||
text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-400
|
||||
hover:bg-gray-100 dark:hover:bg-gray-800"
|
||||
on:click={(e) => e.stopPropagation()}
|
||||
aria-label={$i18n.t('More')}
|
||||
>
|
||||
<EllipsisHorizontal className="size-3.5" />
|
||||
</DropdownMenu.Trigger>
|
||||
|
||||
<DropdownMenu.Content
|
||||
strategy="fixed"
|
||||
class="w-full max-w-[150px] rounded-2xl p-1 z-[9999999] bg-white dark:bg-gray-850 dark:text-white shadow-lg border border-gray-100 dark:border-gray-800"
|
||||
sideOffset={4}
|
||||
side="bottom"
|
||||
align="end"
|
||||
transition={flyAndScale}
|
||||
>
|
||||
{#if entry.type !== 'directory'}
|
||||
<DropdownMenu.Item
|
||||
type="button"
|
||||
class="select-none flex rounded-xl py-1.5 px-3 w-full hover:bg-gray-50 dark:hover:bg-gray-800 transition items-center gap-2 text-sm"
|
||||
on:click={(e) => {
|
||||
e.stopPropagation();
|
||||
onDownload(`${currentPath}${entry.name}`);
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
d="M10.75 2.75a.75.75 0 0 0-1.5 0v8.614L6.295 8.235a.75.75 0 1 0-1.09 1.03l4.25 4.5a.75.75 0 0 0 1.09 0l4.25-4.5a.75.75 0 0 0-1.09-1.03l-2.955 3.129V2.75Z"
|
||||
/>
|
||||
<path
|
||||
d="M3.5 12.75a.75.75 0 0 0-1.5 0v2.5A2.75 2.75 0 0 0 4.75 18h10.5A2.75 2.75 0 0 0 18 15.25v-2.5a.75.75 0 0 0-1.5 0v2.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-2.5Z"
|
||||
/>
|
||||
</svg>
|
||||
<div class="flex items-center">{$i18n.t('Download')}</div>
|
||||
</DropdownMenu.Item>
|
||||
{/if}
|
||||
|
||||
<DropdownMenu.Item
|
||||
type="button"
|
||||
class="select-none flex rounded-xl py-1.5 px-3 w-full hover:bg-gray-50 dark:hover:bg-gray-800 transition items-center gap-2 text-sm"
|
||||
on:click={(e) => {
|
||||
e.stopPropagation();
|
||||
onDelete(`${currentPath}${entry.name}`, entry.name);
|
||||
}}
|
||||
>
|
||||
<GarbageBin className="size-4" />
|
||||
<div class="flex items-center">{$i18n.t('Delete')}</div>
|
||||
</DropdownMenu.Item>
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Root>
|
||||
</div>
|
||||
</li>
|
||||
@@ -0,0 +1,133 @@
|
||||
<script lang="ts">
|
||||
import { getContext, afterUpdate } from 'svelte';
|
||||
import { tick } from 'svelte';
|
||||
import Folder from '../../icons/Folder.svelte';
|
||||
import NewFolderAlt from '../../icons/NewFolderAlt.svelte';
|
||||
import FilePlusAlt from '../../icons/FilePlusAlt.svelte';
|
||||
import Spinner from '../../common/Spinner.svelte';
|
||||
import Tooltip from '../../common/Tooltip.svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let breadcrumbs: { label: string; path: string }[] = [];
|
||||
export let selectedFile: string | null = null;
|
||||
export let loading = false;
|
||||
|
||||
export let onNavigate: (path: string) => void = () => {};
|
||||
export let onRefresh: () => void = () => {};
|
||||
export let onNewFolder: () => void = () => {};
|
||||
export let onNewFile: () => void = () => {};
|
||||
export let onUploadFiles: (files: File[]) => void = () => {};
|
||||
|
||||
let uploadInput: HTMLInputElement;
|
||||
let breadcrumbEl: HTMLDivElement;
|
||||
|
||||
// Scroll breadcrumb to the end after every DOM update
|
||||
afterUpdate(() => {
|
||||
if (breadcrumbEl) breadcrumbEl.scrollLeft = breadcrumbEl.scrollWidth;
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex items-center px-2 pb-1.5 shrink-0 gap-1">
|
||||
<div
|
||||
bind:this={breadcrumbEl}
|
||||
class="flex items-center flex-1 min-w-0 overflow-x-auto scrollbar-none"
|
||||
>
|
||||
{#each breadcrumbs as crumb, i}
|
||||
{#if i > 1}
|
||||
<span class="text-gray-300 dark:text-gray-600 text-xs shrink-0 select-none mx-0.5">/</span>
|
||||
{/if}
|
||||
<button
|
||||
class="text-xs shrink-0 px-1 py-0.5 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition
|
||||
{!selectedFile && i === breadcrumbs.length - 1
|
||||
? 'text-gray-700 dark:text-gray-300'
|
||||
: 'text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400'}"
|
||||
on:click={() => onNavigate(crumb.path)}
|
||||
>
|
||||
{crumb.label}
|
||||
</button>
|
||||
{/each}
|
||||
{#if selectedFile}
|
||||
<span class="text-gray-300 dark:text-gray-600 text-xs shrink-0 select-none mx-0.5">/</span>
|
||||
<span class="text-xs shrink-0 px-1.5 py-0.5 text-gray-700 dark:text-gray-300">
|
||||
{selectedFile.split('/').pop()}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if !selectedFile}
|
||||
<Tooltip content={$i18n.t('Refresh')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={onRefresh}
|
||||
aria-label={$i18n.t('Refresh')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5 {loading ? 'animate-spin' : ''}"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M15.312 11.424a5.5 5.5 0 0 1-9.201 2.466l-.312-.311h2.451a.75.75 0 0 0 0-1.5H4.5a.75.75 0 0 0-.75.75v3.75a.75.75 0 0 0 1.5 0v-2.127l.13.13a7 7 0 0 0 11.712-3.138.75.75 0 0 0-1.449-.39Zm-10.624-2.85a5.5 5.5 0 0 1 9.201-2.465l.312.31H11.75a.75.75 0 0 0 0 1.5h3.75a.75.75 0 0 0 .75-.75V3.42a.75.75 0 0 0-1.5 0v2.126l-.13-.129A7 7 0 0 0 3.239 8.555a.75.75 0 0 0 1.449.39Z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip content={$i18n.t('New Folder')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={onNewFolder}
|
||||
aria-label={$i18n.t('New Folder')}
|
||||
>
|
||||
<NewFolderAlt className="size-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip content={$i18n.t('New File')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={onNewFile}
|
||||
aria-label={$i18n.t('New File')}
|
||||
>
|
||||
<FilePlusAlt className="size-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip content={$i18n.t('Upload')}>
|
||||
<button
|
||||
class="shrink-0 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
|
||||
on:click={() => uploadInput?.click()}
|
||||
aria-label={$i18n.t('Upload')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<input
|
||||
bind:this={uploadInput}
|
||||
type="file"
|
||||
multiple
|
||||
hidden
|
||||
on:change={async () => {
|
||||
if (!uploadInput?.files?.length) return;
|
||||
onUploadFiles(Array.from(uploadInput.files));
|
||||
uploadInput.value = '';
|
||||
}}
|
||||
/>
|
||||
{:else}
|
||||
<slot />
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,270 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy, tick } from 'svelte';
|
||||
import panzoom, { type PanZoom } from 'panzoom';
|
||||
import { marked } from 'marked';
|
||||
import DOMPurify from 'dompurify';
|
||||
import Spinner from '../../common/Spinner.svelte';
|
||||
import PDFViewer from '../../common/PDFViewer.svelte';
|
||||
|
||||
let pdfViewerRef: PDFViewer;
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let selectedFile: string | null = null;
|
||||
export let fileLoading = false;
|
||||
export let fileImageUrl: string | null = null;
|
||||
export let filePdfData: ArrayBuffer | null = null;
|
||||
export let fileContent: string | null = null;
|
||||
|
||||
export let onSave: ((content: string) => Promise<void>) | null = null;
|
||||
|
||||
export let editing = false;
|
||||
let editContent = '';
|
||||
export let saving = false;
|
||||
let editTextarea: HTMLTextAreaElement;
|
||||
|
||||
// Reset edit state when switching files
|
||||
$: selectedFile, resetEdit();
|
||||
|
||||
const resetEdit = () => {
|
||||
editing = false;
|
||||
editContent = '';
|
||||
saving = false;
|
||||
};
|
||||
|
||||
export const startEdit = async () => {
|
||||
editContent = fileContent ?? '';
|
||||
editing = true;
|
||||
showRaw = true;
|
||||
await tick();
|
||||
editTextarea?.focus();
|
||||
};
|
||||
|
||||
export const saveEdit = async () => {
|
||||
if (!onSave) return;
|
||||
saving = true;
|
||||
await onSave(editContent);
|
||||
saving = false;
|
||||
editing = false;
|
||||
};
|
||||
|
||||
export const cancelEdit = () => {
|
||||
editing = false;
|
||||
editContent = '';
|
||||
};
|
||||
|
||||
$: isTextFile = fileContent !== null && fileImageUrl === null && filePdfData === null;
|
||||
|
||||
const MD_EXTS = new Set(['md', 'markdown', 'mdx']);
|
||||
const CSV_EXTS = new Set(['csv', 'tsv']);
|
||||
const getExt = (path: string | null) => path?.split('.').pop()?.toLowerCase() ?? '';
|
||||
|
||||
$: isMarkdown = MD_EXTS.has(getExt(selectedFile));
|
||||
$: isCsv = CSV_EXTS.has(getExt(selectedFile));
|
||||
$: csvDelimiter = getExt(selectedFile) === 'tsv' ? '\t' : ',';
|
||||
$: renderedHtml =
|
||||
isMarkdown && fileContent
|
||||
? DOMPurify.sanitize(marked.parse(fileContent, { async: false }) as string)
|
||||
: '';
|
||||
|
||||
// Simple CSV parser that handles quoted fields
|
||||
const parseCsv = (text: string, delimiter: string): string[][] => {
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let field = '';
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
} else if (ch === '"') {
|
||||
inQuotes = true;
|
||||
} else if (ch === delimiter) {
|
||||
row.push(field);
|
||||
field = '';
|
||||
} else if (ch === '\n' || (ch === '\r' && text[i + 1] === '\n')) {
|
||||
if (ch === '\r') i++;
|
||||
row.push(field);
|
||||
field = '';
|
||||
if (row.some((c) => c !== '')) rows.push(row);
|
||||
row = [];
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
}
|
||||
row.push(field);
|
||||
if (row.some((c) => c !== '')) rows.push(row);
|
||||
return rows;
|
||||
};
|
||||
|
||||
$: csvRows = isCsv && fileContent ? parseCsv(fileContent, csvDelimiter) : [];
|
||||
$: csvHeader = csvRows.length > 0 ? csvRows[0] : [];
|
||||
$: csvBody = csvRows.length > 1 ? csvRows.slice(1) : [];
|
||||
|
||||
export let showRaw = false;
|
||||
$: selectedFile, (showRaw = false); // reset to preview mode when switching files
|
||||
|
||||
let pzInstance: PanZoom | null = null;
|
||||
|
||||
const initImagePanzoom = (node: HTMLElement) => {
|
||||
pzInstance = panzoom(node, {
|
||||
bounds: true,
|
||||
boundsPadding: 0.1,
|
||||
zoomSpeed: 0.065
|
||||
});
|
||||
};
|
||||
|
||||
export const resetImageView = () => {
|
||||
if (pzInstance) {
|
||||
pzInstance.moveTo(0, 0);
|
||||
pzInstance.zoomAbs(0, 0, 1);
|
||||
}
|
||||
};
|
||||
|
||||
export const disposePanzoom = () => {
|
||||
if (pzInstance) {
|
||||
pzInstance.dispose();
|
||||
pzInstance = null;
|
||||
}
|
||||
};
|
||||
|
||||
export const resetPdfView = () => {
|
||||
pdfViewerRef?.resetView();
|
||||
};
|
||||
|
||||
onDestroy(() => {
|
||||
disposePanzoom();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="flex-1 {fileImageUrl !== null
|
||||
? 'overflow-hidden'
|
||||
: 'overflow-y-auto'} min-h-0 relative h-full"
|
||||
>
|
||||
<!-- File preview -->
|
||||
{#if fileLoading}
|
||||
<div class="flex items-center justify-center h-full"><Spinner className="size-4" /></div>
|
||||
{:else if fileImageUrl !== null}
|
||||
<div class="w-full h-full flex items-center justify-center" use:initImagePanzoom>
|
||||
<img
|
||||
src={fileImageUrl}
|
||||
alt={selectedFile?.split('/').pop()}
|
||||
class="max-w-full max-h-full object-contain p-3"
|
||||
draggable="false"
|
||||
/>
|
||||
</div>
|
||||
{:else if filePdfData !== null}
|
||||
<PDFViewer bind:this={pdfViewerRef} data={filePdfData} className="w-full h-full" />
|
||||
{:else if fileContent !== null}
|
||||
{#if isMarkdown && !showRaw}
|
||||
<div class="prose dark:prose-invert max-w-full text-sm p-3">
|
||||
{@html renderedHtml}
|
||||
</div>
|
||||
{:else if isCsv && !showRaw && csvRows.length > 0}
|
||||
<div class="overflow-auto h-full px-3 pb-3">
|
||||
<table class="csv-table w-full text-xs font-mono border-collapse">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="csv-row-num">#</th>
|
||||
{#each csvHeader as cell}
|
||||
<th>{cell}</th>
|
||||
{/each}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each csvBody as row, i}
|
||||
<tr>
|
||||
<td class="csv-row-num">{i + 1}</td>
|
||||
{#each row as cell}
|
||||
<td>{cell}</td>
|
||||
{/each}
|
||||
<!-- Pad missing columns -->
|
||||
{#each Array(Math.max(0, csvHeader.length - row.length)) as _}
|
||||
<td></td>
|
||||
{/each}
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{:else if editing}
|
||||
<textarea
|
||||
bind:this={editTextarea}
|
||||
bind:value={editContent}
|
||||
class="w-full h-full text-xs font-mono text-gray-800 dark:text-gray-200 whitespace-pre break-all leading-relaxed p-3 bg-transparent border-none outline-none resize-none"
|
||||
spellcheck="false"
|
||||
/>
|
||||
{:else}
|
||||
<pre
|
||||
class="text-xs font-mono text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-all leading-relaxed p-3">{fileContent}</pre>
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="text-sm text-gray-400 text-center pt-8">
|
||||
{$i18n.t('Could not read file.')}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.csv-table {
|
||||
font-size: 0.7rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.csv-table th,
|
||||
.csv-table td {
|
||||
padding: 4px 8px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
border: 1px solid rgba(128, 128, 128, 0.15);
|
||||
}
|
||||
.csv-table thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: rgba(243, 244, 246, 0.95);
|
||||
backdrop-filter: blur(4px);
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
border-bottom: 2px solid rgba(128, 128, 128, 0.25);
|
||||
z-index: 1;
|
||||
}
|
||||
:global(.dark) .csv-table thead th {
|
||||
background: rgba(31, 41, 55, 0.95);
|
||||
color: #d1d5db;
|
||||
}
|
||||
.csv-table tbody tr:nth-child(even) {
|
||||
background: rgba(128, 128, 128, 0.04);
|
||||
}
|
||||
.csv-table tbody tr:hover {
|
||||
background: rgba(59, 130, 246, 0.06);
|
||||
}
|
||||
:global(.dark) .csv-table tbody tr:hover {
|
||||
background: rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
.csv-table td {
|
||||
color: #374151;
|
||||
}
|
||||
:global(.dark) .csv-table td {
|
||||
color: #d1d5db;
|
||||
}
|
||||
.csv-row-num {
|
||||
color: #9ca3af;
|
||||
font-size: 0.6rem;
|
||||
text-align: right !important;
|
||||
user-select: none;
|
||||
width: 1px;
|
||||
padding-right: 6px !important;
|
||||
}
|
||||
:global(.dark) .csv-row-num {
|
||||
color: #6b7280;
|
||||
}
|
||||
</style>
|
||||
@@ -11,7 +11,7 @@
|
||||
dayjs.extend(duration);
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
import { onMount, tick, getContext, createEventDispatcher, onDestroy } from 'svelte';
|
||||
import { onMount, tick, getContext, createEventDispatcher } from 'svelte';
|
||||
|
||||
import { createPicker, getAuthToken } from '$lib/utils/google-drive-picker';
|
||||
import { pickAndDownloadFile } from '$lib/utils/onedrive-file-picker';
|
||||
@@ -28,8 +28,11 @@
|
||||
showCallOverlay,
|
||||
tools,
|
||||
toolServers,
|
||||
terminalServers,
|
||||
user as _user,
|
||||
showControls,
|
||||
showSettings,
|
||||
selectedTerminalId,
|
||||
TTSWorker,
|
||||
temporaryChatEnabled
|
||||
} from '$lib/stores';
|
||||
@@ -62,13 +65,14 @@
|
||||
|
||||
import InputMenu from './MessageInput/InputMenu.svelte';
|
||||
import VoiceRecording from './MessageInput/VoiceRecording.svelte';
|
||||
import FilesOverlay from './MessageInput/FilesOverlay.svelte';
|
||||
|
||||
import ToolServersModal from './ToolServersModal.svelte';
|
||||
|
||||
import RichTextInput from '../common/RichTextInput.svelte';
|
||||
import Tooltip from '../common/Tooltip.svelte';
|
||||
import FileItem from '../common/FileItem.svelte';
|
||||
import Image from '../common/Image.svelte';
|
||||
import Spinner from '../common/Spinner.svelte';
|
||||
|
||||
import XMark from '../icons/XMark.svelte';
|
||||
import GlobeAlt from '../icons/GlobeAlt.svelte';
|
||||
@@ -78,10 +82,15 @@
|
||||
|
||||
import InputVariablesModal from './MessageInput/InputVariablesModal.svelte';
|
||||
import Voice from '../icons/Voice.svelte';
|
||||
import Terminal from '../icons/Terminal.svelte';
|
||||
import Cloud from '../icons/Cloud.svelte';
|
||||
import IntegrationsMenu from './MessageInput/IntegrationsMenu.svelte';
|
||||
import TerminalMenu from './MessageInput/TerminalMenu.svelte';
|
||||
import Component from '../icons/Component.svelte';
|
||||
import PlusAlt from '../icons/PlusAlt.svelte';
|
||||
import Dropdown from '../common/Dropdown.svelte';
|
||||
|
||||
import { DropdownMenu } from 'bits-ui';
|
||||
import { flyAndScale } from '$lib/utils/transitions';
|
||||
|
||||
import CommandSuggestionList from './MessageInput/CommandSuggestionList.svelte';
|
||||
import Knobs from '../icons/Knobs.svelte';
|
||||
@@ -102,6 +111,7 @@
|
||||
|
||||
export let autoScroll = false;
|
||||
export let generating = false;
|
||||
export let uploadPending = false;
|
||||
|
||||
export let atSelectedModel: Model | undefined = undefined;
|
||||
export let selectedModels: [''];
|
||||
@@ -122,6 +132,8 @@
|
||||
export let webSearchEnabled = false;
|
||||
export let codeInterpreterEnabled = false;
|
||||
|
||||
let showTerminalMenu = false;
|
||||
|
||||
export let messageQueue: { id: string; prompt: string; files: any[] }[] = [];
|
||||
export let onQueueSendNow: (id: string) => void = () => {};
|
||||
export let onQueueEdit: (id: string) => void = () => {};
|
||||
@@ -435,7 +447,7 @@
|
||||
|
||||
let showInputModal = false;
|
||||
|
||||
let dragged = false;
|
||||
export let dragged = false;
|
||||
let shiftKey = false;
|
||||
|
||||
let user = null;
|
||||
@@ -786,7 +798,7 @@
|
||||
}
|
||||
};
|
||||
|
||||
const onDragOver = (e) => {
|
||||
const onDragOver = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Check if a file is being dragged.
|
||||
@@ -797,14 +809,14 @@
|
||||
}
|
||||
};
|
||||
|
||||
const onDragLeave = (e) => {
|
||||
if (e.currentTarget.contains(e.relatedTarget)) {
|
||||
const onDragLeave = (e: DragEvent) => {
|
||||
if ((e.currentTarget as HTMLElement)?.contains(e.relatedTarget as Node)) {
|
||||
return;
|
||||
}
|
||||
dragged = false;
|
||||
};
|
||||
|
||||
const onDrop = async (e) => {
|
||||
const onDrop = async (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
console.log(e);
|
||||
|
||||
@@ -819,7 +831,7 @@
|
||||
dragged = false;
|
||||
};
|
||||
|
||||
const onKeyDown = (e) => {
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Shift') {
|
||||
shiftKey = true;
|
||||
}
|
||||
@@ -843,7 +855,7 @@
|
||||
}
|
||||
};
|
||||
|
||||
const onKeyUp = (e) => {
|
||||
const onKeyUp = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Shift') {
|
||||
shiftKey = false;
|
||||
}
|
||||
@@ -855,7 +867,7 @@
|
||||
shiftKey = false;
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
onMount(() => {
|
||||
suggestions = [
|
||||
{
|
||||
char: '@',
|
||||
@@ -988,36 +1000,41 @@
|
||||
window.addEventListener('focus', onFocus);
|
||||
window.addEventListener('blur', onBlur);
|
||||
|
||||
await tick();
|
||||
let isDestroyed = false;
|
||||
let dropzoneElement: HTMLElement | null = null;
|
||||
const initialize = async () => {
|
||||
await tick();
|
||||
if (isDestroyed) return;
|
||||
|
||||
const dropzoneElement = document.getElementById('chat-container');
|
||||
dropzoneElement = document.getElementById('chat-pane');
|
||||
if (dropzoneElement) {
|
||||
dropzoneElement.addEventListener('dragover', onDragOver);
|
||||
dropzoneElement.addEventListener('drop', onDrop);
|
||||
dropzoneElement.addEventListener('dragleave', onDragLeave);
|
||||
}
|
||||
|
||||
dropzoneElement?.addEventListener('dragover', onDragOver);
|
||||
dropzoneElement?.addEventListener('drop', onDrop);
|
||||
dropzoneElement?.addEventListener('dragleave', onDragLeave);
|
||||
tools.set(await getTools(localStorage.token));
|
||||
};
|
||||
initialize();
|
||||
|
||||
await tools.set(await getTools(localStorage.token));
|
||||
});
|
||||
return () => {
|
||||
isDestroyed = true;
|
||||
|
||||
onDestroy(() => {
|
||||
console.log('destroy');
|
||||
window.removeEventListener('keydown', onKeyDown);
|
||||
window.removeEventListener('keyup', onKeyUp);
|
||||
window.removeEventListener('keydown', onKeyDown);
|
||||
window.removeEventListener('keyup', onKeyUp);
|
||||
|
||||
window.removeEventListener('focus', onFocus);
|
||||
window.removeEventListener('blur', onBlur);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
window.removeEventListener('blur', onBlur);
|
||||
|
||||
const dropzoneElement = document.getElementById('chat-container');
|
||||
|
||||
if (dropzoneElement) {
|
||||
dropzoneElement?.removeEventListener('dragover', onDragOver);
|
||||
dropzoneElement?.removeEventListener('drop', onDrop);
|
||||
dropzoneElement?.removeEventListener('dragleave', onDragLeave);
|
||||
}
|
||||
if (dropzoneElement) {
|
||||
dropzoneElement.removeEventListener('dragover', onDragOver);
|
||||
dropzoneElement.removeEventListener('drop', onDrop);
|
||||
dropzoneElement.removeEventListener('dragleave', onDragLeave);
|
||||
}
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<FilesOverlay show={dragged} />
|
||||
<ToolServersModal bind:show={showTools} {selectedToolIds} />
|
||||
|
||||
<InputVariablesModal
|
||||
@@ -1158,7 +1175,7 @@
|
||||
<!-- Queued messages display -->
|
||||
{#if messageQueue.length > 0}
|
||||
<div
|
||||
class="mb-1 mx-2 py-0.5 px-1.5 rounded-2xl bg-gray-900/60 border border-gray-800/50 overflow-hidden"
|
||||
class="mb-1 mx-2 py-0.5 px-1.5 rounded-2xl bg-white dark:bg-gray-900/60 border border-gray-100 dark:border-gray-800/50 overflow-hidden"
|
||||
>
|
||||
{#each messageQueue as queuedMessage (queuedMessage.id)}
|
||||
<QueuedMessageItem
|
||||
@@ -1619,10 +1636,12 @@
|
||||
{/if}
|
||||
|
||||
<div class="ml-1 flex gap-1.5">
|
||||
{#if (selectedToolIds ?? []).length > 0}
|
||||
{#if (selectedToolIds ?? []).filter((id) => !id.startsWith('direct_server:terminal_')).length > 0}
|
||||
<Tooltip
|
||||
content={$i18n.t('{{COUNT}} Available Tools', {
|
||||
COUNT: selectedToolIds.length
|
||||
COUNT: (selectedToolIds ?? []).filter(
|
||||
(id) => !id.startsWith('direct_server:terminal_')
|
||||
).length
|
||||
})}
|
||||
>
|
||||
<button
|
||||
@@ -1636,7 +1655,9 @@
|
||||
<Wrench className="size-4" strokeWidth="1.75" />
|
||||
|
||||
<span class="text-sm">
|
||||
{selectedToolIds.length}
|
||||
{(selectedToolIds ?? []).filter(
|
||||
(id) => !id.startsWith('direct_server:terminal_')
|
||||
).length}
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
@@ -1732,7 +1753,7 @@
|
||||
? 'm-1'
|
||||
: 'focus:outline-hidden rounded-full'}"
|
||||
>
|
||||
<Terminal className="size-3.5" strokeWidth="2" />
|
||||
<Cloud className="size-3.5" strokeWidth="2" />
|
||||
|
||||
<div class="hidden group-hover:block">
|
||||
<XMark className="size-4" strokeWidth="1.75" />
|
||||
@@ -1787,6 +1808,11 @@
|
||||
{/if}
|
||||
|
||||
{#if (!history?.currentId || history.messages[history.currentId]?.done == true) && ($_user?.role === 'admin' || ($_user?.permissions?.chat?.stt ?? true))}
|
||||
<!-- Terminal Server Selector -->
|
||||
{#if ($terminalServers ?? []).length > 0 || ($settings?.terminalServers ?? []).some((s) => s.url)}
|
||||
<TerminalMenu bind:show={showTerminalMenu} />
|
||||
{/if}
|
||||
|
||||
<!-- {$i18n.t('Record voice')} -->
|
||||
<Tooltip content={$i18n.t('Dictate')}>
|
||||
<button
|
||||
@@ -1901,27 +1927,35 @@
|
||||
</div>
|
||||
{:else}
|
||||
<div class=" flex items-center">
|
||||
<Tooltip content={$i18n.t('Send message')}>
|
||||
<Tooltip
|
||||
content={uploadPending
|
||||
? $i18n.t('Waiting for upload...')
|
||||
: $i18n.t('Send message')}
|
||||
>
|
||||
<button
|
||||
id="send-message-button"
|
||||
class="{!(prompt === '' && files.length === 0)
|
||||
class="{!(prompt === '' && files.length === 0) || uploadPending
|
||||
? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
|
||||
: 'text-white bg-gray-200 dark:text-gray-900 dark:bg-gray-700 disabled'} transition rounded-full p-1.5 self-center"
|
||||
type="submit"
|
||||
disabled={prompt === '' && files.length === 0}
|
||||
disabled={(prompt === '' && files.length === 0) || uploadPending}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
class="size-5"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{#if uploadPending}
|
||||
<Spinner className="size-5" />
|
||||
{:else}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
class="size-5"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{/if}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -1,25 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { showSidebar } from '$lib/stores';
|
||||
import AddFilesPlaceholder from '$lib/components/AddFilesPlaceholder.svelte';
|
||||
|
||||
export let show = false;
|
||||
let overlayElement = null;
|
||||
|
||||
$: if (show && overlayElement) {
|
||||
document.body.appendChild(overlayElement);
|
||||
document.body.style.overflow = 'hidden';
|
||||
} else if (overlayElement) {
|
||||
document.body.removeChild(overlayElement);
|
||||
document.body.style.overflow = 'unset';
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if show}
|
||||
<div
|
||||
bind:this={overlayElement}
|
||||
class="fixed {$showSidebar
|
||||
? 'left-0 md:left-[var(--sidebar-width)] md:w-[calc(100%-var(--sidebar-width))]'
|
||||
: 'left-0'} fixed top-0 right-0 bottom-0 w-full h-full flex z-9999 touch-none pointer-events-none"
|
||||
class="absolute inset-0 w-full h-full flex z-[9999] touch-none pointer-events-none"
|
||||
id="dropzone"
|
||||
role="region"
|
||||
aria-label="Drag and Drop Container"
|
||||
|
||||
@@ -4,7 +4,15 @@
|
||||
import { fly } from 'svelte/transition';
|
||||
import { flyAndScale } from '$lib/utils/transitions';
|
||||
|
||||
import { config, user, tools as _tools, mobile, settings, toolServers } from '$lib/stores';
|
||||
import {
|
||||
config,
|
||||
user,
|
||||
tools as _tools,
|
||||
mobile,
|
||||
settings,
|
||||
toolServers,
|
||||
terminalServers
|
||||
} from '$lib/stores';
|
||||
|
||||
import { getOAuthClientAuthorizationUrl } from '$lib/apis/configs';
|
||||
import { getTools } from '$lib/apis/tools';
|
||||
@@ -88,7 +96,9 @@
|
||||
}
|
||||
}
|
||||
|
||||
selectedToolIds = selectedToolIds.filter((id) => Object.keys(tools).includes(id));
|
||||
selectedToolIds = selectedToolIds.filter(
|
||||
(id) => Object.keys(tools).includes(id) || id.startsWith('direct_server:terminal_')
|
||||
);
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
<!-- Message content -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-sm text-gray-300 truncate">{content}</p>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-300 truncate">{content}</p>
|
||||
</div>
|
||||
|
||||
<!-- Actions -->
|
||||
@@ -31,7 +31,7 @@
|
||||
<Tooltip content={$i18n.t('Send now')}>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1 text-gray-500 hover:text-gray-300 transition-colors"
|
||||
class="p-1 text-gray-400 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"
|
||||
on:click={() => onSendNow(id)}
|
||||
aria-label={$i18n.t('Send now')}
|
||||
>
|
||||
@@ -56,7 +56,7 @@
|
||||
<Tooltip content={$i18n.t('Edit')}>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1 text-gray-500 hover:text-gray-300 transition-colors"
|
||||
class="p-1 text-gray-400 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"
|
||||
on:click={() => onEdit(id)}
|
||||
aria-label={$i18n.t('Edit')}
|
||||
>
|
||||
@@ -68,7 +68,7 @@
|
||||
<Tooltip content={$i18n.t('Delete')}>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1 text-gray-500 hover:text-gray-300 transition-colors"
|
||||
class="p-1 text-gray-400 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"
|
||||
on:click={() => onDelete(id)}
|
||||
aria-label={$i18n.t('Delete')}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { DropdownMenu } from 'bits-ui';
|
||||
import { flyAndScale } from '$lib/utils/transitions';
|
||||
|
||||
import { settings, showSettings, terminalServers, selectedTerminalId, user } from '$lib/stores';
|
||||
import { getToolServersData } from '$lib/apis';
|
||||
|
||||
import Dropdown from '$lib/components/common/Dropdown.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import Cloud from '$lib/components/icons/Cloud.svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let show = false;
|
||||
|
||||
$: systemTerminals = ($terminalServers ?? []).filter((t) => t.id);
|
||||
$: directTerminals = ($settings?.terminalServers ?? []).filter((s) => s.url);
|
||||
|
||||
const refreshTerminalServersStore = async (servers: typeof directTerminals) => {
|
||||
// Preserve system terminals (those with an `id`) — only refresh direct ones
|
||||
const existingSystemTerminals = ($terminalServers ?? []).filter((t) => t.id);
|
||||
|
||||
const activeTerminals = servers.filter((s) => s.enabled);
|
||||
if (activeTerminals.length > 0) {
|
||||
let data = await getToolServersData(
|
||||
activeTerminals.map((t) => ({
|
||||
url: t.url,
|
||||
auth_type: t.auth_type ?? 'bearer',
|
||||
key: t.key ?? '',
|
||||
path: t.path ?? '/openapi.json',
|
||||
config: { enable: true }
|
||||
}))
|
||||
);
|
||||
data = data.filter((d) => d && !d.error);
|
||||
terminalServers.set([...data, ...existingSystemTerminals]);
|
||||
} else {
|
||||
terminalServers.set(existingSystemTerminals);
|
||||
}
|
||||
};
|
||||
|
||||
const selectDirect = async (terminal: (typeof directTerminals)[0]) => {
|
||||
const newId = $selectedTerminalId === terminal.url ? null : terminal.url;
|
||||
selectedTerminalId.set(newId);
|
||||
|
||||
// Enable the selected direct terminal, disable all others
|
||||
const updatedServers = ($settings?.terminalServers ?? []).map((s) => ({
|
||||
...s,
|
||||
enabled: newId !== null && s.url === terminal.url
|
||||
}));
|
||||
|
||||
settings.set({
|
||||
...$settings,
|
||||
terminalServers: updatedServers
|
||||
});
|
||||
|
||||
show = false;
|
||||
|
||||
// Refresh the store so Chat.svelte can inject it as a tool
|
||||
await refreshTerminalServersStore(updatedServers);
|
||||
};
|
||||
|
||||
const selectSystem = async (terminal: (typeof systemTerminals)[0]) => {
|
||||
selectedTerminalId.set($selectedTerminalId === terminal.id ? null : terminal.id);
|
||||
|
||||
// Disable all direct terminals when switching to a system terminal
|
||||
if ($settings?.terminalServers?.some((s) => s.enabled)) {
|
||||
const updatedServers = ($settings.terminalServers ?? []).map((s) => ({
|
||||
...s,
|
||||
enabled: false
|
||||
}));
|
||||
settings.set({
|
||||
...$settings,
|
||||
terminalServers: updatedServers
|
||||
});
|
||||
await refreshTerminalServersStore(updatedServers);
|
||||
}
|
||||
|
||||
show = false;
|
||||
};
|
||||
|
||||
$: selectedSystemTerminal = systemTerminals.find((t) => t.id === $selectedTerminalId);
|
||||
$: selectedDirectTerminal = directTerminals.find((t) => t.url === $selectedTerminalId);
|
||||
|
||||
$: selectedLabel =
|
||||
selectedSystemTerminal?.name ||
|
||||
selectedSystemTerminal?.id ||
|
||||
selectedDirectTerminal?.name ||
|
||||
selectedDirectTerminal?.url?.replace(/^https?:\/\//, '') ||
|
||||
$i18n.t('Terminal');
|
||||
</script>
|
||||
|
||||
<div class="flex items-center translate-x-0.5">
|
||||
<Dropdown bind:show>
|
||||
<Tooltip content={$i18n.t('Terminal')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1.5 translate-y-[1px] hover:bg-gray-50 dark:hover:bg-gray-850 text-sm transition rounded-lg cursor-pointer {$selectedTerminalId &&
|
||||
selectedLabel
|
||||
? ' px-2.5 py-1 '
|
||||
: ' p-2 opacity-50'}"
|
||||
>
|
||||
<Cloud className="size-3.5" strokeWidth="2" />
|
||||
|
||||
{#if $selectedTerminalId && selectedLabel}
|
||||
<span class="truncate text-[13px] max-w-[100px] sm:max-w-[150px] capitalize"
|
||||
>{selectedLabel}</span
|
||||
>
|
||||
{/if}
|
||||
</button>
|
||||
</Tooltip>
|
||||
|
||||
<div slot="content">
|
||||
<DropdownMenu.Content
|
||||
class="w-full max-w-56 rounded-2xl px-1 py-1 border border-gray-100 dark:border-gray-800 z-50 bg-white dark:bg-gray-850 dark:text-white shadow-lg max-h-72 overflow-y-auto overflow-x-hidden scrollbar-thin"
|
||||
sideOffset={4}
|
||||
side="bottom"
|
||||
align="end"
|
||||
transition={flyAndScale}
|
||||
>
|
||||
<!-- Direct terminals (gated by permission) -->
|
||||
{#if directTerminals.length > 0 && ($user?.role === 'admin' || ($user?.permissions?.features?.direct_tool_servers ?? true))}
|
||||
<div class="flex items-center justify-between px-3 py-1">
|
||||
<span
|
||||
class="text-[10px] font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
{$i18n.t('Direct')}
|
||||
</span>
|
||||
<Tooltip content={$i18n.t('Add Terminal')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="p-0.5 rounded-md text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition"
|
||||
on:click|stopPropagation={() => {
|
||||
show = false;
|
||||
showSettings.set(true);
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{#each directTerminals as terminal}
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full justify-between gap-2 items-center px-3 py-1.5 text-sm cursor-pointer rounded-xl {$selectedTerminalId ===
|
||||
terminal.url
|
||||
? 'bg-gray-50 dark:bg-gray-800/50'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-800/50'}"
|
||||
on:click={() => selectDirect(terminal)}
|
||||
>
|
||||
<div class="flex flex-1 gap-2 items-center truncate">
|
||||
<Cloud className="size-4 shrink-0" strokeWidth="2" />
|
||||
<span class="truncate"
|
||||
>{terminal.name || terminal.url.replace(/^https?:\/\//, '')}</span
|
||||
>
|
||||
</div>
|
||||
{#if $selectedTerminalId === terminal.url}
|
||||
<div class="shrink-0 text-emerald-600 dark:text-emerald-400">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
|
||||
{#if directTerminals.length > 0 && systemTerminals.length > 0}
|
||||
<hr class="border-gray-100 dark:border-gray-800 my-1" />
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<!-- System terminals -->
|
||||
{#if systemTerminals.length > 0}
|
||||
<div class="flex items-center justify-between px-3 py-1">
|
||||
<span
|
||||
class="text-[10px] font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
{$i18n.t('System')}
|
||||
</span>
|
||||
{#if $user?.role === 'admin'}
|
||||
<Tooltip content={$i18n.t('Add Terminal')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="p-0.5 rounded-md text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition"
|
||||
on:click|stopPropagation={() => {
|
||||
show = false;
|
||||
goto('/admin/settings/integrations');
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#each systemTerminals as terminal}
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full justify-between gap-2 items-center px-3 py-1.5 text-sm cursor-pointer rounded-xl {$selectedTerminalId ===
|
||||
terminal.id
|
||||
? 'bg-gray-50 dark:bg-gray-800/50'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-800/50'}"
|
||||
on:click={() => selectSystem(terminal)}
|
||||
>
|
||||
<div class="flex flex-1 gap-2 items-center truncate">
|
||||
<Cloud className="size-4 shrink-0" strokeWidth="2" />
|
||||
<span class="truncate">{terminal.name || $i18n.t('Terminal')}</span>
|
||||
</div>
|
||||
{#if $selectedTerminalId === terminal.id}
|
||||
<div class="shrink-0 text-emerald-600 dark:text-emerald-400">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-4"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</DropdownMenu.Content>
|
||||
</div>
|
||||
</Dropdown>
|
||||
</div>
|
||||
@@ -9,7 +9,7 @@
|
||||
currentChatPage,
|
||||
temporaryChatEnabled
|
||||
} from '$lib/stores';
|
||||
import { tick, getContext, onMount, createEventDispatcher } from 'svelte';
|
||||
import { tick, getContext, onMount, onDestroy, createEventDispatcher } from 'svelte';
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
import { toast } from 'svelte-sonner';
|
||||
@@ -73,7 +73,10 @@
|
||||
messagesLoading = false;
|
||||
};
|
||||
|
||||
$: if (history.currentId) {
|
||||
let pendingRebuild = null;
|
||||
let lastCurrentId = null;
|
||||
|
||||
const buildMessages = () => {
|
||||
let _messages = [];
|
||||
|
||||
let message = history.messages[history.currentId];
|
||||
@@ -86,11 +89,33 @@
|
||||
}
|
||||
visitedMessageIds.add(message.id);
|
||||
|
||||
_messages.unshift({ ...message });
|
||||
_messages.unshift(message);
|
||||
message = message.parentId !== null ? history.messages[message.parentId] : null;
|
||||
}
|
||||
|
||||
messages = _messages;
|
||||
};
|
||||
|
||||
// Throttle message list rebuilds to once per animation frame during streaming.
|
||||
// Structural changes (currentId change) always rebuild immediately.
|
||||
$: if (history.currentId) {
|
||||
const currentIdChanged = history.currentId !== lastCurrentId;
|
||||
lastCurrentId = history.currentId;
|
||||
|
||||
if (currentIdChanged) {
|
||||
// Structural change: new chat, navigation, new message — rebuild immediately
|
||||
cancelAnimationFrame(pendingRebuild);
|
||||
pendingRebuild = null;
|
||||
buildMessages();
|
||||
} else if (history.messages) {
|
||||
// Content update (streaming) — throttle to once per frame
|
||||
if (!pendingRebuild) {
|
||||
pendingRebuild = requestAnimationFrame(() => {
|
||||
pendingRebuild = null;
|
||||
buildMessages();
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
messages = [];
|
||||
}
|
||||
@@ -395,6 +420,10 @@
|
||||
showMessage({ id: parentMessageId }, false);
|
||||
};
|
||||
|
||||
onDestroy(() => {
|
||||
cancelAnimationFrame(pendingRebuild);
|
||||
});
|
||||
|
||||
const triggerScroll = () => {
|
||||
if (autoScroll) {
|
||||
const element = document.getElementById('messages-container');
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
import ChevronUpDown from '$lib/components/icons/ChevronUpDown.svelte';
|
||||
import CommandLine from '$lib/components/icons/CommandLine.svelte';
|
||||
import Cube from '$lib/components/icons/Cube.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
@@ -363,7 +364,9 @@
|
||||
};
|
||||
|
||||
$: if (token) {
|
||||
if (JSON.stringify(token) !== JSON.stringify(_token)) {
|
||||
if (token.text !== _token?.text || token.raw !== _token?.raw) {
|
||||
_token = token;
|
||||
} else if (JSON.stringify(token) !== JSON.stringify(_token)) {
|
||||
_token = token;
|
||||
}
|
||||
}
|
||||
@@ -441,15 +444,17 @@
|
||||
{/if}
|
||||
{:else}
|
||||
<div
|
||||
class="absolute left-0 right-0 py-1.5 pr-3 text-text-300 pl-4.5 text-xs font-medium dark:text-white"
|
||||
class="sticky {stickyButtonsClassName} left-0 right-0 py-1.5 px-3 gap-2 flex items-center justify-end w-full z-10 text-xs text-black dark:text-white bg-white dark:bg-black rounded-t-2xl"
|
||||
>
|
||||
{lang}
|
||||
</div>
|
||||
<div class="flex-1 truncate">
|
||||
<Tooltip content={lang} placement="top-start">
|
||||
<span class=" truncate text-ellipsis">
|
||||
{lang}
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="sticky {stickyButtonsClassName} left-0 right-0 py-1.5 pr-3 flex items-center justify-end w-full z-10 text-xs text-black dark:text-white"
|
||||
>
|
||||
<div class="flex items-center gap-0.5">
|
||||
<div class="flex items-center gap-0.5 shrink-0">
|
||||
<button
|
||||
class="flex gap-1 items-center bg-none border-none transition rounded-md px-1.5 py-0.5 bg-white dark:bg-black"
|
||||
on:click={collapseCodeBlock}
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
settings,
|
||||
showArtifacts,
|
||||
showControls,
|
||||
showEmbeds,
|
||||
showOverview
|
||||
showEmbeds
|
||||
} from '$lib/stores';
|
||||
import FloatingButtons from '../ContentRenderer/FloatingButtons.svelte';
|
||||
import { createMessagesList } from '$lib/utils';
|
||||
@@ -195,7 +194,6 @@
|
||||
await artifactCode.set(value);
|
||||
await showControls.set(true);
|
||||
await showArtifacts.set(true);
|
||||
await showOverview.set(false);
|
||||
await showEmbeds.set(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script>
|
||||
import { onDestroy } from 'svelte';
|
||||
import { marked } from 'marked';
|
||||
import { replaceTokens, processResponseContent } from '$lib/utils';
|
||||
import { user } from '$lib/stores';
|
||||
@@ -34,6 +35,7 @@
|
||||
export let onTaskClick = () => {};
|
||||
|
||||
let tokens = [];
|
||||
let pendingUpdate = null;
|
||||
|
||||
const options = {
|
||||
throwOnError: false,
|
||||
@@ -53,13 +55,27 @@
|
||||
]
|
||||
});
|
||||
|
||||
$: (async () => {
|
||||
if (content) {
|
||||
tokens = marked.lexer(
|
||||
replaceTokens(processResponseContent(content), model?.name, $user?.name)
|
||||
);
|
||||
const parseTokens = () => {
|
||||
tokens = marked.lexer(replaceTokens(processResponseContent(content), model?.name, $user?.name));
|
||||
};
|
||||
|
||||
// Throttle parsing to once per animation frame while streaming
|
||||
$: if (content) {
|
||||
if (done) {
|
||||
cancelAnimationFrame(pendingUpdate);
|
||||
pendingUpdate = null;
|
||||
parseTokens();
|
||||
} else if (!pendingUpdate) {
|
||||
pendingUpdate = requestAnimationFrame(() => {
|
||||
pendingUpdate = null;
|
||||
parseTokens();
|
||||
});
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
cancelAnimationFrame(pendingUpdate);
|
||||
});
|
||||
</script>
|
||||
|
||||
{#key id}
|
||||
|
||||
@@ -1,5 +1,21 @@
|
||||
<script lang="ts">
|
||||
<script lang="ts" context="module">
|
||||
import type { renderToString as katexRenderToString } from 'katex';
|
||||
|
||||
// Module-level singleton: load katex once, share across all KatexRenderer instances
|
||||
let katexRenderer: Promise<typeof katexRenderToString> | null = null;
|
||||
function getKatexRenderer(): Promise<typeof katexRenderToString> {
|
||||
if (!katexRenderer) {
|
||||
katexRenderer = Promise.all([
|
||||
import('katex'),
|
||||
import('katex/contrib/mhchem'),
|
||||
import('katex/dist/katex.min.css')
|
||||
]).then(([katex]) => katex.renderToString);
|
||||
}
|
||||
return katexRenderer;
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
export let content: string;
|
||||
@@ -8,12 +24,7 @@
|
||||
let renderToString: typeof katexRenderToString | null = null;
|
||||
|
||||
onMount(async () => {
|
||||
const [katex] = await Promise.all([
|
||||
import('katex'),
|
||||
import('katex/contrib/mhchem'),
|
||||
import('katex/dist/katex.min.css')
|
||||
]);
|
||||
renderToString = katex.renderToString;
|
||||
renderToString = await getKatexRenderer();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -60,10 +60,15 @@
|
||||
|
||||
let selectedModelIdx = null;
|
||||
|
||||
let message = JSON.parse(JSON.stringify(history.messages[messageId]));
|
||||
let message = structuredClone(history.messages[messageId]);
|
||||
$: if (history.messages) {
|
||||
if (JSON.stringify(message) !== JSON.stringify(history.messages[messageId])) {
|
||||
message = JSON.parse(JSON.stringify(history.messages[messageId]));
|
||||
const source = history.messages[messageId];
|
||||
if (source) {
|
||||
if (message.content !== source.content || message.done !== source.done) {
|
||||
message = structuredClone(source);
|
||||
} else if (JSON.stringify(message) !== JSON.stringify(source)) {
|
||||
message = structuredClone(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +253,9 @@
|
||||
<div class=" flex w-full mb-4.5 border-b border-gray-200 dark:border-gray-850">
|
||||
<div
|
||||
class="flex gap-2 scrollbar-none overflow-x-auto w-fit text-center font-medium bg-transparent pt-1 text-sm"
|
||||
on:wheel|preventDefault={(e) => {
|
||||
e.currentTarget.scrollLeft += e.deltaY;
|
||||
}}
|
||||
>
|
||||
{#each Object.keys(groupedMessageIds) as modelIdx}
|
||||
{#if groupedMessageIdsIdx[modelIdx] !== undefined && (groupedMessageIds[modelIdx]?.messageIds ?? []).length > 0}
|
||||
|
||||
@@ -119,10 +119,18 @@
|
||||
export let messageId;
|
||||
export let selectedModels = [];
|
||||
|
||||
let message: MessageType = JSON.parse(JSON.stringify(history.messages[messageId]));
|
||||
let message: MessageType = structuredClone(history.messages[messageId]);
|
||||
$: if (history.messages) {
|
||||
if (JSON.stringify(message) !== JSON.stringify(history.messages[messageId])) {
|
||||
message = JSON.parse(JSON.stringify(history.messages[messageId]));
|
||||
const source = history.messages[messageId];
|
||||
if (source) {
|
||||
// Fast path: O(1) check on the fields that change most often (content during streaming, done at end)
|
||||
// Avoids 2x O(n) JSON.stringify calls that are always true during streaming anyway
|
||||
if (message.content !== source.content || message.done !== source.done) {
|
||||
message = structuredClone(source);
|
||||
} else if (JSON.stringify(message) !== JSON.stringify(source)) {
|
||||
// Slow path: full comparison for infrequent changes (sources, annotations, status, etc.)
|
||||
message = structuredClone(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
status = history.at(-1);
|
||||
}
|
||||
|
||||
$: if (JSON.stringify(statusHistory) !== JSON.stringify(history)) {
|
||||
$: if (
|
||||
statusHistory.length !== history.length ||
|
||||
JSON.stringify(statusHistory) !== JSON.stringify(history)
|
||||
) {
|
||||
history = statusHistory;
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -52,10 +52,15 @@
|
||||
let messageEditTextAreaElement: HTMLTextAreaElement;
|
||||
let editScrollContainer: HTMLDivElement;
|
||||
|
||||
let message = JSON.parse(JSON.stringify(history.messages[messageId]));
|
||||
let message = structuredClone(history.messages[messageId]);
|
||||
$: if (history.messages) {
|
||||
if (JSON.stringify(message) !== JSON.stringify(history.messages[messageId])) {
|
||||
message = JSON.parse(JSON.stringify(history.messages[messageId]));
|
||||
const source = history.messages[messageId];
|
||||
if (source) {
|
||||
if (message.content !== source.content) {
|
||||
message = structuredClone(source);
|
||||
} else if (JSON.stringify(message) !== JSON.stringify(source)) {
|
||||
message = structuredClone(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class="flex-1 overflow-hidden max-w-full py-0.5
|
||||
class="flex-1 overflow-hidden max-w-full mt-0.5 py-0.5
|
||||
{$showSidebar ? 'ml-1' : ''}
|
||||
"
|
||||
>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="px-4 py-3 shadow-md rounded-xl dark:bg-black bg-white border dark:border-gray-900 w-60 h-20 group"
|
||||
class="px-4 py-3 shadow-md rounded-xl dark:bg-black bg-white border border-gray-100 dark:border-gray-900 w-60 h-20 group"
|
||||
>
|
||||
<Tooltip
|
||||
content={data?.message?.error ? data.message.error.content : data.message.content}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { onMount, tick } from 'svelte';
|
||||
|
||||
import { writable } from 'svelte/store';
|
||||
import { models, showOverview, theme, user } from '$lib/stores';
|
||||
import { models, theme, user } from '$lib/stores';
|
||||
|
||||
import '@xyflow/svelte/dist/style.css';
|
||||
|
||||
@@ -172,31 +172,6 @@
|
||||
</script>
|
||||
|
||||
<div class="w-full h-full relative">
|
||||
<div class=" absolute z-50 w-full flex justify-between dark:text-gray-100 px-4 py-3">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<button
|
||||
class="self-center p-0.5"
|
||||
aria-label={$i18n.t('Back')}
|
||||
on:click={() => {
|
||||
showOverview.set(false);
|
||||
}}
|
||||
>
|
||||
<ArrowLeft className="size-3.5" />
|
||||
</button>
|
||||
<div class=" text-lg font-medium self-center font-primary">{$i18n.t('Chat Overview')}</div>
|
||||
</div>
|
||||
<button
|
||||
class="self-center p-0.5"
|
||||
aria-label={$i18n.t('Close overview')}
|
||||
on:click={() => {
|
||||
onClose();
|
||||
showOverview.set(false);
|
||||
}}
|
||||
>
|
||||
<XMark className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if $nodes.length > 0}
|
||||
<Flow
|
||||
{nodes}
|
||||
|
||||
@@ -60,6 +60,8 @@
|
||||
|
||||
export let toolServers = [];
|
||||
|
||||
export let dragged = false;
|
||||
|
||||
let models = [];
|
||||
let selectedModelIdx = 0;
|
||||
|
||||
@@ -212,6 +214,7 @@
|
||||
bind:webSearchEnabled
|
||||
bind:atSelectedModel
|
||||
bind:showCommands
|
||||
bind:dragged
|
||||
{toolServers}
|
||||
{stopResponse}
|
||||
{createMessagePair}
|
||||
|
||||
@@ -63,7 +63,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class=" py-0.5 flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Stream Chat Response')}
|
||||
</div>
|
||||
<button
|
||||
@@ -100,7 +100,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Stream Delta Chunk Size')}
|
||||
</div>
|
||||
<button
|
||||
@@ -156,7 +156,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class=" py-0.5 flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Function Calling')}
|
||||
</div>
|
||||
<button
|
||||
@@ -185,7 +185,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Reasoning Tags')}
|
||||
</div>
|
||||
<button
|
||||
@@ -250,7 +250,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Seed')}
|
||||
</div>
|
||||
|
||||
@@ -295,7 +295,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Stop Sequence')}
|
||||
</div>
|
||||
|
||||
@@ -339,7 +339,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Temperature')}
|
||||
</div>
|
||||
<button
|
||||
@@ -394,7 +394,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{$i18n.t('Reasoning Effort')}
|
||||
</div>
|
||||
<button
|
||||
@@ -437,7 +437,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'logit_bias'}
|
||||
</div>
|
||||
<button
|
||||
@@ -482,7 +482,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'max_tokens'}
|
||||
</div>
|
||||
|
||||
@@ -537,7 +537,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'top_k'}
|
||||
</div>
|
||||
<button
|
||||
@@ -592,7 +592,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'top_p'}
|
||||
</div>
|
||||
|
||||
@@ -648,7 +648,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'min_p'}
|
||||
</div>
|
||||
<button
|
||||
@@ -703,7 +703,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'frequency_penalty'}
|
||||
</div>
|
||||
|
||||
@@ -759,7 +759,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'presence_penalty'}
|
||||
</div>
|
||||
|
||||
@@ -813,7 +813,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'mirostat'}
|
||||
</div>
|
||||
<button
|
||||
@@ -868,7 +868,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'mirostat_eta'}
|
||||
</div>
|
||||
<button
|
||||
@@ -923,7 +923,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'mirostat_tau'}
|
||||
</div>
|
||||
|
||||
@@ -977,7 +977,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'repeat_last_n'}
|
||||
</div>
|
||||
|
||||
@@ -1033,7 +1033,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'tfs_z'}
|
||||
</div>
|
||||
|
||||
@@ -1089,7 +1089,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'repeat_penalty'}
|
||||
</div>
|
||||
|
||||
@@ -1146,7 +1146,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'use_mmap'}
|
||||
</div>
|
||||
<button
|
||||
@@ -1186,7 +1186,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'use_mlock'}
|
||||
</div>
|
||||
|
||||
@@ -1229,7 +1229,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class=" py-0.5 flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'think'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
<button
|
||||
@@ -1282,7 +1282,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class=" py-0.5 flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'format'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
<button
|
||||
@@ -1321,7 +1321,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'num_keep'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
|
||||
@@ -1374,7 +1374,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'num_ctx'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
|
||||
@@ -1429,7 +1429,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'num_batch'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
|
||||
@@ -1485,7 +1485,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'num_thread'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
|
||||
@@ -1541,7 +1541,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'num_gpu'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
|
||||
@@ -1597,7 +1597,7 @@
|
||||
className="inline-tooltip"
|
||||
>
|
||||
<div class=" py-0.5 flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
{'keep_alive'} ({$i18n.t('Ollama')})
|
||||
</div>
|
||||
<button
|
||||
@@ -1633,7 +1633,7 @@
|
||||
{#each Object.keys(params?.custom_params ?? {}) as key}
|
||||
<div class=" py-0.5 w-full justify-between mb-1">
|
||||
<div class="flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
<div class=" self-center text-xs">
|
||||
<input
|
||||
type="text"
|
||||
class=" text-xs w-full bg-transparent outline-none"
|
||||
|
||||
+61
-26
@@ -1,24 +1,25 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { createEventDispatcher, onMount, getContext, tick } from 'svelte';
|
||||
import { getModels as _getModels, getToolServersData } from '$lib/apis';
|
||||
import { createEventDispatcher, onMount, getContext } from 'svelte';
|
||||
import { getToolServersData } from '$lib/apis';
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import { models, settings, toolServers, user } from '$lib/stores';
|
||||
import { settings, toolServers, terminalServers } from '$lib/stores';
|
||||
|
||||
import Switch from '$lib/components/common/Switch.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import Connection from './Tools/Connection.svelte';
|
||||
import Terminals from './Integrations/Terminals.svelte';
|
||||
|
||||
import AddToolServerModal from '$lib/components/AddToolServerModal.svelte';
|
||||
|
||||
export let saveSettings: Function;
|
||||
|
||||
let servers = null;
|
||||
let terminalServerConfigs: { url: string; key: string; name?: string; enabled: boolean }[] = [];
|
||||
let showConnectionModal = false;
|
||||
|
||||
const addConnectionHandler = async (server) => {
|
||||
@@ -28,27 +29,45 @@
|
||||
|
||||
const updateHandler = async () => {
|
||||
await saveSettings({
|
||||
toolServers: servers
|
||||
toolServers: servers,
|
||||
terminalServers: terminalServerConfigs
|
||||
});
|
||||
|
||||
let toolServersData = await getToolServersData($settings?.toolServers ?? []);
|
||||
toolServersData = toolServersData.filter((data) => {
|
||||
if (data.error) {
|
||||
toast.error(
|
||||
$i18n.t(`Failed to connect to {{URL}} OpenAPI tool server`, {
|
||||
URL: data?.url
|
||||
})
|
||||
$i18n.t(`Failed to connect to {{URL}} OpenAPI tool server`, { URL: data?.url })
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
toolServers.set(toolServersData);
|
||||
|
||||
// Refresh terminal servers store (preserve system terminals)
|
||||
const existingSystemTerminals = ($terminalServers ?? []).filter((t) => t.id);
|
||||
const activeTerminals = terminalServerConfigs.filter((s) => s.enabled);
|
||||
if (activeTerminals.length > 0) {
|
||||
let terminalServersData = await getToolServersData(
|
||||
activeTerminals.map((t) => ({
|
||||
url: t.url,
|
||||
auth_type: t.auth_type ?? 'bearer',
|
||||
key: t.key ?? '',
|
||||
path: t.path ?? '/openapi.json',
|
||||
config: { enable: true }
|
||||
}))
|
||||
);
|
||||
terminalServersData = terminalServersData.filter((data) => data && !data.error);
|
||||
terminalServers.set([...terminalServersData, ...existingSystemTerminals]);
|
||||
} else {
|
||||
terminalServers.set(existingSystemTerminals);
|
||||
}
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
servers = $settings?.toolServers ?? [];
|
||||
terminalServerConfigs = $settings?.terminalServers ?? [];
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -61,24 +80,19 @@
|
||||
updateHandler();
|
||||
}}
|
||||
>
|
||||
<div class=" overflow-y-scroll scrollbar-hidden h-full">
|
||||
<div class="overflow-y-scroll scrollbar-hidden h-full">
|
||||
{#if servers !== null}
|
||||
<div class="">
|
||||
<div>
|
||||
<div class="pr-1.5">
|
||||
<!-- {$i18n.t(`Failed to connect to {{URL}} OpenAPI tool server`, {
|
||||
URL: 'server?.url'
|
||||
})} -->
|
||||
<div class="">
|
||||
<div class="flex justify-between items-center mb-0.5">
|
||||
<div class="font-medium">{$i18n.t('Manage Tool Servers')}</div>
|
||||
|
||||
<Tooltip content={$i18n.t(`Add Connection`)}>
|
||||
<Tooltip content={$i18n.t('Add Connection')}>
|
||||
<button
|
||||
aria-label={$i18n.t(`Add Connection`)}
|
||||
aria-label={$i18n.t('Add Connection')}
|
||||
class="px-1"
|
||||
on:click={() => {
|
||||
showConnectionModal = true;
|
||||
}}
|
||||
on:click={() => (showConnectionModal = true)}
|
||||
type="button"
|
||||
>
|
||||
<Plus />
|
||||
@@ -91,9 +105,7 @@
|
||||
<Connection
|
||||
bind:connection={server}
|
||||
direct
|
||||
onSubmit={() => {
|
||||
updateHandler();
|
||||
}}
|
||||
onSubmit={() => updateHandler()}
|
||||
onDelete={() => {
|
||||
servers = servers.filter((_, i) => i !== idx);
|
||||
updateHandler();
|
||||
@@ -105,8 +117,7 @@
|
||||
|
||||
<div class="my-1.5">
|
||||
<div
|
||||
class={`text-xs
|
||||
${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t('Connect to your own OpenAPI compatible external tool servers.')}
|
||||
<br />
|
||||
@@ -116,14 +127,38 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class=" text-xs text-gray-600 dark:text-gray-300 mb-2">
|
||||
<div class="text-xs text-gray-600 dark:text-gray-300 mb-2">
|
||||
<a
|
||||
class="underline"
|
||||
href="https://github.com/open-webui/openapi-servers"
|
||||
target="_blank">{$i18n.t('Learn more about OpenAPI tool servers.')}</a
|
||||
target="_blank">{$i18n.t('Learn more about OpenAPI tool servers.')} ↗</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class="border-gray-100/50 dark:border-gray-850/50 my-4" />
|
||||
|
||||
<div class="pr-1.5">
|
||||
<Terminals bind:servers={terminalServerConfigs} onChange={() => updateHandler()} />
|
||||
|
||||
<div class="mt-1.5">
|
||||
<div
|
||||
class={`text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>
|
||||
{$i18n.t(
|
||||
'Connect to Open Terminal instances to browse files and use them as always-on tools. Only one can be active at a time.'
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-gray-600 dark:text-gray-300 mt-1">
|
||||
<a
|
||||
class="underline"
|
||||
href="https://github.com/open-webui/open-terminal"
|
||||
target="_blank">{$i18n.t('Learn more about Open Terminal')} ↗</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex h-full justify-center">
|
||||
@@ -0,0 +1,89 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import Connection from './Terminals/Connection.svelte';
|
||||
import AddTerminalServerModal from '$lib/components/AddTerminalServerModal.svelte';
|
||||
|
||||
export let servers = [];
|
||||
export let onChange: (servers: typeof servers) => void = () => {};
|
||||
|
||||
let showAddModal = false;
|
||||
|
||||
const addServer = (server: (typeof servers)[0]) => {
|
||||
servers = [...servers, server];
|
||||
onChange(servers);
|
||||
};
|
||||
|
||||
const enableServer = (idx: number) => {
|
||||
servers = servers.map((s, i) => ({ ...s, enabled: i === idx }));
|
||||
onChange(servers);
|
||||
};
|
||||
|
||||
const disableServer = (idx: number) => {
|
||||
servers = servers.map((s, i) => (i === idx ? { ...s, enabled: false } : s));
|
||||
onChange(servers);
|
||||
};
|
||||
|
||||
const updateServer = (idx: number, updated: (typeof servers)[0]) => {
|
||||
servers = servers.map((s, i) => (i === idx ? updated : s));
|
||||
onChange(servers);
|
||||
};
|
||||
|
||||
const deleteServer = (idx: number) => {
|
||||
servers = servers.filter((_, i) => i !== idx);
|
||||
onChange(servers);
|
||||
};
|
||||
</script>
|
||||
|
||||
<AddTerminalServerModal bind:show={showAddModal} onSubmit={(server) => addServer(server)} />
|
||||
|
||||
<div>
|
||||
<div class="flex justify-between items-center mb-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="font-medium">{$i18n.t('Open Terminal')}</div>
|
||||
<span
|
||||
class="text-[0.65rem] font-medium uppercase px-1.5 py-0.5 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400"
|
||||
>{$i18n.t('Experimental')}</span
|
||||
>
|
||||
</div>
|
||||
<Tooltip content={$i18n.t('Add Connection')}>
|
||||
<button
|
||||
class="px-1"
|
||||
on:click={() => (showAddModal = true)}
|
||||
type="button"
|
||||
aria-label={$i18n.t('Add Connection')}
|
||||
>
|
||||
<Plus />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1.5">
|
||||
{#each servers as server, idx}
|
||||
<Connection
|
||||
bind:connection={server}
|
||||
onSubmit={(updated) => updateServer(idx, updated)}
|
||||
onDelete={() => deleteServer(idx)}
|
||||
onEnable={() => enableServer(idx)}
|
||||
onDisable={() => disableServer(idx)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if servers.length === 0}
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('No terminal connections configured.')}
|
||||
<a
|
||||
href="https://github.com/open-webui/open-terminal"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="underline hover:text-gray-700 dark:hover:text-gray-200"
|
||||
>
|
||||
{$i18n.t('Learn more')} ↗
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import Switch from '$lib/components/common/Switch.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import Cog6 from '$lib/components/icons/Cog6.svelte';
|
||||
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
||||
import AddTerminalServerModal from '$lib/components/AddTerminalServerModal.svelte';
|
||||
import Cloud from '$lib/components/icons/Cloud.svelte';
|
||||
|
||||
export let connection = { url: '', key: '', name: '', path: '/openapi.json', enabled: false };
|
||||
export let onSubmit: (c: typeof connection) => void = () => {};
|
||||
export let onDelete: () => void = () => {};
|
||||
export let onEnable: () => void = () => {};
|
||||
export let onDisable: () => void = () => {};
|
||||
|
||||
let showConfigModal = false;
|
||||
let showDeleteConfirmDialog = false;
|
||||
</script>
|
||||
|
||||
<AddTerminalServerModal
|
||||
edit
|
||||
bind:show={showConfigModal}
|
||||
{connection}
|
||||
onDelete={() => {
|
||||
showDeleteConfirmDialog = true;
|
||||
}}
|
||||
onSubmit={(c) => {
|
||||
connection = c;
|
||||
onSubmit(c);
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:show={showDeleteConfirmDialog}
|
||||
on:confirm={() => {
|
||||
onDelete();
|
||||
showConfigModal = false;
|
||||
}}
|
||||
/>
|
||||
|
||||
<div class="flex w-full gap-2 items-center">
|
||||
<Tooltip className="w-full relative" content={''} placement="top-start">
|
||||
<div class="flex w-full">
|
||||
<div
|
||||
class="flex-1 relative flex gap-1.5 items-center {!connection?.enabled ? 'opacity-50' : ''}"
|
||||
>
|
||||
<Tooltip content={$i18n.t('Terminal')}>
|
||||
<Cloud className="size-4" strokeWidth="1.5" />
|
||||
</Tooltip>
|
||||
|
||||
<div class="outline-hidden w-full bg-transparent text-sm">
|
||||
{connection.name || connection.url || $i18n.t('New Terminal')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
|
||||
<div class="flex gap-1 items-center">
|
||||
<Tooltip content={$i18n.t('Configure')}>
|
||||
<button
|
||||
class="self-center p-1 bg-transparent hover:bg-gray-100 dark:hover:bg-gray-850 rounded-lg transition"
|
||||
on:click={() => {
|
||||
showConfigModal = true;
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<Cog6 />
|
||||
</button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip content={connection?.enabled ? $i18n.t('Enabled') : $i18n.t('Disabled')}>
|
||||
<Switch
|
||||
state={connection?.enabled}
|
||||
on:change={() => (connection?.enabled ? onDisable() : onEnable())}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
@@ -38,10 +38,12 @@
|
||||
'This is an experimental feature, it may not function as expected and is subject to change at any time.'
|
||||
)}
|
||||
>
|
||||
<div class="text-sm font-medium">
|
||||
<div class="flex items-center gap-2 text-sm font-medium">
|
||||
{$i18n.t('Memory')}
|
||||
|
||||
<span class=" text-xs text-gray-500">({$i18n.t('Experimental')})</span>
|
||||
<span
|
||||
class="text-[0.65rem] font-medium uppercase px-1.5 py-0.5 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400"
|
||||
>{$i18n.t('Experimental')}</span
|
||||
>
|
||||
</div>
|
||||
</Tooltip>
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
import Search from '../icons/Search.svelte';
|
||||
import XMark from '../icons/XMark.svelte';
|
||||
import Connections from './Settings/Connections.svelte';
|
||||
import Tools from './Settings/Tools.svelte';
|
||||
import Integrations from './Settings/Integrations.svelte';
|
||||
import DatabaseSettings from '../icons/DatabaseSettings.svelte';
|
||||
import SettingsAlt from '../icons/SettingsAlt.svelte';
|
||||
import Link from '../icons/Link.svelte';
|
||||
@@ -221,14 +221,18 @@
|
||||
},
|
||||
{
|
||||
id: 'tools',
|
||||
title: 'External Tools',
|
||||
title: 'Integrations',
|
||||
keywords: [
|
||||
'addconnection',
|
||||
'add connection',
|
||||
'integrations',
|
||||
'managetools',
|
||||
'manage tools',
|
||||
'manage tool servers',
|
||||
'managetoolservers',
|
||||
'open terminal',
|
||||
'openterminal',
|
||||
'terminal',
|
||||
'settings'
|
||||
]
|
||||
},
|
||||
@@ -720,7 +724,7 @@
|
||||
<div class=" self-center mr-2">
|
||||
<WrenchAlt strokeWidth="2" />
|
||||
</div>
|
||||
<div class=" self-center">{$i18n.t('External Tools')}</div>
|
||||
<div class=" self-center">{$i18n.t('Integrations')}</div>
|
||||
</button>
|
||||
{/if}
|
||||
{:else if tabId === 'personalization'}
|
||||
@@ -894,7 +898,7 @@
|
||||
}}
|
||||
/>
|
||||
{:else if selectedTab === 'tools'}
|
||||
<Tools
|
||||
<Integrations
|
||||
saveSettings={async (updated) => {
|
||||
await saveSettings(updated);
|
||||
toast.success($i18n.t('Settings saved successfully!'));
|
||||
|
||||
@@ -74,6 +74,7 @@
|
||||
<!-- {$i18n.t('New Temporary Chat')} -->
|
||||
<!-- {$i18n.t('Delete Chat')} -->
|
||||
<!-- {$i18n.t('Open Model Selector')} -->
|
||||
<!-- {$i18n.t('Toggle Dictation')} -->
|
||||
<!-- {$i18n.t('Search')} -->
|
||||
<!-- {$i18n.t('Open Settings')} -->
|
||||
<!-- {$i18n.t('Show Shortcuts')} -->
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onMount } from 'svelte';
|
||||
import { models, config, toolServers, tools } from '$lib/stores';
|
||||
import { models, config, toolServers, tools, terminalServers } from '$lib/stores';
|
||||
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { deleteSharedChatById, getChatById, shareChatById } from '$lib/apis/chats';
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import '$lib/utils/codemirror';
|
||||
|
||||
import { basicSetup, EditorView } from 'codemirror';
|
||||
import { keymap, placeholder } from '@codemirror/view';
|
||||
import { Compartment, EditorState } from '@codemirror/state';
|
||||
@@ -6,7 +8,7 @@
|
||||
import { acceptCompletion } from '@codemirror/autocomplete';
|
||||
import { indentWithTab } from '@codemirror/commands';
|
||||
|
||||
import { indentUnit, LanguageDescription } from '@codemirror/language';
|
||||
import { indentUnit } from '@codemirror/language';
|
||||
import { languages } from '@codemirror/language-data';
|
||||
|
||||
import { oneDark } from '@codemirror/theme-one-dark';
|
||||
@@ -75,41 +77,16 @@
|
||||
export let id = '';
|
||||
export let lang = '';
|
||||
|
||||
let codeEditor;
|
||||
let codeEditor: EditorView | null = null;
|
||||
|
||||
export const focus = () => {
|
||||
codeEditor.focus();
|
||||
codeEditor?.focus();
|
||||
};
|
||||
|
||||
let isDarkMode = false;
|
||||
let editorTheme = new Compartment();
|
||||
let editorLanguage = new Compartment();
|
||||
|
||||
languages.push(
|
||||
LanguageDescription.of({
|
||||
name: 'HCL',
|
||||
extensions: ['hcl', 'tf'],
|
||||
load() {
|
||||
return import('codemirror-lang-hcl').then((m) => m.hcl());
|
||||
}
|
||||
})
|
||||
);
|
||||
languages.push(
|
||||
LanguageDescription.of({
|
||||
name: 'Elixir',
|
||||
extensions: ['ex', 'exs'],
|
||||
load() {
|
||||
return import('codemirror-lang-elixir').then((m) => m.elixir());
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Add 'matlab' alias to Octave language (MATLAB-compatible syntax)
|
||||
const octaveLang = languages.find((l) => l.name === 'Octave');
|
||||
if (octaveLang && !octaveLang.alias.includes('matlab')) {
|
||||
octaveLang.alias.push('matlab');
|
||||
}
|
||||
|
||||
const getLang = async () => {
|
||||
const language = languages.find((l) => l.alias.includes(lang));
|
||||
return await language?.load();
|
||||
@@ -326,6 +303,11 @@ print("${endTag}")
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
document.removeEventListener('keydown', keydownHandler);
|
||||
// Must destroy EditorView so CodeMirror releases internal DOMObserver and DOM refs
|
||||
if (codeEditor) {
|
||||
codeEditor.destroy();
|
||||
codeEditor = null;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
}}
|
||||
>
|
||||
<div
|
||||
class=" w-full font-medium flex items-center justify-between gap-2 {attributes?.done &&
|
||||
class=" w-full flex items-center justify-between gap-2 {attributes?.done &&
|
||||
attributes?.done !== 'true'
|
||||
? 'shimmer'
|
||||
: ''}
|
||||
|
||||
@@ -24,6 +24,10 @@
|
||||
import Tooltip from './Tooltip.svelte';
|
||||
import dayjs from 'dayjs';
|
||||
import Spinner from './Spinner.svelte';
|
||||
import PDFViewer from './PDFViewer.svelte';
|
||||
import Reset from '../icons/Reset.svelte';
|
||||
|
||||
import panzoom, { type PanZoom } from 'panzoom';
|
||||
|
||||
export let item;
|
||||
export let show = false;
|
||||
@@ -45,6 +49,23 @@
|
||||
let excelError = '';
|
||||
let rowCount = 0;
|
||||
|
||||
let pzInstance: PanZoom | null = null;
|
||||
|
||||
const initImagePanzoom = (node: HTMLElement) => {
|
||||
pzInstance = panzoom(node, {
|
||||
bounds: true,
|
||||
boundsPadding: 0.1,
|
||||
zoomSpeed: 0.065
|
||||
});
|
||||
};
|
||||
|
||||
const resetImageView = () => {
|
||||
if (pzInstance) {
|
||||
pzInstance.moveTo(0, 0);
|
||||
pzInstance.zoomAbs(0, 0, 1);
|
||||
}
|
||||
};
|
||||
|
||||
$: isPDF =
|
||||
item?.meta?.content_type === 'application/pdf' ||
|
||||
(item?.name && item?.name.toLowerCase().endsWith('.pdf'));
|
||||
@@ -196,6 +217,10 @@
|
||||
if (item?.context === 'full') {
|
||||
enableFullContent = true;
|
||||
}
|
||||
|
||||
return () => {
|
||||
pzInstance?.dispose();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -360,13 +385,26 @@
|
||||
{/if}
|
||||
|
||||
{#if isImage}
|
||||
<div class="w-full max-h-[70vh] overflow-auto">
|
||||
<img
|
||||
src={`${WEBUI_API_BASE_URL}/files/${item.id}/content`}
|
||||
alt={item?.name ?? 'Image'}
|
||||
class="w-full object-contain rounded-lg"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div class="relative w-full max-h-[70vh] overflow-hidden">
|
||||
<div class="absolute top-2 right-2 z-10">
|
||||
<Tooltip content={$i18n.t('Reset view')}>
|
||||
<button
|
||||
class="p-1.5 rounded-lg bg-white/80 dark:bg-gray-850/80 backdrop-blur-sm shadow-sm hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-500 dark:text-gray-400"
|
||||
on:click={resetImageView}
|
||||
>
|
||||
<Reset className="size-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div use:initImagePanzoom>
|
||||
<img
|
||||
src={`${WEBUI_API_BASE_URL}/files/${item.id}/content`}
|
||||
alt={item?.name ?? 'Image'}
|
||||
class="w-full object-contain rounded-lg"
|
||||
loading="lazy"
|
||||
draggable="false"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{:else if selectedTab === ''}
|
||||
{#if item?.file?.data}
|
||||
@@ -443,10 +481,9 @@
|
||||
playsinline
|
||||
/>
|
||||
{:else if isPDF}
|
||||
<iframe
|
||||
title={item?.name}
|
||||
src={`${WEBUI_API_BASE_URL}/files/${item.id}/content`}
|
||||
class="w-full h-[70vh] border-0 rounded-lg"
|
||||
<PDFViewer
|
||||
url={`${WEBUI_API_BASE_URL}/files/${item.id}/content`}
|
||||
className="w-full h-[70vh] border-0 rounded-lg"
|
||||
/>
|
||||
{:else if isExcel}
|
||||
{#if excelError}
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.mjs?url';
|
||||
import panzoom, { type PanZoom } from 'panzoom';
|
||||
import Spinner from './Spinner.svelte';
|
||||
|
||||
export let url: string | null = null;
|
||||
export let data: ArrayBuffer | Uint8Array | null = null;
|
||||
export let className = 'w-full h-[70vh]';
|
||||
|
||||
let outerContainer: HTMLDivElement;
|
||||
let sceneElement: HTMLDivElement;
|
||||
let loading = true;
|
||||
let error = '';
|
||||
let pdfDoc: any = null;
|
||||
let pzInstance: PanZoom | null = null;
|
||||
let zoomLevel = 1;
|
||||
let rerenderTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let lastRenderedZoom = 1;
|
||||
|
||||
const initPanzoom = () => {
|
||||
if (pzInstance) {
|
||||
pzInstance.dispose();
|
||||
}
|
||||
if (sceneElement) {
|
||||
pzInstance = panzoom(sceneElement, {
|
||||
bounds: true,
|
||||
boundsPadding: 0.1,
|
||||
zoomSpeed: 0.065,
|
||||
beforeWheel: (e) => {
|
||||
// Only zoom on pinch (ctrlKey / metaKey); let normal scroll pass through
|
||||
if (!e.ctrlKey && !e.metaKey) {
|
||||
return true; // returning true cancels the panzoom wheel handling
|
||||
}
|
||||
return false;
|
||||
},
|
||||
beforeMouseDown: (e) => {
|
||||
// Only allow drag-to-pan when zoomed in (not at default scale)
|
||||
const transform = pzInstance?.getTransform();
|
||||
if (transform && Math.abs(transform.scale - 1) < 0.01) {
|
||||
return true; // cancel panzoom mouse handling at 1x — allow text selection / normal interaction
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
pzInstance.on('zoom', () => {
|
||||
zoomLevel = pzInstance?.getTransform()?.scale ?? 1;
|
||||
// Debounced re-render at new resolution so text stays crisp
|
||||
if (rerenderTimer) clearTimeout(rerenderTimer);
|
||||
rerenderTimer = setTimeout(() => {
|
||||
if (Math.abs(zoomLevel - lastRenderedZoom) > 0.05) {
|
||||
rerenderPages(zoomLevel);
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const zoomIn = () => {
|
||||
if (!pzInstance || !outerContainer) return;
|
||||
const cx = outerContainer.clientWidth / 2;
|
||||
const cy = outerContainer.clientHeight / 2;
|
||||
pzInstance.zoomTo(cx, cy, 1.25); // +25%
|
||||
zoomLevel = pzInstance.getTransform().scale;
|
||||
};
|
||||
|
||||
const zoomOut = () => {
|
||||
if (!pzInstance || !outerContainer) return;
|
||||
const cx = outerContainer.clientWidth / 2;
|
||||
const cy = outerContainer.clientHeight / 2;
|
||||
pzInstance.zoomTo(cx, cy, 0.8); // -20% (inverse of 1.25)
|
||||
zoomLevel = pzInstance.getTransform().scale;
|
||||
};
|
||||
|
||||
export const resetView = () => {
|
||||
if (pzInstance) {
|
||||
pzInstance.moveTo(0, 0);
|
||||
pzInstance.zoomAbs(0, 0, 1);
|
||||
zoomLevel = 1;
|
||||
rerenderPages(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Re-render existing canvases at a new zoom level (preserves panzoom transform)
|
||||
const rerenderPages = async (forZoom: number) => {
|
||||
if (!pdfDoc || !sceneElement) return;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const containerWidth = outerContainer?.clientWidth || 800;
|
||||
|
||||
const canvases = sceneElement.querySelectorAll('canvas');
|
||||
|
||||
for (let i = 0; i < canvases.length; i++) {
|
||||
const page = await pdfDoc.getPage(i + 1);
|
||||
const viewport = page.getViewport({ scale: 1 });
|
||||
const cssScale = containerWidth / viewport.width;
|
||||
const renderScale = cssScale * forZoom * dpr;
|
||||
const scaledViewport = page.getViewport({ scale: renderScale });
|
||||
|
||||
const canvas = canvases[i];
|
||||
canvas.width = scaledViewport.width;
|
||||
canvas.height = scaledViewport.height;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
await page.render({ canvasContext: ctx, viewport: scaledViewport }).promise;
|
||||
}
|
||||
}
|
||||
lastRenderedZoom = forZoom;
|
||||
};
|
||||
|
||||
const renderAllPages = async () => {
|
||||
if (!pdfDoc || !sceneElement) return;
|
||||
|
||||
// Clear previous canvases
|
||||
sceneElement.innerHTML = '';
|
||||
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
|
||||
for (let i = 1; i <= pdfDoc.numPages; i++) {
|
||||
const page = await pdfDoc.getPage(i);
|
||||
const viewport = page.getViewport({ scale: 1 });
|
||||
|
||||
// Scale to fit container width
|
||||
const containerWidth = outerContainer?.clientWidth || 800;
|
||||
const cssScale = containerWidth / viewport.width;
|
||||
const renderScale = cssScale * dpr;
|
||||
const scaledViewport = page.getViewport({ scale: renderScale });
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = scaledViewport.width;
|
||||
canvas.height = scaledViewport.height;
|
||||
// CSS size stays at the CSS-pixel dimensions for layout
|
||||
canvas.style.width = `${Math.round(cssScale * viewport.width)}px`;
|
||||
canvas.style.height = `${Math.round(cssScale * viewport.height)}px`;
|
||||
canvas.style.display = 'block';
|
||||
|
||||
if (i > 1) {
|
||||
canvas.style.marginTop = '4px';
|
||||
}
|
||||
|
||||
sceneElement.appendChild(canvas);
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
await page.render({
|
||||
canvasContext: ctx,
|
||||
viewport: scaledViewport
|
||||
}).promise;
|
||||
}
|
||||
|
||||
lastRenderedZoom = 1;
|
||||
initPanzoom();
|
||||
};
|
||||
|
||||
const loadPdf = async () => {
|
||||
if (!url && !data) return;
|
||||
|
||||
loading = true;
|
||||
error = '';
|
||||
|
||||
try {
|
||||
const pdfjs = await import('pdfjs-dist');
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = pdfWorkerUrl;
|
||||
|
||||
let pdfData: ArrayBuffer | Uint8Array;
|
||||
if (data) {
|
||||
pdfData = data;
|
||||
} else {
|
||||
// Fetch with credentials so auth cookies are sent
|
||||
const res = await fetch(url!, { credentials: 'include' });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
pdfData = await res.arrayBuffer();
|
||||
}
|
||||
pdfDoc = await pdfjs.getDocument({ data: pdfData }).promise;
|
||||
await renderAllPages();
|
||||
} catch (e) {
|
||||
console.error('PDF render error:', e);
|
||||
error = 'Failed to load PDF.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
loadPdf();
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (rerenderTimer) clearTimeout(rerenderTimer);
|
||||
pzInstance?.dispose();
|
||||
if (pdfDoc) {
|
||||
pdfDoc.destroy();
|
||||
pdfDoc = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="relative {className}">
|
||||
{#if loading}
|
||||
<div class="absolute inset-0 flex items-center justify-center">
|
||||
<Spinner className="size-5" />
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="absolute inset-0 flex items-center justify-center text-sm text-red-500">
|
||||
{error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="overflow-y-auto h-full" bind:this={outerContainer}>
|
||||
<div bind:this={sceneElement} class="w-full"></div>
|
||||
</div>
|
||||
|
||||
{#if !loading && !error && pdfDoc}
|
||||
<div
|
||||
class="absolute bottom-3 left-1/2 -translate-x-1/2 z-10 flex items-center gap-0.5 rounded-lg bg-white/90 dark:bg-gray-850/90 backdrop-blur-sm shadow-lg border border-gray-200/60 dark:border-gray-700/60 px-1 py-0.5"
|
||||
>
|
||||
<button
|
||||
class="p-1.5 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-500 dark:text-gray-400"
|
||||
on:click={zoomOut}
|
||||
aria-label="Zoom out"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M4 10a.75.75 0 0 1 .75-.75h10.5a.75.75 0 0 1 0 1.5H4.75A.75.75 0 0 1 4 10Z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
class="px-1.5 py-1 min-w-[3rem] text-center text-[11px] font-medium text-gray-500 dark:text-gray-400 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition tabular-nums"
|
||||
on:click={resetView}
|
||||
aria-label="Reset zoom"
|
||||
>
|
||||
{Math.round(zoomLevel * 100)}%
|
||||
</button>
|
||||
<button
|
||||
class="p-1.5 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition text-gray-500 dark:text-gray-400"
|
||||
on:click={zoomIn}
|
||||
aria-label="Zoom in"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
d="M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -12,6 +12,7 @@
|
||||
export let inputClassName = 'w-full text-sm py-0.5 bg-transparent';
|
||||
export let showButtonClassName = 'pl-1.5 transition bg-transparent';
|
||||
export let screenReader = true;
|
||||
export let autocomplete = 'off';
|
||||
|
||||
let show = false;
|
||||
</script>
|
||||
@@ -25,13 +26,10 @@
|
||||
class={`${inputClassName} ${show ? '' : 'password'} ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : ' outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-600'}`}
|
||||
{placeholder}
|
||||
type={type === 'password' && !show ? 'password' : 'text'}
|
||||
{value}
|
||||
bind:value
|
||||
required={required && !readOnly}
|
||||
disabled={readOnly}
|
||||
on:change={(e) => {
|
||||
value = e.target.value;
|
||||
}}
|
||||
autocomplete="off"
|
||||
{autocomplete}
|
||||
/>
|
||||
<button
|
||||
class={showButtonClassName}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user