Compare commits

...

26 Commits

Author SHA1 Message Date
Danny Avila
f170d5ba23 chore: add back Call component from rebase, increase max file size cache 2025-02-13 16:42:03 -05:00
Marco Beretta
c768b8feb1 feat: enhance call functionality with VAD integration and mute handling 2025-02-13 16:42:02 -05:00
Marco Beretta
7aed891838 feat: stream back audio to user (test) 2025-02-13 16:42:02 -05:00
Marco Beretta
964d47cfa3 fix: both webrtc-client and webrtc-server 2025-02-13 16:42:01 -05:00
Marco Beretta
9c0c341dee feat: move to Socket.IO 2025-02-13 16:42:01 -05:00
Marco Beretta
7717d3a514 feat: Implement WebRTC messaging and audio handling in the WebRTC service 2025-02-13 16:42:01 -05:00
Marco Beretta
d5bc8d3869 feat: Add WebSocket functionality and integrate call features in the chat component 2025-02-13 16:42:00 -05:00
Marco Beretta
6b90817ae0 WIP: Implement Realtime Ephemeral Token functionality and update related components 2025-02-13 16:42:00 -05:00
Marco Beretta
12d7028a18 feat: Add CallButton component and integrate with SendButton for improved messaging functionality 2025-02-13 16:41:59 -05:00
github-actions[bot]
52a6de2aa7 🌍 i18n: Update translation.json with latest translations (#5855)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-02-13 16:06:25 -05:00
Ruben Talstra
750b22d5f4 🌏 i18n: fix Traditional Chinese Language Option (#5854) 2025-02-13 14:20:30 -05:00
Danny Avila
28fe1218c5 🔧 fix: Ariakit Combobox Virtualization (#5851)
Ariakit Combobox was not working well with several virtualization libraries as automated focus management was conflicting with scrolling/styling required of other virtualization methods. The entire strategy was replaced using experimental ariakit virtualization component `SelectRenderer`

Performance of component was also improved as a result of latest ariakit lib changes
2025-02-13 10:07:40 -05:00
github-actions[bot]
e402979cc5 🌍 i18n: Update translation.json with latest translations (#5849)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-02-13 09:34:14 -05:00
Ruben Talstra
4c8311b606 🛡️ chore: patch elliptic to address GHSA-vjh7-7g9h-fjfh (#5848) 2025-02-13 08:20:11 -05:00
Danny Avila
4fa13f45e3 🔃 refactor: Parent Message ID Handling on Error, Update Translations, Bump Agents (#5833)
* 📦 chore: Update @librechat/agents to version 2.0.5

* fix: Update error handling in AskController and EditController to include overrideParentMessageId when catching errors

* fix: Update parentMessageId assignment in AgentController to prioritize overrideParentMessageId

* 🌍 i18n: Update translation.json with latest translations

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-02-12 16:49:32 -05:00
Ruben Talstra
7f48030452 🔄 chore: Enforce 18next Language Keys (#5803)
* chore: enforcing language keys to adhere to the new standard.

* chore: enforcing i18n forbids to write plain text in JSX markup

* chore: enforcing i18n forbids to write plain text in JSX markup

* fix: ci with checkbox for unused keys :)

* refactor: removed all the unused `i18n` keys
2025-02-12 15:48:13 -05:00
Danny Avila
2a506df443 🪄 fix: Agent Artifacts condition 2025-02-11 19:44:20 -05:00
Danny Avila
bfbaaebd2b 🪄 feat: Agent Artifacts (#5804)
* refactor: remove artifacts toggle

* refactor: allow hiding side panel while allowing artifacts view

* chore: rename SidePanelGroup to SidePanel for clarity

* Revert "refactor: remove artifacts toggle"

This reverts commit f884c2cfcd.

* feat: add artifacts capability to agent configuration

* refactor: conditionally set artifacts mode based on endpoint type

* feat: Artifacts Capability for Agents

* refactor: enhance getStreamText method to handle intermediate replies and add `stream_options` for openai/azure

* feat: localize progress text and improve UX in CodeAnalyze and ExecuteCode components for expanding analysis
2025-02-11 18:00:38 -05:00
Danny Avila
46f034250d v0.7.7-rc1 (#5801) 2025-02-11 11:45:07 -05:00
Danny Avila
4de9619bd9 🧠 fix: Handle Reasoning Chunk Edge Cases (#5800)
* refactor: better reasoning parsing

* style: better model selector mobile styling

* chore: bump vite
2025-02-11 11:28:18 -05:00
Ruben Talstra
404b27d045 📦 chore: Bump Packages (#5791)
* chore: started with updating packages to new version.
(a lot are outdated)

* fix: eslint to pass when no matching files changed.

* fix: eslint to pass when no matching files changed.

* fix: issue with strict in actions with the test

* chore: update more dependencies

* feat: scan for unused imported packages

* feat: scan for unused imported packages

* feat: scan for unused imported packages

* feat: scan for unused imported packages

* feat: scan for unused imported packages

* feat: scan for unused imported packages

* feat: scan for unused imported packages

* chore: removed Unused NPM Packages

* chore: removed Unused NPM Packages in `client/package.json`

* chore: removed Unused NPM Packages in `client/package.json`

* chore: Only comments when there are actual unused dependencies.

* chore: Only comments when there are actual unused dependencies.

* ci: test if it detects unused packages.

* ci: removed unused packages.

* ci: both static and dynamic i18n keys

* ci: revert back to no dynamic. use official nesting

* chore: remove override package: ajv
2025-02-11 09:55:13 -05:00
github-actions[bot]
936199b950 🌍 i18n: Update translation.json with latest translations (#5789)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-02-11 09:53:26 -05:00
owengo
d844e56c50 🔨 feat: Use x-strict attribute in OpenAPI Actions for Strict Function Definition (#4639)
* feat: manage an 'x-strict': true attribute in openapi specs for assistants which generates function calls with stric attribute

* fix typo and lint errors

---------

Co-authored-by: Olivier Schiavo <olivier.schiavo@wengo.com>
2025-02-10 16:02:21 -05:00
Ruben Talstra
aea055b597 🔄 chore: Refactor Locize Workflow for Improved Translation Sync (#5781) 2025-02-10 16:01:27 -05:00
Ruben Talstra
3d0c27f525 🛠️ ci: Add Workflow to Detect Unused i18next Keys in PRs (#5782)
* created: checks for unused i18n keys in codebase.

* updated the file to test this new check on this PR.

* updated the file to test this new check on this PR.

* updated the file to test this new check on this PR.

* updated the file to test this new check on this PR.

* updated the file to test this new check on this PR.

* removed the testing option. will now only run in `client/src/**`
2025-02-10 16:00:57 -05:00
Ruben Talstra
d99a9db3f6 feat: OAuth for Actions (#5693)
* feat: OAuth for Actions

* WIP: PoC flow state manager

* refactor: Add identifier field to token model from action schema

* chore: fix potential file type issues

* ci: fix type issue with action metadata auth

* fix: ensure FlowManagerOptions has a default ttl value

* WIP: OAUTH actions

* WIP: first pass OAuth Action

* fix: standardize identifier usage in OAuth flow handling

* fix: update token retrieval to include userId in query and use correct identifier

* refacotr: update token retrieval to use userId for OAuth token query

* feat: Tool Call Auth styling

* fix: streamline token creation and add type field to token schema

* refactor: cleanup OAuth flow by encrypting client credentials and ensuring oauth operations only run under condition

* refactor: use encrypted credentials in OAuth callback

* fix: update Token collection indexes to use expiresAt TTL index and not createdAt legacy index

* refactor: enhance Token index cleanup by improving logging and removing redundant index creation logic

* refactor: remove unused OAuth login route and related logic for improved clarity

* refactor: replace fetch with axios for OAuth token exchange and improve error handling

* refactor: better UX after authentication before oauth tool execution

* refactor: implement cleanup handlers for FlowStateManager intervals to enhance resource management

* refactor: encrypt OAuth tokens before storing and decrypt upon retrieval for enhanced security

* refactor: enhance authentication success page with improved styling and countdown feature

* refactor: add response_type parameter to OAuth redirect URI for improved compatibility

* chore: update translation.json new localizations

* chore: remove unused OGDialog import from OGDialogTemplate component

* refactor: Actions Auth using new Dialog styling, use same component with Agents/Assistants

* refactor: update removeNullishValues function to support removal of empty strings and adjust transform usage in schemas

* chore: bump version of librechat-data-provider to 0.7.6991

* refactor: integrate removeNullishValues function to clean metadata before encryption in agent and assistant routes

* refactor: update OAuth input fields to use 'password' type for better security

* refactor: update localization placeholders for sign-in message to use double curly braces

* refactor: add access_type parameter for offline access in createActionTool function

* refactor: implement handleOAuthToken function for token management and encryption

* feat: refresh token support

* refactor: add default expiration for access token and error handling for missing token

* feat: localizations for ActionAuth

* refactor: set refresh token expiration to null to not expire if expiry never given

* fix: prevent crash fromerror within async handleAbortError in AskController, EditController, and AgentController

* feat: Action Callback URL

* 🌍 i18n: Update translation.json with latest translations

* refactor: handle errors in flow state checking to prevent unhandled promise rejections

* fix: improve flow state concurrency to prevent multiple token creation calls

* refactor: RequestExecutor to use separate axios instance

* refactor: improve concurrency flows by keeping completed state until TTL expiry

* refactor: increase TTL for flow state management and adjust monitoring interval

* ci: mock axios instance creation in actions spec

* feat: add Babel and Jest configuration files; implement FlowStateManager tests with concurrency handling

* chore: add disableOAuth prop to ActionsAuth (not implemented for Assistants yet)

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-02-10 15:56:08 -05:00
166 changed files with 9217 additions and 4040 deletions

View File

@@ -41,19 +41,32 @@ jobs:
# Extract the base commit SHA from the pull_request event payload.
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
echo "Base commit SHA: $BASE_SHA"
# List files changed between the base commit and HEAD, filtering only those in api/ or client/
CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "$BASE_SHA" HEAD | grep -E '^(api|client)/.*\.(js|jsx|ts|tsx)$')
echo "Files to lint:"
# Get changed files (only JS/TS files in api/ or client/)
CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "$BASE_SHA" HEAD | grep -E '^(api|client)/.*\.(js|jsx|ts|tsx)$' || true)
# Debug output
echo "Changed files:"
echo "$CHANGED_FILES"
# Run ESLint on the changed files.
# Ensure there are files to lint before running ESLint
if [[ -z "$CHANGED_FILES" ]]; then
echo "No matching files changed. Skipping ESLint."
echo "UPLOAD_SARIF=false" >> $GITHUB_ENV
exit 0
fi
# Set variable to allow SARIF upload
echo "UPLOAD_SARIF=true" >> $GITHUB_ENV
# Run ESLint
npx eslint --no-error-on-unmatched-pattern \
--config eslint.config.mjs \
--format @microsoft/eslint-formatter-sarif \
--output-file eslint-results.sarif $CHANGED_FILES || true
- name: Upload analysis results to GitHub
if: env.UPLOAD_SARIF == 'true'
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: eslint-results.sarif

84
.github/workflows/i18n-unused-keys.yml vendored Normal file
View File

@@ -0,0 +1,84 @@
name: Detect Unused i18next Strings
on:
pull_request:
paths:
- "client/src/**"
jobs:
detect-unused-i18n-keys:
runs-on: ubuntu-latest
permissions:
pull-requests: write # Required for posting PR comments
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Find unused i18next keys
id: find-unused
run: |
echo "🔍 Scanning for unused i18next keys..."
# Define paths
I18N_FILE="client/src/locales/en/translation.json"
SOURCE_DIR="client/src"
# Check if translation file exists
if [[ ! -f "$I18N_FILE" ]]; then
echo "::error title=Missing i18n File::Translation file not found: $I18N_FILE"
exit 1
fi
# Extract all keys from the JSON file
KEYS=$(jq -r 'keys[]' "$I18N_FILE")
# Track unused keys
UNUSED_KEYS=()
# Check if each key is used in the source code
for KEY in $KEYS; do
if ! grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$SOURCE_DIR"; then
UNUSED_KEYS+=("$KEY")
fi
done
# Output results
if [[ ${#UNUSED_KEYS[@]} -gt 0 ]]; then
echo "🛑 Found ${#UNUSED_KEYS[@]} unused i18n keys:"
echo "unused_keys=$(echo "${UNUSED_KEYS[@]}" | jq -R -s -c 'split(" ")')" >> $GITHUB_ENV
for KEY in "${UNUSED_KEYS[@]}"; do
echo "::warning title=Unused i18n Key::'$KEY' is defined but not used in the codebase."
done
else
echo "✅ No unused i18n keys detected!"
echo "unused_keys=[]" >> $GITHUB_ENV
fi
- name: Post verified comment on PR
if: env.unused_keys != '[]'
run: |
PR_NUMBER=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
# Format the unused keys list as checkboxes for easy manual checking.
FILTERED_KEYS=$(echo "$unused_keys" | jq -r '.[]' | grep -v '^\s*$' | sed 's/^/- [ ] `/;s/$/`/' )
COMMENT_BODY=$(cat <<EOF
### 🚨 Unused i18next Keys Detected
The following translation keys are defined in \`translation.json\` but are **not used** in the codebase:
$FILTERED_KEYS
⚠️ **Please remove these unused keys to keep the translation files clean.**
EOF
)
gh api "repos/${{ github.repository }}/issues/${PR_NUMBER}/comments" \
-f body="$COMMENT_BODY" \
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Fail workflow if unused keys found
if: env.unused_keys != '[]'
run: exit 1

View File

@@ -1,4 +1,4 @@
name: Push New Keys & Create Translation PR
name: Sync Locize Translations & Create Translation PR
on:
push:
@@ -7,8 +7,8 @@ on:
types: [locize/versionPublished]
jobs:
push-new-keys:
name: Push Missing Translation Keys to locize
sync-translations:
name: Sync Translation Keys with Locize
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
@@ -22,23 +22,22 @@ jobs:
- name: Install locize CLI
run: npm install -g locize-cli
# Only push keys if this workflow was triggered by a push event.
- name: Push Missing Translation Keys to locize
# Sync translations (Push missing keys & remove deleted ones)
- name: Sync Locize with Repository
if: ${{ github.event_name == 'push' }}
run: |
cd client/src/locales
locize save-missing --api-key ${{ secrets.LOCIZE_API_KEY }} --project-id ${{ secrets.LOCIZE_PROJECT_ID }} --language en
locize sync --api-key ${{ secrets.LOCIZE_API_KEY }} --project-id ${{ secrets.LOCIZE_PROJECT_ID }} --language en
# When triggered by repository_dispatch, skip pushing new keys.
- name: Skip push step on non-push events
# When triggered by repository_dispatch, skip sync step.
- name: Skip sync step on non-push events
if: ${{ github.event_name != 'push' }}
run: echo "Skipping push of new keys as the event is not a push."
run: echo "Skipping sync as the event is not a push."
create-pull-request:
name: Create Translation PR on Version Published
runs-on: ubuntu-latest
# This job will wait for push-new-keys to complete.
needs: push-new-keys
needs: sync-translations
permissions:
contents: write
pull-requests: write

147
.github/workflows/unused-packages.yml vendored Normal file
View File

@@ -0,0 +1,147 @@
name: Detect Unused NPM Packages
on: [pull_request]
jobs:
detect-unused-packages:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v4
- name: Use Node.js 20.x
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install depcheck
run: npm install -g depcheck
- name: Validate JSON files
run: |
for FILE in package.json client/package.json api/package.json; do
if [[ -f "$FILE" ]]; then
jq empty "$FILE" || (echo "::error title=Invalid JSON::$FILE is invalid" && exit 1)
fi
done
- name: Extract Dependencies Used in Scripts
id: extract-used-scripts
run: |
extract_deps_from_scripts() {
local package_file=$1
if [[ -f "$package_file" ]]; then
jq -r '.scripts | to_entries[].value' "$package_file" | \
grep -oE '([a-zA-Z0-9_-]+)' | sort -u > used_scripts.txt
else
touch used_scripts.txt
fi
}
extract_deps_from_scripts "package.json"
mv used_scripts.txt root_used_deps.txt
extract_deps_from_scripts "client/package.json"
mv used_scripts.txt client_used_deps.txt
extract_deps_from_scripts "api/package.json"
mv used_scripts.txt api_used_deps.txt
- name: Extract Dependencies Used in Source Code
id: extract-used-code
run: |
extract_deps_from_code() {
local folder=$1
local output_file=$2
if [[ -d "$folder" ]]; then
grep -rEho "require\\(['\"]([a-zA-Z0-9@/._-]+)['\"]\\)" "$folder" --include=\*.{js,ts,mjs,cjs} | \
sed -E "s/require\\(['\"]([a-zA-Z0-9@/._-]+)['\"]\\)/\1/" > "$output_file"
grep -rEho "import .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]" "$folder" --include=\*.{js,ts,mjs,cjs} | \
sed -E "s/import .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]/\1/" >> "$output_file"
sort -u "$output_file" -o "$output_file"
else
touch "$output_file"
fi
}
extract_deps_from_code "." root_used_code.txt
extract_deps_from_code "client" client_used_code.txt
extract_deps_from_code "api" api_used_code.txt
- name: Run depcheck for root package.json
id: check-root
run: |
if [[ -f "package.json" ]]; then
UNUSED=$(depcheck --json | jq -r '.dependencies | join("\n")' || echo "")
UNUSED=$(comm -23 <(echo "$UNUSED" | sort) <(cat root_used_deps.txt root_used_code.txt | sort) || echo "")
echo "ROOT_UNUSED<<EOF" >> $GITHUB_ENV
echo "$UNUSED" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
fi
- name: Run depcheck for client/package.json
id: check-client
run: |
if [[ -f "client/package.json" ]]; then
chmod -R 755 client
cd client
UNUSED=$(depcheck --json | jq -r '.dependencies | join("\n")' || echo "")
UNUSED=$(comm -23 <(echo "$UNUSED" | sort) <(cat ../client_used_deps.txt ../client_used_code.txt | sort) || echo "")
echo "CLIENT_UNUSED<<EOF" >> $GITHUB_ENV
echo "$UNUSED" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
cd ..
fi
- name: Run depcheck for api/package.json
id: check-api
run: |
if [[ -f "api/package.json" ]]; then
chmod -R 755 api
cd api
UNUSED=$(depcheck --json | jq -r '.dependencies | join("\n")' || echo "")
UNUSED=$(comm -23 <(echo "$UNUSED" | sort) <(cat ../api_used_deps.txt ../api_used_code.txt | sort) || echo "")
echo "API_UNUSED<<EOF" >> $GITHUB_ENV
echo "$UNUSED" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
cd ..
fi
- name: Post comment on PR if unused dependencies are found
if: env.ROOT_UNUSED != '' || env.CLIENT_UNUSED != '' || env.API_UNUSED != ''
run: |
PR_NUMBER=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
ROOT_LIST=$(echo "$ROOT_UNUSED" | awk '{print "- `" $0 "`"}')
CLIENT_LIST=$(echo "$CLIENT_UNUSED" | awk '{print "- `" $0 "`"}')
API_LIST=$(echo "$API_UNUSED" | awk '{print "- `" $0 "`"}')
COMMENT_BODY=$(cat <<EOF
### 🚨 Unused NPM Packages Detected
The following **unused dependencies** were found:
$(if [[ ! -z "$ROOT_UNUSED" ]]; then echo "#### 📂 Root \`package.json\`"; echo ""; echo "$ROOT_LIST"; echo ""; fi)
$(if [[ ! -z "$CLIENT_UNUSED" ]]; then echo "#### 📂 Client \`client/package.json\`"; echo ""; echo "$CLIENT_LIST"; echo ""; fi)
$(if [[ ! -z "$API_UNUSED" ]]; then echo "#### 📂 API \`api/package.json\`"; echo ""; echo "$API_LIST"; echo ""; fi)
⚠️ **Please remove these unused dependencies to keep your project clean.**
EOF
)
gh api "repos/${{ github.repository }}/issues/${PR_NUMBER}/comments" \
-f body="$COMMENT_BODY" \
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Fail workflow if unused dependencies found
if: env.ROOT_UNUSED != '' || env.CLIENT_UNUSED != '' || env.API_UNUSED != ''
run: exit 1

3
.gitignore vendored
View File

@@ -105,4 +105,5 @@ auth.json
uploads/
# owner
release/
release/
!/client/src/@types/i18next.d.ts

View File

@@ -1,4 +1,4 @@
# v0.7.6
# v0.7.7-rc1
# Base node image
FROM node:20-alpine AS node

View File

@@ -1,5 +1,5 @@
# Dockerfile.multi
# v0.7.6
# v0.7.7-rc1
# Base for all builds
FROM node:20-alpine AS base-min

View File

@@ -506,9 +506,8 @@ class OpenAIClient extends BaseClient {
if (promptPrefix && this.isOmni === true) {
const lastUserMessageIndex = payload.findLastIndex((message) => message.role === 'user');
if (lastUserMessageIndex !== -1) {
payload[
lastUserMessageIndex
].content = `${promptPrefix}\n${payload[lastUserMessageIndex].content}`;
payload[lastUserMessageIndex].content =
`${promptPrefix}\n${payload[lastUserMessageIndex].content}`;
}
}
@@ -1067,14 +1066,36 @@ ${convo}
});
}
getStreamText() {
/**
*
* @param {string[]} [intermediateReply]
* @returns {string}
*/
getStreamText(intermediateReply) {
if (!this.streamHandler) {
return '';
return intermediateReply?.join('') ?? '';
}
let thinkMatch;
let remainingText;
let reasoningText = '';
if (this.streamHandler.reasoningTokens.length > 0) {
reasoningText = this.streamHandler.reasoningTokens.join('');
thinkMatch = reasoningText.match(/<think>([\s\S]*?)<\/think>/)?.[1]?.trim();
if (thinkMatch != null && thinkMatch) {
const reasoningTokens = `:::thinking\n${thinkMatch}\n:::\n`;
remainingText = reasoningText.split(/<\/think>/)?.[1]?.trim() || '';
return `${reasoningTokens}${remainingText}${this.streamHandler.tokens.join('')}`;
} else if (thinkMatch === '') {
remainingText = reasoningText.split(/<\/think>/)?.[1]?.trim() || '';
return `${remainingText}${this.streamHandler.tokens.join('')}`;
}
}
const reasoningTokens =
this.streamHandler.reasoningTokens.length > 0
? `:::thinking\n${this.streamHandler.reasoningTokens.join('')}\n:::\n`
reasoningText.length > 0
? `:::thinking\n${reasoningText.replace('<think>', '').replace('</think>', '').trim()}\n:::\n`
: '';
return `${reasoningTokens}${this.streamHandler.tokens.join('')}`;
@@ -1314,11 +1335,19 @@ ${convo}
streamPromise = new Promise((resolve) => {
streamResolve = resolve;
});
/** @type {OpenAI.OpenAI.CompletionCreateParamsStreaming} */
const params = {
...modelOptions,
stream: true,
};
if (
this.options.endpoint === EModelEndpoint.openAI ||
this.options.endpoint === EModelEndpoint.azureOpenAI
) {
params.stream_options = { include_usage: true };
}
const stream = await openai.beta.chat.completions
.stream({
...modelOptions,
stream: true,
})
.stream(params)
.on('abort', () => {
/* Do nothing here */
})
@@ -1449,7 +1478,7 @@ ${convo}
this.options.context !== 'title' &&
message.content.startsWith('<think>')
) {
return message.content.replace('<think>', ':::thinking').replace('</think>', ':::');
return this.getStreamText();
}
return message.content;
@@ -1458,7 +1487,7 @@ ${convo}
err?.message?.includes('abort') ||
(err instanceof OpenAI.APIError && err?.message?.includes('abort'))
) {
return intermediateReply.join('');
return this.getStreamText(intermediateReply);
}
if (
err?.message?.includes(
@@ -1473,14 +1502,18 @@ ${convo}
(err instanceof OpenAI.OpenAIError && err?.message?.includes('missing finish_reason'))
) {
logger.error('[OpenAIClient] Known OpenAI error:', err);
if (intermediateReply.length > 0) {
return intermediateReply.join('');
if (this.streamHandler && this.streamHandler.reasoningTokens.length) {
return this.getStreamText();
} else if (intermediateReply.length > 0) {
return this.getStreamText(intermediateReply);
} else {
throw err;
}
} else if (err instanceof OpenAI.APIError) {
if (intermediateReply.length > 0) {
return intermediateReply.join('');
if (this.streamHandler && this.streamHandler.reasoningTokens.length) {
return this.getStreamText();
} else if (intermediateReply.length > 0) {
return this.getStreamText(intermediateReply);
} else {
throw err;
}

View File

@@ -37,6 +37,10 @@ const messages = isRedisEnabled
? new Keyv({ store: keyvRedis, ttl: Time.ONE_MINUTE })
: new Keyv({ namespace: CacheKeys.MESSAGES, ttl: Time.ONE_MINUTE });
const flows = isRedisEnabled
? new Keyv({ store: keyvRedis, ttl: Time.TWO_MINUTES })
: new Keyv({ namespace: CacheKeys.FLOWS, ttl: Time.ONE_MINUTE * 3 });
const tokenConfig = isRedisEnabled
? new Keyv({ store: keyvRedis, ttl: Time.THIRTY_MINUTES })
: new Keyv({ namespace: CacheKeys.TOKEN_CONFIG, ttl: Time.THIRTY_MINUTES });
@@ -88,6 +92,7 @@ const namespaces = {
[CacheKeys.MODEL_QUERIES]: modelQueries,
[CacheKeys.AUDIO_RUNS]: audioRuns,
[CacheKeys.MESSAGES]: messages,
[CacheKeys.FLOWS]: flows,
};
/**

View File

@@ -1,6 +1,6 @@
const KeyvRedis = require('@keyv/redis');
const { logger } = require('~/config');
const { isEnabled } = require('~/server/utils');
const logger = require('~/config/winston');
const { REDIS_URI, USE_REDIS } = process.env;

View File

@@ -1,9 +1,11 @@
const { EventSource } = require('eventsource');
const { Time, CacheKeys } = require('librechat-data-provider');
const logger = require('./winston');
global.EventSource = EventSource;
let mcpManager = null;
let flowManager = null;
/**
* @returns {Promise<MCPManager>}
@@ -16,6 +18,21 @@ async function getMCPManager() {
return mcpManager;
}
/**
* @param {(key: string) => Keyv} getLogStores
* @returns {Promise<FlowStateManager>}
*/
async function getFlowStateManager(getLogStores) {
if (!flowManager) {
const { FlowStateManager } = await import('librechat-mcp');
flowManager = new FlowStateManager(getLogStores(CacheKeys.FLOWS), {
ttl: Time.ONE_MINUTE * 3,
logger,
});
}
return flowManager;
}
/**
* Sends message data in Server Sent Events format.
* @param {ServerResponse} res - The server response.
@@ -34,4 +51,5 @@ module.exports = {
logger,
sendEvent,
getMCPManager,
getFlowStateManager,
};

View File

@@ -1,5 +1,6 @@
const tokenSchema = require('./schema/tokenSchema');
const mongoose = require('mongoose');
const { encryptV2 } = require('~/server/utils/crypto');
const tokenSchema = require('./schema/tokenSchema');
const { logger } = require('~/config');
/**
@@ -7,6 +8,32 @@ const { logger } = require('~/config');
* @type {mongoose.Model}
*/
const Token = mongoose.model('Token', tokenSchema);
/**
* Fixes the indexes for the Token collection from legacy TTL indexes to the new expiresAt index.
*/
async function fixIndexes() {
try {
const indexes = await Token.collection.indexes();
logger.debug('Existing Token Indexes:', JSON.stringify(indexes, null, 2));
const unwantedTTLIndexes = indexes.filter(
(index) => index.key.createdAt === 1 && index.expireAfterSeconds !== undefined,
);
if (unwantedTTLIndexes.length === 0) {
logger.debug('No unwanted Token indexes found.');
return;
}
for (const index of unwantedTTLIndexes) {
logger.debug(`Dropping unwanted Token index: ${index.name}`);
await Token.collection.dropIndex(index.name);
logger.debug(`Dropped Token index: ${index.name}`);
}
logger.debug('Token index cleanup completed successfully.');
} catch (error) {
logger.error('An error occurred while fixing Token indexes:', error);
}
}
fixIndexes();
/**
* Creates a new Token instance.
@@ -29,8 +56,7 @@ async function createToken(tokenData) {
expiresAt,
};
const newToken = new Token(newTokenData);
return await newToken.save();
return await Token.create(newTokenData);
} catch (error) {
logger.debug('An error occurred while creating token:', error);
throw error;
@@ -42,7 +68,8 @@ async function createToken(tokenData) {
* @param {Object} query - The query to match against.
* @param {mongoose.Types.ObjectId|String} query.userId - The ID of the user.
* @param {String} query.token - The token value.
* @param {String} query.email - The email of the user.
* @param {String} [query.email] - The email of the user.
* @param {String} [query.identifier] - Unique, alternative identifier for the token.
* @returns {Promise<Object|null>} The matched Token document, or null if not found.
* @throws Will throw an error if the find operation fails.
*/
@@ -59,6 +86,9 @@ async function findToken(query) {
if (query.email) {
conditions.push({ email: query.email });
}
if (query.identifier) {
conditions.push({ identifier: query.identifier });
}
const token = await Token.findOne({
$and: conditions,
@@ -76,6 +106,8 @@ async function findToken(query) {
* @param {Object} query - The query to match against.
* @param {mongoose.Types.ObjectId|String} query.userId - The ID of the user.
* @param {String} query.token - The token value.
* @param {String} [query.email] - The email of the user.
* @param {String} [query.identifier] - Unique, alternative identifier for the token.
* @param {Object} updateData - The data to update the Token with.
* @returns {Promise<mongoose.Document|null>} The updated Token document, or null if not found.
* @throws Will throw an error if the update operation fails.
@@ -94,14 +126,20 @@ async function updateToken(query, updateData) {
* @param {Object} query - The query to match against.
* @param {mongoose.Types.ObjectId|String} query.userId - The ID of the user.
* @param {String} query.token - The token value.
* @param {String} query.email - The email of the user.
* @param {String} [query.email] - The email of the user.
* @param {String} [query.identifier] - Unique, alternative identifier for the token.
* @returns {Promise<Object>} The result of the delete operation.
* @throws Will throw an error if the delete operation fails.
*/
async function deleteTokens(query) {
try {
return await Token.deleteMany({
$or: [{ userId: query.userId }, { token: query.token }, { email: query.email }],
$or: [
{ userId: query.userId },
{ token: query.token },
{ email: query.email },
{ identifier: query.identifier },
],
});
} catch (error) {
logger.debug('An error occurred while deleting tokens:', error);
@@ -109,9 +147,46 @@ async function deleteTokens(query) {
}
}
/**
* Handles the OAuth token by creating or updating the token.
* @param {object} fields
* @param {string} fields.userId - The user's ID.
* @param {string} fields.token - The full token to store.
* @param {string} fields.identifier - Unique, alternative identifier for the token.
* @param {number} fields.expiresIn - The number of seconds until the token expires.
* @param {object} fields.metadata - Additional metadata to store with the token.
* @param {string} [fields.type="oauth"] - The type of token. Default is 'oauth'.
*/
async function handleOAuthToken({
token,
userId,
identifier,
expiresIn,
metadata,
type = 'oauth',
}) {
const encrypedToken = await encryptV2(token);
const tokenData = {
type,
userId,
metadata,
identifier,
token: encrypedToken,
expiresIn: parseInt(expiresIn, 10) || 3600,
};
const existingToken = await findToken({ userId, identifier });
if (existingToken) {
return await updateToken({ identifier }, tokenData);
} else {
return await createToken(tokenData);
}
}
module.exports = {
createToken,
findToken,
createToken,
updateToken,
deleteTokens,
handleOAuthToken,
};

View File

@@ -35,6 +35,9 @@ const agentSchema = mongoose.Schema(
model_parameters: {
type: Object,
},
artifacts: {
type: String,
},
access_level: {
type: Number,
},

View File

@@ -10,6 +10,10 @@ const tokenSchema = new Schema({
email: {
type: String,
},
type: String,
identifier: {
type: String,
},
token: {
type: String,
required: true,
@@ -23,6 +27,10 @@ const tokenSchema = new Schema({
type: Date,
required: true,
},
metadata: {
type: Map,
of: Schema.Types.Mixed,
},
});
tokenSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });

View File

@@ -1,6 +1,6 @@
{
"name": "@librechat/backend",
"version": "v0.7.6",
"version": "v0.7.7-rc1",
"description": "",
"scripts": {
"start": "echo 'please run this from the root directory'",
@@ -45,11 +45,10 @@
"@langchain/google-genai": "^0.1.7",
"@langchain/google-vertexai": "^0.1.8",
"@langchain/textsplitters": "^0.1.0",
"@librechat/agents": "^2.0.2",
"@librechat/agents": "^2.0.5",
"@waylaidwanderer/fetch-event-source": "^3.0.1",
"axios": "^1.7.7",
"axios": "1.7.8",
"bcryptjs": "^2.4.3",
"cheerio": "^1.0.0-rc.12",
"cohere-ai": "^7.9.1",
"compression": "^1.7.4",
"connect-redis": "^7.1.0",
@@ -66,7 +65,6 @@
"firebase": "^11.0.2",
"googleapis": "^126.0.1",
"handlebars": "^4.7.7",
"html": "^1.0.0",
"ioredis": "^5.3.2",
"js-yaml": "^4.1.0",
"jsonwebtoken": "^9.0.0",
@@ -91,7 +89,6 @@
"openid-client": "^5.4.2",
"passport": "^0.6.0",
"passport-apple": "^2.0.2",
"passport-custom": "^1.1.1",
"passport-discord": "^0.1.4",
"passport-facebook": "^3.0.0",
"passport-github2": "^0.1.12",
@@ -99,20 +96,21 @@
"passport-jwt": "^4.0.1",
"passport-ldapauth": "^3.0.1",
"passport-local": "^1.0.0",
"pino": "^8.12.1",
"sharp": "^0.32.6",
"socket.io": "^4.8.1",
"tiktoken": "^1.0.15",
"traverse": "^0.6.7",
"ua-parser-js": "^1.0.36",
"winston": "^3.11.0",
"winston-daily-rotate-file": "^4.7.1",
"wrtc": "^0.4.7",
"youtube-transcript": "^1.2.1",
"zod": "^3.22.4"
},
"devDependencies": {
"jest": "^29.7.0",
"mongodb-memory-server": "^10.0.0",
"nodemon": "^3.0.1",
"supertest": "^6.3.3"
"mongodb-memory-server": "^10.1.3",
"nodemon": "^3.0.3",
"supertest": "^7.0.0"
}
}

View File

@@ -150,11 +150,13 @@ const AskController = async (req, res, next, initializeClient, addTitle) => {
} catch (error) {
const partialText = getText && getText();
handleAbortError(res, req, error, {
sender,
partialText,
conversationId,
sender,
messageId: responseMessageId,
parentMessageId: userMessageId ?? parentMessageId,
parentMessageId: overrideParentMessageId ?? userMessageId ?? parentMessageId,
}).catch((err) => {
logger.error('[AskController] Error in `handleAbortError`', err);
});
}
};

View File

@@ -135,11 +135,13 @@ const EditController = async (req, res, next, initializeClient) => {
} catch (error) {
const partialText = getText();
handleAbortError(res, req, error, {
sender,
partialText,
conversationId,
sender,
messageId: responseMessageId,
parentMessageId: userMessageId ?? parentMessageId,
parentMessageId: overrideParentMessageId ?? userMessageId ?? parentMessageId,
}).catch((err) => {
logger.error('[EditController] Error in `handleAbortError`', err);
});
}
};

View File

@@ -142,7 +142,9 @@ const AgentController = async (req, res, next, initializeClient, addTitle) => {
conversationId,
sender,
messageId: responseMessageId,
parentMessageId: userMessageId ?? parentMessageId,
parentMessageId: overrideParentMessageId ?? userMessageId ?? parentMessageId,
}).catch((err) => {
logger.error('[api/server/controllers/agents/request] Error in `handleAbortError`', err);
});
}
};

View File

@@ -4,6 +4,7 @@ require('module-alias')({ base: path.resolve(__dirname, '..') });
const cors = require('cors');
const axios = require('axios');
const express = require('express');
const { createServer } = require('http');
const compression = require('compression');
const passport = require('passport');
const mongoSanitize = require('express-mongo-sanitize');
@@ -14,6 +15,7 @@ const { connectDb, indexSync } = require('~/lib/db');
const { isEnabled } = require('~/server/utils');
const { ldapLogin } = require('~/strategies');
const { logger } = require('~/config');
const { SocketIOService } = require('./services/WebSocket/WebSocketServer');
const validateImageRequest = require('./middleware/validateImageRequest');
const errorController = require('./controllers/ErrorController');
const configureSocialLogins = require('./socialLogins');
@@ -36,7 +38,18 @@ const startServer = async () => {
await indexSync();
const app = express();
const server = createServer(app);
app.disable('x-powered-by');
app.use(
cors({
origin: true,
credentials: true,
}),
);
new SocketIOService(server);
await AppService(app);
const indexPath = path.join(app.locals.paths.dist, 'index.html');
@@ -84,6 +97,7 @@ const startServer = async () => {
app.use('/oauth', routes.oauth);
/* API Endpoints */
app.use('/api/auth', routes.auth);
app.use('/api/actions', routes.actions);
app.use('/api/keys', routes.keys);
app.use('/api/user', routes.user);
app.use('/api/search', routes.search);
@@ -108,6 +122,7 @@ const startServer = async () => {
app.use('/api/agents', routes.agents);
app.use('/api/banner', routes.banner);
app.use('/api/bedrock', routes.bedrock);
app.use('/api/websocket', routes.websocket);
app.use('/api/tags', routes.tags);
@@ -125,7 +140,7 @@ const startServer = async () => {
res.send(updatedIndexHtml);
});
app.listen(port, host, () => {
server.listen(port, host, () => {
if (host == '0.0.0.0') {
logger.info(
`Server listening on all interfaces at port ${port}. Use http://localhost:${port} to access it`,
@@ -133,6 +148,8 @@ const startServer = async () => {
} else {
logger.info(`Server listening at http://${host == '0.0.0.0' ? 'localhost' : host}:${port}`);
}
logger.info(`Socket.IO endpoint: http://${host}:${port}`);
});
};

View File

@@ -0,0 +1,136 @@
const express = require('express');
const jwt = require('jsonwebtoken');
const { getAccessToken } = require('~/server/services/TokenService');
const { logger, getFlowStateManager } = require('~/config');
const { getLogStores } = require('~/cache');
const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET;
/**
* Handles the OAuth callback and exchanges the authorization code for tokens.
*
* @route GET /actions/:action_id/oauth/callback
* @param {string} req.params.action_id - The ID of the action.
* @param {string} req.query.code - The authorization code returned by the provider.
* @param {string} req.query.state - The state token to verify the authenticity of the request.
* @returns {void} Sends a success message after updating the action with OAuth tokens.
*/
router.get('/:action_id/oauth/callback', async (req, res) => {
const { action_id } = req.params;
const { code, state } = req.query;
const flowManager = await getFlowStateManager(getLogStores);
let identifier = action_id;
try {
let decodedState;
try {
decodedState = jwt.verify(state, JWT_SECRET);
} catch (err) {
await flowManager.failFlow(identifier, 'oauth', 'Invalid or expired state parameter');
return res.status(400).send('Invalid or expired state parameter');
}
if (decodedState.action_id !== action_id) {
await flowManager.failFlow(identifier, 'oauth', 'Mismatched action ID in state parameter');
return res.status(400).send('Mismatched action ID in state parameter');
}
if (!decodedState.user) {
await flowManager.failFlow(identifier, 'oauth', 'Invalid user ID in state parameter');
return res.status(400).send('Invalid user ID in state parameter');
}
identifier = `${decodedState.user}:${action_id}`;
const flowState = await flowManager.getFlowState(identifier, 'oauth');
if (!flowState) {
throw new Error('OAuth flow not found');
}
const tokenData = await getAccessToken({
code,
userId: decodedState.user,
identifier,
client_url: flowState.metadata.client_url,
redirect_uri: flowState.metadata.redirect_uri,
/** Encrypted values */
encrypted_oauth_client_id: flowState.metadata.encrypted_oauth_client_id,
encrypted_oauth_client_secret: flowState.metadata.encrypted_oauth_client_secret,
});
await flowManager.completeFlow(identifier, 'oauth', tokenData);
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Authentication Successful</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
body {
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont;
background-color: rgb(249, 250, 251);
margin: 0;
padding: 2rem;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.card {
background-color: white;
border-radius: 0.5rem;
padding: 2rem;
max-width: 28rem;
width: 100%;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
text-align: center;
}
.heading {
color: rgb(17, 24, 39);
font-size: 1.875rem;
font-weight: 700;
margin: 0 0 1rem;
}
.description {
color: rgb(75, 85, 99);
font-size: 0.875rem;
margin: 0.5rem 0;
}
.countdown {
color: rgb(99, 102, 241);
font-weight: 500;
}
</style>
</head>
<body>
<div class="card">
<h1 class="heading">Authentication Successful</h1>
<p class="description">
Your authentication was successful. This window will close in
<span class="countdown" id="countdown">3</span> seconds.
</p>
</div>
<script>
let secondsLeft = 3;
const countdownElement = document.getElementById('countdown');
const countdown = setInterval(() => {
secondsLeft--;
countdownElement.textContent = secondsLeft;
if (secondsLeft <= 0) {
clearInterval(countdown);
window.close();
}
}, 1000);
</script>
</body>
</html>
`);
} catch (error) {
logger.error('Error in OAuth callback:', error);
await flowManager.failFlow(identifier, 'oauth', error);
res.status(500).send('Authentication failed. Please try again.');
}
});
module.exports = router;

View File

@@ -1,6 +1,6 @@
const express = require('express');
const { nanoid } = require('nanoid');
const { actionDelimiter, SystemRoles } = require('librechat-data-provider');
const { actionDelimiter, SystemRoles, removeNullishValues } = require('librechat-data-provider');
const { encryptMetadata, domainParser } = require('~/server/services/ActionService');
const { updateAction, getActions, deleteAction } = require('~/models/Action');
const { isActionDomainAllowed } = require('~/server/services/domains');
@@ -51,7 +51,7 @@ router.post('/:agent_id', async (req, res) => {
return res.status(400).json({ message: 'No functions provided' });
}
let metadata = await encryptMetadata(_metadata);
let metadata = await encryptMetadata(removeNullishValues(_metadata, true));
const isDomainAllowed = await isActionDomainAllowed(metadata.domain);
if (!isDomainAllowed) {
return res.status(400).json({ message: 'Domain not allowed' });
@@ -117,10 +117,7 @@ router.post('/:agent_id', async (req, res) => {
}
/** @type {[Action]} */
const updatedAction = await updateAction(
{ action_id },
actionUpdateData,
);
const updatedAction = await updateAction({ action_id }, actionUpdateData);
const sensitiveFields = ['api_key', 'oauth_client_id', 'oauth_client_secret'];
for (let field of sensitiveFields) {

View File

@@ -1,6 +1,6 @@
const express = require('express');
const { nanoid } = require('nanoid');
const { actionDelimiter, EModelEndpoint } = require('librechat-data-provider');
const { actionDelimiter, EModelEndpoint, removeNullishValues } = require('librechat-data-provider');
const { encryptMetadata, domainParser } = require('~/server/services/ActionService');
const { getOpenAIClient } = require('~/server/controllers/assistants/helpers');
const { updateAction, getActions, deleteAction } = require('~/models/Action');
@@ -29,7 +29,7 @@ router.post('/:assistant_id', async (req, res) => {
return res.status(400).json({ message: 'No functions provided' });
}
let metadata = await encryptMetadata(_metadata);
let metadata = await encryptMetadata(removeNullishValues(_metadata, true));
const isDomainAllowed = await isActionDomainAllowed(metadata.domain);
if (!isDomainAllowed) {
return res.status(400).json({ message: 'Domain not allowed' });

View File

@@ -3,7 +3,7 @@ const router = express.Router();
const { getCustomConfigSpeech } = require('~/server/services/Files/Audio');
router.get('/get', async (req, res) => {
router.get('/', async (req, res) => {
await getCustomConfigSpeech(req, res);
});

View File

@@ -4,6 +4,7 @@ const { createTTSLimiters, createSTTLimiters } = require('~/server/middleware');
const stt = require('./stt');
const tts = require('./tts');
const customConfigSpeech = require('./customConfigSpeech');
const realtime = require('./realtime');
const router = express.Router();
@@ -14,4 +15,6 @@ router.use('/tts', ttsIpLimiter, ttsUserLimiter, tts);
router.use('/config', customConfigSpeech);
router.use('/realtime', realtime);
module.exports = router;

View File

@@ -0,0 +1,10 @@
const express = require('express');
const router = express.Router();
const { getRealtimeConfig } = require('~/server/services/Files/Audio');
router.get('/', async (req, res) => {
await getRealtimeConfig(req, res);
});
module.exports = router;

View File

@@ -2,6 +2,7 @@ const assistants = require('./assistants');
const categories = require('./categories');
const tokenizer = require('./tokenizer');
const endpoints = require('./endpoints');
const websocket = require('./websocket');
const staticRoute = require('./static');
const messages = require('./messages');
const presets = require('./presets');
@@ -9,11 +10,13 @@ const prompts = require('./prompts');
const balance = require('./balance');
const plugins = require('./plugins');
const bedrock = require('./bedrock');
const actions = require('./actions');
const search = require('./search');
const models = require('./models');
const convos = require('./convos');
const config = require('./config');
const agents = require('./agents');
const banner = require('./banner');
const roles = require('./roles');
const oauth = require('./oauth');
const files = require('./files');
@@ -24,7 +27,6 @@ const edit = require('./edit');
const keys = require('./keys');
const user = require('./user');
const ask = require('./ask');
const banner = require('./banner');
module.exports = {
ask,
@@ -38,6 +40,7 @@ module.exports = {
files,
share,
agents,
banner,
bedrock,
convos,
search,
@@ -45,13 +48,14 @@ module.exports = {
config,
models,
plugins,
actions,
presets,
balance,
messages,
websocket,
endpoints,
tokenizer,
assistants,
categories,
staticRoute,
banner,
};

View File

@@ -0,0 +1,19 @@
const express = require('express');
const optionalJwtAuth = require('~/server/middleware/optionalJwtAuth');
const router = express.Router();
router.get('/', optionalJwtAuth, async (req, res) => {
const isProduction = process.env.NODE_ENV === 'production';
const protocol = isProduction && req.secure ? 'https' : 'http';
const serverDomain = process.env.SERVER_DOMAIN
? process.env.SERVER_DOMAIN.replace(/^https?:\/\//, '')
: req.headers.host;
const socketIoUrl = `${protocol}://${serverDomain}`;
res.json({ url: socketIoUrl });
});
module.exports = router;

View File

@@ -1,20 +1,28 @@
const jwt = require('jsonwebtoken');
const { nanoid } = require('nanoid');
const { tool } = require('@langchain/core/tools');
const { GraphEvents, sleep } = require('@librechat/agents');
const {
Time,
CacheKeys,
StepTypes,
Constants,
AuthTypeEnum,
actionDelimiter,
isImageVisionTool,
actionDomainSeparator,
} = require('librechat-data-provider');
const { tool } = require('@langchain/core/tools');
const { refreshAccessToken } = require('~/server/services/TokenService');
const { isActionDomainAllowed } = require('~/server/services/domains');
const { logger, getFlowStateManager, sendEvent } = require('~/config');
const { encryptV2, decryptV2 } = require('~/server/utils/crypto');
const { getActions, deleteActions } = require('~/models/Action');
const { deleteAssistant } = require('~/models/Assistant');
const { findToken } = require('~/models/Token');
const { logAxiosError } = require('~/utils');
const { getLogStores } = require('~/cache');
const { logger } = require('~/config');
const JWT_SECRET = process.env.JWT_SECRET;
const toolNameRegex = /^[a-zA-Z0-9_-]+$/;
const replaceSeparatorRegex = new RegExp(actionDomainSeparator, 'g');
@@ -115,6 +123,8 @@ async function loadActionSets(searchParams) {
* Creates a general tool for an entire action set.
*
* @param {Object} params - The parameters for loading action sets.
* @param {ServerRequest} params.req
* @param {ServerResponse} params.res
* @param {Action} params.action - The action set. Necessary for decrypting authentication values.
* @param {ActionRequest} params.requestBuilder - The ActionRequest builder class to execute the API call.
* @param {string | undefined} [params.name] - The name of the tool.
@@ -122,33 +132,185 @@ async function loadActionSets(searchParams) {
* @param {import('zod').ZodTypeAny | undefined} [params.zodSchema] - The Zod schema for tool input validation/definition
* @returns { Promise<typeof tool | { _call: (toolInput: Object | string) => unknown}> } An object with `_call` method to execute the tool input.
*/
async function createActionTool({ action, requestBuilder, zodSchema, name, description }) {
action.metadata = await decryptMetadata(action.metadata);
async function createActionTool({
req,
res,
action,
requestBuilder,
zodSchema,
name,
description,
}) {
const isDomainAllowed = await isActionDomainAllowed(action.metadata.domain);
if (!isDomainAllowed) {
return null;
}
/** @type {(toolInput: Object | string) => Promise<unknown>} */
const _call = async (toolInput) => {
try {
const executor = requestBuilder.createExecutor();
const encrypted = {
oauth_client_id: action.metadata.oauth_client_id,
oauth_client_secret: action.metadata.oauth_client_secret,
};
action.metadata = await decryptMetadata(action.metadata);
// Chain the operations
/** @type {(toolInput: Object | string, config: GraphRunnableConfig) => Promise<unknown>} */
const _call = async (toolInput, config) => {
try {
/** @type {import('librechat-data-provider').ActionMetadataRuntime} */
const metadata = action.metadata;
const executor = requestBuilder.createExecutor();
const preparedExecutor = executor.setParams(toolInput);
if (action.metadata.auth && action.metadata.auth.type !== AuthTypeEnum.None) {
await preparedExecutor.setAuth(action.metadata);
if (metadata.auth && metadata.auth.type !== AuthTypeEnum.None) {
try {
const action_id = action.action_id;
const identifier = `${req.user.id}:${action.action_id}`;
if (metadata.auth.type === AuthTypeEnum.OAuth && metadata.auth.authorization_url) {
const requestLogin = async () => {
const { args: _args, stepId, ...toolCall } = config.toolCall ?? {};
if (!stepId) {
throw new Error('Tool call is missing stepId');
}
const statePayload = {
nonce: nanoid(),
user: req.user.id,
action_id,
};
const stateToken = jwt.sign(statePayload, JWT_SECRET, { expiresIn: '10m' });
try {
const redirectUri = `${process.env.DOMAIN_CLIENT}/api/actions/${action_id}/oauth/callback`;
const params = new URLSearchParams({
client_id: metadata.oauth_client_id,
scope: metadata.auth.scope,
redirect_uri: redirectUri,
access_type: 'offline',
response_type: 'code',
state: stateToken,
});
const authURL = `${metadata.auth.authorization_url}?${params.toString()}`;
/** @type {{ id: string; delta: AgentToolCallDelta }} */
const data = {
id: stepId,
delta: {
type: StepTypes.TOOL_CALLS,
tool_calls: [{ ...toolCall, args: '' }],
auth: authURL,
expires_at: Date.now() + Time.TWO_MINUTES,
},
};
const flowManager = await getFlowStateManager(getLogStores);
await flowManager.createFlowWithHandler(
`${identifier}:login`,
'oauth_login',
async () => {
sendEvent(res, { event: GraphEvents.ON_RUN_STEP_DELTA, data });
logger.debug('Sent OAuth login request to client', { action_id, identifier });
return true;
},
);
logger.debug('Waiting for OAuth Authorization response', { action_id, identifier });
const result = await flowManager.createFlow(identifier, 'oauth', {
state: stateToken,
userId: req.user.id,
client_url: metadata.auth.client_url,
redirect_uri: `${process.env.DOMAIN_CLIENT}/api/actions/${action_id}/oauth/callback`,
/** Encrypted values */
encrypted_oauth_client_id: encrypted.oauth_client_id,
encrypted_oauth_client_secret: encrypted.oauth_client_secret,
});
logger.debug('Received OAuth Authorization response', { action_id, identifier });
data.delta.auth = undefined;
data.delta.expires_at = undefined;
sendEvent(res, { event: GraphEvents.ON_RUN_STEP_DELTA, data });
await sleep(3000);
metadata.oauth_access_token = result.access_token;
metadata.oauth_refresh_token = result.refresh_token;
const expiresAt = new Date(Date.now() + result.expires_in * 1000);
metadata.oauth_token_expires_at = expiresAt.toISOString();
} catch (error) {
const errorMessage = 'Failed to authenticate OAuth tool';
logger.error(errorMessage, error);
throw new Error(errorMessage);
}
};
const tokenPromises = [];
tokenPromises.push(findToken({ userId: req.user.id, type: 'oauth', identifier }));
tokenPromises.push(
findToken({
userId: req.user.id,
type: 'oauth_refresh',
identifier: `${identifier}:refresh`,
}),
);
const [tokenData, refreshTokenData] = await Promise.all(tokenPromises);
if (tokenData) {
// Valid token exists, add it to metadata for setAuth
metadata.oauth_access_token = await decryptV2(tokenData.token);
if (refreshTokenData) {
metadata.oauth_refresh_token = await decryptV2(refreshTokenData.token);
}
metadata.oauth_token_expires_at = tokenData.expiresAt.toISOString();
} else if (!refreshTokenData) {
// No tokens exist, need to authenticate
await requestLogin();
} else if (refreshTokenData) {
// Refresh token is still valid, use it to get new access token
try {
const refresh_token = await decryptV2(refreshTokenData.token);
const refreshTokens = async () =>
await refreshAccessToken({
identifier,
refresh_token,
userId: req.user.id,
client_url: metadata.auth.client_url,
encrypted_oauth_client_id: encrypted.oauth_client_id,
encrypted_oauth_client_secret: encrypted.oauth_client_secret,
});
const flowManager = await getFlowStateManager(getLogStores);
const refreshData = await flowManager.createFlowWithHandler(
`${identifier}:refresh`,
'oauth_refresh',
refreshTokens,
);
metadata.oauth_access_token = refreshData.access_token;
if (refreshData.refresh_token) {
metadata.oauth_refresh_token = refreshData.refresh_token;
}
const expiresAt = new Date(Date.now() + refreshData.expires_in * 1000);
metadata.oauth_token_expires_at = expiresAt.toISOString();
} catch (error) {
logger.error('Failed to refresh token, requesting new login:', error);
await requestLogin();
}
} else {
await requestLogin();
}
}
await preparedExecutor.setAuth(metadata);
} catch (error) {
if (
error.message.includes('No access token found') ||
error.message.includes('Access token is expired')
) {
throw error;
}
throw new Error(`Authentication failed: ${error.message}`);
}
}
const res = await preparedExecutor.execute();
const response = await preparedExecutor.execute();
if (typeof res.data === 'object') {
return JSON.stringify(res.data);
if (typeof response.data === 'object') {
return JSON.stringify(response.data);
}
return res.data;
return response.data;
} catch (error) {
const logMessage = `API call to ${action.metadata.domain} failed`;
logAxiosError({ message: logMessage, error });
throw error;
}
};

View File

@@ -13,6 +13,7 @@ const getBedrockOptions = require('~/server/services/Endpoints/bedrock/options')
const initOpenAI = require('~/server/services/Endpoints/openAI/initialize');
const initCustom = require('~/server/services/Endpoints/custom/initialize');
const initGoogle = require('~/server/services/Endpoints/google/initialize');
const generateArtifactsPrompt = require('~/app/clients/prompts/artifacts');
const { getCustomEndpointConfig } = require('~/server/services/Config');
const { loadAgentTools } = require('~/server/services/ToolService');
const AgentClient = require('~/server/controllers/agents/client');
@@ -72,6 +73,16 @@ const primeResources = async (_attachments, _tool_resources) => {
}
};
/**
* @param {object} params
* @param {ServerRequest} params.req
* @param {ServerResponse} params.res
* @param {Agent} params.agent
* @param {object} [params.endpointOption]
* @param {AgentToolResources} [params.tool_resources]
* @param {boolean} [params.isInitialAgent]
* @returns {Promise<Agent>}
*/
const initializeAgentOptions = async ({
req,
res,
@@ -82,6 +93,7 @@ const initializeAgentOptions = async ({
}) => {
const { tools, toolContextMap } = await loadAgentTools({
req,
res,
agent,
tool_resources,
});
@@ -131,6 +143,13 @@ const initializeAgentOptions = async ({
agent.model_parameters.model = agent.model;
}
if (typeof agent.artifacts === 'string' && agent.artifacts !== '') {
agent.additional_instructions = generateArtifactsPrompt({
endpoint: agent.provider,
artifacts: agent.artifacts,
});
}
const tokensModel =
agent.provider === EModelEndpoint.azureOpenAI ? agent.model : agent.model_parameters.model;

View File

@@ -0,0 +1,102 @@
const { extractEnvVariable, RealtimeVoiceProviders } = require('librechat-data-provider');
const { getCustomConfig } = require('~/server/services/Config');
const { logger } = require('~/config');
class RealtimeService {
constructor(customConfig) {
this.customConfig = customConfig;
this.providerStrategies = {
[RealtimeVoiceProviders.OPENAI]: this.openaiProvider.bind(this),
};
}
static async getInstance() {
const customConfig = await getCustomConfig();
if (!customConfig) {
throw new Error('Custom config not found');
}
return new RealtimeService(customConfig);
}
async getProviderSchema() {
const realtimeSchema = this.customConfig.speech.realtime;
if (!realtimeSchema) {
throw new Error('No Realtime schema is set in config');
}
const providers = Object.entries(realtimeSchema).filter(
([, value]) => Object.keys(value).length > 0,
);
if (providers.length !== 1) {
throw new Error(providers.length > 1 ? 'Multiple providers set' : 'No provider set');
}
return providers[0];
}
async openaiProvider(schema, voice) {
const defaultRealtimeUrl = 'https://api.openai.com/v1/realtime';
const allowedVoices = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];
if (!voice) {
throw new Error('Voice not specified');
}
if (!allowedVoices.includes(voice)) {
throw new Error(`Invalid voice: ${voice}`);
}
const apiKey = extractEnvVariable(schema.apiKey);
if (!apiKey) {
throw new Error('OpenAI API key not configured');
}
const response = await fetch('https://api.openai.com/v1/realtime/sessions', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o-realtime-preview-2024-12-17',
modalities: ['audio', 'text'],
voice: voice,
}),
});
const token = response.json();
return {
provider: RealtimeVoiceProviders.OPENAI,
token: token,
url: schema.url || defaultRealtimeUrl,
};
}
async getRealtimeConfig(req, res) {
try {
const [provider, schema] = await this.getProviderSchema();
const strategy = this.providerStrategies[provider];
if (!strategy) {
throw new Error(`Unsupported provider: ${provider}`);
}
const voice = req.query.voice;
const config = strategy(schema, voice);
res.json(config);
} catch (error) {
logger.error('[RealtimeService] Config generation failed:', error);
res.status(500).json({ error: error.message });
}
}
}
async function getRealtimeConfig(req, res) {
const service = await RealtimeService.getInstance();
await service.getRealtimeConfig(req, res);
}
module.exports = getRealtimeConfig;

View File

@@ -1,4 +1,5 @@
const getCustomConfigSpeech = require('./getCustomConfigSpeech');
const getRealtimeConfig = require('./getRealtimeConfig');
const TTSService = require('./TTSService');
const STTService = require('./STTService');
const getVoices = require('./getVoices');
@@ -6,6 +7,7 @@ const getVoices = require('./getVoices');
module.exports = {
getVoices,
getCustomConfigSpeech,
getRealtimeConfig,
...STTService,
...TTSService,
};

View File

@@ -0,0 +1,170 @@
const axios = require('axios');
const { handleOAuthToken } = require('~/models/Token');
const { decryptV2 } = require('~/server/utils/crypto');
const { logAxiosError } = require('~/utils');
const { logger } = require('~/config');
/**
* Processes the access tokens and stores them in the database.
* @param {object} tokenData
* @param {string} tokenData.access_token
* @param {number} tokenData.expires_in
* @param {string} [tokenData.refresh_token]
* @param {number} [tokenData.refresh_token_expires_in]
* @param {object} metadata
* @param {string} metadata.userId
* @param {string} metadata.identifier
* @returns {Promise<void>}
*/
async function processAccessTokens(tokenData, { userId, identifier }) {
const { access_token, expires_in = 3600, refresh_token, refresh_token_expires_in } = tokenData;
if (!access_token) {
logger.error('Access token not found: ', tokenData);
throw new Error('Access token not found');
}
await handleOAuthToken({
identifier,
token: access_token,
expiresIn: expires_in,
userId,
});
if (refresh_token != null) {
logger.debug('Processing refresh token');
await handleOAuthToken({
token: refresh_token,
type: 'oauth_refresh',
userId,
identifier: `${identifier}:refresh`,
expiresIn: refresh_token_expires_in ?? null,
});
}
logger.debug('Access tokens processed');
}
/**
* Refreshes the access token using the refresh token.
* @param {object} fields
* @param {string} fields.userId - The ID of the user.
* @param {string} fields.client_url - The URL of the OAuth provider.
* @param {string} fields.identifier - The identifier for the token.
* @param {string} fields.refresh_token - The refresh token to use.
* @param {string} fields.encrypted_oauth_client_id - The client ID for the OAuth provider.
* @param {string} fields.encrypted_oauth_client_secret - The client secret for the OAuth provider.
* @returns {Promise<{
* access_token: string,
* expires_in: number,
* refresh_token?: string,
* refresh_token_expires_in?: number,
* }>}
*/
const refreshAccessToken = async ({
userId,
client_url,
identifier,
refresh_token,
encrypted_oauth_client_id,
encrypted_oauth_client_secret,
}) => {
try {
const oauth_client_id = await decryptV2(encrypted_oauth_client_id);
const oauth_client_secret = await decryptV2(encrypted_oauth_client_secret);
const params = new URLSearchParams({
client_id: oauth_client_id,
client_secret: oauth_client_secret,
grant_type: 'refresh_token',
refresh_token,
});
const response = await axios({
method: 'POST',
url: client_url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
data: params.toString(),
});
await processAccessTokens(response.data, {
userId,
identifier,
});
logger.debug(`Access token refreshed successfully for ${identifier}`);
return response.data;
} catch (error) {
const message = 'Error refreshing OAuth tokens';
logAxiosError({
message,
error,
});
throw new Error(message);
}
};
/**
* Handles the OAuth callback and exchanges the authorization code for tokens.
* @param {object} fields
* @param {string} fields.code - The authorization code returned by the provider.
* @param {string} fields.userId - The ID of the user.
* @param {string} fields.identifier - The identifier for the token.
* @param {string} fields.client_url - The URL of the OAuth provider.
* @param {string} fields.redirect_uri - The redirect URI for the OAuth provider.
* @param {string} fields.encrypted_oauth_client_id - The client ID for the OAuth provider.
* @param {string} fields.encrypted_oauth_client_secret - The client secret for the OAuth provider.
* @returns {Promise<{
* access_token: string,
* expires_in: number,
* refresh_token?: string,
* refresh_token_expires_in?: number,
* }>}
*/
const getAccessToken = async ({
code,
userId,
identifier,
client_url,
redirect_uri,
encrypted_oauth_client_id,
encrypted_oauth_client_secret,
}) => {
const oauth_client_id = await decryptV2(encrypted_oauth_client_id);
const oauth_client_secret = await decryptV2(encrypted_oauth_client_secret);
const params = new URLSearchParams({
code,
client_id: oauth_client_id,
client_secret: oauth_client_secret,
grant_type: 'authorization_code',
redirect_uri,
});
try {
const response = await axios({
method: 'POST',
url: client_url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
data: params.toString(),
});
await processAccessTokens(response.data, {
userId,
identifier,
});
logger.debug(`Access tokens successfully created for ${identifier}`);
return response.data;
} catch (error) {
const message = 'Error exchanging OAuth code';
logAxiosError({
message,
error,
});
throw new Error(message);
}
};
module.exports = {
getAccessToken,
refreshAccessToken,
};

View File

@@ -409,11 +409,12 @@ async function processRequiredActions(client, requiredActions) {
* Processes the runtime tool calls and returns the tool classes.
* @param {Object} params - Run params containing user and request information.
* @param {ServerRequest} params.req - The request object.
* @param {ServerResponse} params.res - The request object.
* @param {Agent} params.agent - The agent to load tools for.
* @param {string | undefined} [params.openAIApiKey] - The OpenAI API key.
* @returns {Promise<{ tools?: StructuredTool[] }>} The agent tools.
*/
async function loadAgentTools({ req, agent, tool_resources, openAIApiKey }) {
async function loadAgentTools({ req, res, agent, tool_resources, openAIApiKey }) {
if (!agent.tools || agent.tools.length === 0) {
return {};
}
@@ -546,6 +547,8 @@ async function loadAgentTools({ req, agent, tool_resources, openAIApiKey }) {
if (requestBuilder) {
const tool = await createActionTool({
req,
res,
action: actionSet,
requestBuilder,
zodSchema,

View File

@@ -0,0 +1,193 @@
const { Server } = require('socket.io');
const { RTCPeerConnection, RTCIceCandidate, MediaStream } = require('wrtc');
class WebRTCConnection {
constructor(socket, config) {
this.socket = socket;
this.config = config;
this.peerConnection = null;
this.audioTransceiver = null;
this.pendingCandidates = [];
this.state = 'idle';
this.log = config.log || console.log;
}
async handleOffer(offer) {
try {
if (!this.peerConnection) {
this.peerConnection = new RTCPeerConnection(this.config.rtcConfig);
this.setupPeerConnectionListeners();
}
await this.peerConnection.setRemoteDescription(offer);
const mediaStream = new MediaStream();
this.audioTransceiver = this.peerConnection.addTransceiver('audio', {
direction: 'sendrecv',
streams: [mediaStream],
});
const answer = await this.peerConnection.createAnswer();
await this.peerConnection.setLocalDescription(answer);
this.socket.emit('webrtc-answer', answer);
} catch (error) {
this.log(`Error handling offer: ${error}`, 'error');
this.socket.emit('webrtc-error', {
message: error.message,
code: 'OFFER_ERROR',
});
}
}
setupPeerConnectionListeners() {
if (!this.peerConnection) {
return;
}
this.peerConnection.ontrack = ({ track }) => {
this.log(`Received ${track.kind} track from client`);
if (track.kind === 'audio') {
this.handleIncomingAudio(track);
}
track.onended = () => {
this.log(`${track.kind} track ended`);
};
};
this.peerConnection.onicecandidate = ({ candidate }) => {
if (candidate) {
this.socket.emit('icecandidate', candidate);
}
};
this.peerConnection.onconnectionstatechange = () => {
if (!this.peerConnection) {
return;
}
const state = this.peerConnection.connectionState;
this.log(`Connection state changed to ${state}`);
this.state = state;
if (state === 'failed' || state === 'closed') {
this.cleanup();
}
};
}
handleIncomingAudio(track) {
if (this.peerConnection) {
const stream = new MediaStream([track]);
this.peerConnection.addTrack(track, stream);
}
}
async addIceCandidate(candidate) {
try {
if (this.peerConnection?.remoteDescription) {
if (candidate && candidate.candidate) {
await this.peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
} else {
this.log('Invalid ICE candidate', 'warn');
}
} else {
this.pendingCandidates.push(candidate);
}
} catch (error) {
this.log(`Error adding ICE candidate: ${error}`, 'error');
}
}
cleanup() {
if (this.peerConnection) {
try {
this.peerConnection.close();
} catch (error) {
this.log(`Error closing peer connection: ${error}`, 'error');
}
this.peerConnection = null;
}
this.audioTransceiver = null;
this.pendingCandidates = [];
this.state = 'idle';
}
}
class SocketIOService {
constructor(httpServer, config = {}) {
this.config = {
rtcConfig: {
iceServers: [
{
urls: ['stun:stun.l.google.com:19302', 'stun:stun1.l.google.com:19302'],
},
],
iceCandidatePoolSize: 10,
bundlePolicy: 'max-bundle',
rtcpMuxPolicy: 'require',
},
...config,
};
this.io = new Server(httpServer, {
path: '/socket.io',
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
this.connections = new Map();
this.setupSocketHandlers();
}
setupSocketHandlers() {
this.io.on('connection', (socket) => {
this.log(`Client connected: ${socket.id}`);
const rtcConnection = new WebRTCConnection(socket, {
...this.config,
log: this.log.bind(this),
});
this.connections.set(socket.id, rtcConnection);
socket.on('webrtc-offer', (offer) => {
this.log(`Received WebRTC offer from ${socket.id}`);
rtcConnection.handleOffer(offer);
});
socket.on('icecandidate', (candidate) => {
rtcConnection.addIceCandidate(candidate);
});
socket.on('vad-status', (status) => {
this.log(`VAD status from ${socket.id}: ${JSON.stringify(status)}`);
});
socket.on('disconnect', () => {
this.log(`Client disconnected: ${socket.id}`);
rtcConnection.cleanup();
this.connections.delete(socket.id);
});
});
}
log(message, level = 'info') {
const timestamp = new Date().toISOString();
console.log(`[WebRTC ${timestamp}] [${level.toUpperCase()}] ${message}`);
}
shutdown() {
for (const connection of this.connections.values()) {
connection.cleanup();
}
this.connections.clear();
this.io.close();
}
}
module.exports = { SocketIOService };

View File

@@ -200,6 +200,7 @@ function generateConfig(key, baseURL, endpoint) {
config.capabilities = [
AgentCapabilities.execute_code,
AgentCapabilities.file_search,
AgentCapabilities.artifacts,
AgentCapabilities.actions,
AgentCapabilities.tools,
];

View File

@@ -98,6 +98,12 @@
* @memberof typedefs
*/
/**
* @exports LangChainToolCall
* @typedef {import('@langchain/core/messages/tool').ToolCall} LangChainToolCall
* @memberof typedefs
*/
/**
* @exports GraphRunnableConfig
* @typedef {import('@langchain/core/runnables').RunnableConfig<{
@@ -109,7 +115,9 @@
* agent_index: number;
* last_agent_index: number;
* hide_sequential_outputs: boolean;
* }>} GraphRunnableConfig
* }> & {
* toolCall?: LangChainToolCall & { stepId?: string };
* }} GraphRunnableConfig
* @memberof typedefs
*/
@@ -383,6 +391,12 @@
* @memberof typedefs
*/
/**
* @exports AgentToolCallDelta
* @typedef {import('librechat-data-provider').Agents.ToolCallDelta} AgentToolCallDelta
* @memberof typedefs
*/
/** Prompts */
/**
* @exports TPrompt
@@ -947,12 +961,24 @@
* @memberof typedefs
*/
/**
* @exports Keyv
* @typedef {import('keyv')} Keyv
* @memberof typedefs
*/
/**
* @exports MCPManager
* @typedef {import('librechat-mcp').MCPManager} MCPManager
* @memberof typedefs
*/
/**
* @exports FlowStateManager
* @typedef {import('librechat-mcp').FlowStateManager} FlowStateManager
* @memberof typedefs
*/
/**
* @exports LCAvailableTools
* @typedef {import('librechat-mcp').LCAvailableTools} LCAvailableTools

View File

@@ -1,6 +1,6 @@
{
"name": "@librechat/frontend",
"version": "v0.7.6",
"version": "v0.7.7-rc1",
"description": "",
"type": "module",
"scripts": {
@@ -28,7 +28,8 @@
},
"homepage": "https://librechat.ai",
"dependencies": {
"@ariakit/react": "^0.4.11",
"@ariakit/react": "^0.4.15",
"@ariakit/react-core": "^0.4.15",
"@codesandbox/sandpack-react": "^2.19.10",
"@dicebear/collection": "^7.0.4",
"@dicebear/core": "^7.0.4",
@@ -50,11 +51,9 @@
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.3",
"@radix-ui/react-toast": "^1.1.5",
"@radix-ui/react-tooltip": "^1.0.6",
"@ricky0123/vad-react": "^0.0.28",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.11.7",
"@zattoo/use-double-click": "1.2.0",
"axios": "^1.7.7",
"class-variance-authority": "^0.6.0",
"clsx": "^1.2.1",
"copy-to-clipboard": "^3.3.3",
@@ -65,7 +64,7 @@
"filenamify": "^6.0.0",
"framer-motion": "^11.5.4",
"html-to-image": "^1.11.11",
"image-blob-reduce": "^4.1.0",
"i18next": "^24.2.2",
"js-cookie": "^3.0.5",
"librechat-data-provider": "*",
"lodash": "^4.17.21",
@@ -79,10 +78,10 @@
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^18.2.0",
"react-error-boundary": "^5.0.0",
"react-flip-toolkit": "^7.1.0",
"react-gtm-module": "^2.0.11",
"react-hook-form": "^7.43.9",
"react-i18next": "^15.4.0",
"react-lazy-load-image-component": "^1.6.0",
"react-markdown": "^9.0.1",
"react-resizable-panels": "^2.1.1",
@@ -91,8 +90,6 @@
"react-textarea-autosize": "^8.4.0",
"react-transition-group": "^4.4.5",
"react-virtualized": "^9.22.6",
"react-i18next": "^15.4.0",
"i18next": "^24.2.2",
"recoil": "^0.7.7",
"regenerator-runtime": "^0.14.1",
"rehype-highlight": "^6.0.0",
@@ -101,11 +98,11 @@
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",
"remark-supersub": "^1.0.0",
"socket.io-client": "^4.8.1",
"sse.js": "^2.5.0",
"tailwind-merge": "^1.9.1",
"tailwindcss-animate": "^1.0.5",
"tailwindcss-radix": "^2.8.0",
"url": "^0.11.0",
"zod": "^3.22.4"
},
"devDependencies": {
@@ -118,31 +115,31 @@
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"@types/jest": "^29.5.2",
"@types/jest": "^29.5.14",
"@types/js-cookie": "^3.0.6",
"@types/node": "^20.3.0",
"@types/react": "^18.2.11",
"@types/react-dom": "^18.2.4",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.13",
"autoprefixer": "^10.4.20",
"babel-plugin-replace-ts-export-assignment": "^0.0.2",
"babel-plugin-root-import": "^6.6.0",
"babel-plugin-transform-import-meta": "^2.2.1",
"babel-plugin-transform-import-meta": "^2.3.2",
"babel-plugin-transform-vite-meta-env": "^1.0.3",
"eslint-plugin-jest": "^28.11.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.5.0",
"jest-canvas-mock": "^2.5.1",
"jest-environment-jsdom": "^29.5.0",
"jest": "^29.7.0",
"jest-canvas-mock": "^2.5.2",
"jest-environment-jsdom": "^29.7.0",
"jest-file-loader": "^1.0.3",
"jest-junit": "^16.0.0",
"postcss": "^8.4.31",
"postcss-loader": "^7.1.0",
"postcss-preset-env": "^8.2.0",
"tailwindcss": "^3.4.1",
"ts-jest": "^29.1.0",
"typescript": "^5.0.4",
"vite": "^5.4.14",
"ts-jest": "^29.2.5",
"typescript": "^5.3.3",
"vite": "^6.1.0",
"vite-plugin-node-polyfills": "^0.17.0",
"vite-plugin-pwa": "^0.21.1"
}

9
client/src/@types/i18next.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
import { defaultNS, resources } from '~/locales/i18n';
declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: typeof defaultNS;
resources: typeof resources.en;
strictKeyChecks: true
}
}

View File

@@ -1,4 +1,4 @@
import { AgentCapabilities } from 'librechat-data-provider';
import { AgentCapabilities, ArtifactModes } from 'librechat-data-provider';
import type { Agent, AgentProvider, AgentModelParameters } from 'librechat-data-provider';
import type { OptionWithIcon, ExtendedFile } from './types';
@@ -9,8 +9,8 @@ export type TAgentOption = OptionWithIcon &
};
export type TAgentCapabilities = {
[AgentCapabilities.execute_code]: boolean;
[AgentCapabilities.file_search]: boolean;
[AgentCapabilities.execute_code]: boolean;
[AgentCapabilities.end_after_tools]?: boolean;
[AgentCapabilities.hide_sequential_outputs]?: boolean;
};
@@ -26,4 +26,5 @@ export type AgentForm = {
tools?: string[];
provider?: AgentProvider | OptionWithIcon;
agent_ids?: string[];
[AgentCapabilities.artifacts]?: ArtifactModes | string;
} & TAgentCapabilities;

View File

@@ -48,6 +48,32 @@ export type AudioChunk = {
};
};
export interface RTCMessage {
type:
| 'audio-chunk'
| 'audio-received'
| 'transcription'
| 'llm-response'
| 'tts-chunk'
| 'call-ended'
| 'webrtc-answer'
| 'icecandidate';
payload?: RTCSessionDescriptionInit | RTCIceCandidateInit;
}
export type MessagePayload =
| RTCSessionDescriptionInit
| RTCIceCandidateInit
| { speaking: boolean };
export enum CallState {
IDLE = 'idle',
CONNECTING = 'connecting',
ACTIVE = 'active',
ERROR = 'error',
ENDED = 'ended',
}
export type AssistantListItem = {
id: string;
name: string;
@@ -68,8 +94,8 @@ export type GenericSetter<T> = (value: T | ((currentValue: T) => T)) => void;
export type LastSelectedModels = Record<t.EModelEndpoint, string>;
export type LocalizeFunction = (
phraseKey: TranslationKeys,
options?: Record<string, string | number>
phraseKey: TranslationKeys,
options?: Record<string, string | number>,
) => string;
export type ChatFormValues = { text: string };
@@ -89,6 +115,7 @@ export type IconMapProps = {
iconURL?: string;
context?: 'landing' | 'menu-item' | 'nav' | 'message';
endpoint?: string | null;
endpointType?: string;
assistantName?: string;
agentName?: string;
avatar?: string;
@@ -105,7 +132,7 @@ export type IconsRecord = {
export type AgentIconMapProps = IconMapProps & { agentName?: string };
export type NavLink = {
title: string;
title: TranslationKeys;
label?: string;
icon: LucideIcon | React.FC;
Component?: React.ComponentType;
@@ -369,12 +396,12 @@ export type TDangerButtonProps = {
showText?: boolean;
mutation?: UseMutationResult<unknown>;
onClick: () => void;
infoTextCode: string;
actionTextCode: string;
infoTextCode: TranslationKeys;
actionTextCode: TranslationKeys;
dataTestIdInitial: string;
dataTestIdConfirm: string;
infoDescriptionCode?: string;
confirmActionTextCode?: string;
infoDescriptionCode?: TranslationKeys;
confirmActionTextCode?: TranslationKeys;
};
export type TDialogProps = {

View File

@@ -28,7 +28,7 @@ function ChatView({ index = 0 }: { index?: number }) {
select: useCallback(
(data: TMessage[]) => {
const dataTree = buildTree({ messages: data, fileMap });
return dataTree?.length === 0 ? null : dataTree ?? null;
return dataTree?.length === 0 ? null : (dataTree ?? null);
},
[fileMap],
),
@@ -62,7 +62,7 @@ function ChatView({ index = 0 }: { index?: number }) {
<ChatFormProvider {...methods}>
<ChatContext.Provider value={chatHelpers}>
<AddedChatContext.Provider value={addedChatHelpers}>
<Presentation useSidePanel={true}>
<Presentation>
{content}
<div className="w-full border-t-0 pl-0 pt-2 dark:border-white/20 md:w-[calc(100%-.5rem)] md:border-t-0 md:border-transparent md:pl-0 md:pt-0 md:dark:border-transparent">
<ChatForm index={index} />

View File

@@ -0,0 +1,241 @@
import React, { useEffect, useRef } from 'react';
import { useRecoilState } from 'recoil';
import {
Phone,
PhoneOff,
AlertCircle,
Mic,
MicOff,
Volume2,
VolumeX,
Activity,
} from 'lucide-react';
import { OGDialog, OGDialogContent, Button } from '~/components';
import { useWebSocket, useCall } from '~/hooks';
import { CallState } from '~/common';
import store from '~/store';
export const Call: React.FC = () => {
const { isConnected } = useWebSocket();
const {
callState,
error,
startCall,
hangUp,
isConnecting,
localStream,
remoteStream,
connectionQuality,
isMuted,
toggleMute,
} = useCall();
const [open, setOpen] = useRecoilState(store.callDialogOpen(0));
const [eventLog, setEventLog] = React.useState<string[]>([]);
const [isAudioEnabled, setIsAudioEnabled] = React.useState(true);
const remoteAudioRef = useRef<HTMLAudioElement>(null);
const logEvent = (message: string) => {
console.log(message);
setEventLog((prev) => [...prev, `${new Date().toISOString()}: ${message}`]);
};
useEffect(() => {
if (remoteAudioRef.current && remoteStream) {
remoteAudioRef.current.srcObject = remoteStream;
remoteAudioRef.current.play().catch((err) => console.error('Error playing audio:', err));
}
}, [remoteStream]);
useEffect(() => {
if (localStream) {
localStream.getAudioTracks().forEach((track) => {
track.enabled = !isMuted;
});
}
}, [localStream, isMuted]);
useEffect(() => {
if (isConnected) {
logEvent('Connected to server.');
} else {
logEvent('Disconnected from server.');
}
}, [isConnected]);
useEffect(() => {
if (error) {
logEvent(`Error: ${error.message} (${error.code})`);
}
}, [error]);
useEffect(() => {
logEvent(`Call state changed to: ${callState}`);
}, [callState]);
const handleStartCall = () => {
logEvent('Attempting to start call...');
startCall();
};
const handleHangUp = () => {
logEvent('Attempting to hang up call...');
hangUp();
};
const handleToggleMute = () => {
toggleMute();
logEvent(`Microphone ${isMuted ? 'unmuted' : 'muted'}`);
};
const toggleAudio = () => {
setIsAudioEnabled((prev) => !prev);
if (remoteAudioRef.current) {
remoteAudioRef.current.muted = !isAudioEnabled;
}
logEvent(`Speaker ${isAudioEnabled ? 'disabled' : 'enabled'}`);
};
const isActive = callState === CallState.ACTIVE;
const isError = callState === CallState.ERROR;
// TESTS
useEffect(() => {
if (remoteAudioRef.current && remoteStream) {
console.log('Setting up remote audio:', {
tracks: remoteStream.getTracks().length,
active: remoteStream.active,
});
remoteAudioRef.current.srcObject = remoteStream;
remoteAudioRef.current.muted = false;
remoteAudioRef.current.volume = 1.0;
const playPromise = remoteAudioRef.current.play();
if (playPromise) {
playPromise.catch((err) => {
console.error('Error playing audio:', err);
// Retry play on user interaction
document.addEventListener(
'click',
() => {
remoteAudioRef.current?.play();
},
{ once: true },
);
});
}
}
}, [remoteStream]);
return (
<OGDialog open={open} onOpenChange={setOpen}>
<OGDialogContent className="w-[28rem] p-8">
<div className="flex flex-col items-center gap-6">
{/* Connection Status */}
<div className="flex w-full items-center justify-between">
<div
className={`flex items-center gap-2 rounded-full px-4 py-2 ${
isConnected ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
}`}
>
<div
className={`h-2 w-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`}
/>
<span className="text-sm font-medium">
{isConnected ? 'Connected' : 'Disconnected'}
</span>
</div>
{isActive && (
<div
className={`flex items-center gap-2 rounded-full px-4 py-2 ${
(connectionQuality === 'good' && 'bg-green-100 text-green-700') ||
(connectionQuality === 'poor' && 'bg-yellow-100 text-yellow-700') ||
'bg-gray-100 text-gray-700'
}`}
>
<Activity size={16} />
<span className="text-sm font-medium capitalize">{connectionQuality} Quality</span>
</div>
)}
</div>
{/* Error Display */}
{error && (
<div className="flex w-full items-center gap-2 rounded-md bg-red-100 p-3 text-red-700">
<AlertCircle size={16} />
<span className="text-sm">{error.message}</span>
</div>
)}
{/* Call Controls */}
<div className="flex items-center gap-4">
{isActive && (
<>
<Button
onClick={handleToggleMute}
className={`rounded-full p-3 ${
isMuted ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-700'
}`}
title={isMuted ? 'Unmute microphone' : 'Mute microphone'}
>
{isMuted ? <MicOff size={20} /> : <Mic size={20} />}
</Button>
<Button
onClick={toggleAudio}
className={`rounded-full p-3 ${
!isAudioEnabled ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-700'
}`}
title={isAudioEnabled ? 'Disable speaker' : 'Enable speaker'}
>
{isAudioEnabled ? <Volume2 size={20} /> : <VolumeX size={20} />}
</Button>
</>
)}
{isActive ? (
<Button
onClick={handleHangUp}
className="flex items-center gap-2 rounded-full bg-red-500 px-6 py-3 text-white hover:bg-red-600"
>
<PhoneOff size={20} />
<span>End Call</span>
</Button>
) : (
<Button
onClick={handleStartCall}
disabled={!isConnected || isError || isConnecting}
className="flex items-center gap-2 rounded-full bg-green-500 px-6 py-3 text-white hover:bg-green-600 disabled:opacity-50"
>
<Phone size={20} />
<span>{isConnecting ? 'Connecting...' : 'Start Call'}</span>
</Button>
)}
</div>
{/* Event Log */}
<h3 className="mb-2 text-lg font-medium">Event Log</h3>
<div className="h-64 overflow-y-auto rounded-md bg-surface-secondary p-2 shadow-inner">
<ul className="space-y-1 text-xs text-text-secondary">
{eventLog.map((log, index) => (
<li key={index} className="font-mono">
{log}
</li>
))}
</ul>
</div>
{/* Hidden Audio Element */}
<audio ref={remoteAudioRef} autoPlay>
<track kind="captions" />
</audio>
</div>
</OGDialogContent>
</OGDialog>
);
};

View File

@@ -0,0 +1,40 @@
import React, { forwardRef } from 'react';
import { TooltipAnchor } from '~/components/ui';
import { SendIcon } from '~/components/svg';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
const Button = React.memo(
forwardRef((props: { disabled: boolean }) => {
const localize = useLocalize();
return (
<TooltipAnchor
description={localize('com_nav_call_mode')}
render={
<button
aria-label={localize('com_nav_send_message')}
id="call-button"
disabled={props.disabled}
className={cn(
'rounded-full bg-text-primary p-2 text-text-primary outline-offset-4 transition-all duration-200 disabled:cursor-not-allowed disabled:text-text-secondary disabled:opacity-10',
)}
data-testid="call-button"
type="submit"
>
<span className="" data-state="closed">
<SendIcon size={24} />
</span>
</button>
}
></TooltipAnchor>
);
}),
);
const CallButton = React.memo(
forwardRef((props: { disabled: boolean }) => {
return <Button disabled={props.disabled} />;
}),
);
export default CallButton;

View File

@@ -34,6 +34,7 @@ import StreamAudio from './StreamAudio';
import StopButton from './StopButton';
import SendButton from './SendButton';
import Mention from './Mention';
import { Call } from './Call';
import store from '~/store';
const ChatForm = ({ index = 0 }) => {
@@ -156,116 +157,119 @@ const ChatForm = ({ index = 0 }) => {
: `pl-${uploadActive ? '12' : '4'} pr-12`;
return (
<form
onSubmit={methods.handleSubmit((data) => submitMessage(data))}
className={cn(
'mx-auto flex flex-row gap-3 pl-2 transition-all duration-200 last:mb-2',
maximizeChatSpace ? 'w-full max-w-full' : 'md:max-w-2xl xl:max-w-3xl',
)}
>
<div className="relative flex h-full flex-1 items-stretch md:flex-col">
<div className="flex w-full items-center">
{showPlusPopover && !isAssistantsEndpoint(endpoint) && (
<Mention
setShowMentionPopover={setShowPlusPopover}
newConversation={generateConversation}
textAreaRef={textAreaRef}
commandChar="+"
placeholder="com_ui_add_model_preset"
includeAssistants={false}
/>
)}
{showMentionPopover && (
<Mention
setShowMentionPopover={setShowMentionPopover}
newConversation={newConversation}
textAreaRef={textAreaRef}
/>
)}
<PromptsCommand index={index} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
<div className="transitional-all relative flex w-full flex-grow flex-col overflow-hidden rounded-3xl bg-surface-tertiary text-text-primary duration-200">
<TemporaryChat
isTemporaryChat={isTemporaryChat}
setIsTemporaryChat={setIsTemporaryChat}
/>
<TextareaHeader addedConvo={addedConvo} setAddedConvo={setAddedConvo} />
<FileFormWrapper disableInputs={disableInputs}>
{endpoint && (
<>
<CollapseChat
isCollapsed={isCollapsed}
isScrollable={isScrollable}
setIsCollapsed={setIsCollapsed}
/>
<TextareaAutosize
{...registerProps}
ref={(e) => {
ref(e);
textAreaRef.current = e;
}}
disabled={disableInputs}
onPaste={handlePaste}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onHeightChange={() => {
if (textAreaRef.current) {
const scrollable = checkIfScrollable(textAreaRef.current);
setIsScrollable(scrollable);
}
}}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
id={mainTextareaId}
tabIndex={0}
data-testid="text-input"
rows={1}
onFocus={() => isCollapsed && setIsCollapsed(false)}
onClick={() => isCollapsed && setIsCollapsed(false)}
style={{ height: 44, overflowY: 'auto' }}
className={cn(
baseClasses,
speechClass,
removeFocusRings,
'transition-[max-height] duration-200',
)}
/>
</>
)}
</FileFormWrapper>
{SpeechToText && (
<AudioRecorder
isRTL={isRTL}
methods={methods}
ask={submitMessage}
<>
<form
onSubmit={methods.handleSubmit((data) => submitMessage(data))}
className={cn(
'mx-auto flex flex-row gap-3 pl-2 transition-all duration-200 last:mb-2',
maximizeChatSpace ? 'w-full max-w-full' : 'md:max-w-2xl xl:max-w-3xl',
)}
>
<div className="relative flex h-full flex-1 items-stretch md:flex-col">
<div className="flex w-full items-center">
{showPlusPopover && !isAssistantsEndpoint(endpoint) && (
<Mention
setShowMentionPopover={setShowPlusPopover}
newConversation={generateConversation}
textAreaRef={textAreaRef}
disabled={!!disableInputs}
isSubmitting={isSubmitting}
commandChar="+"
placeholder="com_ui_add_model_preset"
includeAssistants={false}
/>
)}
{TextToSpeech && automaticPlayback && <StreamAudio index={index} />}
</div>
<div
className={cn(
'mb-[5px] ml-[8px] flex flex-col items-end justify-end',
isRTL && 'order-first mr-[8px]',
{showMentionPopover && (
<Mention
setShowMentionPopover={setShowMentionPopover}
newConversation={newConversation}
textAreaRef={textAreaRef}
/>
)}
style={{ alignSelf: 'flex-end' }}
>
{(isSubmitting || isSubmittingAdded) && (showStopButton || showStopAdded) ? (
<StopButton stop={handleStopGenerating} setShowStopButton={setShowStopButton} />
) : (
endpoint && (
<SendButton
ref={submitButtonRef}
control={methods.control}
disabled={!!(filesLoading || isSubmitting || disableInputs)}
<PromptsCommand index={index} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
<div className="transitional-all relative flex w-full flex-grow flex-col overflow-hidden rounded-3xl bg-surface-tertiary text-text-primary duration-200">
<TemporaryChat
isTemporaryChat={isTemporaryChat}
setIsTemporaryChat={setIsTemporaryChat}
/>
<TextareaHeader addedConvo={addedConvo} setAddedConvo={setAddedConvo} />
<FileFormWrapper disableInputs={disableInputs}>
{endpoint && (
<>
<CollapseChat
isCollapsed={isCollapsed}
isScrollable={isScrollable}
setIsCollapsed={setIsCollapsed}
/>
<TextareaAutosize
{...registerProps}
ref={(e) => {
ref(e);
textAreaRef.current = e;
}}
disabled={disableInputs}
onPaste={handlePaste}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onHeightChange={() => {
if (textAreaRef.current) {
const scrollable = checkIfScrollable(textAreaRef.current);
setIsScrollable(scrollable);
}
}}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
id={mainTextareaId}
tabIndex={0}
data-testid="text-input"
rows={1}
onFocus={() => isCollapsed && setIsCollapsed(false)}
onClick={() => isCollapsed && setIsCollapsed(false)}
style={{ height: 44, overflowY: 'auto' }}
className={cn(
baseClasses,
speechClass,
removeFocusRings,
'transition-[max-height] duration-200',
)}
/>
</>
)}
</FileFormWrapper>
{SpeechToText && (
<AudioRecorder
isRTL={isRTL}
methods={methods}
ask={submitMessage}
textAreaRef={textAreaRef}
disabled={!!disableInputs}
isSubmitting={isSubmitting}
/>
)
)}
)}
{TextToSpeech && automaticPlayback && <StreamAudio index={index} />}
</div>
<div
className={cn(
'mb-[5px] ml-[8px] flex flex-col items-end justify-end',
isRTL && 'order-first mr-[8px]',
)}
style={{ alignSelf: 'flex-end' }}
>
{(isSubmitting || isSubmittingAdded) && (showStopButton || showStopAdded) ? (
<StopButton stop={handleStopGenerating} setShowStopButton={setShowStopButton} />
) : (
endpoint && (
<SendButton
ref={submitButtonRef}
control={methods.control}
disabled={!!(filesLoading || isSubmitting || disableInputs)}
/>
)
)}
</div>
</div>
</div>
</div>
</form>
</form>
<Call />
</>
);
};

View File

@@ -1,4 +1,4 @@
/* eslint-disable react-hooks/rules-of-hooks */
import { ArrowUpDown, Database } from 'lucide-react';
import { FileSources, FileContext } from 'librechat-data-provider';
import type { ColumnDef } from '@tanstack/react-table';
@@ -7,10 +7,10 @@ import { Button, Checkbox, OpenAIMinimalIcon, AzureMinimalIcon } from '~/compone
import ImagePreview from '~/components/Chat/Input/Files/ImagePreview';
import FilePreview from '~/components/Chat/Input/Files/FilePreview';
import { SortFilterHeader } from './SortFilterHeader';
import { useLocalize, useMediaQuery } from '~/hooks';
import { TranslationKeys, useLocalize, useMediaQuery } from '~/hooks';
import { formatDate, getFileType } from '~/utils';
const contextMap = {
const contextMap: Record<any, TranslationKeys> = {
[FileContext.avatar]: 'com_ui_avatar',
[FileContext.unknown]: 'com_ui_unknown',
[FileContext.assistants]: 'com_ui_assistants',
@@ -127,8 +127,8 @@ export const columns: ColumnDef<TFile>[] = [
),
}}
valueMap={{
[FileSources.azure]: 'Azure',
[FileSources.openai]: 'OpenAI',
[FileSources.azure]: 'com_ui_azure',
[FileSources.openai]: 'com_ui_openai',
[FileSources.local]: 'com_ui_host',
}}
/>
@@ -182,7 +182,7 @@ export const columns: ColumnDef<TFile>[] = [
const localize = useLocalize();
return (
<div className="flex flex-wrap items-center gap-2">
{localize(contextMap[context ?? FileContext.unknown] ?? 'com_ui_unknown')}
{localize(contextMap[context ?? FileContext.unknown])}
</div>
);
},
@@ -212,4 +212,4 @@ export const columns: ColumnDef<TFile>[] = [
return `${value}${suffix}`;
},
},
];
];

View File

@@ -16,7 +16,7 @@ interface SortFilterHeaderProps<TData, TValue> extends React.HTMLAttributes<HTML
title: string;
column: Column<TData, TValue>;
filters?: Record<string, string[] | number[]>;
valueMap?: Record<string, string>;
valueMap?: Record<any, TranslationKeys>;
}
export function SortFilterHeader<TData, TValue>({
@@ -82,7 +82,7 @@ export function SortFilterHeader<TData, TValue>({
const translationKey = valueMap?.[value ?? ''];
const filterValue =
translationKey != null && translationKey.length
? localize(translationKey as TranslationKeys)
? localize(translationKey)
: String(value);
if (!filterValue) {
return null;

View File

@@ -6,7 +6,7 @@ import type { MentionOption, ConvoGenerator } from '~/common';
import useSelectMention from '~/hooks/Input/useSelectMention';
import { useAssistantsMapContext } from '~/Providers';
import useMentions from '~/hooks/Input/useMentions';
import { useLocalize, useCombobox } from '~/hooks';
import { useLocalize, useCombobox, TranslationKeys } from '~/hooks';
import { removeCharIfLast } from '~/utils';
import MentionItem from './MentionItem';
@@ -24,7 +24,7 @@ export default function Mention({
newConversation: ConvoGenerator;
textAreaRef: React.MutableRefObject<HTMLTextAreaElement | null>;
commandChar?: string;
placeholder?: string;
placeholder?: TranslationKeys;
includeAssistants?: boolean;
}) {
const localize = useLocalize();
@@ -162,7 +162,7 @@ export default function Mention({
<div className="popover border-token-border-light rounded-2xl border bg-white p-2 shadow-lg dark:bg-gray-700">
<input
// The user expects focus to transition to the input field when the popover is opened
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus
ref={inputRef}
placeholder={localize(placeholder)}

View File

@@ -1,49 +1,104 @@
import React, { forwardRef } from 'react';
import { useWatch } from 'react-hook-form';
import { useSetRecoilState } from 'recoil';
import type { TRealtimeEphemeralTokenResponse } from 'librechat-data-provider';
import type { Control } from 'react-hook-form';
import { TooltipAnchor } from '~/components/ui';
import { SendIcon } from '~/components/svg';
import { useRealtimeEphemeralTokenMutation } from '~/data-provider';
import { TooltipAnchor, SendIcon, CallIcon } from '~/components';
import { useToastContext } from '~/Providers/ToastContext';
import { useLocalize } from '~/hooks';
import store from '~/store';
import { cn } from '~/utils';
type SendButtonProps = {
type ButtonProps = {
disabled: boolean;
control: Control<{ text: string }>;
};
const SubmitButton = React.memo(
forwardRef((props: { disabled: boolean }, ref: React.ForwardedRef<HTMLButtonElement>) => {
const localize = useLocalize();
const ActionButton = forwardRef(
(
props: {
disabled: boolean;
icon: React.ReactNode;
tooltip: string;
testId: string;
onClick?: () => void;
},
ref: React.ForwardedRef<HTMLButtonElement>,
) => {
return (
<TooltipAnchor
description={localize('com_nav_send_message')}
description={props.tooltip}
render={
<button
ref={ref}
aria-label={localize('com_nav_send_message')}
id="send-button"
aria-label={props.tooltip}
id="action-button"
disabled={props.disabled}
className={cn(
'rounded-full bg-text-primary p-2 text-text-primary outline-offset-4 transition-all duration-200 disabled:cursor-not-allowed disabled:text-text-secondary disabled:opacity-10',
'rounded-full bg-text-primary p-2 text-text-primary outline-offset-4',
'transition-all duration-200',
'disabled:cursor-not-allowed disabled:text-text-secondary disabled:opacity-10',
)}
data-testid="send-button"
data-testid={props.testId}
type="submit"
onClick={props.onClick}
>
<span className="" data-state="closed">
<SendIcon size={24} />
{props.icon}
</span>
</button>
}
></TooltipAnchor>
/>
);
}),
},
);
const SendButton = React.memo(
forwardRef((props: SendButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => {
const data = useWatch({ control: props.control });
return <SubmitButton ref={ref} disabled={props.disabled || !data.text} />;
}),
);
const SendButton = forwardRef((props: ButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => {
const localize = useLocalize();
const { showToast } = useToastContext();
const { text = '' } = useWatch({ control: props.control });
const setCallOpen = useSetRecoilState(store.callDialogOpen(0));
// const { mutate: startCall, isLoading: isProcessing } = useRealtimeEphemeralTokenMutation({
// onSuccess: async (data: TRealtimeEphemeralTokenResponse) => {
// showToast({
// message: 'IT WORKS!!',
// status: 'success',
// });
// },
// onError: (error: unknown) => {
// showToast({
// message: localize('com_nav_audio_process_error', (error as Error).message),
// status: 'error',
// });
// },
// });
const handleClick = () => {
if (text.trim() === '') {
setCallOpen(true);
// startCall({ voice: 'verse' });
}
};
const buttonProps =
text.trim() !== ''
? {
icon: <SendIcon size={24} />,
tooltip: localize('com_nav_send_message'),
testId: 'send-button',
}
: {
icon: <CallIcon size={24} />,
tooltip: localize('com_nav_call'),
testId: 'call-button',
onClick: handleClick,
};
return <ActionButton ref={ref} disabled={props.disabled} {...buttonProps} />;
});
SendButton.displayName = 'SendButton';
export default SendButton;

View File

@@ -7,6 +7,9 @@ import FinishedIcon from './FinishedIcon';
import MarkdownLite from './MarkdownLite';
import store from '~/store';
const radius = 56.08695652173913;
const circumference = 2 * Math.PI * radius;
export default function CodeAnalyze({
initialProgress = 0.1,
code,
@@ -22,9 +25,6 @@ export default function CodeAnalyze({
const progress = useProgress(initialProgress);
const showAnalysisCode = useRecoilValue(store.showCode);
const [showCode, setShowCode] = useState(showAnalysisCode);
const radius = 56.08695652173913;
const circumference = 2 * Math.PI * radius;
const offset = circumference - progress * circumference;
const logs = outputs.reduce((acc, output) => {
@@ -53,9 +53,10 @@ export default function CodeAnalyze({
<ProgressText
progress={progress}
onClick={() => setShowCode((prev) => !prev)}
inProgressText="Analyzing"
finishedText="Finished analyzing"
inProgressText={localize('com_ui_analyzing')}
finishedText={localize('com_ui_analyzing_finished')}
hasInput={!!code.length}
isExpanded={showCode}
/>
</div>
{showCode && (

View File

@@ -50,11 +50,24 @@ const ContentParts = memo(
[attachments, messageAttachmentsMap, messageId],
);
const hasReasoningParts = useMemo(
() => content?.some((part) => part?.type === ContentTypes.THINK && part.think) ?? false,
[content],
);
const hasReasoningParts = useMemo(() => {
const hasThinkPart = content?.some((part) => part?.type === ContentTypes.THINK) ?? false;
const allThinkPartsHaveContent =
content?.every((part) => {
if (part?.type !== ContentTypes.THINK) {
return true;
}
if (typeof part.think === 'string') {
const cleanedContent = part.think.replace(/<\/?think>/g, '').trim();
return cleanedContent.length > 0;
}
return false;
}) ?? false;
return hasThinkPart && allThinkPartsHaveContent;
}, [content]);
if (!content) {
return null;
}

View File

@@ -9,14 +9,14 @@ const Files = ({ message }: { message?: TMessage }) => {
}, [message?.files]);
const otherFiles = useMemo(() => {
return message?.files?.filter((file) => !file.type?.startsWith('image/')) || [];
return message?.files?.filter((file) => !(file.type?.startsWith('image/') === true)) || [];
}, [message?.files]);
return (
<>
{otherFiles.length > 0 &&
otherFiles.map((file) => <FileContainer key={file.file_id} file={file as TFile} />)}
{imageFiles &&
{imageFiles.length > 0 &&
imageFiles.map((file) => (
<Image
key={file.file_id}

View File

@@ -11,7 +11,7 @@ export default function InProgressCall({
progress: number;
children: React.ReactNode;
}) {
if ((!isSubmitting && progress < 1) || error) {
if ((!isSubmitting && progress < 1) || error === true) {
return <CancelledIcon />;
}

View File

@@ -159,7 +159,9 @@ const MessageContent = ({
return (
<>
{thinkingContent && <Thinking key={`thinking-${messageId}`}>{thinkingContent}</Thinking>}
{thinkingContent.length > 0 && (
<Thinking key={`thinking-${messageId}`}>{thinkingContent}</Thinking>
)}
<DisplayMessage
key={`display-${messageId}`}
showCursor={showRegularCursor}

View File

@@ -81,6 +81,8 @@ const Part = memo(({ part, isSubmitting, attachments, showCursor, isCreatedByUse
initialProgress={toolCall.progress ?? 0.1}
isSubmitting={isSubmitting}
attachments={attachments}
auth={toolCall.auth}
expires_at={toolCall.expires_at}
/>
);
} else if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {

View File

@@ -4,10 +4,10 @@ import type { TAttachment } from 'librechat-data-provider';
import ProgressText from '~/components/Chat/Messages/Content/ProgressText';
import FinishedIcon from '~/components/Chat/Messages/Content/FinishedIcon';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import { useProgress, useLocalize } from '~/hooks';
import { CodeInProgress } from './CodeProgress';
import Attachment from './Attachment';
import LogContent from './LogContent';
import { useProgress } from '~/hooks';
import store from '~/store';
interface ParsedArgs {
@@ -36,6 +36,9 @@ export function useParseArgs(args: string): ParsedArgs {
}, [args]);
}
const radius = 56.08695652173913;
const circumference = 2 * Math.PI * radius;
export default function ExecuteCode({
initialProgress = 0.1,
args,
@@ -49,14 +52,12 @@ export default function ExecuteCode({
isSubmitting: boolean;
attachments?: TAttachment[];
}) {
const localize = useLocalize();
const showAnalysisCode = useRecoilValue(store.showCode);
const [showCode, setShowCode] = useState(showAnalysisCode);
const { lang, code } = useParseArgs(args);
const progress = useProgress(initialProgress);
const radius = 56.08695652173913;
const circumference = 2 * Math.PI * radius;
const offset = circumference - progress * circumference;
return (
@@ -78,9 +79,10 @@ export default function ExecuteCode({
<ProgressText
progress={progress}
onClick={() => setShowCode((prev) => !prev)}
inProgressText="Analyzing"
finishedText="Finished analyzing"
inProgressText={localize('com_ui_analyzing')}
finishedText={localize('com_ui_analyzing_finished')}
hasInput={!!code.length}
isExpanded={showCode}
/>
</div>
{showCode && (
@@ -105,9 +107,7 @@ export default function ExecuteCode({
)}
</div>
)}
{attachments?.map((attachment, index) => (
<Attachment attachment={attachment} key={index} />
))}
{attachments?.map((attachment, index) => <Attachment attachment={attachment} key={index} />)}
</>
);
}

View File

@@ -11,9 +11,16 @@ type ReasoningProps = {
const Reasoning = memo(({ reasoning }: ReasoningProps) => {
const { isExpanded, nextType } = useMessageContext();
const reasoningText = useMemo(() => {
return reasoning.replace(/^<think>\s*/, '').replace(/\s*<\/think>$/, '');
return reasoning
.replace(/^<think>\s*/, '')
.replace(/\s*<\/think>$/, '')
.trim();
}, [reasoning]);
if (!reasoningText) {
return null;
}
return (
<div
className={cn(

View File

@@ -39,16 +39,21 @@ export default function ProgressText({
onClick,
inProgressText,
finishedText,
authText,
hasInput = true,
popover = false,
isExpanded = false,
}: {
progress: number;
onClick: () => void;
onClick?: () => void;
inProgressText: string;
finishedText: string;
authText?: string;
hasInput?: boolean;
popover?: boolean;
isExpanded?: boolean;
}) {
const text = progress < 1 ? (authText ?? inProgressText) : finishedText;
return (
<Wrapper popover={popover}>
<button
@@ -57,8 +62,14 @@ export default function ProgressText({
disabled={!hasInput}
onClick={onClick}
>
{progress < 1 ? inProgressText : finishedText}
<svg width="16" height="17" viewBox="0 0 16 17" fill="none">
{text}
<svg
width="16"
height="17"
viewBox="0 0 16 17"
fill="none"
className={isExpanded ? 'rotate-180' : 'rotate-0'}
>
<path
className={hasInput ? '' : 'stroke-transparent'}
d="M11.3346 7.83203L8.00131 11.1654L4.66797 7.83203"

View File

@@ -1,5 +1,6 @@
import { useMemo } from 'react';
import * as Popover from '@radix-ui/react-popover';
import { ShieldCheck, TriangleAlert } from 'lucide-react';
import { actionDelimiter, actionDomainSeparator, Constants } from 'librechat-data-provider';
import type { TAttachment } from 'librechat-data-provider';
import useLocalize from '~/hooks/useLocalize';
@@ -14,6 +15,9 @@ import WrenchIcon from './WrenchIcon';
import { useProgress } from '~/hooks';
import { logger } from '~/utils';
const radius = 56.08695652173913;
const circumference = 2 * Math.PI * radius;
export default function ToolCall({
initialProgress = 0.1,
isSubmitting,
@@ -21,6 +25,7 @@ export default function ToolCall({
args: _args = '',
output,
attachments,
auth,
}: {
initialProgress: number;
isSubmitting: boolean;
@@ -28,13 +33,10 @@ export default function ToolCall({
args: string | Record<string, unknown>;
output?: string | null;
attachments?: TAttachment[];
auth?: string;
expires_at?: number;
}) {
const localize = useLocalize();
const progress = useProgress(initialProgress);
const radius = 56.08695652173913;
const circumference = 2 * Math.PI * radius;
const offset = circumference - progress * circumference;
const { function_name, domain, isMCPToolCall } = useMemo(() => {
if (typeof name !== 'string') {
return { function_name: '', domain: null, isMCPToolCall: false };
@@ -83,8 +85,37 @@ export default function ToolCall({
[args, output],
);
const authDomain = useMemo(() => {
const authURL = auth ?? '';
if (!authURL) {
return '';
}
try {
const url = new URL(authURL);
return url.hostname;
} catch (e) {
return '';
}
}, [auth]);
const progress = useProgress(error === true ? 1 : initialProgress);
const cancelled = (!isSubmitting && progress < 1) || error === true;
const offset = circumference - progress * circumference;
const renderIcon = () => {
if (progress < 1) {
if (progress < 1 && authDomain.length > 0) {
return (
<div
className="absolute left-0 top-0 flex h-full w-full items-center justify-center rounded-full bg-transparent text-text-secondary"
style={{ opacity: 1, transform: 'none' }}
data-projection-id="849"
>
<div>
<ShieldCheck />
</div>
</div>
);
} else if (progress < 1) {
return (
<InProgressCall progress={progress} isSubmitting={isSubmitting} error={error}>
<div
@@ -101,10 +132,13 @@ export default function ToolCall({
);
}
return error === true ? <CancelledIcon /> : <FinishedIcon />;
return cancelled ? <CancelledIcon /> : <FinishedIcon />;
};
const getFinishedText = () => {
if (cancelled) {
return localize('com_ui_error');
}
if (isMCPToolCall === true) {
return localize('com_assistants_completed_function', { 0: function_name });
}
@@ -116,28 +150,49 @@ export default function ToolCall({
return (
<Popover.Root>
<div className="my-2.5 flex items-center gap-2.5">
<div className="relative h-5 w-5 shrink-0">{renderIcon()}</div>
<ProgressText
progress={progress}
onClick={() => ({})}
inProgressText={localize('com_assistants_running_action')}
finishedText={getFinishedText()}
hasInput={hasInfo}
popover={true}
/>
{hasInfo && (
<ToolPopover
input={args ?? ''}
output={output}
domain={domain ?? ''}
function_name={function_name}
<div className="my-2.5 flex flex-wrap items-center gap-2.5">
<div className="flex w-full items-center gap-2.5">
<div className="relative h-5 w-5 shrink-0">{renderIcon()}</div>
<ProgressText
progress={cancelled ? 1 : progress}
inProgressText={localize('com_assistants_running_action')}
authText={
!cancelled && authDomain.length > 0 ? localize('com_ui_requires_auth') : undefined
}
finishedText={getFinishedText()}
hasInput={hasInfo}
popover={true}
/>
{hasInfo && (
<ToolPopover
input={args ?? ''}
output={output}
domain={authDomain || (domain ?? '')}
function_name={function_name}
pendingAuth={authDomain.length > 0 && !cancelled && progress < 1}
/>
)}
</div>
{auth != null && auth && progress < 1 && !cancelled && (
<div className="flex w-full flex-col gap-2.5">
<div className="mb-1 mt-2">
<a
className="inline-flex items-center justify-center gap-2 rounded-3xl bg-surface-tertiary px-4 py-2 text-sm font-medium hover:bg-surface-hover"
href={auth}
target="_blank"
rel="noopener noreferrer"
>
{localize('com_ui_sign_in_to_domain', { 0: authDomain })}
</a>
</div>
<p className="flex items-center text-xs text-text-secondary">
<TriangleAlert className="mr-1.5 inline-block h-4 w-4" />
{localize('com_assistants_allow_sites_you_trust')}
</p>
</div>
)}
</div>
{attachments?.map((attachment, index) => (
<Attachment attachment={attachment} key={index} />
))}
{attachments?.map((attachment, index) => <Attachment attachment={attachment} key={index} />)}
</Popover.Root>
);
}

View File

@@ -4,13 +4,15 @@ import useLocalize from '~/hooks/useLocalize';
export default function ToolPopover({
input,
output,
function_name,
domain,
function_name,
pendingAuth,
}: {
input: string;
function_name: string;
output?: string | null;
domain?: string;
pendingAuth?: boolean;
}) {
const localize = useLocalize();
const formatText = (text: string) => {
@@ -21,6 +23,17 @@ export default function ToolPopover({
}
};
let title =
domain != null && domain
? localize('com_assistants_domain_info', { 0: domain })
: localize('com_assistants_function_use', { 0: function_name });
if (pendingAuth === true) {
title =
domain != null && domain
? localize('com_assistants_action_attempt', { 0: domain })
: localize('com_assistants_attempt_info');
}
return (
<Popover.Portal>
<Popover.Content
@@ -28,27 +41,23 @@ export default function ToolPopover({
align="start"
sideOffset={12}
alignOffset={-5}
className="w-18 min-w-[180px] max-w-sm rounded-lg bg-white dark:bg-gray-900"
className="w-18 min-w-[180px] max-w-sm rounded-lg bg-surface-primary px-1"
>
<div tabIndex={-1}>
<div className="bg-token-surface-primary max-w-sm rounded-md p-2 shadow-[0_0_24px_0_rgba(0,0,0,0.05),inset_0_0.5px_0_0_rgba(0,0,0,0.05),0_2px_8px_0_rgba(0,0,0,0.05)]">
<div className="mb-2 text-sm font-medium dark:text-gray-100">
{domain != null && domain
? localize('com_assistants_domain_info', { 0: domain })
: localize('com_assistants_function_use', { 0: function_name })}
</div>
<div className="mb-2 text-sm font-medium text-text-primary">{title}</div>
<div className="bg-token-surface-secondary text-token-text-primary dark rounded-md text-xs">
<div className="max-h-32 overflow-y-auto rounded-md p-2 dark:bg-gray-700">
<div className="max-h-32 overflow-y-auto rounded-md bg-surface-tertiary p-2">
<code className="!whitespace-pre-wrap ">{formatText(input)}</code>
</div>
</div>
{output != null && output && (
<>
<div className="mb-2 mt-2 text-sm font-medium dark:text-gray-100">
<div className="mb-2 mt-2 text-sm font-medium text-text-primary">
{localize('com_ui_result')}
</div>
<div className="bg-token-surface-secondary text-token-text-primary dark rounded-md text-xs">
<div className="max-h-32 overflow-y-auto rounded-md p-2 dark:bg-gray-700">
<div className="max-h-32 overflow-y-auto rounded-md bg-surface-tertiary p-2">
<code className="!whitespace-pre-wrap ">{formatText(output)}</code>
</div>
</div>

View File

@@ -1,37 +1,19 @@
import { useRecoilValue } from 'recoil';
import { useEffect, useMemo } from 'react';
import { FileSources, LocalStorageKeys, getConfigDefaults } from 'librechat-data-provider';
import { FileSources, LocalStorageKeys } from 'librechat-data-provider';
import type { ExtendedFile } from '~/common';
import { useDeleteFilesMutation, useGetStartupConfig } from '~/data-provider';
import { useDeleteFilesMutation } from '~/data-provider';
import DragDropWrapper from '~/components/Chat/Input/Files/DragDropWrapper';
import Artifacts from '~/components/Artifacts/Artifacts';
import { SidePanel } from '~/components/SidePanel';
import { SidePanelGroup } from '~/components/SidePanel';
import { useSetFilesToDelete } from '~/hooks';
import { EditorProvider } from '~/Providers';
import store from '~/store';
const defaultInterface = getConfigDefaults().interface;
export default function Presentation({
children,
useSidePanel = false,
panel,
}: {
children: React.ReactNode;
panel?: React.ReactNode;
useSidePanel?: boolean;
}) {
const { data: startupConfig } = useGetStartupConfig();
export default function Presentation({ children }: { children: React.ReactNode }) {
const artifacts = useRecoilValue(store.artifactsState);
const codeArtifacts = useRecoilValue(store.codeArtifacts);
const hideSidePanel = useRecoilValue(store.hideSidePanel);
const artifactsVisible = useRecoilValue(store.artifactsVisible);
const interfaceConfig = useMemo(
() => startupConfig?.interface ?? defaultInterface,
[startupConfig],
);
const setFilesToDelete = useSetFilesToDelete();
const { mutateAsync } = useDeleteFilesMutation({
@@ -83,35 +65,24 @@ export default function Presentation({
</div>
);
if (useSidePanel && !hideSidePanel && interfaceConfig.sidePanel === true) {
return (
<DragDropWrapper className="relative flex w-full grow overflow-hidden bg-presentation">
<SidePanel
defaultLayout={defaultLayout}
defaultCollapsed={defaultCollapsed}
fullPanelCollapse={fullCollapse}
artifacts={
artifactsVisible === true &&
codeArtifacts === true &&
Object.keys(artifacts ?? {}).length > 0 ? (
<EditorProvider>
<Artifacts />
</EditorProvider>
) : null
}
>
<main className="flex h-full flex-col overflow-y-auto" role="main">
{children}
</main>
</SidePanel>
</DragDropWrapper>
);
}
return (
<DragDropWrapper className="relative flex w-full grow overflow-hidden bg-presentation">
{layout()}
{panel != null && panel}
<SidePanelGroup
defaultLayout={defaultLayout}
fullPanelCollapse={fullCollapse}
defaultCollapsed={defaultCollapsed}
artifacts={
artifactsVisible === true && Object.keys(artifacts ?? {}).length > 0 ? (
<EditorProvider>
<Artifacts />
</EditorProvider>
) : null
}
>
<main className="flex h-full flex-col overflow-y-auto" role="main">
{children}
</main>
</SidePanelGroup>
</DragDropWrapper>
);
}

View File

@@ -1,4 +1,4 @@
import { useState, useRef } from 'react';
import React, { useState, useRef } from 'react';
import { useRecoilState } from 'recoil';
import { GitFork, InfoIcon } from 'lucide-react';
import * as Popover from '@radix-ui/react-popover';
@@ -21,9 +21,9 @@ import store from '~/store';
interface PopoverButtonProps {
children: React.ReactNode;
setting: string;
onClick: (setting: string) => void;
setActiveSetting: React.Dispatch<React.SetStateAction<string>>;
setting: ForkOptions;
onClick: (setting: ForkOptions) => void;
setActiveSetting: React.Dispatch<React.SetStateAction<TranslationKeys>>;
sideOffset?: number;
timeoutRef: React.MutableRefObject<NodeJS.Timeout | null>;
hoverInfo?: React.ReactNode | string;
@@ -31,11 +31,11 @@ interface PopoverButtonProps {
hoverDescription?: React.ReactNode | string;
}
const optionLabels = {
const optionLabels: Record<ForkOptions, TranslationKeys> = {
[ForkOptions.DIRECT_PATH]: 'com_ui_fork_visible',
[ForkOptions.INCLUDE_BRANCHES]: 'com_ui_fork_branches',
[ForkOptions.TARGET_LEVEL]: 'com_ui_fork_all_target',
default: 'com_ui_fork_from_message',
[ForkOptions.DEFAULT]: 'com_ui_fork_from_message',
};
const PopoverButton: React.FC<PopoverButtonProps> = ({
@@ -65,10 +65,10 @@ const PopoverButton: React.FC<PopoverButtonProps> = ({
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
setActiveSetting(optionLabels.default);
setActiveSetting(optionLabels[ForkOptions.DEFAULT]);
}, 175);
}}
className="mx-1 max-w-14 flex-1 rounded-lg border-2 bg-white text-gray-700 transition duration-300 ease-in-out hover:bg-gray-200 hover:text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600 dark:hover:text-gray-100 "
className="mx-1 max-w-14 flex-1 rounded-lg border-2 bg-white text-gray-700 transition duration-300 ease-in-out hover:bg-gray-200 hover:text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600 dark:hover:text-gray-100"
type="button"
>
{children}
@@ -77,18 +77,12 @@ const PopoverButton: React.FC<PopoverButtonProps> = ({
(hoverTitle != null && hoverTitle !== '') ||
(hoverDescription != null && hoverDescription !== '')) && (
<HoverCardPortal>
<HoverCardContent
side="right"
className="z-[999] w-80 dark:bg-gray-700"
sideOffset={sideOffset}
>
<HoverCardContent side="right" className="z-[999] w-80 dark:bg-gray-700" sideOffset={sideOffset}>
<div className="space-y-2">
<p className="flex flex-col gap-2 text-sm text-gray-600 dark:text-gray-300">
{hoverInfo != null && hoverInfo !== '' && hoverInfo}
{hoverTitle != null && hoverTitle !== '' && (
<span className="flex flex-wrap gap-1 font-bold">{hoverTitle}</span>
)}
{hoverDescription != null && hoverDescription !== '' && hoverDescription}
{hoverInfo && hoverInfo}
{hoverTitle && <span className="flex flex-wrap gap-1 font-bold">{hoverTitle}</span>}
{hoverDescription && hoverDescription}
</p>
</div>
</HoverCardContent>
@@ -201,7 +195,7 @@ export default function Fork({
align="center"
>
<div className="flex h-6 w-full items-center justify-center text-sm dark:text-gray-200">
{localize(activeSetting as TranslationKeys)}
{localize(activeSetting )}
<HoverCard openDelay={50}>
<HoverCardTrigger asChild>
<InfoIcon className="ml-auto flex h-4 w-4 gap-2 text-gray-500 dark:text-white/50" />
@@ -235,7 +229,7 @@ export default function Fork({
hoverTitle={
<>
<GitCommit className="h-5 w-5 rotate-90" />
{localize(optionLabels[ForkOptions.DIRECT_PATH] as TranslationKeys)}
{localize(optionLabels[ForkOptions.DIRECT_PATH])}
</>
}
hoverDescription={localize('com_ui_fork_info_visible')}
@@ -253,7 +247,7 @@ export default function Fork({
hoverTitle={
<>
<GitBranchPlus className="h-4 w-4 rotate-180" />
{localize(optionLabels[ForkOptions.INCLUDE_BRANCHES] as TranslationKeys)}
{localize(optionLabels[ForkOptions.INCLUDE_BRANCHES])}
</>
}
hoverDescription={localize('com_ui_fork_info_branches')}
@@ -272,7 +266,7 @@ export default function Fork({
<>
<ListTree className="h-5 w-5" />
{`${localize(
optionLabels[ForkOptions.TARGET_LEVEL] as TranslationKeys,
optionLabels[ForkOptions.TARGET_LEVEL],
)} (${localize('com_endpoint_default')})`}
</>
}

View File

@@ -40,13 +40,15 @@ export const TemporaryChat = () => {
};
return (
<div className="sticky bottom-0 border-none bg-surface-tertiary px-6 py-4 ">
<div className="flex items-center">
<div className={cn('flex flex-1 items-center gap-2', isActiveConvo && 'opacity-40')}>
<div className="sticky bottom-0 mt-auto w-full border-none bg-surface-tertiary px-6 py-4">
<div className="flex items-center justify-between">
<div className={cn('flex items-center gap-2', isActiveConvo && 'opacity-40')}>
<MessageCircleDashed className="icon-sm" aria-hidden="true" />
<span className="text-sm text-text-primary">{localize('com_ui_temporary_chat')}</span>
<span className="truncate text-sm text-text-primary">
{localize('com_ui_temporary_chat')}
</span>
</div>
<div className="ml-auto flex items-center">
<div className="flex flex-shrink-0 items-center">
<Switch
id="temporary-chat-switch"
checked={isTemporary}

View File

@@ -1,4 +1,4 @@
import { useState, useRef } from 'react';
import React, { useState, useRef } from 'react';
import * as Tabs from '@radix-ui/react-tabs';
import { MessageSquare, Command } from 'lucide-react';
import { SettingsTabValues } from 'librechat-data-provider';
@@ -6,7 +6,7 @@ import type { TDialogProps } from '~/common';
import { Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from '@headlessui/react';
import { GearIcon, DataIcon, SpeechIcon, UserIcon, ExperimentIcon } from '~/components/svg';
import { General, Chat, Speech, Beta, Commands, Data, Account } from './SettingsTabs';
import { useMediaQuery, useLocalize } from '~/hooks';
import { useMediaQuery, useLocalize, TranslationKeys } from '~/hooks';
import { cn } from '~/utils';
export default function Settings({ open, onOpenChange }: TDialogProps) {
@@ -47,6 +47,44 @@ export default function Settings({ open, onOpenChange }: TDialogProps) {
}
};
const settingsTabs: { value: SettingsTabValues; icon: React.JSX.Element; label: TranslationKeys }[] = [
{
value: SettingsTabValues.GENERAL,
icon: <GearIcon />,
label: 'com_nav_setting_general',
},
{
value: SettingsTabValues.CHAT,
icon: <MessageSquare className="icon-sm" />,
label: 'com_nav_setting_chat',
},
{
value: SettingsTabValues.BETA,
icon: <ExperimentIcon />,
label: 'com_nav_setting_beta',
},
{
value: SettingsTabValues.COMMANDS,
icon: <Command className="icon-sm" />,
label: 'com_nav_commands',
},
{
value: SettingsTabValues.SPEECH,
icon: <SpeechIcon className="icon-sm" />,
label: 'com_nav_setting_speech',
},
{
value: SettingsTabValues.DATA,
icon: <DataIcon />,
label: 'com_nav_setting_data',
},
{
value: SettingsTabValues.ACCOUNT,
icon: <UserIcon />,
label: 'com_nav_setting_account',
},
];
const handleTabChange = (value: string) => {
setActiveTab(value as SettingsTabValues);
};
@@ -126,43 +164,7 @@ export default function Settings({ open, onOpenChange }: TDialogProps) {
)}
onKeyDown={handleKeyDown}
>
{[
{
value: SettingsTabValues.GENERAL,
icon: <GearIcon />,
label: 'com_nav_setting_general',
},
{
value: SettingsTabValues.CHAT,
icon: <MessageSquare className="icon-sm" />,
label: 'com_nav_setting_chat',
},
{
value: SettingsTabValues.BETA,
icon: <ExperimentIcon />,
label: 'com_nav_setting_beta',
},
{
value: SettingsTabValues.COMMANDS,
icon: <Command className="icon-sm" />,
label: 'com_nav_commands',
},
{
value: SettingsTabValues.SPEECH,
icon: <SpeechIcon className="icon-sm" />,
label: 'com_nav_setting_speech',
},
{
value: SettingsTabValues.DATA,
icon: <DataIcon />,
label: 'com_nav_setting_data',
},
{
value: SettingsTabValues.ACCOUNT,
icon: <UserIcon />,
label: 'com_nav_setting_account',
},
].map(({ value, icon, label }) => (
{settingsTabs.map(({ value, icon, label }) => (
<Tabs.Trigger
key={value}
className={cn(

View File

@@ -14,6 +14,7 @@ import { useDeleteUserMutation } from '~/data-provider';
import { useAuthContext } from '~/hooks/AuthContext';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import { LocalizeFunction } from '~/common';
const DeleteAccount = ({ disabled = false }: { title?: string; disabled?: boolean }) => {
const localize = useLocalize();
@@ -103,7 +104,7 @@ const renderDeleteButton = (
handleDeleteUser: () => void,
isDeleting: boolean,
isLocked: boolean,
localize: (key: string) => string,
localize: LocalizeFunction,
) => (
<button
className={cn(

View File

@@ -18,7 +18,6 @@ export default function PlusCommandSwitch() {
id="plusCommand"
checked={plusCommand}
onCheckedChange={handleCheckedChange}
f
className="ml-4"
data-testid="plusCommand"
/>

View File

@@ -18,7 +18,6 @@ export default function SlashCommandSwitch() {
id="slashCommand"
checked={slashCommand}
onCheckedChange={handleCheckedChange}
f
data-testid="slashCommand"
/>
</div>

View File

@@ -52,7 +52,7 @@ export const LangSelector = ({
{ value: 'auto', label: localize('com_nav_lang_auto') },
{ value: 'en-US', label: localize('com_nav_lang_english') },
{ value: 'zh-CN', label: localize('com_nav_lang_chinese') },
{ value: 'zh-TW', label: localize('com_nav_lang_traditionalchinese') },
{ value: 'zh-Hant', label: localize('com_nav_lang_traditional_chinese') },
{ value: 'ar-EG', label: localize('com_nav_lang_arabic') },
{ value: 'de-DE', label: localize('com_nav_lang_german') },
{ value: 'es-ES', label: localize('com_nav_lang_spanish') },

View File

@@ -30,17 +30,13 @@ export default function GroupSidePanel({
<div
className={cn(
'mr-2 flex h-auto w-auto min-w-72 flex-col gap-2 lg:w-1/4 xl:w-1/4',
isDetailView && isSmallerScreen ? 'hidden' : '',
isDetailView === true && isSmallerScreen ? 'hidden' : '',
className,
)}
>
{children}
<div className="flex-grow overflow-y-auto">
<List
groups={promptGroups}
isChatRoute={isChatRoute}
isLoading={!!groupsQuery.isLoading}
/>
<List groups={promptGroups} isChatRoute={isChatRoute} isLoading={!!groupsQuery.isLoading} />
</div>
<PanelNavigation
nextPage={nextPage}

View File

@@ -1,296 +0,0 @@
import { useFormContext } from 'react-hook-form';
import * as RadioGroup from '@radix-ui/react-radio-group';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import {
AuthTypeEnum,
AuthorizationTypeEnum,
TokenExchangeMethodEnum,
} from 'librechat-data-provider';
import { DialogContent } from '~/components/ui/';
export default function ActionsAuth({
setOpenAuthDialog,
}: {
setOpenAuthDialog: React.Dispatch<React.SetStateAction<boolean>>;
}) {
const { watch, setValue, trigger } = useFormContext();
const type = watch('type');
return (
<DialogContent
role="dialog"
id="radix-:rf5:"
aria-describedby="radix-:rf7:"
aria-labelledby="radix-:rf6:"
data-state="open"
className="left-1/2 col-auto col-start-2 row-auto row-start-2 w-full max-w-md -translate-x-1/2 rounded-xl bg-white pb-0 text-left shadow-xl transition-all dark:bg-gray-700 dark:text-gray-100"
tabIndex={-1}
style={{ pointerEvents: 'auto' }}
>
<div className="flex items-center justify-between border-b border-black/10 px-4 pb-4 pt-5 dark:border-white/10 sm:p-6">
<div className="flex">
<div className="flex items-center">
<div className="flex grow flex-col gap-1">
<h2
id="radix-:rf6:"
className="text-token-text-primary text-lg font-medium leading-6"
>
Authentication
</h2>
</div>
</div>
</div>
</div>
<div className="p-4 sm:p-6 sm:pt-0">
<div className="mb-4">
<label className="mb-1 block text-sm font-medium">Authentication Type</label>
<RadioGroup.Root
defaultValue={AuthTypeEnum.None}
onValueChange={(value) => setValue('type', value)}
value={type}
role="radiogroup"
aria-required="false"
dir="ltr"
className="flex gap-4"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rf8:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.None}
id=":rf8:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
None
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rfa:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.ServiceHttp}
id=":rfa:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={0}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
API Key
</label>
</div>
<div className="flex items-center gap-2 text-gray-500">
<label htmlFor=":rfc:" className="flex cursor-not-allowed items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
disabled={true}
value={AuthTypeEnum.OAuth}
id=":rfc:"
className="mr-1 flex h-5 w-5 cursor-not-allowed items-center justify-center rounded-full border border-gray-500 bg-gray-300 dark:border-gray-600 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
OAuth
</label>
</div>
</RadioGroup.Root>
</div>
{type === 'none' ? null : type === 'service_http' ? <ApiKey /> : <OAuth />}
{/* Cancel/Save */}
<div className="mt-5 flex flex-col gap-3 sm:mt-4 sm:flex-row-reverse">
<button
className="btn relative bg-green-500 text-white hover:bg-green-600 dark:hover:bg-green-600"
onClick={async () => {
const result = await trigger(undefined, { shouldFocus: true });
setValue('saved_auth_fields', result);
setOpenAuthDialog(!result);
}}
>
<div className="flex w-full items-center justify-center gap-2">Save</div>
</button>
<DialogPrimitive.Close className="btn btn-neutral relative">
<div className="flex w-full items-center justify-center gap-2">Cancel</div>
</DialogPrimitive.Close>
</div>
</div>
</DialogContent>
);
}
const ApiKey = () => {
const { register, watch, setValue } = useFormContext();
const authorization_type = watch('authorization_type');
const type = watch('type');
return (
<>
<label className="mb-1 block text-sm font-medium">API Key</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="new-password"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-600"
{...register('api_key', { required: type === AuthTypeEnum.ServiceHttp })}
/>
<label className="mb-1 block text-sm font-medium">Auth Type</label>
<RadioGroup.Root
defaultValue={AuthorizationTypeEnum.Basic}
onValueChange={(value) => setValue('authorization_type', value)}
value={authorization_type}
role="radiogroup"
aria-required="true"
dir="ltr"
className="mb-2 flex gap-6 overflow-hidden rounded-lg"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rfu:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Basic}
id=":rfu:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Basic
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rg0:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Bearer}
id=":rg0:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Bearer
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rg2:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Custom}
id=":rg2:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={0}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Custom
</label>
</div>
</RadioGroup.Root>
{authorization_type === AuthorizationTypeEnum.Custom && (
<div className="mt-2">
<label className="mb-1 block text-sm font-medium">Custom Header Name</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-600"
placeholder="X-Api-Key"
{...register('custom_auth_header', {
required: authorization_type === AuthorizationTypeEnum.Custom,
})}
/>
</div>
)}
</>
);
};
const OAuth = () => {
const { register, watch, setValue } = useFormContext();
const token_exchange_method = watch('token_exchange_method');
const type = watch('type');
return (
<>
<label className="mb-1 block text-sm font-medium">Client ID</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="off"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('oauth_client_id', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Client Secret</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="off"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('oauth_client_secret', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Authorization URL</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('authorization_url', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Token URL</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('client_url', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Scope</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('scope', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Token Exchange Method</label>
<RadioGroup.Root
defaultValue={AuthorizationTypeEnum.Basic}
onValueChange={(value) => setValue('token_exchange_method', value)}
value={token_exchange_method}
role="radiogroup"
aria-required="true"
dir="ltr"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rj1:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={TokenExchangeMethodEnum.DefaultPost}
id=":rj1:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-700 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Default (POST request)
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rj3:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={TokenExchangeMethodEnum.BasicAuthHeader}
id=":rj3:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-700 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Basic authorization header
</label>
</div>
</RadioGroup.Root>
</>
);
};

View File

@@ -14,6 +14,7 @@ import type {
} from 'librechat-data-provider';
import type { ActionAuthForm } from '~/common';
import type { Spec } from './ActionsTable';
import ActionCallback from '~/components/SidePanel/Builder/ActionCallback';
import { ActionsTable, columns } from './ActionsTable';
import { useUpdateAgentAction } from '~/data-provider';
import { useToastContext } from '~/Providers';
@@ -248,8 +249,8 @@ export default function ActionsInput({
</div>
</div>
{!!data && (
<div>
<div className="mb-1.5 flex items-center">
<div className="my-2">
<div className="flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_assistants_available_actions')}
</label>
@@ -258,6 +259,7 @@ export default function ActionsInput({
</div>
)}
<div className="relative my-1">
<ActionCallback action_id={action?.action_id} />
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_ui_privacy_policy_url')}
@@ -267,7 +269,7 @@ export default function ActionsInput({
<input
type="text"
placeholder="https://api.example-weather-app.com/privacy"
className="flex-1 rounded-lg bg-transparent px-3 py-1.5 text-sm outline-none focus:ring-1 focus:ring-border-light"
className="flex-1 rounded-lg bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
/>
</div>
</div>

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect } from 'react';
import { useForm, FormProvider } from 'react-hook-form';
import {
AuthTypeEnum,
@@ -7,14 +7,14 @@ import {
} from 'librechat-data-provider';
import { ChevronLeft } from 'lucide-react';
import type { AgentPanelProps, ActionAuthForm } from '~/common';
import { Dialog, DialogTrigger, OGDialog, OGDialogTrigger, Label } from '~/components/ui';
import ActionsAuth from '~/components/SidePanel/Builder/ActionsAuth';
import { OGDialog, OGDialogTrigger, Label } from '~/components/ui';
import OGDialogTemplate from '~/components/ui/OGDialogTemplate';
import { useDeleteAgentAction } from '~/data-provider';
import useLocalize from '~/hooks/useLocalize';
import { useToastContext } from '~/Providers';
import { TrashIcon } from '~/components/svg';
import ActionsInput from './ActionsInput';
import ActionsAuth from './ActionsAuth';
import { Panel } from '~/common';
export default function ActionsPanel({
@@ -26,8 +26,6 @@ export default function ActionsPanel({
}: AgentPanelProps) {
const localize = useLocalize();
const { showToast } = useToastContext();
const [openAuthDialog, setOpenAuthDialog] = useState(false);
const deleteAgentAction = useDeleteAgentAction({
onSuccess: () => {
showToast({
@@ -65,7 +63,6 @@ export default function ActionsPanel({
});
const { reset, watch } = methods;
const type = watch('type');
useEffect(() => {
if (action?.metadata.auth) {
@@ -156,40 +153,7 @@ export default function ActionsPanel({
<a href="https://help.openai.com/en/articles/8554397-creating-a-gpt" target="_blank" rel="noreferrer" className="font-medium">Learn more.</a>
</div> */}
</div>
<Dialog open={openAuthDialog} onOpenChange={setOpenAuthDialog}>
<DialogTrigger asChild>
<div className="relative mb-4">
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_ui_authentication')}
</label>
</div>
<div className="border-token-border-medium flex rounded-lg border text-sm hover:cursor-pointer">
<div className="h-9 grow px-3 py-2">{type}</div>
<div className="bg-token-border-medium w-px"></div>
<button type="button" color="neutral" className="flex items-center gap-2 px-3">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="icon-sm"
>
<path
d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92002 3.98596L9.49644 4.70605C8.96184 5.61487 7.98938 6.17632 6.93501 6.18489L6.09967 6.19168C5.39096 6.19744 4.73823 6.57783 4.38386 7.19161L4.02776 7.80841C3.67339 8.42219 3.67032 9.17767 4.01969 9.7943L4.43151 10.5212C4.95127 11.4386 4.95127 12.5615 4.43151 13.4788L4.01969 14.2057C3.67032 14.8224 3.67339 15.5778 4.02776 16.1916L4.38386 16.8084C4.73823 17.4222 5.39096 17.8026 6.09966 17.8083L6.93502 17.8151C7.98939 17.8237 8.96185 18.3851 9.49645 19.294L9.92002 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"
stroke="currentColor"
strokeWidth="2"
strokeLinejoin="round"
/>
<circle cx="12" cy="12" r="2.5" stroke="currentColor" strokeWidth="2" />
</svg>
</button>
</div>
</div>
</DialogTrigger>
<ActionsAuth setOpenAuthDialog={setOpenAuthDialog} />
</Dialog>
<ActionsAuth />
<ActionsInput action={action} agent_id={agent_id} setAction={setAction} />
</div>
</form>

View File

@@ -22,7 +22,7 @@ export default function DataTable<TData, TValue>({ columns, data }: DataTablePro
className="border-token-border-light text-token-text-tertiary border-b text-left text-xs"
>
{headerGroup.headers.map((header, j) => (
<th key={j} className="py-1 font-normal">
<th key={j} className="py-1 font-normal text-text-secondary-alt">
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}

View File

@@ -10,7 +10,7 @@ import {
AgentCapabilities,
} from 'librechat-data-provider';
import type { TPlugin } from 'librechat-data-provider';
import type { AgentForm, AgentPanelProps } from '~/common';
import type { AgentForm, AgentPanelProps, IconComponentTypes } from '~/common';
import { cn, defaultTextProps, removeFocusOutlines, getEndpointField, getIconKey } from '~/utils';
import { useCreateAgentMutation, useUpdateAgentMutation } from '~/data-provider';
import { useLocalize, useAuthContext, useHasAccess } from '~/hooks';
@@ -26,6 +26,7 @@ import AgentAvatar from './AgentAvatar';
import { Spinner } from '~/components';
import FileSearch from './FileSearch';
import ShareAgent from './ShareAgent';
import Artifacts from './Artifacts';
import AgentTool from './AgentTool';
import CodeForm from './Code/Form';
import { Panel } from '~/common';
@@ -77,6 +78,10 @@ export default function AgentConfig({
() => agentsConfig?.capabilities.includes(AgentCapabilities.actions),
[agentsConfig],
);
const artifactsEnabled = useMemo(
() => agentsConfig?.capabilities.includes(AgentCapabilities.artifacts) ?? false,
[agentsConfig],
);
const fileSearchEnabled = useMemo(
() => agentsConfig?.capabilities.includes(AgentCapabilities.file_search) ?? false,
[agentsConfig],
@@ -150,7 +155,7 @@ export default function AgentConfig({
onSuccess: (data) => {
setCurrentAgentId(data.id);
showToast({
message: `${localize('com_assistants_create_success ')} ${
message: `${localize('com_assistants_create_success')} ${
data.name ?? localize('com_ui_agent')
}`,
});
@@ -178,18 +183,10 @@ export default function AgentConfig({
}, [agent_id, setActivePanel, showToast, localize]);
const providerValue = typeof provider === 'string' ? provider : provider?.value;
let Icon: IconComponentTypes | null | undefined;
let endpointType: EModelEndpoint | undefined;
let endpointIconURL: string | undefined;
let iconKey: string | undefined;
let Icon:
| React.ComponentType<
React.SVGProps<SVGSVGElement> & {
endpoint: string;
endpointType: EModelEndpoint | undefined;
iconURL: string | undefined;
}
>
| undefined;
if (providerValue !== undefined) {
endpointType = getEndpointField(endpointsConfig, providerValue as string, 'type');
@@ -337,7 +334,7 @@ export default function AgentConfig({
</div>
</button>
</div>
{(codeEnabled || fileSearchEnabled) && (
{(codeEnabled || fileSearchEnabled || artifactsEnabled) && (
<div className="mb-4 flex w-full flex-col items-start gap-3">
<label className="text-token-text-primary block font-medium">
{localize('com_assistants_capabilities')}
@@ -346,6 +343,8 @@ export default function AgentConfig({
{codeEnabled && <CodeForm agent_id={agent_id} files={code_files} />}
{/* File Search */}
{fileSearchEnabled && <FileSearch agent_id={agent_id} files={knowledge_files} />}
{/* Artifacts */}
{artifactsEnabled && <Artifacts />}
</div>
)}
{/* Agent Tools & Actions */}

View File

@@ -120,6 +120,7 @@ export default function AgentPanel({
const {
name,
artifacts,
description,
instructions,
model: _model,
@@ -139,6 +140,7 @@ export default function AgentPanel({
agent_id,
data: {
name,
artifacts,
description,
instructions,
model,
@@ -162,6 +164,7 @@ export default function AgentPanel({
create.mutate({
name,
artifacts,
description,
instructions,
model,
@@ -184,7 +187,7 @@ export default function AgentPanel({
const canEditAgent = useMemo(() => {
const canEdit =
agentQuery.data?.isCollaborative ?? false
(agentQuery.data?.isCollaborative ?? false)
? true
: agentQuery.data?.author === user?.id || user?.role === SystemRoles.ADMIN;

View File

@@ -55,8 +55,8 @@ export default function AgentSelect({
};
const capabilities: TAgentCapabilities = {
[AgentCapabilities.execute_code]: false,
[AgentCapabilities.file_search]: false,
[AgentCapabilities.execute_code]: false,
[AgentCapabilities.end_after_tools]: false,
[AgentCapabilities.hide_sequential_outputs]: false,
};

View File

@@ -0,0 +1,124 @@
import { useFormContext } from 'react-hook-form';
import { ArtifactModes, AgentCapabilities } from 'librechat-data-provider';
import type { AgentForm } from '~/common';
import {
Switch,
HoverCard,
HoverCardPortal,
HoverCardContent,
HoverCardTrigger,
} from '~/components/ui';
import { useLocalize } from '~/hooks';
import { CircleHelpIcon } from '~/components/svg';
import { ESide } from '~/common';
export default function Artifacts() {
const localize = useLocalize();
const methods = useFormContext<AgentForm>();
const { setValue, watch } = methods;
const artifactsMode = watch(AgentCapabilities.artifacts);
const handleArtifactsChange = (value: boolean) => {
setValue(AgentCapabilities.artifacts, value ? ArtifactModes.DEFAULT : '', {
shouldDirty: true,
});
};
const handleShadcnuiChange = (value: boolean) => {
setValue(AgentCapabilities.artifacts, value ? ArtifactModes.SHADCNUI : ArtifactModes.DEFAULT, {
shouldDirty: true,
});
};
const handleCustomModeChange = (value: boolean) => {
setValue(AgentCapabilities.artifacts, value ? ArtifactModes.CUSTOM : ArtifactModes.DEFAULT, {
shouldDirty: true,
});
};
const isEnabled = artifactsMode !== undefined && artifactsMode !== '';
const isCustomEnabled = artifactsMode === ArtifactModes.CUSTOM;
const isShadcnEnabled = artifactsMode === ArtifactModes.SHADCNUI;
return (
<div className="w-full">
<div className="mb-1.5 flex items-center gap-2">
<span>
<label className="text-token-text-primary block font-medium">
{localize('com_ui_artifacts')}
</label>
</span>
</div>
<div className="flex flex-col gap-3">
<SwitchItem
id="artifacts"
label={localize('com_ui_artifacts_toggle_agent')}
checked={isEnabled}
onCheckedChange={handleArtifactsChange}
hoverCardText={localize('com_nav_info_code_artifacts_agent')}
/>
<SwitchItem
id="includeShadcnui"
label={localize('com_ui_include_shadcnui_agent')}
checked={isShadcnEnabled}
onCheckedChange={handleShadcnuiChange}
hoverCardText={localize('com_nav_info_include_shadcnui')}
disabled={!isEnabled || isCustomEnabled}
/>
<SwitchItem
id="customPromptMode"
label={localize('com_ui_custom_prompt_mode')}
checked={isCustomEnabled}
onCheckedChange={handleCustomModeChange}
hoverCardText={localize('com_nav_info_custom_prompt_mode')}
disabled={!isEnabled}
/>
</div>
</div>
);
}
function SwitchItem({
id,
label,
checked,
onCheckedChange,
hoverCardText,
disabled = false,
}: {
id: string;
label: string;
checked: boolean;
onCheckedChange: (value: boolean) => void;
hoverCardText: string;
disabled?: boolean;
}) {
return (
<HoverCard openDelay={50}>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2">
<div className={disabled ? 'text-text-tertiary' : ''}>{label}</div>
<HoverCardTrigger>
<CircleHelpIcon className="h-4 w-4 text-text-tertiary" />
</HoverCardTrigger>
</div>
<HoverCardPortal>
<HoverCardContent side={ESide.Top} className="w-80">
<div className="space-y-2">
<p className="text-sm text-text-secondary">{hoverCardText}</p>
</div>
</HoverCardContent>
</HoverCardPortal>
<Switch
id={id}
checked={checked}
onCheckedChange={onCheckedChange}
className="ml-4"
data-testid={id}
disabled={disabled}
/>
</div>
</HoverCard>
);
}

View File

@@ -86,7 +86,7 @@ export default function Action({ authType = '', isToolAuthenticated = false }) {
</button>
)}
<HoverCardTrigger>
<CircleHelpIcon className="h-5 w-5 text-gray-500" />
<CircleHelpIcon className="h-4 w-4 text-text-tertiary" />
</HoverCardTrigger>
</div>
<HoverCardPortal>

View File

@@ -29,7 +29,7 @@ export default function FileSearchCheckbox() {
{...field}
checked={field.value}
onCheckedChange={field.onChange}
className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"
className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"
value={field.value.toString()}
/>
)}
@@ -38,7 +38,6 @@ export default function FileSearchCheckbox() {
type="button"
className="flex items-center space-x-2"
onClick={() =>
setValue(AgentCapabilities.file_search, !getValues(AgentCapabilities.file_search), {
shouldDirty: true,
})
@@ -51,7 +50,7 @@ export default function FileSearchCheckbox() {
{localize('com_agents_enable_file_search')}
</label>
<HoverCardTrigger>
<CircleHelpIcon className="h-5 w-5 text-gray-500" />
<CircleHelpIcon className="h-4 w-4 text-text-tertiary" />
</HoverCardTrigger>
</button>
<HoverCardPortal>

View File

@@ -0,0 +1,63 @@
import { useState } from 'react';
import { Copy, CopyCheck } from 'lucide-react';
import { useFormContext } from 'react-hook-form';
import { AuthTypeEnum } from 'librechat-data-provider';
import { useLocalize, useCopyToClipboard } from '~/hooks';
import { useToastContext } from '~/Providers';
import { Button } from '~/components/ui';
import { cn } from '~/utils';
export default function ActionCallback({ action_id }: { action_id?: string }) {
const localize = useLocalize();
const { watch } = useFormContext();
const { showToast } = useToastContext();
const [isCopying, setIsCopying] = useState(false);
const callbackURL = `${window.location.protocol}//${window.location.host}/api/actions/${action_id}/oauth/callback`;
const copyLink = useCopyToClipboard({ text: callbackURL });
if (!action_id) {
return null;
}
const type = watch('type');
if (type !== AuthTypeEnum.OAuth) {
return null;
}
return (
<div className="mb-1.5 flex flex-col space-y-2">
<label className="font-semibold">{localize('com_ui_callback_url')}</label>
<div className="relative flex items-center">
<div className="border-token-border-medium bg-token-surface-primary hover:border-token-border-hover flex h-10 w-full rounded-lg border">
<div className="flex-1 overflow-hidden">
<div className="relative w-full">
<input
type="text"
readOnly
value={callbackURL}
className="w-full border-0 bg-transparent px-3 py-2 pr-12 text-sm text-text-secondary-alt focus:outline-none"
style={{ direction: 'rtl' }}
/>
</div>
</div>
<div className="absolute right-0 flex h-full items-center pr-1">
<Button
size="sm"
variant="ghost"
type="button"
onClick={() => {
if (isCopying) {
return;
}
showToast({ message: localize('com_ui_copied_to_clipboard') });
copyLink(setIsCopying);
}}
className={cn('h-8 rounded-md px-2', isCopying ? 'cursor-default' : '')}
aria-label={localize('com_ui_copy_link')}
>
{isCopying ? <CopyCheck className="size-4" /> : <Copy className="size-4" />}
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,144 +1,190 @@
import { useState } from 'react';
import { useFormContext } from 'react-hook-form';
import * as RadioGroup from '@radix-ui/react-radio-group';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import {
AuthTypeEnum,
AuthorizationTypeEnum,
TokenExchangeMethodEnum,
} from 'librechat-data-provider';
import { DialogContent } from '~/components/ui/';
import {
OGDialog,
OGDialogClose,
OGDialogTitle,
OGDialogHeader,
OGDialogContent,
OGDialogTrigger,
} from '~/components/ui';
import { TranslationKeys, useLocalize } from '~/hooks';
import { cn } from '~/utils';
export default function ActionsAuth({
setOpenAuthDialog,
}: {
setOpenAuthDialog: React.Dispatch<React.SetStateAction<boolean>>;
}) {
export default function ActionsAuth({ disableOAuth }: { disableOAuth?: boolean }) {
const localize = useLocalize();
const [openAuthDialog, setOpenAuthDialog] = useState(false);
const { watch, setValue, trigger } = useFormContext();
const type = watch('type');
return (
<DialogContent
role="dialog"
id="radix-:rf5:"
aria-describedby="radix-:rf7:"
aria-labelledby="radix-:rf6:"
data-state="open"
className="left-1/2 col-auto col-start-2 row-auto row-start-2 w-full max-w-md -translate-x-1/2 rounded-xl bg-white pb-0 text-left shadow-xl transition-all dark:bg-gray-700 dark:text-gray-100"
tabIndex={-1}
style={{ pointerEvents: 'auto' }}
>
<div className="flex items-center justify-between border-b border-black/10 px-4 pb-4 pt-5 dark:border-white/10 sm:p-6">
<div className="flex">
<div className="flex items-center">
<div className="flex grow flex-col gap-1">
<h2
id="radix-:rf6:"
className="text-token-text-primary text-lg font-medium leading-6"
>
Authentication
</h2>
<OGDialog open={openAuthDialog} onOpenChange={setOpenAuthDialog}>
<OGDialogTrigger asChild>
<div className="relative mb-4">
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_ui_authentication')}
</label>
</div>
<div className="border-token-border-medium flex rounded-lg border text-sm hover:cursor-pointer">
<div className="h-9 grow px-3 py-2">
{localize(getAuthLocalizationKey(type))}
</div>
<div className="bg-token-border-medium w-px"></div>
<button type="button" color="neutral" className="flex items-center gap-2 px-3">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="icon-sm"
>
<path
d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92002 3.98596L9.49644 4.70605C8.96184 5.61487 7.98938 6.17632 6.93501 6.18489L6.09967 6.19168C5.39096 6.19744 4.73823 6.57783 4.38386 7.19161L4.02776 7.80841C3.67339 8.42219 3.67032 9.17767 4.01969 9.7943L4.43151 10.5212C4.95127 11.4386 4.95127 12.5615 4.43151 13.4788L4.01969 14.2057C3.67032 14.8224 3.67339 15.5778 4.02776 16.1916L4.38386 16.8084C4.73823 17.4222 5.39096 17.8026 6.09966 17.8083L6.93502 17.8151C7.98939 17.8237 8.96185 18.3851 9.49645 19.294L9.92002 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"
stroke="currentColor"
strokeWidth="2"
strokeLinejoin="round"
/>
<circle cx="12" cy="12" r="2.5" stroke="currentColor" strokeWidth="2" />
</svg>
</button>
</div>
</div>
</div>
<div className="p-4 sm:p-6 sm:pt-0">
<div className="mb-4">
<label className="mb-1 block text-sm font-medium">Authentication Type</label>
<RadioGroup.Root
defaultValue={AuthTypeEnum.None}
onValueChange={(value) => setValue('type', value)}
value={type}
role="radiogroup"
aria-required="false"
dir="ltr"
className="flex gap-4"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rf8:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.None}
id=":rf8:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={-1}
</OGDialogTrigger>
<OGDialogContent className="w-full max-w-md border-none bg-surface-primary text-text-primary">
<OGDialogHeader className="border-b border-border-light sm:p-3">
<OGDialogTitle>{localize('com_ui_authentication')}</OGDialogTitle>
</OGDialogHeader>
<div className="p-4 sm:p-6 sm:pt-0">
<div className="mb-4">
<label className="mb-1 block text-sm font-medium">
{localize('com_ui_authentication_type')}
</label>
<RadioGroup.Root
defaultValue={AuthTypeEnum.None}
onValueChange={(value) => setValue('type', value)}
value={type}
role="radiogroup"
aria-required="false"
dir="ltr"
className="flex gap-4"
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rf8:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.None}
id=":rf8:"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_none')}
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rfa:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.ServiceHttp}
id=":rfa:"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_api_key')}
</label>
</div>
<div className="flex items-center gap-2">
<label
htmlFor=":rfc:"
className={cn(
'flex items-center gap-1',
disableOAuth === true ? 'cursor-not-allowed' : 'cursor-pointer',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
None
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rfa:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.ServiceHttp}
id=":rfa:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={0}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
API Key
</label>
</div>
<div className="flex items-center gap-2 text-gray-500">
<label htmlFor=":rfc:" className="flex cursor-not-allowed items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
disabled={true}
value={AuthTypeEnum.OAuth}
id=":rfc:"
className="mr-1 flex h-5 w-5 cursor-not-allowed items-center justify-center rounded-full border border-gray-500 bg-gray-300 dark:border-gray-600 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
OAuth
</label>
</div>
</RadioGroup.Root>
<RadioGroup.Item
type="button"
role="radio"
disabled={disableOAuth}
value={AuthTypeEnum.OAuth}
id=":rfc:"
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
disableOAuth === true ? 'cursor-not-allowed' : '',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
{localize('com_ui_oauth')}
</label>
</div>
</RadioGroup.Root>
</div>
{type === 'none' ? null : type === 'service_http' ? <ApiKey /> : <OAuth />}
{/* Cancel/Save */}
<div className="mt-5 flex flex-col gap-3 sm:mt-4 sm:flex-row-reverse">
<button
className="btn relative bg-surface-submit text-primary-foreground hover:bg-surface-submit-hover"
onClick={async () => {
const result = await trigger(undefined, { shouldFocus: true });
setValue('saved_auth_fields', result);
setOpenAuthDialog(!result);
}}
>
<div className="flex w-full items-center justify-center gap-2 text-white">
{localize('com_ui_save')}
</div>
</button>
<OGDialogClose className="btn btn-neutral relative">
<div className="flex w-full items-center justify-center gap-2">
{localize('com_ui_cancel')}
</div>
</OGDialogClose>
</div>
</div>
{type === 'none' ? null : type === 'service_http' ? <ApiKey /> : <OAuth />}
{/* Cancel/Save */}
<div className="mt-5 flex flex-col gap-3 sm:mt-4 sm:flex-row-reverse">
<button
className="btn relative bg-green-500 text-white hover:bg-green-600 dark:hover:bg-green-600"
onClick={async () => {
const result = await trigger(undefined, { shouldFocus: true });
setValue('saved_auth_fields', result);
setOpenAuthDialog(!result);
}}
>
<div className="flex w-full items-center justify-center gap-2">Save</div>
</button>
<DialogPrimitive.Close className="btn btn-neutral relative">
<div className="flex w-full items-center justify-center gap-2">Cancel</div>
</DialogPrimitive.Close>
</div>
</div>
</DialogContent>
</OGDialogContent>
</OGDialog>
);
}
const ApiKey = () => {
const localize = useLocalize();
const { register, watch, setValue } = useFormContext();
const authorization_type = watch('authorization_type');
const type = watch('type');
return (
<>
<label className="mb-1 block text-sm font-medium">API Key</label>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_api_key')}</label>
<input
placeholder="<HIDDEN>"
type="password"
type="new-password"
autoComplete="new-password"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-600"
className={cn(
'mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm',
'border-border-medium bg-surface-primary outline-none',
'focus:ring-2 focus:ring-ring',
)}
{...register('api_key', { required: type === AuthTypeEnum.ServiceHttp })}
/>
<label className="mb-1 block text-sm font-medium">Auth Type</label>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_auth_type')}</label>
<RadioGroup.Root
defaultValue={AuthorizationTypeEnum.Basic}
onValueChange={(value) => setValue('authorization_type', value)}
@@ -147,7 +193,6 @@ const ApiKey = () => {
aria-required="true"
dir="ltr"
className="mb-2 flex gap-6 overflow-hidden rounded-lg"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
@@ -157,12 +202,14 @@ const ApiKey = () => {
role="radio"
value={AuthorizationTypeEnum.Basic}
id=":rfu:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={-1}
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
Basic
{localize('com_ui_basic')}
</label>
</div>
<div className="flex items-center gap-2">
@@ -172,12 +219,14 @@ const ApiKey = () => {
role="radio"
value={AuthorizationTypeEnum.Bearer}
id=":rg0:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={-1}
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
Bearer
{localize('com_ui_bearer')}
</label>
</div>
<div className="flex items-center gap-2">
@@ -187,20 +236,28 @@ const ApiKey = () => {
role="radio"
value={AuthorizationTypeEnum.Custom}
id=":rg2:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-500 dark:bg-gray-500"
tabIndex={0}
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
Custom
{localize('com_ui_custom')}
</label>
</div>
</RadioGroup.Root>
{authorization_type === AuthorizationTypeEnum.Custom && (
<div className="mt-2">
<label className="mb-1 block text-sm font-medium">Custom Header Name</label>
<label className="mb-1 block text-sm font-medium">
{localize('com_ui_custom_header_name')}
</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-600"
className={cn(
'mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm',
'border-border-medium bg-surface-primary outline-none',
'focus:ring-2 focus:ring-ring',
)}
placeholder="X-Api-Key"
{...register('custom_auth_header', {
required: authorization_type === AuthorizationTypeEnum.Custom,
@@ -212,44 +269,66 @@ const ApiKey = () => {
);
};
/** Returns the appropriate localization key for authentication type */
function getAuthLocalizationKey(type: AuthTypeEnum): TranslationKeys {
switch (type) {
case AuthTypeEnum.ServiceHttp:
return 'com_ui_api_key';
case AuthTypeEnum.OAuth:
return 'com_ui_oauth';
default:
return 'com_ui_none';
}
}
const OAuth = () => {
const localize = useLocalize();
const { register, watch, setValue } = useFormContext();
const token_exchange_method = watch('token_exchange_method');
const type = watch('type');
const inputClasses = cn(
'mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm',
'border-border-medium bg-surface-primary outline-none',
'focus:ring-2 focus:ring-ring',
);
return (
<>
<label className="mb-1 block text-sm font-medium">Client ID</label>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_client_id')}</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="off"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('oauth_client_id', { required: type === AuthTypeEnum.OAuth })}
autoComplete="new-password"
className={inputClasses}
{...register('oauth_client_id', { required: false })}
/>
<label className="mb-1 block text-sm font-medium">Client Secret</label>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_client_secret')}</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="off"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('oauth_client_secret', { required: type === AuthTypeEnum.OAuth })}
autoComplete="new-password"
className={inputClasses}
{...register('oauth_client_secret', { required: false })}
/>
<label className="mb-1 block text-sm font-medium">Authorization URL</label>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_auth_url')}</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
className={inputClasses}
{...register('authorization_url', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Token URL</label>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_token_url')}</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
className={inputClasses}
{...register('client_url', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Scope</label>
<label className="mb-1 block text-sm font-medium">{localize('com_ui_scope')}</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
className={inputClasses}
{...register('scope', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Token Exchange Method</label>
<label className="mb-1 block text-sm font-medium">
{localize('com_ui_token_exchange_method')}
</label>
<RadioGroup.Root
defaultValue={AuthorizationTypeEnum.Basic}
onValueChange={(value) => setValue('token_exchange_method', value)}
@@ -257,7 +336,6 @@ const OAuth = () => {
role="radiogroup"
aria-required="true"
dir="ltr"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
@@ -267,12 +345,14 @@ const OAuth = () => {
role="radio"
value={TokenExchangeMethodEnum.DefaultPost}
id=":rj1:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-700 dark:bg-gray-700"
tabIndex={-1}
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
Default (POST request)
{localize('com_ui_default_post_request')}
</label>
</div>
<div className="flex items-center gap-2">
@@ -282,12 +362,14 @@ const OAuth = () => {
role="radio"
value={TokenExchangeMethodEnum.BasicAuthHeader}
id=":rj3:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-700 dark:bg-gray-700"
tabIndex={-1}
className={cn(
'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',
'border-border-heavy bg-surface-primary',
)}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />
</RadioGroup.Item>
Basic authorization header
{localize('com_ui_basic_auth_header')}
</label>
</div>
</RadioGroup.Root>

View File

@@ -15,6 +15,7 @@ import type {
} from 'librechat-data-provider';
import type { ActionAuthForm, ActionWithNullableMetadata } from '~/common';
import type { Spec } from './ActionsTable';
import ActionCallback from '~/components/SidePanel/Builder/ActionCallback';
import { useAssistantsMapContext, useToastContext } from '~/Providers';
import { ActionsTable, columns } from './ActionsTable';
import { useUpdateAction } from '~/data-provider';
@@ -259,8 +260,8 @@ export default function ActionsInput({
</div>
</div>
{!!data && (
<div>
<div className="mb-1.5 flex items-center">
<div className="my-2">
<div className="flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_assistants_available_actions')}
</label>
@@ -269,6 +270,7 @@ export default function ActionsInput({
</div>
)}
<div className="relative my-1">
<ActionCallback action_id={action?.action_id} />
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_ui_privacy_policy_url')}
@@ -278,7 +280,7 @@ export default function ActionsInput({
<input
type="text"
placeholder="https://api.example-weather-app.com/privacy"
className="flex-1 rounded-lg bg-transparent px-3 py-1.5 text-sm outline-none focus:ring-1 focus:ring-border-light"
className="flex-1 rounded-lg bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"
/>
</div>
</div>

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect } from 'react';
import { useForm, FormProvider } from 'react-hook-form';
import {
AuthTypeEnum,
@@ -8,7 +8,7 @@ import {
import { ChevronLeft } from 'lucide-react';
import type { AssistantPanelProps, ActionAuthForm } from '~/common';
import { useAssistantsMapContext, useToastContext } from '~/Providers';
import { Dialog, DialogTrigger, OGDialog, OGDialogTrigger, Label } from '~/components/ui';
import { OGDialog, OGDialogTrigger, Label } from '~/components/ui';
import OGDialogTemplate from '~/components/ui/OGDialogTemplate';
import { useDeleteAction } from '~/data-provider';
import { TrashIcon } from '~/components/svg';
@@ -29,7 +29,6 @@ export default function ActionsPanel({
const localize = useLocalize();
const { showToast } = useToastContext();
const assistantMap = useAssistantsMapContext();
const [openAuthDialog, setOpenAuthDialog] = useState(false);
const deleteAction = useDeleteAction({
onSuccess: () => {
showToast({
@@ -68,7 +67,6 @@ export default function ActionsPanel({
});
const { reset, watch } = methods;
const type = watch('type');
useEffect(() => {
if (action?.metadata?.auth) {
@@ -162,40 +160,7 @@ export default function ActionsPanel({
<a href="https://help.openai.com/en/articles/8554397-creating-a-gpt" target="_blank" rel="noreferrer" className="font-medium">Learn more.</a>
</div> */}
</div>
<Dialog open={openAuthDialog} onOpenChange={setOpenAuthDialog}>
<DialogTrigger asChild>
<div className="relative mb-4">
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">
{localize('com_ui_authentication')}
</label>
</div>
<div className="border-token-border-medium flex rounded-lg border text-sm hover:cursor-pointer">
<div className="h-9 grow px-3 py-2">{type}</div>
<div className="bg-token-border-medium w-px"></div>
<button type="button" color="neutral" className="flex items-center gap-2 px-3">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="icon-sm"
>
<path
d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92002 3.98596L9.49644 4.70605C8.96184 5.61487 7.98938 6.17632 6.93501 6.18489L6.09967 6.19168C5.39096 6.19744 4.73823 6.57783 4.38386 7.19161L4.02776 7.80841C3.67339 8.42219 3.67032 9.17767 4.01969 9.7943L4.43151 10.5212C4.95127 11.4386 4.95127 12.5615 4.43151 13.4788L4.01969 14.2057C3.67032 14.8224 3.67339 15.5778 4.02776 16.1916L4.38386 16.8084C4.73823 17.4222 5.39096 17.8026 6.09966 17.8083L6.93502 17.8151C7.98939 17.8237 8.96185 18.3851 9.49645 19.294L9.92002 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"
stroke="currentColor"
strokeWidth="2"
strokeLinejoin="round"
/>
<circle cx="12" cy="12" r="2.5" stroke="currentColor" strokeWidth="2" />
</svg>
</button>
</div>
</div>
</DialogTrigger>
<ActionsAuth setOpenAuthDialog={setOpenAuthDialog} />
</Dialog>
<ActionsAuth disableOAuth={true} />
<ActionsInput
action={action}
assistant_id={assistant_id}

View File

@@ -4,12 +4,12 @@ import ImagePreview from '~/components/Chat/Input/Files/ImagePreview';
import FilePreview from '~/components/Chat/Input/Files/FilePreview';
import { getFileType } from '~/utils';
export default function PanelFileCell({ row }: { row: Row<TFile> }) {
export default function PanelFileCell({ row }: { row: Row<TFile | undefined> }) {
const file = row.original;
return (
<div className="flex w-full items-center gap-2">
{file.type.startsWith('image') ? (
{file?.type.startsWith('image') === true ? (
<ImagePreview
url={file.filepath}
className="h-10 w-10 flex-shrink-0"
@@ -17,11 +17,11 @@ export default function PanelFileCell({ row }: { row: Row<TFile> }) {
alt={file.filename}
/>
) : (
<FilePreview fileType={getFileType(file.type)} file={file} />
<FilePreview fileType={getFileType(file?.type)} file={file} />
)}
<div className="min-w-0 flex-1 overflow-hidden">
<span className="block w-full overflow-hidden truncate text-ellipsis whitespace-nowrap text-xs">
{file.filename}
{file?.filename}
</span>
</div>
</div>

View File

@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
import { OptionTypes } from 'librechat-data-provider';
import type { DynamicSettingProps } from 'librechat-data-provider';
import { Label, Checkbox, HoverCard, HoverCardTrigger } from '~/components/ui';
import { useLocalize, useParameterEffects } from '~/hooks';
import { TranslationKeys, useLocalize, useParameterEffects } from '~/hooks';
import { useChatContext } from '~/Providers';
import OptionHover from './OptionHover';
import { ESide } from '~/common';
@@ -66,7 +66,7 @@ function DynamicCheckbox({
htmlFor={`${settingKey}-dynamic-checkbox`}
className="text-left text-sm font-medium"
>
{labelCode ? localize(label) ?? label : label || settingKey}{' '}
{labelCode ? localize(label as TranslationKeys) ?? label : label || settingKey}{' '}
{showDefault && (
<small className="opacity-40">
({localize('com_endpoint_default')}:{' '}
@@ -85,7 +85,7 @@ function DynamicCheckbox({
</HoverCardTrigger>
{description && (
<OptionHover
description={descriptionCode ? localize(description) ?? description : description}
description={descriptionCode ? localize(description as TranslationKeys) ?? description : description}
side={ESide.Left}
/>
)}

View File

@@ -3,7 +3,7 @@ import { OptionTypes } from 'librechat-data-provider';
import type { DynamicSettingProps } from 'librechat-data-provider';
import { Label, HoverCard, HoverCardTrigger } from '~/components/ui';
import ControlCombobox from '~/components/ui/ControlCombobox';
import { useLocalize, useParameterEffects } from '~/hooks';
import { TranslationKeys, useLocalize, useParameterEffects } from '~/hooks';
import { useChatContext } from '~/Providers';
import OptionHover from './OptionHover';
import { ESide } from '~/common';
@@ -93,7 +93,7 @@ function DynamicCombobox({
htmlFor={`${settingKey}-dynamic-combobox`}
className="text-left text-sm font-medium"
>
{labelCode ? localize(label) ?? label : label || settingKey}
{labelCode ? localize(label as TranslationKeys) ?? label : label || settingKey}
{showDefault && (
<small className="opacity-40">
({localize('com_endpoint_default')}: {defaultValue})
@@ -105,10 +105,10 @@ function DynamicCombobox({
<ControlCombobox
displayValue={selectedValue}
selectPlaceholder={
selectPlaceholderCode === true ? localize(selectPlaceholder) : selectPlaceholder
selectPlaceholderCode === true ? localize(selectPlaceholder as TranslationKeys) : selectPlaceholder
}
searchPlaceholder={
searchPlaceholderCode === true ? localize(searchPlaceholder) : searchPlaceholder
searchPlaceholderCode === true ? localize(searchPlaceholder as TranslationKeys) : searchPlaceholder
}
isCollapsed={isCollapsed}
ariaLabel={settingKey}
@@ -120,7 +120,7 @@ function DynamicCombobox({
</HoverCardTrigger>
{description && (
<OptionHover
description={descriptionCode ? localize(description) ?? description : description}
description={descriptionCode ? localize(description as TranslationKeys) ?? description : description}
side={ESide.Left}
/>
)}

View File

@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
import { OptionTypes } from 'librechat-data-provider';
import type { DynamicSettingProps } from 'librechat-data-provider';
import { Label, HoverCard, HoverCardTrigger, SelectDropDown } from '~/components/ui';
import { useLocalize, useParameterEffects } from '~/hooks';
import { TranslationKeys, useLocalize, useParameterEffects } from '~/hooks';
import { useChatContext } from '~/Providers';
import OptionHover from './OptionHover';
import { ESide } from '~/common';
@@ -78,7 +78,7 @@ function DynamicDropdown({
htmlFor={`${settingKey}-dynamic-dropdown`}
className="text-left text-sm font-medium"
>
{labelCode ? localize(label) ?? label : label || settingKey}
{labelCode ? localize(label as TranslationKeys) ?? label : label || settingKey}
{showDefault && (
<small className="opacity-40">
({localize('com_endpoint_default')}: {defaultValue})
@@ -96,12 +96,12 @@ function DynamicDropdown({
availableValues={options}
containerClassName="w-full"
id={`${settingKey}-dynamic-dropdown`}
placeholder={placeholderCode ? localize(placeholder) ?? placeholder : placeholder}
placeholder={placeholderCode ? localize(placeholder as TranslationKeys) ?? placeholder : placeholder}
/>
</HoverCardTrigger>
{description && (
<OptionHover
description={descriptionCode ? localize(description) ?? description : description}
description={descriptionCode ? localize(description as TranslationKeys) ?? description : description}
side={ESide.Left}
/>
)}

View File

@@ -1,6 +1,6 @@
import { OptionTypes } from 'librechat-data-provider';
import type { DynamicSettingProps } from 'librechat-data-provider';
import { useLocalize, useDebouncedInput, useParameterEffects } from '~/hooks';
import { useLocalize, useDebouncedInput, useParameterEffects, TranslationKeys } from '~/hooks';
import { Label, Input, HoverCard, HoverCardTrigger } from '~/components/ui';
import { useChatContext } from '~/Providers';
import OptionHover from './OptionHover';
@@ -73,7 +73,7 @@ function DynamicInput({
htmlFor={`${settingKey}-dynamic-input`}
className="text-left text-sm font-medium"
>
{labelCode ? localize(label) || label : label || settingKey}{' '}
{labelCode ? localize(label as TranslationKeys) || label : label || settingKey}{' '}
{showDefault && (
<small className="opacity-40">
(
@@ -90,7 +90,7 @@ function DynamicInput({
disabled={readonly}
value={inputValue ?? ''}
onChange={handleInputChange}
placeholder={placeholderCode ? localize(placeholder) || placeholder : placeholder}
placeholder={placeholderCode ? localize(placeholder as TranslationKeys) || placeholder : placeholder}
className={cn(
'flex h-10 max-h-10 w-full resize-none border-none bg-surface-secondary px-3 py-2',
)}
@@ -98,7 +98,7 @@ function DynamicInput({
</HoverCardTrigger>
{description && (
<OptionHover
description={descriptionCode ? localize(description) || description : description}
description={descriptionCode ? localize(description as TranslationKeys) || description : description}
side={ESide.Left}
/>
)}

View File

@@ -2,7 +2,7 @@ import { useMemo, useCallback } from 'react';
import { OptionTypes } from 'librechat-data-provider';
import type { DynamicSettingProps } from 'librechat-data-provider';
import { Label, Slider, HoverCard, Input, InputNumber, HoverCardTrigger } from '~/components/ui';
import { useLocalize, useDebouncedInput, useParameterEffects } from '~/hooks';
import { useLocalize, useDebouncedInput, useParameterEffects, TranslationKeys } from '~/hooks';
import { cn, defaultTextProps, optionText } from '~/utils';
import { ESide, defaultDebouncedDelay } from '~/common';
import { useChatContext } from '~/Providers';
@@ -117,7 +117,7 @@ function DynamicSlider({
htmlFor={`${settingKey}-dynamic-setting`}
className="text-left text-sm font-medium"
>
{labelCode ? localize(label) ?? label : label || settingKey}{' '}
{labelCode ? localize(label as TranslationKeys) ?? label : label || settingKey}{' '}
{showDefault && (
<small className="opacity-40">
({localize('com_endpoint_default')}: {defaultValue})
@@ -176,7 +176,7 @@ function DynamicSlider({
</HoverCardTrigger>
{description && (
<OptionHover
description={descriptionCode ? localize(description) ?? description : description}
description={descriptionCode ? localize(description as TranslationKeys) ?? description : description}
side={ESide.Left}
/>
)}

View File

@@ -2,7 +2,7 @@ import { useState, useMemo } from 'react';
import { OptionTypes } from 'librechat-data-provider';
import type { DynamicSettingProps } from 'librechat-data-provider';
import { Label, Switch, HoverCard, HoverCardTrigger } from '~/components/ui';
import { useLocalize, useParameterEffects } from '~/hooks';
import { TranslationKeys, useLocalize, useParameterEffects } from '~/hooks';
import { useChatContext } from '~/Providers';
import OptionHover from './OptionHover';
import { ESide } from '~/common';
@@ -65,7 +65,7 @@ function DynamicSwitch({
htmlFor={`${settingKey}-dynamic-switch`}
className="text-left text-sm font-medium"
>
{labelCode ? localize(label) ?? label : label || settingKey}{' '}
{labelCode ? localize(label as TranslationKeys) ?? label : label || settingKey}{' '}
{showDefault && (
<small className="opacity-40">
({localize('com_endpoint_default')}:{' '}
@@ -84,7 +84,7 @@ function DynamicSwitch({
</HoverCardTrigger>
{description && (
<OptionHover
description={descriptionCode ? localize(description) ?? description : description}
description={descriptionCode ? localize(description as TranslationKeys) ?? description : description}
side={ESide.Left}
/>
)}

View File

@@ -1,7 +1,7 @@
import { OptionTypes } from 'librechat-data-provider';
import type { DynamicSettingProps } from 'librechat-data-provider';
import { Label, TextareaAutosize, HoverCard, HoverCardTrigger } from '~/components/ui';
import { useLocalize, useDebouncedInput, useParameterEffects } from '~/hooks';
import { useLocalize, useDebouncedInput, useParameterEffects, TranslationKeys } from '~/hooks';
import { cn, defaultTextProps } from '~/utils';
import { useChatContext } from '~/Providers';
import OptionHover from './OptionHover';
@@ -58,7 +58,7 @@ function DynamicTextarea({
htmlFor={`${settingKey}-dynamic-textarea`}
className="text-left text-sm font-medium"
>
{labelCode ? localize(label) ?? label : label || settingKey}{' '}
{labelCode ? localize(label as TranslationKeys) ?? label : label || settingKey}{' '}
{showDefault && (
<small className="opacity-40">
(
@@ -75,7 +75,7 @@ function DynamicTextarea({
disabled={readonly}
value={inputValue ?? ''}
onChange={setInputValue}
placeholder={placeholderCode ? localize(placeholder) ?? placeholder : placeholder}
placeholder={placeholderCode ? localize(placeholder as TranslationKeys) ?? placeholder : placeholder}
className={cn(
// TODO: configurable max height
'flex max-h-[138px] min-h-[100px] w-full resize-none rounded-lg bg-surface-secondary px-3 py-2 focus:outline-none',
@@ -84,7 +84,7 @@ function DynamicTextarea({
</HoverCardTrigger>
{description && (
<OptionHover
description={descriptionCode ? localize(description) ?? description : description}
description={descriptionCode ? localize(description as TranslationKeys) ?? description : description}
side={ESide.Left}
/>
)}

View File

@@ -1,6 +1,6 @@
import React from 'react';
import { HoverCardPortal, HoverCardContent } from '~/components/ui';
import { useLocalize } from '~/hooks';
import { TranslationKeys, useLocalize } from '~/hooks';
import { ESide } from '~/common';
type TOptionHoverProps = {
@@ -24,7 +24,7 @@ function OptionHover({
if (disabled) {
return null;
}
const text = langCode ? localize(description) : description;
const text = langCode ? localize(description as TranslationKeys) : description;
return (
<HoverCardPortal>
<HoverCardContent side={side} className={`z-[999] w-80 ${className}`} sideOffset={sideOffset}>

View File

@@ -1,78 +1,58 @@
import throttle from 'lodash/throttle';
import { getConfigDefaults } from 'librechat-data-provider';
import { useState, useCallback, useMemo, memo } from 'react';
import { useUserKeyQuery } from 'librechat-data-provider/react-query';
import { useState, useRef, useCallback, useEffect, useMemo, memo } from 'react';
import type { TEndpointsConfig, TInterfaceConfig } from 'librechat-data-provider';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import { ResizableHandleAlt, ResizablePanel, ResizablePanelGroup } from '~/components/ui/Resizable';
import { useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';
import { ResizableHandleAlt, ResizablePanel } from '~/components/ui/Resizable';
import { useMediaQuery, useLocalStorage, useLocalize } from '~/hooks';
import useSideNavLinks from '~/hooks/Nav/useSideNavLinks';
import { useGetEndpointsQuery } from '~/data-provider';
import NavToggle from '~/components/Nav/NavToggle';
import { cn, getEndpointField } from '~/utils';
import { useChatContext } from '~/Providers';
import Switcher from './Switcher';
import Nav from './Nav';
interface SidePanelProps {
defaultLayout?: number[] | undefined;
defaultCollapsed?: boolean;
navCollapsedSize?: number;
fullPanelCollapse?: boolean;
artifacts?: React.ReactNode;
children: React.ReactNode;
}
const defaultMinSize = 20;
const defaultInterface = getConfigDefaults().interface;
const normalizeLayout = (layout: number[]) => {
const sum = layout.reduce((acc, size) => acc + size, 0);
if (Math.abs(sum - 100) < 0.01) {
return layout.map((size) => Number(size.toFixed(2)));
}
const factor = 100 / sum;
const normalizedLayout = layout.map((size) => Number((size * factor).toFixed(2)));
const adjustedSum = normalizedLayout.reduce(
(acc, size, index) => (index === layout.length - 1 ? acc : acc + size),
0,
);
normalizedLayout[normalizedLayout.length - 1] = Number((100 - adjustedSum).toFixed(2));
return normalizedLayout;
};
const SidePanel = ({
defaultLayout = [97, 3],
defaultCollapsed = false,
fullPanelCollapse = false,
defaultSize,
panelRef,
navCollapsedSize = 3,
artifacts,
children,
}: SidePanelProps) => {
hasArtifacts,
minSize,
setMinSize,
collapsedSize,
setCollapsedSize,
isCollapsed,
setIsCollapsed,
fullCollapse,
setFullCollapse,
interfaceConfig,
}: {
defaultSize?: number;
hasArtifacts: boolean;
navCollapsedSize?: number;
minSize: number;
setMinSize: React.Dispatch<React.SetStateAction<number>>;
collapsedSize: number;
setCollapsedSize: React.Dispatch<React.SetStateAction<number>>;
isCollapsed: boolean;
setIsCollapsed: React.Dispatch<React.SetStateAction<boolean>>;
fullCollapse: boolean;
setFullCollapse: React.Dispatch<React.SetStateAction<boolean>>;
panelRef: React.RefObject<ImperativePanelHandle>;
interfaceConfig: TInterfaceConfig;
}) => {
const localize = useLocalize();
const [isHovering, setIsHovering] = useState(false);
const [minSize, setMinSize] = useState(defaultMinSize);
const [newUser, setNewUser] = useLocalStorage('newUser', true);
const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
const [fullCollapse, setFullCollapse] = useState(fullPanelCollapse);
const [collapsedSize, setCollapsedSize] = useState(navCollapsedSize);
const { data: endpointsConfig = {} as TEndpointsConfig } = useGetEndpointsQuery();
const { data: startupConfig } = useGetStartupConfig();
const interfaceConfig = useMemo(
() => (startupConfig?.interface ?? defaultInterface) as Partial<TInterfaceConfig>,
[startupConfig],
);
const isSmallScreen = useMediaQuery('(max-width: 767px)');
const { conversation } = useChatContext();
const { endpoint } = conversation ?? {};
const { data: keyExpiry = { expiresAt: undefined } } = useUserKeyQuery(endpoint ?? '');
const panelRef = useRef<ImperativePanelHandle>(null);
const defaultActive = useMemo(() => {
const activePanel = localStorage.getItem('side:active-panel');
return typeof activePanel === 'string' ? activePanel : undefined;
@@ -113,46 +93,6 @@ const SidePanel = ({
interfaceConfig,
});
const calculateLayout = useCallback(() => {
if (artifacts == null) {
const navSize = defaultLayout.length === 2 ? defaultLayout[1] : defaultLayout[2];
return [100 - navSize, navSize];
} else {
const navSize = 0;
const remainingSpace = 100 - navSize;
const newMainSize = Math.floor(remainingSpace / 2);
const artifactsSize = remainingSpace - newMainSize;
return [newMainSize, artifactsSize, navSize];
}
}, [artifacts, defaultLayout]);
const currentLayout = useMemo(() => normalizeLayout(calculateLayout()), [calculateLayout]);
// eslint-disable-next-line react-hooks/exhaustive-deps
const throttledSaveLayout = useCallback(
throttle((sizes: number[]) => {
const normalizedSizes = normalizeLayout(sizes);
localStorage.setItem('react-resizable-panels:layout', JSON.stringify(normalizedSizes));
}, 350),
[],
);
useEffect(() => {
if (isSmallScreen) {
setIsCollapsed(true);
setCollapsedSize(0);
setMinSize(defaultMinSize);
setFullCollapse(true);
localStorage.setItem('fullPanelCollapse', 'true');
panelRef.current?.collapse();
return;
} else {
setIsCollapsed(defaultCollapsed);
setCollapsedSize(navCollapsedSize);
setMinSize(defaultMinSize);
}
}, [isSmallScreen, defaultCollapsed, navCollapsedSize, fullPanelCollapse]);
const toggleNavVisible = useCallback(() => {
if (newUser) {
setNewUser(false);
@@ -173,127 +113,84 @@ const SidePanel = ({
}
}, [isCollapsed, newUser, setNewUser, navCollapsedSize]);
const minSizeMain = useMemo(() => (artifacts != null ? 15 : 30), [artifacts]);
return (
<>
<ResizablePanelGroup
direction="horizontal"
onLayout={(sizes) => throttledSaveLayout(sizes)}
className="transition-width relative h-full w-full flex-1 overflow-auto bg-presentation"
<div
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
className="relative flex w-px items-center justify-center"
>
<ResizablePanel
defaultSize={currentLayout[0]}
minSize={minSizeMain}
order={1}
id="messages-view"
>
{children}
</ResizablePanel>
{artifacts != null && (
<>
<ResizableHandleAlt withHandle className="ml-3 bg-border-medium text-text-primary" />
<ResizablePanel
defaultSize={currentLayout[1]}
minSize={minSizeMain}
order={2}
id="artifacts-panel"
>
{artifacts}
</ResizablePanel>
</>
)}
<div
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
className="relative flex w-px items-center justify-center"
>
<NavToggle
navVisible={!isCollapsed}
isHovering={isHovering}
onToggle={toggleNavVisible}
setIsHovering={setIsHovering}
className={cn(
'fixed top-1/2',
(isCollapsed && (minSize === 0 || collapsedSize === 0)) || fullCollapse
? 'mr-9'
: 'mr-16',
)}
translateX={false}
side="right"
/>
</div>
{(!isCollapsed || minSize > 0) && !isSmallScreen && !fullCollapse && (
<ResizableHandleAlt withHandle className="bg-transparent text-text-primary" />
)}
<ResizablePanel
tagName="nav"
id="controls-nav"
order={artifacts != null ? 3 : 2}
aria-label={localize('com_ui_controls')}
role="region"
collapsedSize={collapsedSize}
defaultSize={currentLayout[currentLayout.length - 1]}
collapsible={true}
minSize={minSize}
maxSize={40}
ref={panelRef}
style={{
overflowY: 'auto',
transition: 'width 0.2s ease, visibility 0s linear 0.2s',
}}
onExpand={() => {
setIsCollapsed(false);
localStorage.setItem('react-resizable-panels:collapsed', 'false');
}}
onCollapse={() => {
setIsCollapsed(true);
localStorage.setItem('react-resizable-panels:collapsed', 'true');
}}
<NavToggle
navVisible={!isCollapsed}
isHovering={isHovering}
onToggle={toggleNavVisible}
setIsHovering={setIsHovering}
className={cn(
'sidenav hide-scrollbar border-l border-border-light bg-background transition-opacity',
isCollapsed ? 'min-w-[50px]' : 'min-w-[340px] sm:min-w-[352px]',
(isSmallScreen && isCollapsed && (minSize === 0 || collapsedSize === 0)) || fullCollapse
? 'hidden min-w-0'
: 'opacity-100',
'fixed top-1/2',
(isCollapsed && (minSize === 0 || collapsedSize === 0)) || fullCollapse
? 'mr-9'
: 'mr-16',
)}
>
{interfaceConfig.modelSelect === true && (
<div
className={cn(
'sticky left-0 right-0 top-0 z-[100] flex h-[52px] flex-wrap items-center justify-center bg-background',
isCollapsed ? 'h-[52px]' : 'px-2',
)}
>
<Switcher
isCollapsed={isCollapsed}
endpointKeyProvided={keyProvided}
endpoint={endpoint}
/>
</div>
)}
<Nav
resize={panelRef.current?.resize}
isCollapsed={isCollapsed}
defaultActive={defaultActive}
links={Links}
/>
</ResizablePanel>
</ResizablePanelGroup>
<button
aria-label="Close right side panel"
className={`nav-mask ${!isCollapsed ? 'active' : ''}`}
onClick={() => {
setIsCollapsed(() => {
localStorage.setItem('fullPanelCollapse', 'true');
setFullCollapse(true);
setCollapsedSize(0);
setMinSize(0);
return false;
});
panelRef.current?.collapse();
translateX={false}
side="right"
/>
</div>
{(!isCollapsed || minSize > 0) && !isSmallScreen && !fullCollapse && (
<ResizableHandleAlt withHandle className="bg-transparent text-text-primary" />
)}
<ResizablePanel
tagName="nav"
id="controls-nav"
order={hasArtifacts != null ? 3 : 2}
aria-label={localize('com_ui_controls')}
role="region"
collapsedSize={collapsedSize}
defaultSize={defaultSize}
collapsible={true}
minSize={minSize}
maxSize={40}
ref={panelRef}
style={{
overflowY: 'auto',
transition: 'width 0.2s ease, visibility 0s linear 0.2s',
}}
/>
onExpand={() => {
setIsCollapsed(false);
localStorage.setItem('react-resizable-panels:collapsed', 'false');
}}
onCollapse={() => {
setIsCollapsed(true);
localStorage.setItem('react-resizable-panels:collapsed', 'true');
}}
className={cn(
'sidenav hide-scrollbar border-l border-border-light bg-background transition-opacity',
isCollapsed ? 'min-w-[50px]' : 'min-w-[340px] sm:min-w-[352px]',
(isSmallScreen && isCollapsed && (minSize === 0 || collapsedSize === 0)) || fullCollapse
? 'hidden min-w-0'
: 'opacity-100',
)}
>
{interfaceConfig.modelSelect === true && (
<div
className={cn(
'sticky left-0 right-0 top-0 z-[100] flex h-[52px] flex-wrap items-center justify-center bg-background',
isCollapsed ? 'h-[52px]' : 'px-2',
)}
>
<Switcher
isCollapsed={isCollapsed}
endpointKeyProvided={keyProvided}
endpoint={endpoint}
/>
</div>
)}
<Nav
resize={panelRef.current?.resize}
isCollapsed={isCollapsed}
defaultActive={defaultActive}
links={Links}
/>
</ResizablePanel>
</>
);
};

View File

@@ -0,0 +1,152 @@
import { useState, useRef, useCallback, useEffect, useMemo, memo } from 'react';
import throttle from 'lodash/throttle';
import { useRecoilValue } from 'recoil';
import { getConfigDefaults } from 'librechat-data-provider';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import { ResizableHandleAlt, ResizablePanel, ResizablePanelGroup } from '~/components/ui/Resizable';
import { useGetStartupConfig } from '~/data-provider';
import { normalizeLayout } from '~/utils';
import { useMediaQuery } from '~/hooks';
import SidePanel from './SidePanel';
import store from '~/store';
interface SidePanelProps {
defaultLayout?: number[] | undefined;
defaultCollapsed?: boolean;
navCollapsedSize?: number;
fullPanelCollapse?: boolean;
artifacts?: React.ReactNode;
children: React.ReactNode;
}
const defaultMinSize = 20;
const defaultInterface = getConfigDefaults().interface;
const SidePanelGroup = ({
defaultLayout = [97, 3],
defaultCollapsed = false,
fullPanelCollapse = false,
navCollapsedSize = 3,
artifacts,
children,
}: SidePanelProps) => {
const { data: startupConfig } = useGetStartupConfig();
const interfaceConfig = useMemo(
() => startupConfig?.interface ?? defaultInterface,
[startupConfig],
);
const panelRef = useRef<ImperativePanelHandle>(null);
const [minSize, setMinSize] = useState(defaultMinSize);
const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
const [fullCollapse, setFullCollapse] = useState(fullPanelCollapse);
const [collapsedSize, setCollapsedSize] = useState(navCollapsedSize);
const isSmallScreen = useMediaQuery('(max-width: 767px)');
const hideSidePanel = useRecoilValue(store.hideSidePanel);
const calculateLayout = useCallback(() => {
if (artifacts == null) {
const navSize = defaultLayout.length === 2 ? defaultLayout[1] : defaultLayout[2];
return [100 - navSize, navSize];
} else {
const navSize = 0;
const remainingSpace = 100 - navSize;
const newMainSize = Math.floor(remainingSpace / 2);
const artifactsSize = remainingSpace - newMainSize;
return [newMainSize, artifactsSize, navSize];
}
}, [artifacts, defaultLayout]);
const currentLayout = useMemo(() => normalizeLayout(calculateLayout()), [calculateLayout]);
const throttledSaveLayout = useCallback(
throttle((sizes: number[]) => {
const normalizedSizes = normalizeLayout(sizes);
localStorage.setItem('react-resizable-panels:layout', JSON.stringify(normalizedSizes));
}, 350),
[],
);
useEffect(() => {
if (isSmallScreen) {
setIsCollapsed(true);
setCollapsedSize(0);
setMinSize(defaultMinSize);
setFullCollapse(true);
localStorage.setItem('fullPanelCollapse', 'true');
panelRef.current?.collapse();
return;
} else {
setIsCollapsed(defaultCollapsed);
setCollapsedSize(navCollapsedSize);
setMinSize(defaultMinSize);
}
}, [isSmallScreen, defaultCollapsed, navCollapsedSize, fullPanelCollapse]);
const minSizeMain = useMemo(() => (artifacts != null ? 15 : 30), [artifacts]);
return (
<>
<ResizablePanelGroup
direction="horizontal"
onLayout={(sizes) => throttledSaveLayout(sizes)}
className="transition-width relative h-full w-full flex-1 overflow-auto bg-presentation"
>
<ResizablePanel
defaultSize={currentLayout[0]}
minSize={minSizeMain}
order={1}
id="messages-view"
>
{children}
</ResizablePanel>
{artifacts != null && (
<>
<ResizableHandleAlt withHandle className="ml-3 bg-border-medium text-text-primary" />
<ResizablePanel
defaultSize={currentLayout[1]}
minSize={minSizeMain}
order={2}
id="artifacts-panel"
>
{artifacts}
</ResizablePanel>
</>
)}
{!hideSidePanel && interfaceConfig.sidePanel === true && (
<SidePanel
panelRef={panelRef}
minSize={minSize}
setMinSize={setMinSize}
isCollapsed={isCollapsed}
setIsCollapsed={setIsCollapsed}
collapsedSize={collapsedSize}
setCollapsedSize={setCollapsedSize}
fullCollapse={fullCollapse}
setFullCollapse={setFullCollapse}
defaultSize={currentLayout[currentLayout.length - 1]}
hasArtifacts={artifacts != null}
interfaceConfig={interfaceConfig}
/>
)}
</ResizablePanelGroup>
<button
aria-label="Close right side panel"
className={`nav-mask ${!isCollapsed ? 'active' : ''}`}
onClick={() => {
setIsCollapsed(() => {
localStorage.setItem('fullPanelCollapse', 'true');
setFullCollapse(true);
setCollapsedSize(0);
setMinSize(0);
return false;
});
panelRef.current?.collapse();
}}
/>
</>
);
};
export default memo(SidePanelGroup);

View File

@@ -1,2 +1,2 @@
export { default as SidePanel } from './SidePanel';
export { default as SidePanelGroup } from './SidePanelGroup';
export { default as SideNav } from './Nav';

View File

@@ -0,0 +1,30 @@
import { cn } from '~/utils';
export default function CallIcon({ size = 24, className = '' }) {
return (
<svg
width={size}
height={size}
viewBox={'0 0 24 24'}
fill="none"
className={cn('text-white dark:text-black', className)}
>
<path
d="M9.5 4C8.67157 4 8 4.67157 8 5.5V18.5C8 19.3284 8.67157 20 9.5 20C10.3284 20 11 19.3284 11 18.5V5.5C11 4.67157 10.3284 4 9.5 4Z"
fill="currentColor"
></path>
<path
d="M13 8.5C13 7.67157 13.6716 7 14.5 7C15.3284 7 16 7.67157 16 8.5V15.5C16 16.3284 15.3284 17 14.5 17C13.6716 17 13 16.3284 13 15.5V8.5Z"
fill="currentColor"
></path>
<path
d="M4.5 9C3.67157 9 3 9.67157 3 10.5V13.5C3 14.3284 3.67157 15 4.5 15C5.32843 15 6 14.3284 6 13.5V10.5C6 9.67157 5.32843 9 4.5 9Z"
fill="currentColor"
></path>
<path
d="M19.5 9C18.6716 9 18 9.67157 18 10.5V13.5C18 14.3284 18.6716 15 19.5 15C20.3284 15 21 14.3284 21 13.5V10.5C21 9.67157 20.3284 9 19.5 9Z"
fill="currentColor"
></path>
</svg>
);
}

View File

@@ -56,3 +56,4 @@ export { default as SpeechIcon } from './SpeechIcon';
export { default as SaveIcon } from './SaveIcon';
export { default as CircleHelpIcon } from './CircleHelpIcon';
export { default as BedrockIcon } from './BedrockIcon';
export { default as CallIcon } from './CallIcon';

View File

@@ -1,10 +1,10 @@
import { Search } from 'lucide-react';
import * as Ariakit from '@ariakit/react';
import { matchSorter } from 'match-sorter';
import { AutoSizer, List } from 'react-virtualized';
import { startTransition, useMemo, useState, useEffect, useRef, memo } from 'react';
import { cn } from '~/utils';
import { useMemo, useState, useRef, memo, useEffect } from 'react';
import { SelectRenderer } from '@ariakit/react-core/select/select-renderer';
import type { OptionWithIcon } from '~/common';
import { Search } from 'lucide-react';
import { cn } from '~/utils';
interface ControlComboboxProps {
selectedValue: string;
@@ -35,11 +35,33 @@ function ControlCombobox({
const buttonRef = useRef<HTMLButtonElement>(null);
const [buttonWidth, setButtonWidth] = useState<number | null>(null);
const getItem = (option: OptionWithIcon) => ({
id: `item-${option.value}`,
value: option.value as string | undefined,
label: option.label,
icon: option.icon,
});
const combobox = Ariakit.useComboboxStore({
defaultItems: items.map(getItem),
resetValueOnHide: true,
value: searchValue,
setValue: setSearchValue,
});
const select = Ariakit.useSelectStore({
combobox,
defaultItems: items.map(getItem),
value: selectedValue,
setValue,
});
const matches = useMemo(() => {
return matchSorter(items, searchValue, {
const filteredItems = matchSorter(items, searchValue, {
keys: ['value', 'label'],
baseSort: (a, b) => (a.index < b.index ? -1 : 1),
});
return filteredItems.map(getItem);
}, [searchValue, items]);
useEffect(() => {
@@ -48,104 +70,74 @@ function ControlCombobox({
}
}, [isCollapsed]);
const rowRenderer = ({
index,
key,
style,
}: {
index: number;
key: string;
style: React.CSSProperties;
}) => {
const item = matches[index];
return (
<Ariakit.SelectItem
key={key}
value={`${item.value ?? ''}`}
aria-label={`${item.label ?? item.value ?? ''}`}
className={cn(
'flex cursor-pointer items-center px-3 text-sm',
'text-text-primary hover:bg-surface-tertiary',
'data-[active-item]:bg-surface-tertiary',
)}
render={<Ariakit.ComboboxItem />}
style={style}
>
{item.icon != null && (
<div className="assistant-item mr-2 flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">
{item.icon}
</div>
)}
<span className="flex-grow truncate text-left">{item.label}</span>
</Ariakit.SelectItem>
);
};
return (
<div className="flex w-full items-center justify-center px-1">
<Ariakit.ComboboxProvider
resetValueOnHide
setValue={(value) => {
startTransition(() => {
setSearchValue(value);
});
}}
<Ariakit.SelectLabel store={select} className="sr-only">
{ariaLabel}
</Ariakit.SelectLabel>
<Ariakit.Select
ref={buttonRef}
store={select}
className={cn(
'flex items-center justify-center gap-2 rounded-full bg-surface-secondary',
'text-text-primary hover:bg-surface-tertiary',
'border border-border-light',
isCollapsed ? 'h-10 w-10' : 'h-10 w-full rounded-md px-3 py-2 text-sm',
)}
>
<Ariakit.SelectProvider value={selectedValue} setValue={setValue}>
<Ariakit.SelectLabel className="sr-only">{ariaLabel}</Ariakit.SelectLabel>
<Ariakit.Select
ref={buttonRef}
className={cn(
'flex items-center justify-center gap-2 rounded-full bg-surface-secondary',
'text-text-primary hover:bg-surface-tertiary',
'border border-border-light',
isCollapsed ? 'h-10 w-10' : 'h-10 w-full rounded-md px-3 py-2 text-sm',
)}
>
{SelectIcon != null && (
<div className="assistant-item flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">
{SelectIcon}
</div>
)}
{!isCollapsed && (
<span className="flex-grow truncate text-left">
{displayValue ?? selectPlaceholder}
</span>
)}
</Ariakit.Select>
<Ariakit.SelectPopover
gutter={4}
portal
className="z-50 overflow-hidden rounded-md border border-border-light bg-surface-secondary shadow-lg"
style={{ width: isCollapsed ? '300px' : buttonWidth ?? '300px' }}
>
<div className="p-2">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-primary" />
<Ariakit.Combobox
autoSelect
placeholder={searchPlaceholder}
className="w-full rounded-md border border-border-light bg-surface-tertiary py-2 pl-9 pr-3 text-sm text-text-primary focus:outline-none"
/>
</div>
</div>
<div className="max-h-[50vh]">
<AutoSizer disableHeight>
{({ width }) => (
<List
width={width}
height={Math.min(matches.length * ROW_HEIGHT, 300)}
rowCount={matches.length}
rowHeight={ROW_HEIGHT}
rowRenderer={rowRenderer}
overscanRowCount={5}
/>
)}
</AutoSizer>
</div>
</Ariakit.SelectPopover>
</Ariakit.SelectProvider>
</Ariakit.ComboboxProvider>
{SelectIcon != null && (
<div className="assistant-item flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">
{SelectIcon}
</div>
)}
{!isCollapsed && (
<span className="flex-grow truncate text-left">{displayValue ?? selectPlaceholder}</span>
)}
</Ariakit.Select>
<Ariakit.SelectPopover
store={select}
gutter={4}
portal
className="z-50 overflow-hidden rounded-md border border-border-light bg-surface-secondary shadow-lg"
style={{ width: isCollapsed ? '300px' : (buttonWidth ?? '300px') }}
>
<div className="p-2">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-primary" />
<Ariakit.Combobox
store={combobox}
autoSelect
placeholder={searchPlaceholder}
className="w-full rounded-md border border-border-light bg-surface-tertiary py-2 pl-9 pr-3 text-sm text-text-primary focus:outline-none"
/>
</div>
</div>
<div className="max-h-[300px] overflow-auto">
<Ariakit.ComboboxList store={combobox}>
<SelectRenderer store={select} items={matches} itemSize={ROW_HEIGHT} overscan={5}>
{({ value, icon, label, ...item }) => (
<Ariakit.ComboboxItem
key={item.id}
{...item}
className={cn(
'flex w-full cursor-pointer items-center px-3 text-sm',
'text-text-primary hover:bg-surface-tertiary',
'data-[active-item]:bg-surface-tertiary',
)}
render={<Ariakit.SelectItem value={value} />}
>
{icon != null && (
<div className="assistant-item mr-2 flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">
{icon}
</div>
)}
<span className="flex-grow truncate text-left">{label}</span>
</Ariakit.ComboboxItem>
)}
</SelectRenderer>
</Ariakit.ComboboxList>
</div>
</Ariakit.SelectPopover>
</div>
);
}

View File

@@ -27,6 +27,7 @@ import {
import { TrashIcon, Spinner } from '~/components/svg';
import { useLocalize, useMediaQuery } from '~/hooks';
import { cn } from '~/utils';
import { LocalizeFunction } from '~/common';
type TableColumn<TData, TValue> = ColumnDef<TData, TValue> & {
meta?: {
@@ -177,7 +178,7 @@ const DeleteButton = memo(
isDeleting: boolean;
disabled: boolean;
isSmallScreen: boolean;
localize: (key: string) => string;
localize:LocalizeFunction;
}) => {
if (!onDelete) {
return null;

View File

@@ -1,5 +1,5 @@
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { useLocalize } from '~/hooks';
import { TranslationKeys, useLocalize } from '~/hooks';
import { Minus, Plus } from 'lucide-react';
interface ModelParametersProps {
@@ -33,7 +33,7 @@ const ModelParameters: React.FC<ModelParametersProps> = ({
const rangeRef = useRef<HTMLInputElement>(null);
const id = `model-parameter-${ariaLabel.toLowerCase().replace(/\s+/g, '-')}`;
const displayLabel = label.startsWith('com_') ? localize(label) : label;
const displayLabel = label.startsWith('com_') ? localize(label as TranslationKeys) : label;
const getDecimalPlaces = (num: number) => {
const match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);

View File

@@ -6,7 +6,6 @@ import {
OGDialogHeader,
OGDialogContent,
OGDialogDescription,
OGDialog,
} from './OriginalDialog';
import { useLocalize } from '~/hooks';
import { Spinner } from '../svg';

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