diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000..53e4d9b2 --- /dev/null +++ b/.babelrc @@ -0,0 +1,14 @@ +{ + "presets": [ + [ + "next/babel", + { + "preset-env": { + "targets": { + "browsers": ["> 0.25%, not dead"] + } + } + } + ] + ] +} diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..95ed9e26 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,97 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Node.js dependencies +/node_modules +/jspm_packages + +# TypeScript v1 declaration files +typings + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.test + +# local env files +.env*.local + +# Next.js build output +.next +out + +# Nuxt.js build output +.nuxt +dist + +# Gatsby files +.cache/ + + +# Vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# Temporary folders +tmp +temp + +# IDE and editor directories +.idea +.vscode +*.swp +*.swo +*~ + +# OS generated files +.DS_Store +Thumbs.db + +# secret key +*.key +*.key.pub diff --git a/.env.template b/.env.template new file mode 100644 index 00000000..b2a0438d --- /dev/null +++ b/.env.template @@ -0,0 +1,63 @@ + +# Your openai api key. (required) +OPENAI_API_KEY=sk-xxxx + +# Access password, separated by comma. (optional) +CODE=your-password + +# You can start service behind a proxy +PROXY_URL=http://localhost:7890 + +# (optional) +# Default: Empty +# Googel Gemini Pro API key, set if you want to use Google Gemini Pro API. +GOOGLE_API_KEY= + +# (optional) +# Default: https://generativelanguage.googleapis.com/ +# Googel Gemini Pro API url without pathname, set if you want to customize Google Gemini Pro API url. +GOOGLE_URL= + +# Override openai api request base url. (optional) +# Default: https://api.openai.com +# Examples: http://your-openai-proxy.com +BASE_URL= + +# Specify OpenAI organization ID.(optional) +# Default: Empty +OPENAI_ORG_ID= + +# (optional) +# Default: Empty +# If you do not want users to use GPT-4, set this value to 1. +DISABLE_GPT4= + +# (optional) +# Default: Empty +# If you do not want users to input their own API key, set this value to 1. +HIDE_USER_API_KEY= + +# (optional) +# Default: Empty +# If you do want users to query balance, set this value to 1. +ENABLE_BALANCE_QUERY= + +# (optional) +# Default: Empty +# If you want to disable parse settings from url, set this value to 1. +DISABLE_FAST_LINK= + + +# anthropic claude Api Key.(optional) +ANTHROPIC_API_KEY= + +### anthropic claude Api version. (optional) +ANTHROPIC_API_VERSION= + + + +### anthropic claude Api url (optional) +ANTHROPIC_URL= + +### (optional) +WHITE_WEBDEV_ENDPOINTS= \ No newline at end of file diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..58cd548c --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +lib/** \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 00000000..d229e86f --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "next/core-web-vitals", + "plugins": ["prettier"] +} diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..bdba257d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,146 @@ +name: Bug report +description: Create a report to help us improve +title: "[Bug] " +labels: ["bug"] + +body: + - type: markdown + attributes: + value: "## Describe the bug" + - type: textarea + id: bug-description + attributes: + label: "Bug Description" + description: "A clear and concise description of what the bug is." + placeholder: "Explain the bug..." + validations: + required: true + + - type: markdown + attributes: + value: "## To Reproduce" + - type: textarea + id: steps-to-reproduce + attributes: + label: "Steps to Reproduce" + description: "Steps to reproduce the behavior:" + placeholder: | + 1. Go to '...' + 2. Click on '....' + 3. Scroll down to '....' + 4. See error + validations: + required: true + + - type: markdown + attributes: + value: "## Expected behavior" + - type: textarea + id: expected-behavior + attributes: + label: "Expected Behavior" + description: "A clear and concise description of what you expected to happen." + placeholder: "Describe what you expected to happen..." + validations: + required: true + + - type: markdown + attributes: + value: "## Screenshots" + - type: textarea + id: screenshots + attributes: + label: "Screenshots" + description: "If applicable, add screenshots to help explain your problem." + placeholder: "Paste your screenshots here or write 'N/A' if not applicable..." + validations: + required: false + + - type: markdown + attributes: + value: "## Deployment" + - type: checkboxes + id: deployment + attributes: + label: "Deployment Method" + description: "Please select the deployment method you are using." + options: + - label: "Docker" + - label: "Vercel" + - label: "Server" + + - type: markdown + attributes: + value: "## Desktop (please complete the following information):" + - type: input + id: desktop-os + attributes: + label: "Desktop OS" + description: "Your desktop operating system." + placeholder: "e.g., Windows 10" + validations: + required: false + - type: input + id: desktop-browser + attributes: + label: "Desktop Browser" + description: "Your desktop browser." + placeholder: "e.g., Chrome, Safari" + validations: + required: false + - type: input + id: desktop-version + attributes: + label: "Desktop Browser Version" + description: "Version of your desktop browser." + placeholder: "e.g., 89.0" + validations: + required: false + + - type: markdown + attributes: + value: "## Smartphone (please complete the following information):" + - type: input + id: smartphone-device + attributes: + label: "Smartphone Device" + description: "Your smartphone device." + placeholder: "e.g., iPhone X" + validations: + required: false + - type: input + id: smartphone-os + attributes: + label: "Smartphone OS" + description: "Your smartphone operating system." + placeholder: "e.g., iOS 14.4" + validations: + required: false + - type: input + id: smartphone-browser + attributes: + label: "Smartphone Browser" + description: "Your smartphone browser." + placeholder: "e.g., Safari" + validations: + required: false + - type: input + id: smartphone-version + attributes: + label: "Smartphone Browser Version" + description: "Version of your smartphone browser." + placeholder: "e.g., 14" + validations: + required: false + + - type: markdown + attributes: + value: "## Additional Logs" + - type: textarea + id: additional-logs + attributes: + label: "Additional Logs" + description: "Add any logs about the problem here." + placeholder: "Paste any relevant logs here..." + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..49978133 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,53 @@ +name: Feature request +description: Suggest an idea for this project +title: "[Feature Request]: " +labels: ["enhancement"] + +body: + - type: markdown + attributes: + value: "## Is your feature request related to a problem? Please describe." + - type: textarea + id: problem-description + attributes: + label: Problem Description + description: "A clear and concise description of what the problem is. Example: I'm always frustrated when [...]" + placeholder: "Explain the problem you are facing..." + validations: + required: true + + - type: markdown + attributes: + value: "## Describe the solution you'd like" + - type: textarea + id: desired-solution + attributes: + label: Solution Description + description: A clear and concise description of what you want to happen. + placeholder: "Describe the solution you'd like..." + validations: + required: true + + - type: markdown + attributes: + value: "## Describe alternatives you've considered" + - type: textarea + id: alternatives-considered + attributes: + label: Alternatives Considered + description: A clear and concise description of any alternative solutions or features you've considered. + placeholder: "Describe any alternative solutions or features you've considered..." + validations: + required: false + + - type: markdown + attributes: + value: "## Additional context" + - type: textarea + id: additional-context + attributes: + label: Additional Context + description: Add any other context or screenshots about the feature request here. + placeholder: "Add any other context or screenshots about the feature request here..." + validations: + required: false diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..3a3cce57 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "npm" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml new file mode 100644 index 00000000..727b98b3 --- /dev/null +++ b/.github/workflows/deploy.yaml @@ -0,0 +1,21 @@ +name: Vercel Production Deployment +env: + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} +on: + push: + branches: + - main +jobs: + Deploy-Production: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Vercel CLI + run: npm install --global vercel@latest + - name: Pull Vercel Environment Information + run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }} + - name: Build Project Artifacts + run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }} + - name: Deploy Project Artifacts to Vercel + run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }} diff --git a/.github/workflows/deploy_preview.yml b/.github/workflows/deploy_preview.yml new file mode 100644 index 00000000..17580a24 --- /dev/null +++ b/.github/workflows/deploy_preview.yml @@ -0,0 +1,21 @@ +name: Vercel Preview Deployment +env: + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} +on: + push: + branches-ignore: + - main +jobs: + Deploy-Preview: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Vercel CLI + run: npm install --global vercel@latest + - name: Pull Vercel Environment Information + run: vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }} + - name: Build Project Artifacts + run: vercel build --token=${{ secrets.VERCEL_TOKEN }} + - name: Deploy Project Artifacts to Vercel + run: vercel deploy --prebuilt --token=${{ secrets.VERCEL_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/issue-translator.yml b/.github/workflows/issue-translator.yml new file mode 100644 index 00000000..560f66d3 --- /dev/null +++ b/.github/workflows/issue-translator.yml @@ -0,0 +1,15 @@ +name: Issue Translator +on: + issue_comment: + types: [created] + issues: + types: [opened] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: usthe/issues-translate-action@v2.7 + with: + IS_MODIFY_TITLE: false + CUSTOM_BOT_NOTE: Bot detected the issue body's language is not English, translate it automatically. diff --git a/.github/workflows/remove_deploy_preview.yml b/.github/workflows/remove_deploy_preview.yml new file mode 100644 index 00000000..4846cda2 --- /dev/null +++ b/.github/workflows/remove_deploy_preview.yml @@ -0,0 +1,40 @@ +name: Removedeploypreview + +permissions: + contents: read + statuses: write + pull-requests: write + +env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} + +on: + pull_request_target: + types: + - closed + +jobs: + delete-deployments: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Extract branch name + shell: bash + run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT + id: extract_branch + + - name: Hash branch name + uses: pplanel/hash-calculator-action@v1.3.1 + id: hash_branch + with: + input: ${{ steps.extract_branch.outputs.branch }} + method: MD5 + + - name: Call the delete-deployment-preview.sh script + env: + META_TAG: ${{ steps.hash_branch.outputs.digest }} + run: | + bash ./scripts/delete-deployment-preview.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..60f3fa23 --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts +dev + +.vscode +.idea + +# docker-compose env files +.env + +*.key +*.key.pub + +# service worker generated files +public/sw.js +public/workbox-*.js +public/workbox-*.js.map +public/worker-*.js \ No newline at end of file diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 00000000..d81f2dab --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,11 @@ +# This configuration file was automatically generated by Gitpod. +# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml) +# and commit this file to your remote git repository to share the goodness with others. + +# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart + +tasks: + - init: yarn install && yarn run dev + command: yarn run dev + + diff --git a/.lintstagedrc.json b/.lintstagedrc.json new file mode 100644 index 00000000..58784bad --- /dev/null +++ b/.lintstagedrc.json @@ -0,0 +1,6 @@ +{ + "./app/**/*.{js,ts,jsx,tsx,json,html,css,md}": [ + "eslint --fix", + "prettier --write" + ] +} diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..95cc75ff --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,10 @@ +module.exports = { + printWidth: 80, + tabWidth: 2, + useTabs: false, + semi: true, + singleQuote: false, + trailingComma: 'all', + bracketSpacing: true, + arrowParens: 'always', +}; diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..436d39d8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,64 @@ +FROM node:18-alpine AS base + +FROM base AS deps + +RUN apk add --no-cache libc6-compat + +WORKDIR /app + +COPY package.json yarn.lock ./ + +RUN yarn config set registry 'https://registry.npmmirror.com/' +RUN yarn install + +FROM base AS builder + +RUN apk update && apk add --no-cache git + +ENV OPENAI_API_KEY="" +ENV GOOGLE_API_KEY="" +ENV CODE="" + +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY . . + +RUN yarn build + +FROM base AS runner +WORKDIR /app + +RUN apk add proxychains-ng + +ENV PROXY_URL="" +ENV OPENAI_API_KEY="" +ENV GOOGLE_API_KEY="" +ENV CODE="" + +COPY --from=builder /app/public ./public +COPY --from=builder /app/.next/standalone ./ +COPY --from=builder /app/.next/static ./.next/static +COPY --from=builder /app/.next/server ./.next/server + +EXPOSE 3000 + +CMD if [ -n "$PROXY_URL" ]; then \ + export HOSTNAME="127.0.0.1"; \ + protocol=$(echo $PROXY_URL | cut -d: -f1); \ + host=$(echo $PROXY_URL | cut -d/ -f3 | cut -d: -f1); \ + port=$(echo $PROXY_URL | cut -d: -f3); \ + conf=/etc/proxychains.conf; \ + echo "strict_chain" > $conf; \ + echo "proxy_dns" >> $conf; \ + echo "remote_dns_subnet 224" >> $conf; \ + echo "tcp_read_time_out 15000" >> $conf; \ + echo "tcp_connect_time_out 8000" >> $conf; \ + echo "localnet 127.0.0.0/255.0.0.0" >> $conf; \ + echo "localnet ::1/128" >> $conf; \ + echo "[ProxyList]" >> $conf; \ + echo "$protocol $host $port" >> $conf; \ + cat /etc/proxychains.conf; \ + proxychains -f $conf node server.js; \ + else \ + node server.js; \ + fi diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..7d10a85f --- /dev/null +++ b/LICENSE @@ -0,0 +1,211 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------------------------------------------------------------------------ +This product bundles various third-party components under other open source licenses. +This section summarizes those components and their licenses. See licenses/ +for text of these licenses. + +Apache Software Foundation License 2.0 +-------------------------------------- + +src/openai_api_protocols diff --git a/README.md b/README.md new file mode 100644 index 00000000..ec704317 --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +
+ + +# WebLLM Chat + + +Static Badge + +**AI Conversations, Fully In-Browser.** + +[**Chat Now**](https://chat.webllm.ai/) + +
+ +## Introduction + +WebLLM Chat is an AI chat webapp that brings [WebLLM](https://github.com/mlc-ai/web-llm) with a user-friendly interface to deliver an fully open-source and accssible AI chat application. WebLLM Chat leverages WebGPU to run large language models (LLMs) natively in your browser, offering a seamless AI chatting experience with unprecedented privacy and performance. + +## Key Features + +- **Browser-Native AI**: Experience cutting-edge language models running natively within your web browser with WebGPU acceleration, eliminating the need for server-side processing or cloud dependencies. +- **User-Friendly Interface**: Enjoy the intuitive and feature-rich user interface of [NextChat](), complete with markdown support, dark mode, and a responsive design optimized for various screen sizes. +- **Privacy-Focused**: With all data processing happening locally within your browser, WebLLM Chat prioritizes your privacy and ensures your data remains secure locally. +- **Open Source and Customizable**: Build and customize your own AI-powered applications with our open-source framework. + +WebLLM Chat is a pioneering initiative that combines the robust backend capabilities of WebLLM with the user-friendly interface of NextChat. As a part of the broader MLC.ai family, this project contributes to our mission of democratizing AI technology by making powerful tools accessible directly to end-users. By integrating with NextChat, WebLLM Chat not only enhances the chatting experience but also broadens the scope for deployment of self-hosted and customizable language models. + +## Getting Started + +To jumpstart your WebLLM Chat experience, visit our GitHub repository for detailed setup instructions, examples, and documentation. Whether you're a developer looking to integrate AI into your projects or an end-user keen on exploring AI capabilities, WebLLM Chat provides all the tools you need to get started. + +## Community and Contributions + +WebLLM Chat thrives on community involvement. We are committed to fostering an inclusive and innovative community where developers and AI enthusiasts can collaborate, contribute, and push the boundaries of what's possible in AI technology. Join us on Discord to connect with fellow developers and contribute to the project. + +## Acknowledgements + +WebLLM Chat is built upon the remarkable work of the [WebLLM](https://github.com/mlc-ai/web-llm/) and [NextChat](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web) projects. We extend our sincere gratitude to the developers and contributors of these projects for their invaluable efforts in advancing the field of browser-based AI and creating user-friendly chat interfaces. + +Further more, this project is only possible thanks to the shoulders of open-source ecosystems that we stand on. We want to thank the Apache TVM community and developers of the TVM Unity effort. The open-source ML community members made these models publicly available. PyTorch and Hugging Face communities make these models accessible. We would like to thank the teams behind Vicuna, SentencePiece, LLaMA, Alpaca. We also would like to thank the WebAssembly, Emscripten, and WebGPU communities. Finally, thanks to Dawn and WebGPU developers. diff --git a/app/api/config/route.ts b/app/api/config/route.ts new file mode 100644 index 00000000..8ce21592 --- /dev/null +++ b/app/api/config/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from "next/server"; + +import { getServerSideConfig } from "../../config/server"; + +const serverConfig = getServerSideConfig(); + +// Danger! Do not hard code any secret value here! +// 警告!不要在这里写入任何敏感信息! +const DANGER_CONFIG = { + disableFastLink: serverConfig.disableFastLink, + customModels: serverConfig.customModels, + defaultModel: serverConfig.defaultModel, +}; + +declare global { + type DangerConfig = typeof DANGER_CONFIG; +} + +async function handle() { + return NextResponse.json(DANGER_CONFIG); +} + +export const GET = handle; +export const POST = handle; + +export const runtime = "edge"; diff --git a/app/azure.ts b/app/azure.ts new file mode 100644 index 00000000..48406c55 --- /dev/null +++ b/app/azure.ts @@ -0,0 +1,9 @@ +export function makeAzurePath(path: string, apiVersion: string) { + // should omit /v1 prefix + path = path.replaceAll("v1/", ""); + + // should add api-key to query string + path += `${path.includes("?") ? "&" : "?"}api-version=${apiVersion}`; + + return path; +} diff --git a/app/client/api.ts b/app/client/api.ts new file mode 100644 index 00000000..8f9dac01 --- /dev/null +++ b/app/client/api.ts @@ -0,0 +1,65 @@ +import { getClientConfig } from "../config/client"; +import { ACCESS_CODE_PREFIX } from "../constant"; +import { CacheType, ModelType, useChatStore } from "../store"; +export const ROLES = ["system", "user", "assistant"] as const; +export type MessageRole = (typeof ROLES)[number]; + +export const Models = ["gpt-3.5-turbo", "gpt-4"] as const; +export type ChatModel = ModelType; + +export interface MultimodalContent { + type: "text" | "image_url"; + text?: string; + image_url?: { + url: string; + }; +} + +export interface RequestMessage { + role: MessageRole; + content: string | MultimodalContent[]; +} + +export interface LLMConfig { + model: string; + cache: CacheType; + temperature?: number; + top_p?: number; + stream?: boolean; + presence_penalty?: number; + frequency_penalty?: number; +} + +export interface ChatOptions { + messages: RequestMessage[]; + config: LLMConfig; + + onUpdate?: (message: string, chunk: string) => void; + onFinish: (message: string) => void; + onError?: (err: Error) => void; + onController?: (controller: AbortController) => void; +} + +export interface LLMUsage { + used: number; + total: number; +} + +export interface LLMModel { + name: string; + available: boolean; + provider: LLMModelProvider; +} + +export interface LLMModelProvider { + id: string; + providerName: string; + providerType: string; +} + +export abstract class LLMApi { + abstract chat(options: ChatOptions): Promise; + abstract usage(): Promise; + abstract models(): Promise; + abstract clear(): void; +} diff --git a/app/client/controller.ts b/app/client/controller.ts new file mode 100644 index 00000000..a2e00173 --- /dev/null +++ b/app/client/controller.ts @@ -0,0 +1,37 @@ +// To store message streaming controller +export const ChatControllerPool = { + controllers: {} as Record, + + addController( + sessionId: string, + messageId: string, + controller: AbortController, + ) { + const key = this.key(sessionId, messageId); + this.controllers[key] = controller; + return key; + }, + + stop(sessionId: string, messageId: string) { + const key = this.key(sessionId, messageId); + const controller = this.controllers[key]; + controller?.abort(); + }, + + stopAll() { + Object.values(this.controllers).forEach((v) => v.abort()); + }, + + hasPending() { + return Object.values(this.controllers).length > 0; + }, + + remove(sessionId: string, messageId: string) { + const key = this.key(sessionId, messageId); + delete this.controllers[key]; + }, + + key(sessionId: string, messageIndex: string) { + return `${sessionId},${messageIndex}`; + }, +}; diff --git a/app/client/webllm.ts b/app/client/webllm.ts new file mode 100644 index 00000000..6eeed47e --- /dev/null +++ b/app/client/webllm.ts @@ -0,0 +1,94 @@ +import { + EngineInterface, + CreateWebServiceWorkerEngine, + InitProgressReport, + prebuiltAppConfig, + ChatCompletionMessageParam, +} from "@neet-nestor/web-llm"; + +import { ChatOptions, LLMApi, LLMConfig } from "./api"; + +export class WebLLMApi implements LLMApi { + private currentModel?: string; + private engine?: EngineInterface; + + clear() { + this.engine = undefined; + } + + async initModel( + config: LLMConfig, + onUpdate?: (message: string, chunk: string) => void, + ) { + this.currentModel = config.model; + this.engine = await CreateWebServiceWorkerEngine(config.model, { + chatOpts: { + temperature: config.temperature, + top_p: config.top_p, + presence_penalty: config.presence_penalty, + frequency_penalty: config.frequency_penalty, + }, + appConfig: { + ...prebuiltAppConfig, + useIndexedDBCache: config.cache === "index_db", + }, + initProgressCallback: (report: InitProgressReport) => { + onUpdate?.(report.text, report.text); + }, + }); + } + + async chat(options: ChatOptions): Promise { + if (options.config.model !== this.currentModel) { + await this.initModel(options.config, options.onUpdate); + } + + let reply: string | null = ""; + if (options.config.stream) { + const asyncChunkGenerator = await this.engine!.chatCompletion({ + stream: options.config.stream, + messages: options.messages as ChatCompletionMessageParam[], + }); + + for await (const chunk of asyncChunkGenerator) { + if (chunk.choices[0].delta.content) { + reply += chunk.choices[0].delta.content; + options.onUpdate?.(reply, chunk.choices[0].delta.content); + } + } + } else { + const completion = await this.engine!.chatCompletion({ + stream: options.config.stream, + messages: options.messages as ChatCompletionMessageParam[], + }); + reply = completion.choices[0].message.content; + } + + if (reply) { + options.onFinish(reply); + } else { + options.onError?.(new Error("Empty response generated by LLM")); + } + } + + async usage() { + return { + used: 0, + total: 0, + }; + } + + async models() { + return prebuiltAppConfig.model_list.map((record) => ({ + name: record.model_id, + available: true, + provider: { + id: "huggingface", + providerName: "huggingface", + providerType: "huggingface", + }, + })); + } +} + +export const webllm: LLMApi = new WebLLMApi(); diff --git a/app/command.ts b/app/command.ts new file mode 100644 index 00000000..9330d4ff --- /dev/null +++ b/app/command.ts @@ -0,0 +1,73 @@ +import { useEffect } from "react"; +import { useSearchParams } from "react-router-dom"; +import Locale from "./locales"; + +type Command = (param: string) => void; +interface Commands { + fill?: Command; + submit?: Command; + mask?: Command; +} + +export function useCommand(commands: Commands = {}) { + const [searchParams, setSearchParams] = useSearchParams(); + + useEffect(() => { + let shouldUpdate = false; + searchParams.forEach((param, name) => { + const commandName = name as keyof Commands; + if (typeof commands[commandName] === "function") { + commands[commandName]!(param); + searchParams.delete(name); + shouldUpdate = true; + } + }); + + if (shouldUpdate) { + setSearchParams(searchParams); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [searchParams, commands]); +} + +interface ChatCommands { + new?: Command; + newm?: Command; + next?: Command; + prev?: Command; + clear?: Command; + del?: Command; +} + +export const ChatCommandPrefix = ":"; + +export function useChatCommand(commands: ChatCommands = {}) { + function extract(userInput: string) { + return ( + userInput.startsWith(ChatCommandPrefix) ? userInput.slice(1) : userInput + ) as keyof ChatCommands; + } + + function search(userInput: string) { + const input = extract(userInput); + const desc = Locale.Chat.Commands; + return Object.keys(commands) + .filter((c) => c.startsWith(input)) + .map((c) => ({ + title: desc[c as keyof ChatCommands], + content: ChatCommandPrefix + c, + })); + } + + function match(userInput: string) { + const command = extract(userInput); + const matched = typeof commands[command] === "function"; + + return { + matched, + invoke: () => matched && commands[command]!(userInput), + }; + } + + return { match, search }; +} diff --git a/app/components/button.module.scss b/app/components/button.module.scss new file mode 100644 index 00000000..e332df2d --- /dev/null +++ b/app/components/button.module.scss @@ -0,0 +1,83 @@ +.icon-button { + background-color: var(--white); + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + padding: 10px; + + cursor: pointer; + transition: all 0.3s ease; + overflow: hidden; + user-select: none; + outline: none; + border: none; + color: var(--black); + + &[disabled] { + cursor: not-allowed; + opacity: 0.5; + } + + &.primary { + background-color: var(--primary); + color: white; + + path { + fill: white !important; + } + } + + &.danger { + color: rgba($color: red, $alpha: 0.8); + border-color: rgba($color: red, $alpha: 0.5); + background-color: rgba($color: red, $alpha: 0.05); + + &:hover { + border-color: red; + background-color: rgba($color: red, $alpha: 0.1); + } + + path { + fill: red !important; + } + } + + &:hover, + &:focus { + border-color: var(--primary); + } +} + +.shadow { + box-shadow: var(--card-shadow); +} + +.border { + border: var(--border-in-light); +} + +.icon-button-icon { + width: 16px; + height: 16px; + display: flex; + justify-content: center; + align-items: center; +} + +@media only screen and (max-width: 600px) { + .icon-button { + padding: 16px; + } +} + +.icon-button-text { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + + &:not(:first-child) { + margin-left: 5px; + } +} diff --git a/app/components/button.tsx b/app/components/button.tsx new file mode 100644 index 00000000..7a563392 --- /dev/null +++ b/app/components/button.tsx @@ -0,0 +1,51 @@ +import * as React from "react"; + +import styles from "./button.module.scss"; + +export type ButtonType = "primary" | "danger" | null; + +export function IconButton(props: { + onClick?: () => void; + icon?: JSX.Element; + type?: ButtonType; + text?: string; + bordered?: boolean; + shadow?: boolean; + className?: string; + title?: string; + disabled?: boolean; + tabIndex?: number; + autoFocus?: boolean; +}) { + return ( + + ); +} diff --git a/app/components/chat-list.tsx b/app/components/chat-list.tsx new file mode 100644 index 00000000..7ef6e7b8 --- /dev/null +++ b/app/components/chat-list.tsx @@ -0,0 +1,174 @@ +import DeleteIcon from "../icons/delete.svg"; +import BotIcon from "../icons/bot.svg"; + +import styles from "./home.module.scss"; +import { + DragDropContext, + Droppable, + Draggable, + OnDragEndResponder, +} from "@hello-pangea/dnd"; + +import { useChatStore } from "../store"; + +import Locale from "../locales"; +import { Link, useLocation, useNavigate } from "react-router-dom"; +import { Path } from "../constant"; +import { MaskAvatar } from "./mask"; +import { Mask } from "../store/mask"; +import { useRef, useEffect } from "react"; +import { showConfirm } from "./ui-lib"; +import { useMobileScreen } from "../utils"; + +export function ChatItem(props: { + onClick?: () => void; + onDelete?: () => void; + title: string; + count: number; + time: string; + selected: boolean; + id: string; + index: number; + narrow?: boolean; + mask: Mask; +}) { + const draggableRef = useRef(null); + useEffect(() => { + if (props.selected && draggableRef.current) { + draggableRef.current?.scrollIntoView({ + block: "center", + }); + } + }, [props.selected]); + + const { pathname: currentPath } = useLocation(); + return ( + + {(provided) => ( +
{ + draggableRef.current = ele; + provided.innerRef(ele); + }} + {...provided.draggableProps} + {...provided.dragHandleProps} + title={`${props.title}\n${Locale.ChatItem.ChatItemCount( + props.count, + )}`} + > + {props.narrow ? ( +
+
+ +
+
+ {props.count} +
+
+ ) : ( + <> +
{props.title}
+
+
+ {Locale.ChatItem.ChatItemCount(props.count)} +
+
{props.time}
+
+ + )} + +
{ + props.onDelete?.(); + e.preventDefault(); + e.stopPropagation(); + }} + > + +
+
+ )} +
+ ); +} + +export function ChatList(props: { narrow?: boolean }) { + const [sessions, selectedIndex, selectSession, moveSession] = useChatStore( + (state) => [ + state.sessions, + state.currentSessionIndex, + state.selectSession, + state.moveSession, + ], + ); + const chatStore = useChatStore(); + const navigate = useNavigate(); + const isMobileScreen = useMobileScreen(); + + const onDragEnd: OnDragEndResponder = (result) => { + const { destination, source } = result; + if (!destination) { + return; + } + + if ( + destination.droppableId === source.droppableId && + destination.index === source.index + ) { + return; + } + + moveSession(source.index, destination.index); + }; + + return ( + + + {(provided) => ( +
+ {sessions.map((item, i) => ( + { + navigate(Path.Chat); + selectSession(i); + }} + onDelete={async () => { + if ( + (!props.narrow && !isMobileScreen) || + (await showConfirm(Locale.Home.DeleteChat)) + ) { + chatStore.deleteSession(i); + } + }} + narrow={props.narrow} + mask={item.mask} + /> + ))} + {provided.placeholder} +
+ )} +
+
+ ); +} diff --git a/app/components/chat.module.scss b/app/components/chat.module.scss new file mode 100644 index 00000000..76ea1b83 --- /dev/null +++ b/app/components/chat.module.scss @@ -0,0 +1,625 @@ +@import "../styles/animation.scss"; + +.attach-images { + position: absolute; + left: 30px; + bottom: 32px; + display: flex; +} + +.attach-image { + cursor: default; + width: 64px; + height: 64px; + border: rgba($color: #888, $alpha: 0.2) 1px solid; + border-radius: 5px; + margin-right: 10px; + background-size: cover; + background-position: center; + background-color: var(--white); + + .attach-image-mask { + width: 100%; + height: 100%; + opacity: 0; + transition: all ease 0.2s; + } + + .attach-image-mask:hover { + opacity: 1; + } + + .delete-image { + width: 24px; + height: 24px; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + border-radius: 5px; + float: right; + background-color: var(--white); + } +} + +.chat-input-actions { + display: flex; + flex-wrap: wrap; + + .chat-input-action { + display: inline-flex; + border-radius: 20px; + font-size: 12px; + background-color: var(--white); + color: var(--black); + border: var(--border-in-light); + padding: 4px 10px; + animation: slide-in ease 0.3s; + box-shadow: var(--card-shadow); + transition: width ease 0.3s; + align-items: center; + height: 16px; + width: var(--icon-width); + overflow: hidden; + + &:not(:last-child) { + margin-right: 5px; + } + + .text { + white-space: nowrap; + padding-left: 5px; + opacity: 0; + transform: translateX(-5px); + transition: all ease 0.3s; + pointer-events: none; + } + + &:hover { + --delay: 0.5s; + width: var(--full-width); + transition-delay: var(--delay); + + .text { + transition-delay: var(--delay); + opacity: 1; + transform: translate(0); + } + } + + .text, + .icon { + display: flex; + align-items: center; + justify-content: center; + } + } +} + +.prompt-toast { + position: absolute; + bottom: -50px; + z-index: 999; + display: flex; + justify-content: center; + width: calc(100% - 40px); + + .prompt-toast-inner { + display: flex; + justify-content: center; + align-items: center; + font-size: 12px; + background-color: var(--white); + color: var(--black); + + border: var(--border-in-light); + box-shadow: var(--card-shadow); + padding: 10px 20px; + border-radius: 100px; + + animation: slide-in-from-top ease 0.3s; + + .prompt-toast-content { + margin-left: 10px; + } + } +} + +.section-title { + font-size: 12px; + font-weight: bold; + margin-bottom: 10px; + display: flex; + justify-content: space-between; + align-items: center; + + .section-title-action { + display: flex; + align-items: center; + } +} + +.context-prompt { + .context-prompt-insert { + display: flex; + justify-content: center; + padding: 4px; + opacity: 0.2; + transition: all ease 0.3s; + background-color: rgba(0, 0, 0, 0); + cursor: pointer; + border-radius: 4px; + margin-top: 4px; + margin-bottom: 4px; + + &:hover { + opacity: 1; + background-color: rgba(0, 0, 0, 0.05); + } + } + + .context-prompt-row { + display: flex; + justify-content: center; + width: 100%; + + &:hover { + .context-drag { + opacity: 1; + } + } + + .context-drag { + display: flex; + align-items: center; + opacity: 0.5; + transition: all ease 0.3s; + } + + .context-role { + margin-right: 10px; + } + + .context-content { + flex: 1; + max-width: 100%; + text-align: left; + } + + .context-delete-button { + margin-left: 10px; + } + } + + .context-prompt-button { + flex: 1; + } +} + +.memory-prompt { + margin: 20px 0; + + .memory-prompt-content { + background-color: var(--white); + color: var(--black); + border: var(--border-in-light); + border-radius: 10px; + padding: 10px; + font-size: 12px; + user-select: text; + } +} + +.clear-context { + margin: 20px 0 0 0; + padding: 4px 0; + + border-top: var(--border-in-light); + border-bottom: var(--border-in-light); + box-shadow: var(--card-shadow) inset; + + display: flex; + justify-content: center; + align-items: center; + + color: var(--black); + transition: all ease 0.3s; + cursor: pointer; + overflow: hidden; + position: relative; + font-size: 12px; + + animation: slide-in ease 0.3s; + + $linear: linear-gradient(to right, + rgba(0, 0, 0, 0), + rgba(0, 0, 0, 1), + rgba(0, 0, 0, 0)); + mask-image: $linear; + + @mixin show { + transform: translateY(0); + position: relative; + transition: all ease 0.3s; + opacity: 1; + } + + @mixin hide { + transform: translateY(-50%); + position: absolute; + transition: all ease 0.1s; + opacity: 0; + } + + &-tips { + @include show; + opacity: 0.5; + } + + &-revert-btn { + color: var(--primary); + @include hide; + } + + &:hover { + opacity: 1; + border-color: var(--primary); + + .clear-context-tips { + @include hide; + } + + .clear-context-revert-btn { + @include show; + } + } +} + +.chat { + display: flex; + flex-direction: column; + position: relative; + height: 100%; +} + +.chat-body { + flex: 1; + overflow: auto; + overflow-x: hidden; + padding: 20px; + padding-bottom: 40px; + position: relative; + overscroll-behavior: none; +} + +.chat-body-main-title { + cursor: pointer; + + &:hover { + text-decoration: underline; + } +} + +@media only screen and (max-width: 600px) { + .chat-body-title { + text-align: center; + } +} + +.chat-message { + display: flex; + flex-direction: row; + + &:last-child { + animation: slide-in ease 0.3s; + } +} + +.chat-message-user { + display: flex; + flex-direction: row-reverse; + + .chat-message-header { + flex-direction: row-reverse; + } +} + +.chat-message-header { + margin-top: 20px; + display: flex; + align-items: center; + + .chat-message-actions { + display: flex; + box-sizing: border-box; + font-size: 12px; + align-items: flex-end; + justify-content: space-between; + transition: all ease 0.3s; + transform: scale(0.9) translateY(5px); + margin: 0 10px; + opacity: 0; + pointer-events: none; + + .chat-input-actions { + display: flex; + flex-wrap: nowrap; + } + } +} + +.chat-message-container { + max-width: var(--message-max-width); + display: flex; + flex-direction: column; + align-items: flex-start; + + &:hover { + .chat-message-edit { + opacity: 0.9; + } + + .chat-message-actions { + opacity: 1; + pointer-events: all; + transform: scale(1) translateY(0); + } + } +} + +.chat-message-user>.chat-message-container { + align-items: flex-end; +} + +.chat-message-avatar { + position: relative; + + .chat-message-edit { + position: absolute; + height: 100%; + width: 100%; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + opacity: 0; + transition: all ease 0.3s; + + button { + padding: 7px; + } + } + + /* Specific styles for iOS devices */ + @media screen and (max-device-width: 812px) and (-webkit-min-device-pixel-ratio: 2) { + @supports (-webkit-touch-callout: none) { + .chat-message-edit { + top: -8%; + } + } + } +} + +.chat-message-status { + font-size: 12px; + color: #aaa; + line-height: 1.5; + margin-top: 5px; +} + +.chat-message-item { + box-sizing: border-box; + max-width: 100%; + margin-top: 10px; + border-radius: 10px; + background-color: rgba(0, 0, 0, 0.05); + padding: 10px; + font-size: 14px; + user-select: text; + word-break: break-word; + border: var(--border-in-light); + position: relative; + transition: all ease 0.3s; +} + +.chat-message-item-image { + width: 100%; + margin-top: 10px; +} + +.chat-message-item-images { + width: 100%; + display: grid; + justify-content: left; + grid-gap: 10px; + grid-template-columns: repeat(var(--image-count), auto); + margin-top: 10px; +} + +.chat-message-item-image-multi { + object-fit: cover; + background-size: cover; + background-position: center; + background-repeat: no-repeat; +} + +.chat-message-item-image, +.chat-message-item-image-multi { + box-sizing: border-box; + border-radius: 10px; + border: rgba($color: #888, $alpha: 0.2) 1px solid; +} + + +@media only screen and (max-width: 600px) { + $calc-image-width: calc(100vw/3*2/var(--image-count)); + + .chat-message-item-image-multi { + width: $calc-image-width; + height: $calc-image-width; + } + + .chat-message-item-image { + max-width: calc(100vw/3*2); + } +} + +@media screen and (min-width: 600px) { + $max-image-width: calc(calc(1200px - var(--sidebar-width))/3*2/var(--image-count)); + $image-width: calc(calc(var(--window-width) - var(--sidebar-width))/3*2/var(--image-count)); + + .chat-message-item-image-multi { + width: $image-width; + height: $image-width; + max-width: $max-image-width; + max-height: $max-image-width; + } + + .chat-message-item-image { + max-width: calc(calc(1200px - var(--sidebar-width))/3*2); + } +} + +.chat-message-action-date { + font-size: 12px; + opacity: 0.2; + white-space: nowrap; + transition: all ease 0.6s; + color: var(--black); + text-align: right; + width: 100%; + box-sizing: border-box; + padding-right: 10px; + pointer-events: none; + z-index: 1; +} + +.chat-message-user>.chat-message-container>.chat-message-item { + background-color: var(--second); + + &:hover { + min-width: 0; + } +} + +.chat-input-panel { + position: relative; + width: 100%; + padding: 20px; + padding-top: 10px; + box-sizing: border-box; + flex-direction: column; + border-top: var(--border-in-light); + box-shadow: var(--card-shadow); + + .chat-input-actions { + .chat-input-action { + margin-bottom: 10px; + } + } +} + +@mixin single-line { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.prompt-hints { + min-height: 20px; + width: 100%; + max-height: 50vh; + overflow: auto; + display: flex; + flex-direction: column-reverse; + + background-color: var(--white); + border: var(--border-in-light); + border-radius: 10px; + margin-bottom: 10px; + box-shadow: var(--shadow); + + .prompt-hint { + color: var(--black); + padding: 6px 10px; + animation: slide-in ease 0.3s; + cursor: pointer; + transition: all ease 0.3s; + border: transparent 1px solid; + margin: 4px; + border-radius: 8px; + + &:not(:last-child) { + margin-top: 0; + } + + .hint-title { + font-size: 12px; + font-weight: bolder; + + @include single-line(); + } + + .hint-content { + font-size: 12px; + + @include single-line(); + } + + &-selected, + &:hover { + border-color: var(--primary); + } + } +} + +.chat-input-panel-inner { + cursor: text; + display: flex; + flex: 1; + border-radius: 10px; + border: var(--border-in-light); +} + +.chat-input-panel-inner-attach { + padding-bottom: 80px; +} + +.chat-input-panel-inner:has(.chat-input:focus) { + border: 1px solid var(--primary); +} + +.chat-input { + height: 100%; + width: 100%; + border-radius: 10px; + border: none; + box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.03); + background-color: var(--white); + color: var(--black); + font-family: inherit; + padding: 10px 90px 10px 14px; + resize: none; + outline: none; + box-sizing: border-box; + min-height: 68px; +} + +.chat-input-send { + background-color: var(--primary); + color: white; + + position: absolute; + right: 30px; + bottom: 32px; +} + +@media only screen and (max-width: 600px) { + .chat-input { + font-size: 16px; + } + + .chat-input-send { + bottom: 30px; + } +} \ No newline at end of file diff --git a/app/components/chat.tsx b/app/components/chat.tsx new file mode 100644 index 00000000..2de70d52 --- /dev/null +++ b/app/components/chat.tsx @@ -0,0 +1,1532 @@ +import { useDebouncedCallback } from "use-debounce"; +import React, { + useState, + useRef, + useEffect, + useMemo, + useCallback, + Fragment, + RefObject, +} from "react"; + +import SendWhiteIcon from "../icons/send-white.svg"; +import BrainIcon from "../icons/brain.svg"; +import RenameIcon from "../icons/rename.svg"; +import ExportIcon from "../icons/share.svg"; +import ReturnIcon from "../icons/return.svg"; +import CopyIcon from "../icons/copy.svg"; +import LoadingIcon from "../icons/three-dots.svg"; +import LoadingButtonIcon from "../icons/loading.svg"; +import PromptIcon from "../icons/prompt.svg"; +import MaskIcon from "../icons/mask.svg"; +import MaxIcon from "../icons/max.svg"; +import MinIcon from "../icons/min.svg"; +import ResetIcon from "../icons/reload.svg"; +import BreakIcon from "../icons/break.svg"; +import SettingsIcon from "../icons/chat-settings.svg"; +import DeleteIcon from "../icons/clear.svg"; +import PinIcon from "../icons/pin.svg"; +import EditIcon from "../icons/rename.svg"; +import ConfirmIcon from "../icons/confirm.svg"; +import CancelIcon from "../icons/cancel.svg"; +import ImageIcon from "../icons/image.svg"; + +import LightIcon from "../icons/light.svg"; +import DarkIcon from "../icons/dark.svg"; +import AutoIcon from "../icons/auto.svg"; +import BottomIcon from "../icons/bottom.svg"; +import StopIcon from "../icons/pause.svg"; +import RobotIcon from "../icons/robot.svg"; + +import { + ChatMessage, + SubmitKey, + useChatStore, + BOT_HELLO, + createMessage, + Theme, + useAppConfig, + DEFAULT_TOPIC, + ModelType, +} from "../store"; + +import { + copyToClipboard, + selectOrCopy, + autoGrowTextArea, + useMobileScreen, + getMessageTextContent, + getMessageImages, + isVisionModel, + compressImage, +} from "../utils"; + +import dynamic from "next/dynamic"; + +import { ChatControllerPool } from "../client/controller"; +import { Prompt, usePromptStore } from "../store/prompt"; +import Locale from "../locales"; + +import { IconButton } from "./button"; +import styles from "./chat.module.scss"; + +import { + List, + ListItem, + Modal, + Selector, + showConfirm, + showPrompt, + showToast, +} from "./ui-lib"; +import { useNavigate } from "react-router-dom"; +import { + CHAT_PAGE_SIZE, + LAST_INPUT_KEY, + Path, + REQUEST_TIMEOUT_MS, + UNFINISHED_INPUT, +} from "../constant"; +import { Avatar } from "./emoji"; +import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask"; +import { useMaskStore } from "../store/mask"; +import { ChatCommandPrefix, useChatCommand, useCommand } from "../command"; +import { prettyObject } from "../utils/format"; +import { ExportMessageModal } from "./exporter"; +import { getClientConfig } from "../config/client"; +import { useAllModels } from "../utils/hooks"; +import { MultimodalContent } from "../client/api"; + +const Markdown = dynamic(async () => (await import("./markdown")).Markdown, { + loading: () => , +}); + +export function SessionConfigModel(props: { onClose: () => void }) { + const chatStore = useChatStore(); + const session = chatStore.currentSession(); + const maskStore = useMaskStore(); + const navigate = useNavigate(); + + return ( +
+ props.onClose()} + actions={[ + } + bordered + text={Locale.Chat.Config.Reset} + onClick={async () => { + if (await showConfirm(Locale.Memory.ResetConfirm)) { + chatStore.updateCurrentSession( + (session) => (session.memoryPrompt = ""), + ); + } + }} + />, + } + bordered + text={Locale.Chat.Config.SaveAs} + onClick={() => { + navigate(Path.Masks); + setTimeout(() => { + maskStore.create(session.mask); + }, 500); + }} + />, + ]} + > + { + const mask = { ...session.mask }; + updater(mask); + chatStore.updateCurrentSession((session) => (session.mask = mask)); + }} + extraListItems={ + session.mask.modelConfig.sendMemory ? ( + + ) : ( + <> + ) + } + > + +
+ ); +} + +function PromptToast(props: { + showToast?: boolean; + showModal?: boolean; + setShowModal: (_: boolean) => void; +}) { + const chatStore = useChatStore(); + const session = chatStore.currentSession(); + const context = session.mask.context; + + return ( +
+ {props.showToast && ( +
props.setShowModal(true)} + > + + + {Locale.Context.Toast(context.length)} + +
+ )} + {props.showModal && ( + props.setShowModal(false)} /> + )} +
+ ); +} + +function useSubmitHandler() { + const config = useAppConfig(); + const submitKey = config.submitKey; + const isComposing = useRef(false); + + useEffect(() => { + const onCompositionStart = () => { + isComposing.current = true; + }; + const onCompositionEnd = () => { + isComposing.current = false; + }; + + window.addEventListener("compositionstart", onCompositionStart); + window.addEventListener("compositionend", onCompositionEnd); + + return () => { + window.removeEventListener("compositionstart", onCompositionStart); + window.removeEventListener("compositionend", onCompositionEnd); + }; + }, []); + + const shouldSubmit = (e: React.KeyboardEvent) => { + // Fix Chinese input method "Enter" on Safari + if (e.keyCode == 229) return false; + if (e.key !== "Enter") return false; + if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current)) + return false; + return ( + (config.submitKey === SubmitKey.AltEnter && e.altKey) || + (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) || + (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) || + (config.submitKey === SubmitKey.MetaEnter && e.metaKey) || + (config.submitKey === SubmitKey.Enter && + !e.altKey && + !e.ctrlKey && + !e.shiftKey && + !e.metaKey) + ); + }; + + return { + submitKey, + shouldSubmit, + }; +} + +export type RenderPompt = Pick; + +export function PromptHints(props: { + prompts: RenderPompt[]; + onPromptSelect: (prompt: RenderPompt) => void; +}) { + const noPrompts = props.prompts.length === 0; + const [selectIndex, setSelectIndex] = useState(0); + const selectedRef = useRef(null); + + useEffect(() => { + setSelectIndex(0); + }, [props.prompts.length]); + + useEffect(() => { + const onKeyDown = (e: KeyboardEvent) => { + if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) { + return; + } + // arrow up / down to select prompt + const changeIndex = (delta: number) => { + e.stopPropagation(); + e.preventDefault(); + const nextIndex = Math.max( + 0, + Math.min(props.prompts.length - 1, selectIndex + delta), + ); + setSelectIndex(nextIndex); + selectedRef.current?.scrollIntoView({ + block: "center", + }); + }; + + if (e.key === "ArrowUp") { + changeIndex(1); + } else if (e.key === "ArrowDown") { + changeIndex(-1); + } else if (e.key === "Enter") { + const selectedPrompt = props.prompts.at(selectIndex); + if (selectedPrompt) { + props.onPromptSelect(selectedPrompt); + } + } + }; + + window.addEventListener("keydown", onKeyDown); + + return () => window.removeEventListener("keydown", onKeyDown); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [props.prompts.length, selectIndex]); + + if (noPrompts) return null; + return ( +
+ {props.prompts.map((prompt, i) => ( +
props.onPromptSelect(prompt)} + onMouseEnter={() => setSelectIndex(i)} + > +
{prompt.title}
+
{prompt.content}
+
+ ))} +
+ ); +} + +function ClearContextDivider() { + const chatStore = useChatStore(); + + return ( +
+ chatStore.updateCurrentSession( + (session) => (session.clearContextIndex = undefined), + ) + } + > +
{Locale.Context.Clear}
+
+ {Locale.Context.Revert} +
+
+ ); +} + +function ChatAction(props: { + text: string; + icon: JSX.Element; + onClick: () => void; +}) { + const iconRef = useRef(null); + const textRef = useRef(null); + const [width, setWidth] = useState({ + full: 16, + icon: 16, + }); + + function updateWidth() { + if (!iconRef.current || !textRef.current) return; + const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width; + const textWidth = getWidth(textRef.current); + const iconWidth = getWidth(iconRef.current); + setWidth({ + full: textWidth + iconWidth, + icon: iconWidth, + }); + } + + return ( +
{ + props.onClick(); + setTimeout(updateWidth, 1); + }} + onMouseEnter={updateWidth} + onTouchStart={updateWidth} + style={ + { + "--icon-width": `${width.icon}px`, + "--full-width": `${width.full}px`, + } as React.CSSProperties + } + > +
+ {props.icon} +
+
+ {props.text} +
+
+ ); +} + +function useScrollToBottom( + scrollRef: RefObject, + detach: boolean = false, +) { + // for auto-scroll + + const [autoScroll, setAutoScroll] = useState(true); + function scrollDomToBottom() { + const dom = scrollRef.current; + if (dom) { + requestAnimationFrame(() => { + setAutoScroll(true); + dom.scrollTo(0, dom.scrollHeight); + }); + } + } + + // auto scroll + useEffect(() => { + if (autoScroll && !detach) { + scrollDomToBottom(); + } + }); + + return { + scrollRef, + autoScroll, + setAutoScroll, + scrollDomToBottom, + }; +} + +export function ChatActions(props: { + uploadImage: () => void; + setAttachImages: (images: string[]) => void; + setUploading: (uploading: boolean) => void; + showPromptModal: () => void; + scrollToBottom: () => void; + showPromptHints: () => void; + hitBottom: boolean; + uploading: boolean; +}) { + const config = useAppConfig(); + const navigate = useNavigate(); + const chatStore = useChatStore(); + + // switch themes + const theme = config.theme; + function nextTheme() { + const themes = [Theme.Auto, Theme.Light, Theme.Dark]; + const themeIndex = themes.indexOf(theme); + const nextIndex = (themeIndex + 1) % themes.length; + const nextTheme = themes[nextIndex]; + config.update((config) => (config.theme = nextTheme)); + } + + // stop all responses + const couldStop = ChatControllerPool.hasPending(); + const stopAll = () => ChatControllerPool.stopAll(); + + // switch model + const currentModel = chatStore.currentSession().mask.modelConfig.model; + const allModels = useAllModels(); + const models = useMemo(() => { + const filteredModels = allModels.filter((m) => m.available); + const defaultModel = filteredModels.find((m) => m.isDefault); + + if (defaultModel) { + const arr = [ + defaultModel, + ...filteredModels.filter((m) => m !== defaultModel), + ]; + return arr; + } else { + return filteredModels; + } + }, [allModels]); + const [showModelSelector, setShowModelSelector] = useState(false); + const [showUploadImage, setShowUploadImage] = useState(false); + + useEffect(() => { + const show = isVisionModel(currentModel); + setShowUploadImage(show); + if (!show) { + props.setAttachImages([]); + props.setUploading(false); + } + // if current model is not available + // switch to first available model + const isUnavaliableModel = !models.some((m) => m.name === currentModel); + if (isUnavaliableModel && models.length > 0) { + // show next model to default model if exist + let nextModel: ModelType = ( + models.find((model) => model.isDefault) || models[0] + ).name; + chatStore.updateCurrentSession( + (session) => (session.mask.modelConfig.model = nextModel), + ); + showToast(nextModel); + } + }, [chatStore, currentModel, models]); + + return ( +
+ {couldStop && ( + } + /> + )} + {!props.hitBottom && ( + } + /> + )} + {props.hitBottom && ( + } + /> + )} + + {showUploadImage && ( + : } + /> + )} + + {theme === Theme.Auto ? ( + + ) : theme === Theme.Light ? ( + + ) : theme === Theme.Dark ? ( + + ) : null} + + } + /> + + } + /> + + { + navigate(Path.Masks); + }} + text={Locale.Chat.InputActions.Masks} + icon={} + /> + + } + onClick={() => { + chatStore.updateCurrentSession((session) => { + if (session.clearContextIndex === session.messages.length) { + session.clearContextIndex = undefined; + } else { + session.clearContextIndex = session.messages.length; + session.memoryPrompt = ""; // will clear memory + } + }); + }} + /> + + setShowModelSelector(true)} + text={currentModel} + icon={} + /> + + {showModelSelector && ( + ({ + title: m.displayName, + value: m.name, + }))} + onClose={() => setShowModelSelector(false)} + onSelection={(s) => { + if (s.length === 0) return; + chatStore.updateCurrentSession((session) => { + session.mask.modelConfig.model = s[0] as ModelType; + session.mask.syncGlobalConfig = false; + }); + showToast(s[0]); + }} + /> + )} +
+ ); +} + +export function EditMessageModal(props: { onClose: () => void }) { + const chatStore = useChatStore(); + const session = chatStore.currentSession(); + const [messages, setMessages] = useState(session.messages.slice()); + + return ( +
+ } + key="cancel" + onClick={() => { + props.onClose(); + }} + />, + } + key="ok" + onClick={() => { + chatStore.updateCurrentSession( + (session) => (session.messages = messages), + ); + props.onClose(); + }} + />, + ]} + > + + + + chatStore.updateCurrentSession( + (session) => (session.topic = e.currentTarget.value), + ) + } + > + + + { + const newMessages = messages.slice(); + updater(newMessages); + setMessages(newMessages); + }} + /> + +
+ ); +} + +export function DeleteImageButton(props: { deleteImage: () => void }) { + return ( +
+ +
+ ); +} + +function _Chat() { + type RenderMessage = ChatMessage & { preview?: boolean }; + + const chatStore = useChatStore(); + const session = chatStore.currentSession(); + const config = useAppConfig(); + const fontSize = config.fontSize; + + const isGenerating = session.isGenerating; + + const [showExport, setShowExport] = useState(false); + + const inputRef = useRef(null); + const [userInput, setUserInput] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const { submitKey, shouldSubmit } = useSubmitHandler(); + const scrollRef = useRef(null); + const isScrolledToBottom = scrollRef?.current + ? Math.abs( + scrollRef.current.scrollHeight - + (scrollRef.current.scrollTop + scrollRef.current.clientHeight), + ) <= 1 + : false; + const { setAutoScroll, scrollDomToBottom } = useScrollToBottom( + scrollRef, + isScrolledToBottom, + ); + const [hitBottom, setHitBottom] = useState(true); + const isMobileScreen = useMobileScreen(); + const navigate = useNavigate(); + const [attachImages, setAttachImages] = useState([]); + const [uploading, setUploading] = useState(false); + + // prompt hints + const promptStore = usePromptStore(); + const [promptHints, setPromptHints] = useState([]); + const onSearch = useDebouncedCallback( + (text: string) => { + const matchedPrompts = promptStore.search(text); + setPromptHints(matchedPrompts); + }, + 100, + { leading: true, trailing: true }, + ); + + // auto grow input + const [inputRows, setInputRows] = useState(2); + const measure = useDebouncedCallback( + () => { + const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1; + const inputRows = Math.min( + 20, + Math.max(2 + Number(!isMobileScreen), rows), + ); + setInputRows(inputRows); + }, + 100, + { + leading: true, + trailing: true, + }, + ); + + // eslint-disable-next-line react-hooks/exhaustive-deps + useEffect(measure, [userInput]); + + // chat commands shortcuts + const chatCommands = useChatCommand({ + new: () => chatStore.newSession(), + prev: () => chatStore.nextSession(-1), + next: () => chatStore.nextSession(1), + clear: () => + chatStore.updateCurrentSession( + (session) => (session.clearContextIndex = session.messages.length), + ), + del: () => chatStore.deleteSession(chatStore.currentSessionIndex), + }); + + // only search prompts when user input is short + const SEARCH_TEXT_LIMIT = 30; + const onInput = (text: string) => { + setUserInput(text); + const n = text.trim().length; + + // clear search results + if (n === 0) { + setPromptHints([]); + } else if (text.startsWith(ChatCommandPrefix)) { + setPromptHints(chatCommands.search(text)); + } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) { + // check if need to trigger auto completion + if (text.startsWith("/")) { + let searchText = text.slice(1); + onSearch(searchText); + } + } + }; + + const doSubmit = (userInput: string) => { + if (userInput.trim() === "") return; + + const matchCommand = chatCommands.match(userInput); + if (matchCommand.matched) { + setUserInput(""); + setPromptHints([]); + matchCommand.invoke(); + return; + } + + if (isGenerating) return; + setIsLoading(true); + chatStore + .onUserInput(userInput, attachImages) + .then(() => setIsLoading(false)); + setAttachImages([]); + localStorage.setItem(LAST_INPUT_KEY, userInput); + setUserInput(""); + setPromptHints([]); + if (!isMobileScreen) inputRef.current?.focus(); + setAutoScroll(true); + }; + + const onPromptSelect = (prompt: RenderPompt) => { + setTimeout(() => { + setPromptHints([]); + + const matchedChatCommand = chatCommands.match(prompt.content); + if (matchedChatCommand.matched) { + // if user is selecting a chat command, just trigger it + matchedChatCommand.invoke(); + setUserInput(""); + } else { + // or fill the prompt + setUserInput(prompt.content); + } + inputRef.current?.focus(); + }, 30); + }; + + // stop response + const onUserStop = (messageId: string) => { + ChatControllerPool.stop(session.id, messageId); + }; + + // Reset session status on initial loading + useEffect(() => { + chatStore.resetGeneratingStatus(); + }, []); + + useEffect(() => { + chatStore.updateCurrentSession((session) => { + const stopTiming = Date.now() - REQUEST_TIMEOUT_MS; + session.messages.forEach((m) => { + // check if should stop all stale messages + if (m.isError || new Date(m.date).getTime() < stopTiming) { + if (m.streaming) { + m.streaming = false; + } + + if (m.content.length === 0) { + m.isError = true; + m.content = prettyObject({ + error: true, + message: "empty response", + }); + } + } + }); + + // auto sync mask config from global config + if (session.mask.syncGlobalConfig) { + console.log("[Mask] syncing from global, name = ", session.mask.name); + session.mask.modelConfig = { ...config.modelConfig }; + } + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // check if should send message + const onInputKeyDown = (e: React.KeyboardEvent) => { + // if ArrowUp and no userInput, fill with last input + if ( + e.key === "ArrowUp" && + userInput.length <= 0 && + !(e.metaKey || e.altKey || e.ctrlKey) + ) { + setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? ""); + e.preventDefault(); + return; + } + if (shouldSubmit(e) && promptHints.length === 0) { + doSubmit(userInput); + e.preventDefault(); + } + }; + const onRightClick = (e: any, message: ChatMessage) => { + // copy to clipboard + if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) { + if (userInput.length === 0) { + setUserInput(getMessageTextContent(message)); + } + + e.preventDefault(); + } + }; + + const deleteMessage = (msgId?: string) => { + chatStore.updateCurrentSession( + (session) => + (session.messages = session.messages.filter((m) => m.id !== msgId)), + ); + }; + + const onDelete = (msgId: string) => { + deleteMessage(msgId); + }; + + const onResend = (message: ChatMessage) => { + // when it is resending a message + // 1. for a user's message, find the next bot response + // 2. for a bot's message, find the last user's input + // 3. delete original user input and bot's message + // 4. resend the user's input + + const resendingIndex = session.messages.findIndex( + (m) => m.id === message.id, + ); + + if (resendingIndex < 0 || resendingIndex >= session.messages.length) { + console.error("[Chat] failed to find resending message", message); + return; + } + + let userMessage: ChatMessage | undefined; + let botMessage: ChatMessage | undefined; + + if (message.role === "assistant") { + // if it is resending a bot's message, find the user input for it + botMessage = message; + for (let i = resendingIndex; i >= 0; i -= 1) { + if (session.messages[i].role === "user") { + userMessage = session.messages[i]; + break; + } + } + } else if (message.role === "user") { + // if it is resending a user's input, find the bot's response + userMessage = message; + for (let i = resendingIndex; i < session.messages.length; i += 1) { + if (session.messages[i].role === "assistant") { + botMessage = session.messages[i]; + break; + } + } + } + + if (userMessage === undefined) { + console.error("[Chat] failed to resend", message); + return; + } + + // delete the original messages + deleteMessage(userMessage.id); + deleteMessage(botMessage?.id); + + // resend the message + setIsLoading(true); + const textContent = getMessageTextContent(userMessage); + const images = getMessageImages(userMessage); + chatStore.onUserInput(textContent, images).then(() => setIsLoading(false)); + inputRef.current?.focus(); + }; + + const onPinMessage = (message: ChatMessage) => { + chatStore.updateCurrentSession((session) => + session.mask.context.push(message), + ); + + showToast(Locale.Chat.Actions.PinToastContent, { + text: Locale.Chat.Actions.PinToastAction, + onClick: () => { + setShowPromptModal(true); + }, + }); + }; + + const context: RenderMessage[] = useMemo(() => { + return session.mask.hideContext ? [] : session.mask.context.slice(); + }, [session.mask.context, session.mask.hideContext]); + + if ( + context.length === 0 && + session.messages.at(0)?.content !== BOT_HELLO.content + ) { + const copiedHello = Object.assign({}, BOT_HELLO); + context.push(copiedHello); + } + + // preview messages + const renderMessages = useMemo(() => { + return context + .concat(session.messages as RenderMessage[]) + .concat( + isLoading + ? [ + { + ...createMessage({ + role: "assistant", + content: "……", + }), + preview: true, + }, + ] + : [], + ) + .concat( + userInput.length > 0 && config.sendPreviewBubble + ? [ + { + ...createMessage({ + role: "user", + content: userInput, + }), + preview: true, + }, + ] + : [], + ); + }, [ + config.sendPreviewBubble, + context, + isLoading, + session.messages, + userInput, + ]); + + const [msgRenderIndex, _setMsgRenderIndex] = useState( + Math.max(0, renderMessages.length - CHAT_PAGE_SIZE), + ); + function setMsgRenderIndex(newIndex: number) { + newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex); + newIndex = Math.max(0, newIndex); + _setMsgRenderIndex(newIndex); + } + + const messages = useMemo(() => { + const endRenderIndex = Math.min( + msgRenderIndex + 3 * CHAT_PAGE_SIZE, + renderMessages.length, + ); + return renderMessages.slice(msgRenderIndex, endRenderIndex); + }, [msgRenderIndex, renderMessages]); + + const onChatBodyScroll = (e: HTMLElement) => { + const bottomHeight = e.scrollTop + e.clientHeight; + const edgeThreshold = e.clientHeight; + + const isTouchTopEdge = e.scrollTop <= edgeThreshold; + const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold; + const isHitBottom = + bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10); + + const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE; + const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE; + + if (isTouchTopEdge && !isTouchBottomEdge) { + setMsgRenderIndex(prevPageMsgIndex); + } else if (isTouchBottomEdge) { + setMsgRenderIndex(nextPageMsgIndex); + } + + setHitBottom(isHitBottom); + setAutoScroll(isHitBottom); + }; + function scrollToBottom() { + setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE); + scrollDomToBottom(); + } + + // clear context index = context length + index in messages + const clearContextIndex = + (session.clearContextIndex ?? -1) >= 0 + ? session.clearContextIndex! + context.length - msgRenderIndex + : -1; + + const [showPromptModal, setShowPromptModal] = useState(false); + + const clientConfig = useMemo(() => getClientConfig(), []); + + const autoFocus = !isMobileScreen; // wont auto focus on mobile screen + const showMaxIcon = !isMobileScreen; + + useCommand({ + fill: setUserInput, + submit: (text) => { + doSubmit(text); + }, + }); + + // edit / insert message modal + const [isEditingMessage, setIsEditingMessage] = useState(false); + + // remember unfinished input + useEffect(() => { + // try to load from local storage + const key = UNFINISHED_INPUT(session.id); + const mayBeUnfinishedInput = localStorage.getItem(key); + if (mayBeUnfinishedInput && userInput.length === 0) { + setUserInput(mayBeUnfinishedInput); + localStorage.removeItem(key); + } + + const dom = inputRef.current; + return () => { + localStorage.setItem(key, dom?.value ?? ""); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const handlePaste = useCallback( + async (event: React.ClipboardEvent) => { + const currentModel = chatStore.currentSession().mask.modelConfig.model; + if (!isVisionModel(currentModel)) { + return; + } + const items = (event.clipboardData || window.clipboardData).items; + for (const item of items) { + if (item.kind === "file" && item.type.startsWith("image/")) { + event.preventDefault(); + const file = item.getAsFile(); + if (file) { + const images: string[] = []; + images.push(...attachImages); + images.push( + ...(await new Promise((res, rej) => { + setUploading(true); + const imagesData: string[] = []; + compressImage(file, 256 * 1024) + .then((dataUrl) => { + imagesData.push(dataUrl); + setUploading(false); + res(imagesData); + }) + .catch((e) => { + setUploading(false); + rej(e); + }); + })), + ); + const imagesLength = images.length; + + if (imagesLength > 3) { + images.splice(3, imagesLength - 3); + } + setAttachImages(images); + } + } + } + }, + [attachImages, chatStore], + ); + + async function uploadImage() { + const images: string[] = []; + images.push(...attachImages); + + images.push( + ...(await new Promise((res, rej) => { + const fileInput = document.createElement("input"); + fileInput.type = "file"; + fileInput.accept = + "image/png, image/jpeg, image/webp, image/heic, image/heif"; + fileInput.multiple = true; + fileInput.onchange = (event: any) => { + setUploading(true); + const files = event.target.files; + const imagesData: string[] = []; + for (let i = 0; i < files.length; i++) { + const file = event.target.files[i]; + compressImage(file, 256 * 1024) + .then((dataUrl) => { + imagesData.push(dataUrl); + if ( + imagesData.length === 3 || + imagesData.length === files.length + ) { + setUploading(false); + res(imagesData); + } + }) + .catch((e) => { + setUploading(false); + rej(e); + }); + } + }; + fileInput.click(); + })), + ); + + const imagesLength = images.length; + if (imagesLength > 3) { + images.splice(3, imagesLength - 3); + } + setAttachImages(images); + } + + return ( +
+
+ {isMobileScreen && ( +
+
+ } + bordered + title={Locale.Chat.Actions.ChatList} + onClick={() => navigate(Path.Home)} + /> +
+
+ )} + +
+
setIsEditingMessage(true)} + > + {!session.topic ? DEFAULT_TOPIC : session.topic} +
+
+ {Locale.Chat.SubTitle(session.messages.length)} +
+
+
+ {!isMobileScreen && ( +
+ } + bordered + onClick={() => setIsEditingMessage(true)} + /> +
+ )} +
+ } + bordered + title={Locale.Chat.Actions.Export} + onClick={() => { + setShowExport(true); + }} + /> +
+ {showMaxIcon && ( +
+ : } + bordered + onClick={() => { + config.update( + (config) => (config.tightBorder = !config.tightBorder), + ); + }} + /> +
+ )} +
+ + +
+ +
onChatBodyScroll(e.currentTarget)} + onMouseDown={() => inputRef.current?.blur()} + onTouchStart={() => { + inputRef.current?.blur(); + setAutoScroll(false); + }} + > + {messages.map((message, i) => { + const isUser = message.role === "user"; + const isContext = i < context.length; + const showActions = + i > 0 && + !(message.preview || message.content.length === 0) && + !isContext; + const showTyping = message.preview || message.streaming; + + const shouldShowClearContextDivider = i === clearContextIndex - 1; + + return ( + +
+
+
+
+
+ } + onClick={async () => { + const newMessage = await showPrompt( + Locale.Chat.Actions.Edit, + getMessageTextContent(message), + 10, + ); + let newContent: string | MultimodalContent[] = + newMessage; + const images = getMessageImages(message); + if (images.length > 0) { + newContent = [{ type: "text", text: newMessage }]; + for (let i = 0; i < images.length; i++) { + newContent.push({ + type: "image_url", + image_url: { + url: images[i], + }, + }); + } + } + chatStore.updateCurrentSession((session) => { + const m = session.mask.context + .concat(session.messages) + .find((m) => m.id === message.id); + if (m) { + m.content = newContent; + } + }); + }} + > +
+ {isUser ? ( + + ) : ( + <> + {["system"].includes(message.role) ? ( + + ) : ( + + )} + + )} +
+ + {showActions && ( +
+
+ {message.streaming ? ( + } + onClick={() => onUserStop(message.id ?? i)} + /> + ) : ( + <> + } + onClick={() => onResend(message)} + /> + + } + onClick={() => onDelete(message.id ?? i)} + /> + + } + onClick={() => onPinMessage(message)} + /> + } + onClick={() => + copyToClipboard( + getMessageTextContent(message), + ) + } + /> + + )} +
+
+ )} +
+ {showTyping && ( +
+ {Locale.Chat.Typing} +
+ )} +
+ onRightClick(e, message)} + onDoubleClickCapture={() => { + if (!isMobileScreen) return; + setUserInput(getMessageTextContent(message)); + }} + fontSize={fontSize} + parentRef={scrollRef} + defaultShow={i >= messages.length - 6} + /> + {getMessageImages(message).length == 1 && ( + + )} + {getMessageImages(message).length > 1 && ( +
+ {getMessageImages(message).map((image, index) => { + return ( + + ); + })} +
+ )} +
+ +
+ {isContext + ? Locale.Chat.IsContext + : message.date.toLocaleString()} +
+
+
+ {shouldShowClearContextDivider && } +
+ ); + })} +
+ +
+ + + setShowPromptModal(true)} + scrollToBottom={scrollToBottom} + hitBottom={hitBottom} + uploading={uploading} + showPromptHints={() => { + // Click again to close + if (promptHints.length > 0) { + setPromptHints([]); + return; + } + + inputRef.current?.focus(); + setUserInput("/"); + onSearch(""); + }} + /> +