commit 983960e2dd9e95f5c19e1e96d70bf52d4d461c91 Author: wehub-resource-sync Date: Mon Jul 13 12:44:08 2026 +0800 chore: import upstream snapshot with attribution diff --git a/.changelogrc b/.changelogrc new file mode 100644 index 0000000..3f2db1d --- /dev/null +++ b/.changelogrc @@ -0,0 +1,25 @@ +{ + "app_name": "Leon", + "sections": [ + { + "title": "BREAKING CHANGES", + "grep": "BREAKING" + }, + { + "title": "Features", + "grep": "^feat" + }, + { + "title": "Bug Fixes", + "grep": "^fix" + }, + { + "title": "Performance Improvements", + "grep": "^perf" + }, + { + "title": "Documentation Changes", + "grep": "^docs" + } + ] +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ac3a4a1 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +end_of_line = lf +insert_final_newline = true + +[*.py] +indent_size = 4 diff --git a/.env.sample b/.env.sample new file mode 100644 index 0000000..c5a0109 --- /dev/null +++ b/.env.sample @@ -0,0 +1,45 @@ +# Leon profile secrets. +# Non-secret profile configuration lives in config.yml. + +# LLM provider API keys + +# Optional local llama.cpp API key +LEON_LLAMACPP_API_KEY= + +# Optional Linux high-performance local provider API key (OpenAI-compatible) +LEON_SGLANG_API_KEY= + +# OpenRouter API key +LEON_OPENROUTER_API_KEY= + +# Z.AI API key +LEON_ZAI_API_KEY= + +# MiniMax API key +LEON_MINIMAX_API_KEY= + +# OpenAI API key +LEON_OPENAI_API_KEY= + +# Anthropic API key +LEON_ANTHROPIC_API_KEY= + +# Moonshot AI API key +LEON_MOONSHOTAI_API_KEY= + +# HuggingFace API key +LEON_HUGGINGFACE_API_KEY= + +# Cerebras API key +LEON_CEREBRAS_API_KEY= + +# Groq API key +LEON_GROQ_API_KEY= + +# Misc + +# Optional token required by LeonClientInterface when client_interface.auth.enabled=true +LEON_CLIENT_INTERFACE_TOKEN= + +# Optional token required by HTTP plugins when http_plugins.auth.enabled=true +LEON_HTTP_PLUGIN_TOKEN= diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..07ec84a --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or + advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at . All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..2641e77 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,197 @@ +# Contributing + +Thanks a lot for your interest in contributing to Leon! :heart: + +**Leon needs open source to live**, the more skills he has, the more skillful he becomes. + +**Before submitting your contribution**, please take a moment to review this document. + +Please note we have a [code of conduct](https://github.com/leon-ai/leon/blob/develop/.github/CODE_OF_CONDUCT.md), please follow it in all your interactions with the project. + +## How You Can Help + +Here are few examples about how you could help on Leon, by: + +- [Creating a new module](https://docs.getleon.ai/packages-modules). +- [Working on new features](http://roadmap.getleon.ai) (what is in backlog or todo). +- [Suggesting new ideas](https://github.com/leon-ai/leon/issues/new/choose). +- [Reporting a bug](https://github.com/leon-ai/leon/issues/new?labels=bug&template=BUG.md). +- [Improving the documentation](https://github.com/leon-ai/docs.getleon.ai) (translations, typos, better writing, etc.). +- [Sponsoring Leon](http://sponsor.getleon.ai). + +## Pull Requests + +**Working on your first Pull Request?** You can learn how from this _free_ series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github). + +- **Please first discuss** the change you wish to make via [issue](https://github.com/leon-ai/leon/issues), + email, or any other method with the owners of this repository before making a change. + It might avoid a waste of your time. + +- The `master` branch is actually used as a snapshot of the latest stable release. **Do not submit your PRs + against the `master` branch**. + +- Ensure your code **respect our coding standards** (cf. [.eslintrc.json](https://github.com/leon-ai/leon/blob/develop/.eslintrc.json)). + To do so, you can run: + + ```sh + pnpm run lint + ``` + +- Make sure your **code passes the tests**. You can run the tests via the following command: + + ```sh + npm test + ``` + + If you're adding new features to Leon, please include tests. + +## Development Setup + +Choose the setup method you want to go for. + +### Single-Click + +Gitpod will automatically set up an environment and run an instance for you. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/leon-ai/leon) + +### Basic + +```sh +# Clone the repository +git clone https://github.com/leon-ai/leon.git leon + +# Go to the project root +cd leon + +# Install +pnpm install + +# Check the setup went well +pnpm run check + +# Run the development server +pnpm run dev:server + +# Run the development web app +pnpm run dev:app +``` + +## Versioning + +- We use [Semantic Versioning](https://semver.org) for releases. + +## Commits + +The commit message guideline is adapted from the [AngularJS Git Commit Guidelines](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines). + +### Types + +Types define which kind of changes you made to the project. + +| Types | Description | +| -------- | -------------------------------------------------------------------------------------------------------- | +| BREAKING | Changes including breaking changes. | +| build | New build version. | +| chore | Changes to the build process or auxiliary tools such as changelog generation. No production code change. | +| ci | Changes related to continuous integration only (GitHub Actions, CircleCI, etc.). | +| docs | Documentation only changes. | +| feat | A new feature. | +| fix | A bug fix. | +| perf | A code change that improves performance. | +| refactor | A code change that neither fixes a bug nor adds a feature. | +| style | Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc.). | +| test | Adding missing or correcting existing tests. | + +### Scopes + +Scopes define high-level nodes of Leon. + +- bridge/python +- bridge/nodejs +- hotword +- scripts +- server +- tcp server +- web app +- skill/skill_name + +### Examples + +```sh +git commit -m "feat(server): awesome new server feature" +git commit -m "docs(skill/leon): fix spelling" +git commit -m "chore: split training script into awesome blocks" +git commit -m "style(web app): remove chatbot useless parentheses" +``` + +### GUI Clients + +If you are using a GUI client such as GitKraken, you may need to disable the default Git executable to make sure to use your default shell. +Otherwise you may encounter an error such as "npx not found". + +## Sponsor + +You can also contribute by [sponsoring Leon](http://sponsor.getleon.ai). + +Please note that I dedicate most of my free time to Leon. + +By sponsoring the project you make the project sustainable and faster to develop features. + +The focus is not only limited to the activity you see on GitHub but also a lot of thinking about the direction of the project. Which is naturally related to the overall design, architecture, vision, learning process and so on... + +## Contributing to the Python Bridge or TCP HttpServer + +Leon makes use of two binaries, the Python bridge and the TCP server. These binaries are compiled from Python sources. + +The Python bridge is used to communicate between the core and skills made with Python. + +The TCP server is used to communicate between the core and third-party nodes, such as spaCy. + +### Set Up the Python Environment + +To contribute to these parts, you need to set up a Python environment running with a specific Python version and a specific Pipenv version. + +It is recommended to use Pyenv to manage your Python versions. + +If you are on GNU/Linux Ubuntu, you can run the following to install Pyenv, otherwise, please refer to the [Pyenv documentation to install it](https://github.com/pyenv/pyenv#installation): + +```bash +# Update registry +sudo apt-get update + +# Install Pyenv deps +sudo apt-get install make build-essential libssl-dev zlib1g-dev \ +libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \ +libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev + +# Install Pyenv +curl https://pyenv.run | bash + +# Add output lines to .bashrc + +# Restart shell +exec "$SHELL" +``` + +Once Pyenv installed, run: + +```bash +# Install Python +pyenv install 3.11.9 --force +pyenv global 3.11.9 +``` + +Your Python environment should be ready now. Leon uses `uv` as the Python dependency standard, and `postinstall` provisions the Python bridge and TCP server environments automatically from `pyproject.toml`: + +```bash +# Run the Python bridge +npm run python-bridge + +# Run the TCP server +npm run start:tcp-server +``` + +## Spread the Word + +Use [#LeonAI]() if you tweet about Leon and/or mention [@grenlouis](https://twitter.com/grenlouis). diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..7a12ea6 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,8 @@ +# These are supported funding model platforms + +github: [louistiti] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +custom: # http://sponsor.getleon.ai diff --git a/.github/ISSUE_TEMPLATE/BUG.md b/.github/ISSUE_TEMPLATE/BUG.md new file mode 100644 index 0000000..ca1f5db --- /dev/null +++ b/.github/ISSUE_TEMPLATE/BUG.md @@ -0,0 +1,27 @@ +--- +name: 🐞 Bug Report +about: Report an unexpected problem or unintended behavior. +labels: bug +--- + + + +### Specs + +- Leon version: +- OS (or browser) version: +- Node.js version: +- Complete "leon check" (or "pnpm run check") output: +- (optional) Leon skill version: + +### Expected Behavior + +### Actual Behavior + +### How Do We Reproduce? + +### Extra (like a sample repo to reproduce the issue, etc.) diff --git a/.github/ISSUE_TEMPLATE/DOCS.md b/.github/ISSUE_TEMPLATE/DOCS.md new file mode 100644 index 0000000..8f1800b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/DOCS.md @@ -0,0 +1,23 @@ +--- +name: 📝 Documentation +about: Are the docs missing, confusing, etc.? Tell us more about it. +--- + + + +### Documentation Is: + +- [ ] Missing +- [ ] Needed +- [ ] Confusing +- [ ] Not Sure? + +### Explanation + +### Proposal diff --git a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md new file mode 100644 index 0000000..ebf304c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md @@ -0,0 +1,14 @@ +--- +name: ✨ Feature Request +about: Suggest a new feature idea. +labels: feature request +--- + + + +### Feature Use Case + +### Feature Proposal diff --git a/.github/ISSUE_TEMPLATE/IMPROVEMENT.md b/.github/ISSUE_TEMPLATE/IMPROVEMENT.md new file mode 100644 index 0000000..362140b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/IMPROVEMENT.md @@ -0,0 +1,16 @@ +--- +name: 🔧 Improvement +about: Suggest an idea which is not a feature. +labels: improvement +--- + + + +### Expected Behavior + +### Actual Behavior + +### Proposal diff --git a/.github/ISSUE_TEMPLATE/QUESTION.md b/.github/ISSUE_TEMPLATE/QUESTION.md new file mode 100644 index 0000000..1e32379 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/QUESTION.md @@ -0,0 +1,14 @@ +--- +name: ❓ Question +about: Ask a question about Leon. +labels: question +--- + + + +### Question diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..3b6342e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,31 @@ + + +### What type of change does this PR introduce? + +- [ ] Bugfix +- [ ] Feature +- [ ] Refactor +- [ ] Documentation +- [ ] Not Sure? + +### Does this PR introduce breaking changes? + +- [ ] Yes +- [ ] No + +### List any relevant issue numbers: + +### Description: diff --git a/.github/assets/thanks/jetbrains-mono-black.svg b/.github/assets/thanks/jetbrains-mono-black.svg new file mode 100644 index 0000000..778d2bb --- /dev/null +++ b/.github/assets/thanks/jetbrains-mono-black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/.github/assets/thanks/jetbrains-mono-white.svg b/.github/assets/thanks/jetbrains-mono-white.svg new file mode 100644 index 0000000..1381f6d --- /dev/null +++ b/.github/assets/thanks/jetbrains-mono-white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/.github/assets/thanks/macstadium-logo-dark-mode.svg b/.github/assets/thanks/macstadium-logo-dark-mode.svg new file mode 100644 index 0000000..6239d29 --- /dev/null +++ b/.github/assets/thanks/macstadium-logo-dark-mode.svg @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.github/assets/thanks/macstadium-logo-light-mode.svg b/.github/assets/thanks/macstadium-logo-light-mode.svg new file mode 100644 index 0000000..7806548 --- /dev/null +++ b/.github/assets/thanks/macstadium-logo-light-mode.svg @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.github/assets/thanks/openai-logo-dark-mode.svg b/.github/assets/thanks/openai-logo-dark-mode.svg new file mode 100644 index 0000000..cc4616c --- /dev/null +++ b/.github/assets/thanks/openai-logo-dark-mode.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/.github/assets/thanks/openai-logo-light-mode.svg b/.github/assets/thanks/openai-logo-light-mode.svg new file mode 100644 index 0000000..87ab03e --- /dev/null +++ b/.github/assets/thanks/openai-logo-light-mode.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..f0026c9 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,39 @@ +name: Build + +on: + push: + # branches: [master, develop] + branches: [master] + pull_request: + # branches: [master, develop] + branches: [master] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Use Python + uses: actions/setup-python@v2 + with: + python-version: 3.x + + - name: Use Node.js + uses: actions/setup-node@v2 + with: + node-version: 24.x + cache: pnpm + + - name: Enable Corepack + run: corepack enable + + - name: Install + run: pnpm install + + - name: Check setup + run: pnpm run check + + - name: Build + run: pnpm run build diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..cb1812c --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,36 @@ +name: Lint + +on: + push: + # branches: [master, develop] + branches: [master] + pull_request: + # branches: [master, develop] + branches: [master] + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Use Python + uses: actions/setup-python@v2 + with: + python-version: 3.x + + - name: Use Node.js + uses: actions/setup-node@v2 + with: + node-version: 24.x + cache: pnpm + + - name: Enable Corepack + run: corepack enable + + - name: Install + run: pnpm install + + - name: Run linter + run: pnpm run lint diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..6b9fcd7 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,42 @@ +name: Tests + +on: + push: + # branches: [master, develop] + branches: [master] + pull_request: + # branches: [master, develop] + branches: [master] + +jobs: + tests: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Use Python + uses: actions/setup-python@v2 + with: + python-version: 3.x + + - name: Use Node.js + uses: actions/setup-node@v2 + with: + node-version: 24.x + cache: pnpm + + - name: Enable Corepack + run: corepack enable + + - name: Install + run: pnpm install + + - name: Run agent unit tests + run: pnpm run test:agent:unit + + - name: Run workflow unit tests + run: pnpm run test:workflow:unit + + - name: Run workflow e2e tests + run: pnpm run test:workflow:e2e diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6361a44 --- /dev/null +++ b/.gitignore @@ -0,0 +1,36 @@ +__pycache__/ +.idea/ +.fleet/ +.vscode/ +**/dist/* +**/build/ +**/node_modules/ +**/.venv/ +**/.last-skill-deps-sync +**/.last-source-deps-sync +skills/**/reports/* +test/coverage/ +**/tmp/* +core/config/**/*.json +scripts/out/*.md + +package-lock.json +*.pyc +.DS_Store +*.sublime-workspace +npm-debug.log +debug.log +# Keep ignoring a repo-root .env on the safe side. +.env +.last-native-node-modules-rebuild +bridges/nodejs/.last-nodejs-bridge-deps-sync +bridges/python/src/.last-python-bridge-deps-sync +tcp_server/src/.last-tcp-server-deps-sync +bridges/python/src/Pipfile.lock +tcp_server/src/Pipfile.lock +!bridges/python/**/.gitkeep +!bridges/nodejs/**/.gitkeep +!**/*.sample* +package.json.backup +.python-version +schemas/**/*.json diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 0000000..71d4290 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,19 @@ +image: gitpod/workspace-full + +tasks: + - before: npm install -g @leon-ai/cli + init: leon create birth + command: leon start + +ports: + - port: 1337 + onOpen: notify + +github: + prebuilds: + master: true + branches: true + pullRequests: true + addComment: true + addBadge: true + addLabel: true diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 0000000..39e63b7 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1 @@ +tsx scripts/commit-msg.js diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 0000000..c27d889 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +lint-staged diff --git a/.lintstagedrc b/.lintstagedrc new file mode 100644 index 0000000..2633255 --- /dev/null +++ b/.lintstagedrc @@ -0,0 +1,3 @@ +{ + "*.{js,jsx,ts,tsx,mjs,cjs}": ["eslint --fix --ignore-pattern .gitignore"] +} diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..b009dfb --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +lts/* diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..94491b3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,362 @@ +# [1.0.0-beta.8](https://github.com/leon-ai/leon/compare/v1.0.0-beta.7...v1.0.0-beta.8) (2023-05-01) / Binaries and TypeScript Rewrite + +_Please refer to [our latest blog post](https://blog.getleon.ai/binaries-and-typescript-rewrite-1-0-0-beta-8/) for more information on the new release of our dear Leon._ + +# [1.0.0-beta.7](https://github.com/leon-ai/leon/compare/v1.0.0-beta.6...v1.0.0-beta.7) (2022-08-24) / A Much Better NLP + +_Please [read this blog post](https://blog.getleon.ai/a-much-better-nlp-and-future-1-0-0-beta-7/) to know more about all the new features and the exciting future of Leon._ + +### BREAKING CHANGES + +- remove legacy packages [07743657](https://github.com/leon-ai/leon/commit/07743657cd2954e7f850c08eea7c032c24b28a96) + +### Features + +- create new NLP skills resolvers model + NLP global resolvers model [602604e4](https://github.com/leon-ai/leon/commit/602604e43788c6b6be8c402d54fe54342d0cd5d6) +- better isolate skill resolvers from global resolvers + finish up Akinator skill [905d248e](https://github.com/leon-ai/leon/commit/905d248ebf7e84b1ccc74450520228aef9a8804a) +- transfer language from core to skills + support thematics on Akinator skill [b35a249b](https://github.com/leon-ai/leon/commit/b35a249bf68000d6708aaee4abc4cd97f5b80035) +- actions on slot level + akinator skill progress [7101b8b4](https://github.com/leon-ai/leon/commit/7101b8b4b828b49e009da2fcdac7c5ed2e48c8f8) +- add Cartesian sample training on resolvers + enum entities [6ed88a59](https://github.com/leon-ai/leon/commit/6ed88a5946c77b356e49fe8b9cbe890b8dd1f037) +- map skills resolvers intents [eb5ade76](https://github.com/leon-ai/leon/commit/eb5ade76844dd14f5d5a5c5eeb434eed70fe62f4) +- train skills resolvers and remap as per changes [82df0a3c](https://github.com/leon-ai/leon/commit/82df0a3c235fbd50ad0cfe12e23a51f777dcd658) +- achieve Cartesian training [a1e9011d](https://github.com/leon-ai/leon/commit/a1e9011d5db48ed8e9f49cef2d813ee7e2400ec2) +- introduce suggestions [dcddacca](https://github.com/leon-ai/leon/commit/dcddacca2956529de0aea8ff98e1e6f16104966a) +- communicate suggestions to the client [4b5a8835](https://github.com/leon-ai/leon/commit/4b5a883510fd4421a491f999cc21d8f7dd369a03) +- shared skills memory [795acc5b](https://github.com/leon-ai/leon/commit/795acc5bdd29e9a27d1cf3b4407453648d573973) +- support dynamic variables on skill NLU settings for logic type [10d10a16](https://github.com/leon-ai/leon/commit/10d10a1690cb65970932ee7230e3f324ec67dbce) +- tmp resolvers mapping [b1a332ba](https://github.com/leon-ai/leon/commit/b1a332bab6af8b74a8c58c07bac3ef3a1cebad89) +- start to map resolvers between the core and skills [e88495a9](https://github.com/leon-ai/leon/commit/e88495a9a94e86026fd0c7c4c44f3ff06edb2e80) +- train affirmation and denial resolver [993d52e8](https://github.com/leon-ai/leon/commit/993d52e8686f335039ff3d5e2a82c1a37efb1825) +- Python TCP server and Node.js TCP client for IPC (wip) [5970ec9e](https://github.com/leon-ai/leon/commit/5970ec9e8e4c2784c50e2ddc76b34b71aa4310e6) +- introduce spaCy for complete NER (wip) [caa86fc8](https://github.com/leon-ai/leon/commit/caa86fc8a6850b18f67ba7bedb423be693a88d17) +- slot filling (wip) [76547d94](https://github.com/leon-ai/leon/commit/76547d9411c32e0eb2ccfdac3a4901d2d2fb37f6) +- share data across domains [f4f9fff9](https://github.com/leon-ai/leon/commit/f4f9fff9783861be183990d7869973c7a30c8104) +- dynamic variable binding on NLG [0367b44f](https://github.com/leon-ai/leon/commit/0367b44f211c1629fffe6981a730f171707bf0c0) +- context and slot filling preparation (wip) [975b8ebc](https://github.com/leon-ai/leon/commit/975b8ebcf00db91b44dd067be6dde5c1bf32fff1) +- annotate entities on the fly + prepare for dialog skill type and cross-domains data [4107932d](https://github.com/leon-ai/leon/commit/4107932d000086188d6f44ef67b73cc322fc58e5) +- new NLP training [d8023308](https://github.com/leon-ai/leon/commit/d8023308d0ef1f3eede37f21f45daa2f893031b0) + +- **server:** + - trigger next action suggestions or current ones [244d08c0](https://github.com/leon-ai/leon/commit/244d08c0bd0fea315269f52ab899f9b7fe083f51) + - introduce main NLP model and resolvers NLP model [e37526d9](https://github.com/leon-ai/leon/commit/e37526d9056d858ebcf17b81f6714f47b67c77cb) + - change log emojis [843bc428](https://github.com/leon-ai/leon/commit/843bc428b8deb397e2d051a8e0bfaf1b82b459a2) + - provide nextAction even when no slot is set and clean up NLU object on context switch [8377c63d](https://github.com/leon-ai/leon/commit/8377c63db4e4e42ed929171cd8b9abdb13c44b2a) + - report full traceback from skills execution [b69b1fea](https://github.com/leon-ai/leon/commit/b69b1fea16250421bc7d5def1c973dd43e453071) + - support on-the-fly entity annotation for built-in entities [567b030c](https://github.com/leon-ai/leon/commit/567b030c4fcf8df266c39cca61a146fb33b9e0fc) + - save slots within conversation context [fce47cdb](https://github.com/leon-ai/leon/commit/fce47cdbd570993ac5cca2b4ff5bc97969df4e40) + - resolve resolvers tmp [ceea47ff](https://github.com/leon-ai/leon/commit/ceea47ff7dd536bfd3adf3cc355e90e3e94b1cbd) + - prepare the next action on non-slot-filled skills [0acb31a9](https://github.com/leon-ai/leon/commit/0acb31a9c61c1c094b29f3d0ff2647d625eab0be) + - add more affirmative utterance samples [870ab2e8](https://github.com/leon-ai/leon/commit/870ab2e87eba2c548d38dc90d30553e7fa380c1e) + - restart a skill with the original utterance saved in context [f4446ef1](https://github.com/leon-ai/leon/commit/f4446ef17796d38d0f98d5b7e889503622a1a998) + - clean up context if the action loop does not meet the expected items [035c9d52](https://github.com/leon-ai/leon/commit/035c9d5240472ac19a84ae8c1a87844fa0d0af5d) + - add handsigns custom entity [1529c720](https://github.com/leon-ai/leon/commit/1529c72039092c7b8f37304d6064e04f2dc7b795) + - reprocess NLU in case of slot filling interruption [9e242d77](https://github.com/leon-ai/leon/commit/9e242d77d32109e9355eec422790a5a66fd18f9c) + - handle action loop when slots have all been filled at once [f8830502](https://github.com/leon-ai/leon/commit/f88305020a5bc79056b7ff9c1a31f8d3c3a7cdce) + - break the action loop from the skill [27dc801c](https://github.com/leon-ai/leon/commit/27dc801cf53de5af3d54b95f42d2b9e627090867) + - stop action loop from skill to core [99681e25](https://github.com/leon-ai/leon/commit/99681e257795a18361be379b93244088401f640b) + - introduce basic concept of action loop [c5b38400](https://github.com/leon-ai/leon/commit/c5b38400821e5bc5edc4402d007f815f24319d44) + - prepare action loop feature [19e1aa22](https://github.com/leon-ai/leon/commit/19e1aa22f6e989e90eb745e3a7b7ccb8ff5adbfa) + - add current utterance entities to differentiate from the whole context [8b56a185](https://github.com/leon-ai/leon/commit/8b56a1850c9d76e335f1bad1b4395d73ddc5ea19) + - when a context is activated, pick up the most probable classification [8e186879](https://github.com/leon-ai/leon/commit/8e1868798c8750c19b1719a44dc6fb8bca68b250) + - persist entities into contexts [87575773](https://github.com/leon-ai/leon/commit/875757739f6701f54805eeff2c7c350cff36c4ac) + - forward slots to skill + add original utterance [68e40f65](https://github.com/leon-ai/leon/commit/68e40f65df0d1fe29ccad991868a2408c6e1015e) + - handle case when all slots have been filled in one utterance [22e9234b](https://github.com/leon-ai/leon/commit/22e9234b3d2c97e83eaafaeeb5aa9d27c351c95a) + - trigger next action once all slots have been filled [9b870010](https://github.com/leon-ai/leon/commit/9b870010dd929bc1aed6d87696f1cc4e9f177c0b) + - complete slot filling before triggering the next action [9124687e](https://github.com/leon-ai/leon/commit/9124687eb0e17295a30f860752ee622ba44d1440) + - from modules to skills with type at the actions level [77ebaf4a](https://github.com/leon-ai/leon/commit/77ebaf4a9c78b2e471d39872e361ea05b163580d) + - verify if all slots are filled [e27c1b9c](https://github.com/leon-ai/leon/commit/e27c1b9c8f5c2f668f464f152ad227d65ba5ef6b) + - context and slot filling, keep context and await for entities [25adf406](https://github.com/leon-ai/leon/commit/25adf406c810e48b1277105dd6c269a2ed601d28) + - unstack oldest context [1ece25a4](https://github.com/leon-ai/leon/commit/1ece25a497acc9f9876fe158ace5da38beec31e6) + - context setup with slot for each conversation (wip) [8257eb87](https://github.com/leon-ai/leon/commit/8257eb8792c9f4fc90bcc1b393d3fddf8ff541dc) + - resolve slots from slot filling [960a6dc7](https://github.com/leon-ai/leon/commit/960a6dc71c2efb50ad6a8448d447ebd79c559c41) + - pickup questions for slot filling [3bbc2f8a](https://github.com/leon-ai/leon/commit/3bbc2f8a254d10f0c37cdb7abf016b3e418f594a) + - main slots structure (wip) [1d9b1809](https://github.com/leon-ai/leon/commit/1d9b18093b6e042ae49f557149a7822b4420cdb8) + - introduce resolvers for slot filling (wip) [334bf393](https://github.com/leon-ai/leon/commit/334bf393f2c43edd326d9de2e93c037ffeebeab5) + - slot filling PoC (tmp wip) [95bfcfe4](https://github.com/leon-ai/leon/commit/95bfcfe422f21a2946e50031a3623675dfe81b9d) + - slot filling (wip) [969a83e6](https://github.com/leon-ai/leon/commit/969a83e6081de20ec5e2bdd0329a21a3fe448f13) + - trigger unsupported language [1845eed7](https://github.com/leon-ai/leon/commit/1845eed71dadd5f693d76abd7633864014bf8af1) + - context (wip) [d1c2a11d](https://github.com/leon-ai/leon/commit/d1c2a11d8284ca4e1d4563b871c50c006e8ef8a0) + - context (wip) [a9a43ac4](https://github.com/leon-ai/leon/commit/a9a43ac478c46f3832d2af49c287bb574a70cc14) + - differenciate cities from countries for location entities [bf9bf231](https://github.com/leon-ai/leon/commit/bf9bf231f714e1edc1417e43af12fa54c00ba064) + - auto restart the TCP server when language is switching [9be7c700](https://github.com/leon-ai/leon/commit/9be7c700767672ac6e0c875d3b5ae7fa6414e4fa) + - support multi languages on TCP server [a808742c](https://github.com/leon-ai/leon/commit/a808742c927d45c18df45af133e67c98d4a0415a) + - add auto reconnect on TCP client [cbe89ed6](https://github.com/leon-ai/leon/commit/cbe89ed6ccfd727356eb34078a8a4348b2fd696f) + - make TCP client global [006e9fb0](https://github.com/leon-ai/leon/commit/006e9fb01148c2107f6acc6a562ace4809da92be) + - fully implement low-level networking for IPC [8acb82da](https://github.com/leon-ai/leon/commit/8acb82da9bacdb9b7952c4a4d130d094e07def5e) + - more accurate NLG [d5577b1e](https://github.com/leon-ai/leon/commit/d5577b1ef5cf1b8b4a924636ba4425b8b4ae133d) + - unknown_answers fallback on dialog type [28efe6e7](https://github.com/leon-ai/leon/commit/28efe6e7d542f19bf12ddede1815f7fa8cf01036) + - deep data mapping on enum NER [3ca48265](https://github.com/leon-ai/leon/commit/3ca48265e7115c8e0f02c65ba92d90412325ad76) + - NLG and entities mapping [8f2f935b](https://github.com/leon-ai/leon/commit/8f2f935b949ceb965941460d4ff1ed0084b72442) + - bootstrap skill structure [fe90c68e](https://github.com/leon-ai/leon/commit/fe90c68ea0e9b0e857b62aa9f3b0a42ba1ffed6b) + - on-the-fly language switching [f24513a2](https://github.com/leon-ai/leon/commit/f24513a22395d1903e485883f4813cdceccdbd18) + - new NLP containers [34b2aa56](https://github.com/leon-ai/leon/commit/34b2aa5655e55284d59db4569960c49965a0483c) + - (WIP) NLU refactoring [ca3f5f42](https://github.com/leon-ai/leon/commit/ca3f5f42da26eb634e10b56e9b84bd45b5543024) + - add skills domains [cf2a28aa](https://github.com/leon-ai/leon/commit/cf2a28aac2d936cc15e6aa9aa13747015d952053) +- **skill/akinator:** + - finish up [79e7df02](https://github.com/leon-ai/leon/commit/79e7df022f7daedf43db7f892e049a31924ce985) + - finished main business logic [76cae42f](https://github.com/leon-ai/leon/commit/76cae42fdeac0edcd3ebd6aa7718728617687b1b) + - backbone [02a2f714](https://github.com/leon-ai/leon/commit/02a2f71470bb4c0c6ca04526e89461d863d17145) +- **skill/birthday:** + remove birthday skill [be0b345d](https://github.com/leon-ai/leon/commit/be0b345d3f7fea562548e3fbed62b65c32eff4c0) +- **skill/color:** + introduce color skill [ce00989b](https://github.com/leon-ai/leon/commit/ce00989b01f65c5cbb5a2e13f454207c1ba7741c) +- **skill/guess_the_number:** + introduce the Guess the Number skill [fba80966](https://github.com/leon-ai/leon/commit/fba80966c937a32182e48670c47358babb539d64) +- **skill/introduction:** + - add one utterance sample [af0fdd1e](https://github.com/leon-ai/leon/commit/af0fdd1e18975bf8b60abb2957ddf79831281817) + - ask about owner info if necessary [c5cc9bdd](https://github.com/leon-ai/leon/commit/c5cc9bdd52afaaa710f9476d1e9918f3d168e243) +- **skill/mbti:** + - complete form resolver [aad9f3f1](https://github.com/leon-ai/leon/commit/aad9f3f1ef61499d438ea40c9d2d95764667678d) + - finish business logic [99a3f103](https://github.com/leon-ai/leon/commit/99a3f103e00b5a58745ee851d2fa95c61871f75a) + - questions mapping [ae4f69f7](https://github.com/leon-ai/leon/commit/ae4f69f7c7189ff75e004f68c9a2a8b6bb37b6bd) + - complete questionnaire [7f1f8871](https://github.com/leon-ai/leon/commit/7f1f8871598746c5475b24e086ea6e581f2a988e) + - main logic backbone [33109a4c](https://github.com/leon-ai/leon/commit/33109a4c8b5df82e7b98e48e66f8d53f0cc114fb) + - main NLU structure [skip ci] [86d5040a](https://github.com/leon-ai/leon/commit/86d5040a7dc2006036c7e67a2cf54a4c992e64aa) +- **skill/rochambeau:** + - add start answers [192dd0a8](https://github.com/leon-ai/leon/commit/192dd0a87ab5dc025bb90b20b187e36a58be54ea) + - introduce paper scissors rock [57370470](https://github.com/leon-ai/leon/commit/573704706c843d870f2498146bc3cd659bab4f06) + - init [7f5e30ac](https://github.com/leon-ai/leon/commit/7f5e30ac82f2a2d7579e361229a4044348915867) +- **web app:** + - join us on Discord [141c89ec](https://github.com/leon-ai/leon/commit/141c89ecbfd329a8e63d5a603d0ae6b42f9abf38) + - wait for TCP client to be connected first [bc228a68](https://github.com/leon-ai/leon/commit/bc228a68600c07871c489d6624bbc837971079a6) + ### Bug Fixes +- check script with new intent-object format [fdf0a389](https://github.com/leon-ai/leon/commit/fdf0a389b76caba5dd47996a43a34c0c7821c70a) +- check new resolvers paths [cfd8f7cb](https://github.com/leon-ai/leon/commit/cfd8f7cbe5e8fd9ce3d1659c725d7af261db8d71) +- use ports.ubuntu.com mirror for the offline TTS [skip ci] [3dd90396](https://github.com/leon-ai/leon/commit/3dd9039678820fceb7ccbb1c96358c8d2f188ede) +- set skill config only when a bridge is set [7513aa7d](https://github.com/leon-ai/leon/commit/7513aa7d20fee1fe9ca5442a7909d22fd1c3b39e) +- only set skill config when it is a logic type [9ce9a8bc](https://github.com/leon-ai/leon/commit/9ce9a8bc4fe0864730a08d8e9a436982f1365aa5) +- **docker:** + - usage of Ubuntu base image with pyenv and nvm (#408) [f507f6f7](https://github.com/leon-ai/leon/commit/f507f6f7e499f56768b3e624164cbcd58193b153) + - check should not allocate a pseudo-TTY (#359) [4372b45f](https://github.com/leon-ai/leon/commit/4372b45fc605893d4130cf7110dd87519b934345) +- **server:** + - make leon handle multiple socket.io-client instances [6e7c0aac](https://github.com/leon-ai/leon/commit/6e7c0aac57008b152b45f1b0f3886ae38777467b) + - fallback on global resolver during resolver classification [ec77dd0f](https://github.com/leon-ai/leon/commit/ec77dd0f02a8ae94fb3f02c7b7847b5509d71406) + - make use of current entities to match global entities [a8d82050](https://github.com/leon-ai/leon/commit/a8d82050c86b5c24c4c898c06e5ffc3882524c0b) + - multiple slots filling [2ac1bc63](https://github.com/leon-ai/leon/commit/2ac1bc63ccd11757d586adfb2e75ce04e3ffbcb5) + - context switching on action loop [6712ae55](https://github.com/leon-ai/leon/commit/6712ae5539ef44ed33e360cfcad71c760c4b13b1) + - check one-shot slot filling case causing infinite loop [782a3aaa](https://github.com/leon-ai/leon/commit/782a3aaa0a07dda667557bc84db906b3fa9b237c) + - clean up active context after all slots have been filled [faabc2c7](https://github.com/leon-ai/leon/commit/faabc2c7b0992fcea035eedf66103d84b101e1a7) + - correctly extract all spaCy entities [6aa60bfb](https://github.com/leon-ai/leon/commit/6aa60bfbd8c72e678fe3faf5e7f9dbd37dfd209f) + - intent not found [8280c658](https://github.com/leon-ai/leon/commit/8280c65897dba0fe470a3589d151b391c51e344e) + - fallback due to modules to skills refactoring [ef0c54b2](https://github.com/leon-ai/leon/commit/ef0c54b22667ef2bd1d2c07003f6b4beb5fa25c0) + - NER due to modules to skills refactoring [e4d3904c](https://github.com/leon-ai/leon/commit/e4d3904ceeb2a3ee2c0187a1817331fac916e1a7) + - **skill/akinator:** + remove direct end on guess action [f6461f73](https://github.com/leon-ai/leon/commit/f6461f733b4a5d944dfa4a987dd1109628c6cbca) + - **skill/color:** + more appropriate answer [cb18ed63](https://github.com/leon-ai/leon/commit/cb18ed6397cb0e0ad8fbea30c57d7d40137441ee) + - **skill/rochambeau:** + final logic [0ebc0518](https://github.com/leon-ai/leon/commit/0ebc0518e61b899c35dd13df65a43f69399e784d) + ### Performance Improvements +- check Pipfile instead of Pipfile.lock to judge whether Python packages must be installed [afdb71f7](https://github.com/leon-ai/leon/commit/afdb71f766f2956c5cb4a5e0be9025340d1a89db) + +### Documentation Changes + +- change newsletter link [4bf2a9af](https://github.com/leon-ai/leon/commit/4bf2a9af963f75aeff96f4a43da8ec1024ac583a) +- README - Edited sentence for clarity (#389) [e83a1c42](https://github.com/leon-ai/leon/commit/e83a1c4230897e8b63251ef86225cf773148c38e) +- edit newsletter link [fa558a44](https://github.com/leon-ai/leon/commit/fa558a447ade4071f352d56f14602690ed90f521) +- update sponsor [skip ci] [f30ddb6b](https://github.com/leon-ai/leon/commit/f30ddb6be5f531df2b0042be0ed5ffbe79f73b07) +- remove sponsor [skip ci] [5dbc010f](https://github.com/leon-ai/leon/commit/5dbc010fa643279a24081f3148022e2211af63f4) +- remove sponsor [skip ci] [f36dd20f](https://github.com/leon-ai/leon/commit/f36dd20f822cd33c9e8a03efc2849c8d8d1fc75e) +- remove sponsor [skip ci] [5ee57ddf](https://github.com/leon-ai/leon/commit/5ee57ddf2a9f7817ec35b2e70d49e5bb422d8f78) +- add @ant-media sponsor [skip ci] [b47cbc3a](https://github.com/leon-ai/leon/commit/b47cbc3a5ecb6591f7abb4f62feae8102b9a6468) +- add long dev notice to README [skip ci] [499be77d](https://github.com/leon-ai/leon/commit/499be77d509231b853f591e27f726381da5a50d8) +- move sponsor to new section [skip ci] [8825d687](https://github.com/leon-ai/leon/commit/8825d6877c19d86495e89a858b859b7ab1f9ae37) +- change Twitter handle [skip ci] [c1afc11c](https://github.com/leon-ai/leon/commit/c1afc11cdb283526540d0fecdf83efddf3f3a9f7) +- remove sponsor [skip ci] [99b401a6](https://github.com/leon-ai/leon/commit/99b401a668a6fb248e33c22782940402be7c9b17) +- add new sponsor self-hosted img [skip ci] [238d928c](https://github.com/leon-ai/leon/commit/238d928cace13d4ecd174ca14b136967d8845e0f) +- remove new sponsor link (broken) [skip ci] [254f2848](https://github.com/leon-ai/leon/commit/254f2848aab622b79cce16d10c58d53ff6db9a8f) +- in GitHub BUG.md from modules to skills [4a5480a3](https://github.com/leon-ai/leon/commit/4a5480a3ccc54ee34d42f6edcec2a40224dee7ed) +- change @FluxIndustries sponsorship [skip ci] [1a118b71](https://github.com/leon-ai/leon/commit/1a118b718e5d4ade123756ac94758a01c50b12ae) +- add @FluxIndustries sponsor [skip ci] [9a604d7c](https://github.com/leon-ai/leon/commit/9a604d7ccc0c6aaec257299078141dd0c3077933) +- new #LeonAI link [skip ci] [a0107d62](https://github.com/leon-ai/leon/commit/a0107d629473f7fd057d367926e83822d46f1227) +- changelog new version diff link fix [skip ci] [e14c2498](https://github.com/leon-ai/leon/commit/e14c249826db92af7b85422e566be6aa834a7fb7) + +# [1.0.0-beta.6](https://github.com/leon-ai/leon/compare/v1.0.0-beta.5...v1.0.0-beta.6) (2022-02-07) / Leon Over HTTP + Making Friends with Coqui STT + +### Features + +- simple coqui-ai stt integration [86a4816b](https://github.com/leon-ai/leon/commit/86a4816b777fee8ec9c89648c5866a75de56c017) +- HTTP API key generator [d10a7fa7](https://github.com/leon-ai/leon/commit/d10a7fa7880a0bf2fb1cae7904d1ef4257f05257) +- avoid unnecessary routes generation + +- **server:** + - make Coqui STT the default STT solution [70399187](https://github.com/leon-ai/leon/commit/7039918760c0ef7ba93bf45820e3cae774c42d8c) + - add HTTP API key middleware [cdf41499](https://github.com/leon-ai/leon/commit/cdf4149939cbe3f3ae81039957dba3377a78f5a6) + - expose queries over HTTP [b6428d03](https://github.com/leon-ai/leon/commit/b6428d038452619f1682c863892cd8f376efca84) + - add timeout action over HTTP [115f9c16](https://github.com/leon-ai/leon/commit/115f9c164559d761625cc6f362749f7d2417d300) + - handle built-in and trim entities over HTTP + add "disabled" HTTP API action option [82fb967a](https://github.com/leon-ai/leon/commit/82fb967af8f49421e3b2474184da3d34fb17294f) + - execute modules over HTTP [2e5b2c59](https://github.com/leon-ai/leon/commit/2e5b2c59da0bafe3acd966773c6fac3611b3bd0c) + - generate Fastify routes on the file to expose packages over HTTP [5b41713a](https://github.com/leon-ai/leon/commit/5b41713a68ee628e695212dbebc88f6b9a94b461) + +### Bug Fixes + +- do not ask to regenerate the HTTP API key if this one isn't available yet [d265377a](https://github.com/leon-ai/leon/commit/d265377a43fd4506cf12db46f261b891f2054ed2) +- Python deps tree check [c6c01291](https://github.com/leon-ai/leon/commit/c6c012915824227efdf0c50df6a8f1cd8d70ed42) +- hotword offline (#342) [f563d01d](https://github.com/leon-ai/leon/commit/f563d01d077499c836e94c86f85cedc2ad4d56e6) +- addressed comments by @JRMeyer [b1c6f5c8](https://github.com/leon-ai/leon/commit/b1c6f5c883103d57d4fe566af640fc3ac5ce713d) +- allow to detect STT offline capabilities [04d62288](https://github.com/leon-ai/leon/commit/04d622884165e0bde65785569a659f59cf9e8582) +- Amazon Polly is always configured on check script due to new structure [e6246d1f](https://github.com/leon-ai/leon/commit/e6246d1f8f9ec15a4ebe9600764afffbaa7e62d9) + +### Performance Improvements + +- check if Python deps tree has been updated before going through deps install [2d0b0f13](https://github.com/leon-ai/leon/commit/2d0b0f1365d8e4d6eadf9f7cc0a16b7b4b4306f4) + +# [1.0.0-beta.5](https://github.com/leon-ai/leon/compare/v1.0.0-beta.4...v1.0.0-beta.5) (2021-12-28) / Refocus + +_This release marks a major turn in the future versions of the Leon core. Please [read this blog post](https://blog.getleon.ai/i-ran-away-from-open-source/) to know more._ + +### BREAKING CHANGES + +- Node.js 16+ and npm 8+ minimum requirements [2f66f1c1](https://github.com/leon-ai/leon/commit/2f66f1c17bb2e4a1c18b4251d49de252b8d87344) + +### Features + +- **server:** support arrays on NER between conditions [7cf7f979](https://github.com/leon-ai/leon/commit/7cf7f9791254e1950fe9128ce1b3a58079cc2ada) + +### Bug Fixes + +- jest-extended new setup due to latest update [02f766d6](https://github.com/leon-ai/leon/commit/02f766d6a8453609ebaec78356aa6e6d4df0967b) + +### Performance Improvements + +- Windows setup on DeepSpeech dep removal [13f5a49f](https://github.com/leon-ai/leon/commit/13f5a49f678f8f67a93b67d4f558cddcf237e204) + +### Documentation Changes + +- URL redirect managed by registrar [c16d5b28](https://github.com/leon-ai/leon/commit/c16d5b280b758f7e18305e30678adec79f0a0716) + +# [1.0.0-beta.4](https://github.com/leon-ai/leon/compare/1.0.0-beta.2...v1.0.0-beta.4) (2021-05-01) / Getting Rid of Dust + +_This release includes a lot of changes that are made under the hood and are not displayed here, please **[read the blog post](https://blog.getleon.ai/getting-rid-of-dust-1-0-0-beta-4/)** to know more._ + +### BREAKING CHANGES + +- **package/checker:** introduce Have I Been Pwned v3 API with API key ([0ca89fe3](https://github.com/leon-ai/leon/commit/0ca89fe32d51c80cec5f9446acf14990390a5917)) +- **server:** + - AWS SDK new structure due to v3 and adapt Amazon Polly changes ([f15f2db7](https://github.com/leon-ai/leon/commit/f15f2db78e5781d05e5e2bcb186645966d17debf)) + - IBM Watson TTS and STT new structure ([f41ea0e9](https://github.com/leon-ai/leon/commit/f41ea0e9a1479bfd6a1cb2e8d1f70aec744c685b) | [2668c295](https://github.com/leon-ai/leon/commit/2668c295880ee753ef7ca26a91dbc7e0901febff)) + +### Features + +- **package/calendar:** introduce To-Do list module ([0cdd73d6](https://github.com/leon-ai/leon/commit/0cdd73d6c24a287915f691e3b12edacd75fd383a) | [857be947](https://github.com/leon-ai/leon/commit/857be947792c650ac35847e14fc41064008cef24) | [2041be14](https://github.com/leon-ai/leon/commit/2041be14dbc01640a61de96d1982cc20cd05a8b3) | [12e8f5c3](https://github.com/leon-ai/leon/commit/12e8f5c3bfb436aa212557cd99d9926aa431ab4f) | [8575e9e3](https://github.com/leon-ai/leon/commit/8575e9e3ef01499d9f7be6d313a85d48549e9107) | [5e128df0](https://github.com/leon-ai/leon/commit/5e128df023977525de3e66ce2826aace87569308) | [602aa694](https://github.com/leon-ai/leon/commit/602aa694ac49333f48c119cf2ca2aa7f54b8ae44) | [b9693df9](https://github.com/leon-ai/leon/commit/b9693df90cbc01067e18e64db4d377e41b3fd1d4) | [581da8cd](https://github.com/leon-ai/leon/commit/581da8cd9806323aabb0e85778d645df3c0948b9) | [53f7db55](https://github.com/leon-ai/leon/commit/53f7db55c6e916751f1d59c239628d5ea8914009) | [ae073971](https://github.com/leon-ai/leon/commit/ae0739717b6a17373d8f9bc69571c67c1c571b4a)) +- **package/checker:** introduce Have I Been Pwned module ([61c1b55a](https://github.com/leon-ai/leon/commit/61c1b55af5691c03f6a6dae0cf3f236a374f1fe7) | [5a999bc6](https://github.com/leon-ai/leon/commit/5a999bc63aa0c667c4e3092daac6a05a6c4b4499) | [36368664](https://github.com/leon-ai/leon/commit/36368664fce8bcf0c17c4c83818aeb418f1e2f23) | [a7a6d885](https://github.com/leon-ai/leon/commit/a7a6d885a83455163eeca74a355177d65db156b8) | [c73ba52b](https://github.com/leon-ai/leon/commit/c73ba52ba8575a64b3329e59a50050d15281d0ec) | [8374e548](https://github.com/leon-ai/leon/commit/8374e5481022de9b134f49180a8dfe28db136261) | [a476fd0f](https://github.com/leon-ai/leon/commit/a476fd0f38f18bf8035db213be2c55f83871038d)) +- **package/network:** add speedtest module ([09ad4340](https://github.com/leon-ai/leon/commit/09ad43406d3df8ca65f385a91c159def51f91811)) +- **server:** + - add regex entity type [3fda3526](https://github.com/leon-ai/leon/commit/3fda3526c7425bdea4b669474fa77efd61c06a8e) + - catch unsupported action entity type [5bc6c3f1](https://github.com/leon-ai/leon/commit/5bc6c3f116d6b9ece2cc3bebdbdb08f019ee90b9) + - NER backbone [24cf3c9a](https://github.com/leon-ai/leon/commit/24cf3c9a4facd05a4c626ff9d2e7c83a5ae15298) + - introduce actions module [b449376f](https://github.com/leon-ai/leon/commit/b449376f61dc995e2e264c6a14ba123926f5cc58) + +### Bug Fixes + +- set correct status code for GET /downloads [690f1841](https://github.com/leon-ai/leon/commit/690f1841d681a1e48e1837e3e166228d6c2ddaf6) +- take `.env` in consideration when using Docker [d38e6095](https://github.com/leon-ai/leon/commit/d38e6095f9b71467b8486430fba4bb7007ec4c5a) +- spinner test [9071c927](https://github.com/leon-ai/leon/commit/9071c92790be674687590e4a896bbf44bc26fb43) +- e2e tests by adding modules actions level [5cf77d90](https://github.com/leon-ai/leon/commit/5cf77d9011a80b326f229b2309a6910ac0f1cfa2) + +- **package/leon:** fix english translations [90225707](https://github.com/leon-ai/leon/commit/90225707f94154021cadeb9c61bdc48c3de5aa29) +- **package/network:** make use of new compatible speedtest lib [0c925626](https://github.com/leon-ai/leon/commit/0c925626df65858fa039972b3f3d5f38fde93eb6) +- **package/trend:** + - GitHub module new scraping [68414937](https://github.com/leon-ai/leon/commit/6841493740ca859000c1fd8d692b73fc79fcf500) + - when there is no star provided on the GitHub module [563fb409](https://github.com/leon-ai/leon/commit/563fb40955e2deb5c6d0bd064fc9cc8766a6fcaf) +- **server:** + - make use of Basic plugin from the main NLP container [e1d5bed3](https://github.com/leon-ai/leon/commit/e1d5bed3e688db566a0cb803dda5c2d57c599d8c) + - NER trim entity on after conditions [fa6a5a43](https://github.com/leon-ai/leon/commit/fa6a5a43a60b493aa403a44957082382494c129b) + +### Documentation Changes + +- add minimum Pipenv version requirement to README [72e46bd6](https://github.com/leon-ai/leon/commit/72e46bd6c175a4a149fb6b14522823b224d7c152) +- hunt broken links [b2a22792](https://github.com/leon-ai/leon/commit/b2a2279243e7566b57fb7f696024bdf08294e853) +- add "ci" commit type in CONTRIBUTING.md [09e2672b](https://github.com/leon-ai/leon/commit/09e2672b0b399f5ce9dd7cd446d04f4d6fd7c13a) +- use emojies in README [0ea7a78b](https://github.com/leon-ai/leon/commit/0ea7a78b7c94dc44c992913ae1c90fb1cf8a7692) +- add social badges to README [c55c7532](https://github.com/leon-ai/leon/commit/c55c7532b25bf420c4819be71b0f9c21ccc58711) +- Node.js 14 requirement [d1034bd1](https://github.com/leon-ai/leon/commit/d1034bd135fd5a6314a1571d4088fd85a8e6a1da) + +# [1.0.0-beta.2](https://github.com/leon-ai/leon/compare/1.0.0-beta.1...1.0.0-beta.2) (2019-04-24) + +### Features + +- can send custom HTTP headers + ([2685cdab](https://github.com/leon-ai/leon/commit/2685cdab07cc1a9ea418eab812e5163d2dd0da90)) +- allow HTML output + ([ec3f02df](https://github.com/leon-ai/leon/commit/ec3f02dfaf2f4b7623ce350350ebee28cf18740e)) +- NLU improvement with node-nlp + ([6585db71](https://github.com/leon-ai/leon/commit/6585db718ccae1d750a35783075cf61cc8fe84f1)) + +- **package/trend:** + - add answer when the Product Hunt developer token is not provided + ([f40b479b](https://github.com/leon-ai/leon/commit/f40b479b295247c5a8a0e6ed81afe56fadfd2730)) + - Product Hunt module done + ([37794306](https://github.com/leon-ai/leon/commit/3779430621bef970be0e8d048eb0b4bf160ae8a4)) + - basics done on the Product Hunt module + ([32cc7dbe](https://github.com/leon-ai/leon/commit/32cc7dbe36592fb9618d9c10da5f05a4be7e41b6)) + - complete dedicated answers according to the technology and given time + ([8997d691](https://github.com/leon-ai/leon/commit/8997d6917445f837c9647a5a9b4d6998d2df4952)) + - GitHub module done + ([7c6f3922](https://github.com/leon-ai/leon/commit/7c6f3922f299193ee0fb54d0fc97f8b436fc706b)) + - be able to choose a limit and a date range for the GitHub module + ([3c088371](https://github.com/leon-ai/leon/commit/3c0883716e1c10371c399843a578095a1e16781d)) + - format GitHub results in one message + ([9d026b94](https://github.com/leon-ai/leon/commit/9d026b94efa8871d421ae2b593b96622a98537ac)) + - simple GitHub module results + ([5baec074](https://github.com/leon-ai/leon/commit/5baec07455f453d4ad003f1da360b2663b7e15e0)) + - list GitHub trends in HTML raw + ([3441629e](https://github.com/leon-ai/leon/commit/3441629e3cde933b322cb114d9f1bc3ef0eb3944) | [6b932e94](https://github.com/leon-ai/leon/commit/6b932e947fc365ea6435fda798b7cca32708b443)) + - expressions dataset and structure + ([f406a5a0](https://github.com/leon-ai/leon/commit/f406a5a09894e12c56a1e76dda609adada00b0d7) | [f54c2272](https://github.com/leon-ai/leon/commit/f54c2272b4b4dc5c56b512b0ccc1519d77ef15a3)) + +### Bug Fixes + +- Leon was not fully installed with Docker if a `.env` file was existing + ([c8a68ab0](https://github.com/leon-ai/leon/commit/c8a68ab02eec9ddaf803b6e36cd7e91a4989cdea)) + +- **package/trend:** + when there is no contributor on GitHub module + ([d845e49b](https://github.com/leon-ai/leon/commit/d845e49b0f18caeb306e2d399c50a03883b2f55d)) +- **server:** + - skip Pipenv locking until they fix it + ([029381e3](https://github.com/leon-ai/leon/commit/029381e3256933f37f5c2950c4eb1f0192f55ec6) | [ecfdc73f](https://github.com/leon-ai/leon/commit/ecfdc73f8290dd9e1910df9519095516a1227763)) + +### Documentation Changes + +- add `What is Leon able to do?` section in the readme + ([87f53c91](https://github.com/leon-ai/leon/commit/87f53c91368141966959f3ad7299bb7b643828a5) | [d558fc8b](https://github.com/leon-ai/leon/commit/d558fc8b7c6494babf5dec799802227f77c33d8a)) +- open-source != open source + ([16a9372e](https://github.com/leon-ai/leon/commit/16a9372e05d4d31a7a39a65a52d4708b72499d4c) | [2155cd88](https://github.com/leon-ai/leon/commit/2155cd88decbbd671bd58840291d9330ce06ebba)) + +# [1.0.0-beta.1](https://github.com/leon-ai/leon/compare/1.0.0-beta.0...1.0.0-beta.1) (2019-02-24) + +### Features + +- add Docker support + ([209760db](https://github.com/leon-ai/leon/commit/209760dba747001300692fb6a6af97543de584d6)) + +### Bug Fixes + +- **package/checker:** + isitdown module fails with capital letters in URL + ([ada6aaef](https://github.com/leon-ai/leon/commit/ada6aaef4bada47e87d28f9f6eaa05b9e23f58d2)) +- **web app:** + enable environment variables + ([a438d6f9](https://github.com/leon-ai/leon/commit/a438d6f942812f74e3dda75a9875609f8bea21cd)) + +### Performance Improvements + +- **web app:** + favicon compression + ([33dbcb42](https://github.com/leon-ai/leon/commit/33dbcb425eaafba90176ff64e5f689eb36bc6ce1)) + +### Documentation Changes + +- update README to make the reader genderless + ([58662658](https://github.com/leon-ai/leon/commit/586626586b7a2f84cb2cd84028111976bc5172f0)) +- use "to rule them all" in README + ([c74dda4c](https://github.com/leon-ai/leon/commit/c74dda4cb9acc78de143ae01fdc6b4ef0a5ec3ef)) + +- **readme:** + add story write-up + ([08a68e37](https://github.com/leon-ai/leon/commit/08a68e376b6a9367425947380564120943376500)) + +# [1.0.0-beta.0](https://github.com/leon-ai/leon/compare/https://github.com/leon-ai/leon.git...1.0.0-beta.0) (2019-02-10) + +Initial release. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..2d4f245 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-present, Louis Grenard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c4e4563 --- /dev/null +++ b/README.md @@ -0,0 +1,183 @@ +

+ +

+ +

+ Leon
+ Leon +

+ +_

Your open-source personal AI assistant.

_ + +

+ + +

+ +

+ I share Leon progress most regularly on X / @grenlouis +

+ +

+ Follow progress on X / @grenlouis · + Website · + Newsletter · + Roadmap · + Story +

+ +--- + +## ⚠️ Important Notice (as of 2026-03-29) + +> [!IMPORTANT] +> Leon is currently focused on the **2.0 Developer Preview** on the `develop` branch. +> +> - The new documentation is **not ready yet**. +> - The current docs site and older guides mostly reflect the legacy architecture. +> - If you want the legacy, more stable pre-agentic version of Leon, use the `master` branch. +> - If you want to explore or contribute to Leon's new core, `develop` is the right place. + +The most accurate high-level references for Leon's current state are: + +- [`core/context/LEON.md`](./core/context/LEON.md) +- [`core/context/ARCHITECTURE.md`](./core/context/ARCHITECTURE.md) + +## 👋 Introduction + +**Leon** is **your open-source personal AI assistant** built around **tools, context, memory, and agentic execution**. + +Leon is designed to stay practical, privacy-aware, and grounded in your real environment. It can operate locally, use dedicated tools instead of relying on free-form guessing, and complete tasks from start to finish across deterministic workflows and agent-style execution. + +## 🧠 What Leon Is Today + +Leon is no longer just a classic intent-classification assistant like it was for its first release in 2019. + +Today, Leon is being built as a more capable assistant that can understand a goal, choose how to handle it, use tools, remember useful information, and recover when something goes wrong. + +- Leon can run in different ways depending on the task: `smart` mode chooses for you, `controlled` mode follows deterministic native skills and actions, and `agent` mode can plan step by step. +- Leon supports native skills for controlled actions and agent skills for `SKILL.md`-backed workflows. +- Leon can use real tools to get work done instead of only replying with plain text. +- Leon can use context about your environment so answers stay grounded in what is actually happening on your machine and setup. +- Leon keeps layered memory so it can remember durable preferences, day-to-day context, and recent discussion context. +- Leon supports both local and remote AI providers, which helps balance privacy, control, and capability. +- Under the hood, Leon-native skills follow `Skills -> Actions -> Tools -> Functions (-> Binaries)`. + +Leon also keeps a compact self-model and a bounded proactive pulse system so it can stay more consistent over time without flooding itself with unnecessary context. + +## Why? + +- **Privacy matters**: Leon can work with local models and local context instead of forcing everything through third-party services. +- **Grounded behavior matters**: Leon prefers explicit tools, context, and memory over vague model-only responses. +- **Extensibility matters**: skills, toolkits, bridges, and binaries make it possible to keep Leon modular. +- **Open source matters**: anyone can inspect the architecture, build on top of it, and help shape where it goes next. + +## 🚀 Getting Started + +### Prerequisites + +- [Node.js](https://nodejs.org/) >= 24.0.0 +- Supported OSes: Linux, macOS, and Windows + +Recommended: manage Node.js with [Volta](https://volta.sh/). + +### Installation + +```sh +# Clone the repository +git clone https://github.com/leon-ai/leon.git + +# Go to the project root +cd leon + +# Install pnpm +npm install --global pnpm@latest + +# Install dependencies +pnpm install +``` + +### Run Leon + +```sh +# Run Leon +pnpm start +``` + +### Check Your Setup + +```sh +# Check the setup went well +pnpm run check +``` + +By default, Leon runs locally and the app is available on `http://localhost:5366`. + +## 🏗️ Architecture Snapshot + +At a high level, Leon currently consists of: + +- `server/`: the main runtime, routing, memory, context management, HTTP API, and agent/controlled execution +- `app/`: the web application +- `aurora/`: UI components and preview environment +- `skills/`: built-in capabilities, split between `native/` skills and `agent/` skills +- `bridges/`: Node.js and Python bridges plus toolkit definitions and tool runtimes +- `tcp_server/`: Python services used by parts of the runtime stack +- `core/context/`: generated identity and architecture context documents that describe Leon's current behavior + +This repository already includes skills and toolkits for areas such as search, productivity, system utilities, media workflows, coding assistance, memory-backed interactions, and voice/audio features. + +## 📚 Documentation Status + +The new docs for Leon 2.0 are not ready yet. + +For now: + +- treat this repository as the source of truth for the **2.0 Developer Preview** +- use [`core/context/LEON.md`](./core/context/LEON.md) for Leon's current identity and behavior +- use [`core/context/ARCHITECTURE.md`](./core/context/ARCHITECTURE.md) for the current architecture overview +- expect the public docs site to lag behind the new core until the updated documentation is published + +## ❤️ Contributing + +We are starting to progressively onboard contributors for the **2.0 Developer Preview**. + +If you want to follow the project or express interest in joining that onboarding: + +- [2.0 Developer Preview contributor form](https://forms.gle/6PCG2D5rYo1q8tKMA) +- [Roadmap](http://roadmap.getleon.ai) +- [Discord](https://discord.gg/MNQqqKg) +- [GitHub issues](https://github.com/leon-ai/leon/issues) + +### Why is there a small amount of contributors? + +Leon has been evolving for a long time, but the current 2.0 work is a major transition period. + +For a long time, Leon was a smaller assistant project with a simpler architecture. Today, the core is being rebuilt into a much more capable system around tools, memory, context, and agent-style execution. That means a lot of things are still moving, and it makes contribution harder than it will be once the new docs and architecture settle down. + +Another important reason is simply time: Leon is still developed largely during spare time. So progress can be uneven, and opening the project more broadly has to be balanced with keeping the direction coherent while the 2.0 Developer Preview is still taking shape. + +## 📖 The Story Behind Leon + +Leon started in 2017 and has been active since 2019. If you want the longer backstory, read [the story behind Leon](https://blog.getleon.ai/the-story-behind-leon/). + +## 🔔 Stay Tuned + +- [X / Twitter](https://x.com/grenlouis) is the main place where I share Leon progress updates +- [Newsletter](https://leonai.substack.com/subscribe) +- [Blog](https://blog.getleon.ai) +- [YouTube](https://www.youtube.com/channel/UCW6mk6j6nQUzFYY97r47emQ) + +## 👨 Author + +**Louis Grenard** ([@grenlouis](https://x.com/grenlouis)) + +## 👍 Sponsors + +You can also contribute by [sponsoring Leon](http://sponsor.getleon.ai). + +## Thanks + +| ![OpenAI logo.](./.github/assets/thanks/openai-logo-light-mode.svg?v=2#gh-light-mode-only)![OpenAI logo.](./.github/assets/thanks/openai-logo-dark-mode.svg?v=2#gh-dark-mode-only) | ![JetBrains logo.](./.github/assets/thanks/jetbrains-mono-black.svg?v=2#gh-light-mode-only)![JetBrains logo.](./.github/assets/thanks/jetbrains-mono-white.svg?v=2#gh-dark-mode-only) | ![MacStadium logo.](./.github/assets/thanks/macstadium-logo-light-mode.svg?v=2#gh-light-mode-only)![MacStadium logo.](./.github/assets/thanks/macstadium-logo-dark-mode.svg?v=2#gh-dark-mode-only) | +| --- | --- | --- | +| [openai.com/form/codex-for-oss](https://openai.com/form/codex-for-oss/) | [jb.gg/OpenSource](https://jb.gg/OpenSource) | [macstadium.com/company/opensource](https://macstadium.com/company/opensource) | diff --git a/README.wehub.md b/README.wehub.md new file mode 100644 index 0000000..71c0248 --- /dev/null +++ b/README.wehub.md @@ -0,0 +1,7 @@ +# WeHub 来源说明 + +- 原始项目:`leon-ai/leon` +- 原始仓库:https://github.com/leon-ai/leon +- 导入方式:上游默认分支的最新快照 +- 原作者、版权和许可证信息以原始仓库及本仓库 LICENSE 为准 +- 本文件仅用于记录来源,不代表 WeHub 是原项目作者 diff --git a/app/src/css/built-in-commands.scss b/app/src/css/built-in-commands.scss new file mode 100644 index 0000000..015404f --- /dev/null +++ b/app/src/css/built-in-commands.scss @@ -0,0 +1,220 @@ +.built-in-commands-modal { + position: fixed; + inset: 0; + z-index: 120; + display: block; + opacity: 0; + visibility: visible; + pointer-events: none; + transition: + opacity 0.18s ease, + visibility 0.18s ease; +} + +.built-in-commands-modal--hidden { + opacity: 0; + visibility: hidden; + pointer-events: none; +} + +.built-in-commands-modal--open { + opacity: 1; + visibility: visible; + pointer-events: auto; +} + +.built-in-commands-modal__mask { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.56); + backdrop-filter: blur(10px); +} + +.built-in-commands-modal__panel { + position: absolute; + top: 33%; + left: 50%; + transform: translate(-50%, -33%) scale(0.985); + width: min(864px, 100%); + min-height: 400px; + max-height: min(78vh, 756px); + display: flex; + flex-direction: column; + border: 1px solid transparent; + border-radius: 24px; + background: + linear-gradient( + var(--a-color-background-surface), + var(--a-color-background-surface) + ) + padding-box, + linear-gradient(135deg, rgba(28, 117, 219, 0.8) 0%, rgba(237, 41, 122, 0.4) 100%) + border-box; + box-shadow: + 0 28px 60px rgba(0, 0, 0, 0.45), + 0 0 0 1px rgba(255, 255, 255, 0.03) inset; + overflow: hidden; + opacity: 0; + transition: + transform 0.18s cubic-bezier(0.18, 0.89, 0.32, 1.08), + opacity 0.18s ease; +} + +.built-in-commands-modal--open .built-in-commands-modal__panel { + transform: translate(-50%, -33%) scale(1); + opacity: 1; +} + +.built-in-commands-modal__section { + padding: 20px 22px; +} + +.built-in-commands-modal__section--top { + border-bottom: 1px solid rgba(255, 255, 255, 0.08); +} + +.built-in-commands-modal__section--bottom { + border-top: 1px solid rgba(255, 255, 255, 0.08); +} + +.built-in-commands-modal__section--middle { + flex: 0 0 512px; + height: 512px; + min-height: 512px; + padding: 12px; + overflow: hidden; +} + +.built-in-commands-modal__scroll-area { + height: 100%; +} + +.built-in-commands-modal__input-field { + flex: 1; +} + +.built-in-commands-modal__input-field .aurora-input-container { + --a-icon-container-width: 72px; +} + +.built-in-commands-modal__input-field .aurora-input { + height: 72px; + font-size: 28px; + font-weight: 600; +} + +.built-in-commands-modal__input-field .aurora-input-icon-container { + height: 72px; +} + +.built-in-commands-modal__return-button .aurora-button { + min-height: 44px; + min-width: 44px; + padding: 0 14px; + font-size: var(--a-font-size-md); +} + +.built-in-commands-modal__return-button .aurora-button .aurora-icon { + font-size: 22px; +} + +.built-in-commands-modal__suggestion-copy { + min-width: 0; +} + +.built-in-commands-modal .aurora-list-item > .aurora-flexbox .aurora-icon { + font-size: 28px; + padding: 23px; + border-radius: 12px; +} + +.built-in-commands-modal + .aurora-list-item--selected + .aurora-list-item-clickable-icon + .aurora-icon { + color: var(--a-color-accent); +} + +.built-in-commands-modal__result-item { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + width: 100%; +} + +.built-in-commands-modal__result-copy, +.built-in-commands-modal__result-value { + min-width: 0; +} + +.built-in-commands-modal__result-value { + margin-left: auto; +} + +.built-in-commands-modal .aurora-scroll-container-scrollview { + color-scheme: dark; + scrollbar-width: thin; + scrollbar-color: rgba(255, 255, 255, 0.2) rgba(10, 14, 18, 0.9); +} + +.built-in-commands-modal .aurora-scroll-container-scrollview::-webkit-scrollbar { + width: 10px; +} + +.built-in-commands-modal + .aurora-scroll-container-scrollview::-webkit-scrollbar-track { + background: rgba(10, 14, 18, 0.9); + border-radius: 999px; +} + +.built-in-commands-modal + .aurora-scroll-container-scrollview::-webkit-scrollbar-thumb { + background: linear-gradient( + 180deg, + rgba(54, 65, 76, 0.95) 0%, + rgba(30, 38, 46, 0.95) 100% + ); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 999px; +} + +.built-in-commands-modal + .aurora-scroll-container-scrollview::-webkit-scrollbar-thumb:hover { + background: linear-gradient( + 180deg, + rgba(70, 82, 95, 0.98) 0%, + rgba(40, 49, 58, 0.98) 100% + ); +} + +@media (max-width: 900px) { + .built-in-commands-modal__panel { + width: auto; + min-height: 360px; + max-height: calc(100vh - 24px); + left: 12px; + right: 12px; + top: 18%; + transform: translate(0, 0) scale(0.985); + } + + .built-in-commands-modal--open .built-in-commands-modal__panel { + transform: translate(0, 0) scale(1); + } + + .built-in-commands-modal__section { + padding: 16px; + } + + .built-in-commands-modal__section--middle { + flex-basis: 280px; + height: 280px; + min-height: 280px; + } + + .built-in-commands-modal__result-item { + flex-direction: column; + gap: 6px; + } +} diff --git a/app/src/css/file-system-autocomplete.scss b/app/src/css/file-system-autocomplete.scss new file mode 100644 index 0000000..2178249 --- /dev/null +++ b/app/src/css/file-system-autocomplete.scss @@ -0,0 +1,69 @@ +.file-system-autocomplete { + position: fixed; + z-index: 150; + overflow-y: auto; + padding: 6px; + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 8px; + background: #111315; + box-shadow: + 0 18px 42px rgba(0, 0, 0, 0.42), + 0 0 0 1px rgba(255, 255, 255, 0.03) inset; + color: var(--white-color); +} + +.file-system-autocomplete--hidden { + display: none; +} + +.file-system-autocomplete__item { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + min-height: 42px; + padding: 9px 10px; + border: 0; + border-radius: 6px; + background: transparent; + color: inherit; + cursor: pointer; + font: inherit; + line-height: 1.35; + text-align: left; +} + +.file-system-autocomplete__item:hover, +.file-system-autocomplete__item--selected { + background: rgba(28, 117, 219, 0.22); +} + +.file-system-autocomplete__item i { + flex: 0 0 auto; + width: 18px; + color: var(--blue-color); + font-size: 18px; +} + +.file-system-autocomplete__label { + min-width: 0; + overflow: hidden; + line-height: 1.35; + text-overflow: ellipsis; + white-space: nowrap; +} + +.file-system-autocomplete__empty { + padding: 10px; + color: rgba(255, 255, 255, 0.58); + font-size: 0.95rem; +} + +.file-system-autocomplete::-webkit-scrollbar { + width: 6px; +} + +.file-system-autocomplete::-webkit-scrollbar-thumb { + background-color: rgba(255, 255, 255, 0.2); + border-radius: 12px; +} diff --git a/app/src/css/style.scss b/app/src/css/style.scss new file mode 100644 index 0000000..c630931 --- /dev/null +++ b/app/src/css/style.scss @@ -0,0 +1,863 @@ +@use 'sass:meta'; + +@import '@fontsource/source-sans-pro/200.css'; +@import '@fontsource/source-sans-pro/300.css'; +@import '@fontsource/source-sans-pro/400.css'; +@import '@fontsource/source-sans-pro/600.css'; +@import '@fontsource/source-sans-pro/700.css'; +@import '@fontsource/source-sans-pro/900.css'; +@import 'remixicon/fonts/remixicon.css'; + +@include meta.load-css('tool-ui'); +@include meta.load-css('voice-energy/main'); +@include meta.load-css('file-system-autocomplete'); + +html, +body, +div, +span, +applet, +object, +iframes, +h1, +h2, +h3, +h4, +h5, +h6, +p, +blockquote, +pre, +a, +abbr, +acronym, +address, +big, +cite, +code, +del, +dfn, +em, +img, +ins, +kbd, +q, +s, +samp, +small, +strike, +sub, +sup, +tt, +var, +u, +i, +center, +dl, +dt, +dd, +ol, +ul, +li, +fieldset, +form, +label, +legend, +table, +caption, +tbody, +tfoot, +thead, +tr, +th, +td, +article, +aside, +canvas, +details, +embed, +figure, +figcaption, +footer, +header, +hgroup, +menu, +nav, +output, +ruby, +section, +summary, +time, +mark, +audio, +video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + vertical-align: baseline; +} + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +menu, +nav, +section { + display: block; +} + +blockquote, +q { + quotes: none; +} + +blockquote:before, +blockquote:after, +q:before, +q:after { + content: ''; + content: none; +} + +table { + border-collapse: collapse; + border-spacing: 0; +} + +* { + box-sizing: border-box; + outline: none; +} + +:root { + color-scheme: dark; + + --black-color: #000; + --light-black-color: #222426; + --white-color: #fff; + --grey-color: #323739; + --blue-color: #1c75db; + --pink-color: #ed297a; + --sessions-panel-width: 292px; + + --a-loader-size-md: 20px !important; +} + +a { + color: inherit; +} + +#feed ul li:not(.aurora-list-item) { + margin-left: 20px; +} + +body { + color: var(--white-color); + background-color: var(--black-color); + font-family: + 'Source Sans Pro', + system-ui, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + Roboto, + 'Helvetica Neue', + Arial, + 'Noto Sans', + sans-serif, + 'Apple Color Emoji', + 'Segoe UI Emoji', + 'Segoe UI Symbol', + 'Noto Color Emoji'; + font-weight: 400; +} + + +@keyframes plan-tool-status-cozy-shine { + 0% { + opacity: 0.4; + filter: drop-shadow(0 0 0 rgba(255, 255, 255, 0)); + } + + 50% { + opacity: 1; + filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.22)); + } + + 100% { + opacity: 0.4; + filter: drop-shadow(0 0 0 rgba(255, 255, 255, 0)); + } +} + +#feed + .bubble-container[data-message-id^='plan-'] + .aurora-list + .aurora-list-item--center:last-child + .aurora-status + .aurora-icon { + animation: plan-tool-status-cozy-shine 2.6s ease-in-out infinite; +} + +body > * { + transition: opacity 0.5s; +} +body.settingup > *:not(#init) { + opacity: 0; +} +#init .not-initialized { + visibility: hidden; +} +#init .initialized { + opacity: 0; + visibility: hidden; +} + +kbd { + font-family: 'Source Sans Pro', monospace; + display: inline-block; + background-color: var(--light-black-color); + color: rgba(255, 255, 255, 0.4); + border-radius: 4px; + text-align: center; + min-width: 16px; + min-height: 16px; + line-height: 16px !important; + padding: 2px 6px !important; + margin: 0 !important; +} + +#sessions-panel { + position: absolute; + left: 2%; + top: 2%; + bottom: 8%; + width: var(--sessions-panel-width); + border-right: 1px solid rgba(255, 255, 255, 0.12); + color: var(--white-color); + overflow: hidden; +} + +#sessions-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 14px 14px 0; +} + +#sessions-eyebrow { + color: rgba(255, 255, 255, 0.42); + font-size: 0.9rem; + font-weight: 700; + text-transform: uppercase; +} + +#new-session, +.session-action { + border: 0; + background: rgba(255, 255, 255, 0.08); + color: var(--white-color); + cursor: pointer; + transition: + background-color 0.18s, + color 0.18s, + transform 0.18s; +} + +#new-session { + width: 34px; + height: 34px; + border-radius: 8px; + font-size: 1.2rem; +} + +#new-session:hover, +.session-action:hover { + background: rgba(28, 117, 219, 0.22); + color: #86bdff; +} + +#sessions-list { + height: calc(100% - 48px); + padding-right: 14px; + overflow-y: auto; +} + +#sessions-list::-webkit-scrollbar { + width: 6px; +} + +#sessions-list::-webkit-scrollbar-thumb { + background-color: rgba(255, 255, 255, 0.16); + border-radius: 12px; +} + +.session-group { + position: relative; + padding: 0 0 12px 14px; +} + +.session-group::before { + content: ''; + position: absolute; + left: 3px; + top: 22px; + bottom: 0; + width: 1px; + background: linear-gradient( + rgba(28, 117, 219, 0.7), + rgba(237, 41, 122, 0.22) + ); +} + +.session-group-title { + position: relative; + margin-bottom: 8px; + color: rgba(255, 255, 255, 0.44); + font-size: 0.78rem; + font-weight: 700; + text-transform: uppercase; +} + +.session-group-title::before { + content: ''; + position: absolute; + left: -14px; + top: 7px; + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--blue-color); + box-shadow: 0 0 12px rgba(28, 117, 219, 0.8); +} + +.session-item { + position: relative; + padding: 10px 8px; + border-radius: 8px; + cursor: pointer; + animation: sessionTimelineIn 0.24s ease-out both; +} + +.session-item:hover, +.session-item--active { + background: rgba(255, 255, 255, 0.07); +} + +.session-item--active::before { + content: ''; + position: absolute; + left: -11px; + top: 18px; + width: 5px; + height: 5px; + border-radius: 50%; + background: var(--pink-color); + box-shadow: 0 0 10px rgba(237, 41, 122, 0.9); +} + +.session-title { + overflow: hidden; + color: rgba(255, 255, 255, 0.9); + font-size: 0.98rem; + font-weight: 700; + line-height: 1.2rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.session-meta { + overflow: hidden; + margin-top: 2px; + color: rgba(255, 255, 255, 0.36); + font-size: 0.8rem; + line-height: 1rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.session-actions { + display: flex; + gap: 4px; + margin-top: 8px; + opacity: 0; + transition: opacity 0.16s; +} + +.session-item:hover .session-actions, +.session-item--active .session-actions { + opacity: 1; +} + +.session-action { + width: 26px; + height: 26px; + border-radius: 6px; +} + +.session-action[aria-pressed='true'] { + color: #ff7caf; +} + +@keyframes sessionTimelineIn { + from { + opacity: 0; + transform: translateY(8px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +main { + position: absolute; + width: calc(94% - var(--sessions-panel-width)); + top: 0; + left: calc(4% + var(--sessions-panel-width)); + height: 100%; +} + +#footer { + display: flex; + position: absolute; + align-items: center; + justify-content: space-between; + left: calc(4% + var(--sessions-panel-width)); + bottom: 2%; + width: calc(94% - var(--sessions-panel-width)); + line-height: 18px; +} +#logo-container { + display: flex; + gap: 6px; + align-items: center; +} +#version { + color: var(--grey-color); +} + +textarea { + font-family: inherit; + text-align: center; + color: var(--white-color); + width: 100%; + border: none; + border-bottom: 2px solid var(--grey-color); + background: none; + font-weight: 600; + font-size: 4em; + padding-right: 39px; + height: 140px; + resize: none; + overflow-y: auto; +} +textarea::-webkit-scrollbar { + width: 6px; +} +textarea::-webkit-scrollbar-thumb { + background-color: rgba(255, 255, 255, 0.2); + border-radius: 12px; +} + +#tip { + display: inline-flex; + margin-top: 2px; + color: var(--white-color); + line-height: 22px; + font-size: 0.9em; + gap: 20px; + li { + margin-left: 0; + } +} + +.hide { + display: none; +} + +#logo { + background: no-repeat url(../img/logo.svg); + width: 34px; + height: 34px; +} + +#top-container { + position: absolute; + top: 2%; + color: var(--grey-color); + display: flex; + width: 100%; + justify-content: space-between; +} +#mood { + position: relative; + font-size: 16px; +} +#info { + position: relative; + text-decoration: underline; + background: none; + border: none; + color: var(--grey-color); + cursor: pointer; + font-size: inherit; +} + +#feed { + position: absolute; + width: 100%; + top: 6%; + height: 58%; + overflow-y: auto; + border: 2px solid var(--grey-color); + border-radius: 12px; +} +#feed::-webkit-scrollbar { + width: 6px; +} +#feed::-webkit-scrollbar-thumb { + background-color: rgba(255, 255, 255, 0.2); + border-radius: 12px; +} + +#no-bubble { + margin-top: 64px; + text-align: center; +} + +#is-typing { + position: absolute; + top: 65%; + padding: 0 8px; + opacity: 0; + transition: opacity 0.3s; +} +#is-typing.on { + opacity: 1; +} + +#is-typing .circle { + display: inline-block; + border-radius: 50%; + width: 10px; + height: 10px; + background-color: var(--white-color); + transform: scale(1); +} +#is-typing .circle:nth-child(1) { + animation: typing 0.2s linear infinite alternate; + background-color: #0071f0; +} +#is-typing .circle:nth-child(2) { + animation: typing 0.2s 0.2s linear infinite alternate; + background-color: var(--white-color); +} +#is-typing .circle:nth-child(3) { + animation: typing 0.2s linear infinite alternate; + background-color: #ec297a; +} +@keyframes typing { + 100% { + transform: scale(1.5); + } +} + +.llm-token { + opacity: 0; + transition: opacity 2.5s; +} + +.llm-token.fade-in { + animation: fadeIn 2.5s forwards; +} + +.reasoning-block-container { + padding: 6px; + text-align: left; +} + +.reasoning-block { + max-width: 72%; + border: 1px solid rgba(255, 255, 255, 0.16); + border-radius: 12px; + background-color: #111315; + overflow: hidden; + animation: fadeIn 0.2s ease-in forwards; +} + +.reasoning-header { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 12px; + border-bottom: 1px solid rgba(255, 255, 255, 0.1); + background-color: rgba(255, 255, 255, 0.03); +} + +.reasoning-icon { + color: var(--blue-color); + font-size: 15px; +} + +.reasoning-title { + font-size: 0.85rem; + letter-spacing: 0.04em; + text-transform: uppercase; + color: rgba(255, 255, 255, 0.8); +} + +.reasoning-content { + padding: 10px 12px; + font-family: 'Courier New', Consolas, monospace; + font-size: 0.95rem; + line-height: 1.45; + color: rgba(255, 255, 255, 0.82); + white-space: pre-wrap; + word-break: break-word; + max-height: 296px; + overflow-y: auto; +} + +.reasoning-content::-webkit-scrollbar { + width: 6px; +} + +.reasoning-content::-webkit-scrollbar-thumb { + background-color: rgba(255, 255, 255, 0.2); + border-radius: 12px; +} + +.reasoning-token { + opacity: 0; +} + +.reasoning-token.fade-in { + animation: fadeIn 0.35s forwards; +} + +.bubble-container { + padding: 6px; + display: flex; + flex-direction: column; + width: fit-content; + max-width: 85%; +} +.bubble-container.me { + margin-left: auto; + align-items: flex-end; + text-align: right; +} +.bubble-container.leon { + margin-right: auto; + align-items: flex-start; + text-align: left; +} +.show-more { + margin: 3px; + text-decoration: underline; +} +.show-more:hover { + cursor: pointer; + text-decoration: none; +} +.show-all { + max-height: 100% !important; +} + +.bubble { + padding: 10px 16px; + border-radius: 16px; + display: inline-block; + max-width: 100%; + word-break: break-word; + text-align: left; + opacity: 0; + animation: fadeIn 0.2s ease-in forwards; + overflow: hidden; + font-size: 1.8rem; + line-height: 2.4rem; +} +.bubble-metrics { + cursor: default; + margin-top: 2px; + padding: 0 4px; + display: inline-flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 10px; + font-size: 0.95rem; + line-height: 1.2rem; + color: var(--grey-color); + align-self: flex-end; + text-align: right; +} +.bubble-metric-item { + display: inline-flex; + align-items: center; + gap: 4px; +} +.bubble-metric-item i { + font-size: 1rem; +} +#feed .me .bubble-metrics { + text-align: right; +} +#feed .me .bubble { + background-color: #1c75db; + color: var(--white-color); + right: 0; +} +#feed .leon .bubble { + background-color: var(--light-black-color); + color: var(--white-color); +} +@keyframes fadeIn { + 100% { + opacity: 1; + } +} + +#input-container { + position: absolute; + width: 100%; + bottom: 13%; +} + +#mic-container { + position: absolute; + right: 0; + margin-top: 38px; +} + +.italic { + font-style: italic; +} + +#mic-button { + position: absolute; + border: none; + cursor: pointer; + height: 26px; + width: 26px; + border-radius: 50%; + background-color: #888; + -webkit-mask-image: url(../img/mic.svg); + mask-image: url(../img/mic.svg); + transition: background-color 0.2s; +} +#mic-button:not(.enabled) { + margin-left: -26px; +} +#mic-button:hover { + background-color: var(--white-color); +} +#mic-button.enabled { + background-color: #00e676; +} +#mic-button.enabled + #sonar { + width: 26px; + height: 26px; + border-radius: 50%; + opacity: 0.3; + background-color: #575757; + pointer-events: none; + animation: sonar 1.3s linear infinite; +} +@keyframes sonar { + 25% { + transform: scale(1.5); + } + 50% { + transform: scale(1.2); + } + 60% { + transform: scale(1.5); + } + 75% { + transform: scale(2); + } + 100% { + transform: scale(1); + } +} + +/* Clickable URL styles */ +.clickable-url { + text-decoration: underline; +} + +/* Clickable file path styles */ +.clickable-path { + cursor: pointer; + text-decoration: underline; +} + +@media (max-width: 940px) { + :root { + --sessions-panel-width: 100%; + } + + #sessions-panel { + left: 4%; + right: 4%; + top: 1%; + bottom: auto; + width: auto; + height: 168px; + border-right: 0; + border-bottom: 1px solid rgba(255, 255, 255, 0.12); + } + + #sessions-list { + display: flex; + gap: 12px; + height: 112px; + overflow-x: auto; + overflow-y: hidden; + } + + .session-group { + min-width: 220px; + } + + main { + top: 176px; + left: 4%; + width: 92%; + height: calc(100% - 176px); + } + + #footer { + display: none; + } + + #top-container { + top: 1%; + } + + #feed { + top: 7%; + height: 50%; + } + + #is-typing { + top: 58%; + } + + textarea { + font-size: 2.4em; + } + + #tip { + flex-wrap: wrap; + gap: 8px; + } +} diff --git a/app/src/css/tool-ui.scss b/app/src/css/tool-ui.scss new file mode 100644 index 0000000..ff377a8 --- /dev/null +++ b/app/src/css/tool-ui.scss @@ -0,0 +1,418 @@ +/* Tool Output Container Styles */ +.tool-group-container { + margin: 10px 6px; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 14px; + background: + linear-gradient( + 180deg, + rgba(255, 255, 255, 0.04) 0%, + rgba(255, 255, 255, 0.02) 100% + ), + #15181a; + box-shadow: + 0 10px 30px rgba(0, 0, 0, 0.24), + inset 0 1px 0 rgba(255, 255, 255, 0.03); + opacity: 0; + animation: fadeIn 0.3s ease-in forwards; + overflow: hidden; +} + +.tool-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + width: 100%; + padding: 14px 16px; + background: transparent; + border: 0; + cursor: pointer; + color: inherit; + text-align: left; + transition: background-color 0.2s ease; +} + +.tool-header:hover { + background-color: rgba(255, 255, 255, 0.03); +} + +.tool-icon { + color: var(--blue-color); + font-size: 18px; + flex-shrink: 0; +} + +.tool-name { + flex: 1; + font-weight: 600; + color: var(--white-color); + font-size: 0.95em; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.expand-icon { + color: rgba(255, 255, 255, 0.48); + font-size: 18px; + transition: transform 0.2s ease; +} + +.expand-icon.rotated { + transform: rotate(180deg); +} + +.tool-content { + max-height: 0; + overflow: hidden; + transition: max-height 0.3s ease, border-top-color 0.2s ease; + border-top: 1px solid transparent; +} + +.tool-content.expanded { + max-height: 900px; + overflow-y: auto; + border-top-color: rgba(255, 255, 255, 0.06); +} + +.tool-content::-webkit-scrollbar { + width: 4px; +} + +.tool-content::-webkit-scrollbar-thumb { + background-color: rgba(255, 255, 255, 0.1); + border-radius: 2px; +} + +.shell-output { + padding: 12px; + background-color: #0d1117; + border-radius: 0 0 14px 14px; + min-height: 40px; + font-family: 'Courier New', Consolas, monospace; + font-size: 0.9em; +} + +.shell-message { + margin: 2px 0; + line-height: 1.4; + color: #e6edf3; + word-break: break-word; +} + +.shell-prompt { + color: var(--pink-color); + font-weight: bold; + margin-right: 8px; +} + +.shell-message .clickable-path { + color: var(--blue-color); + background-color: rgba(28, 117, 219, 0.1); + padding: 1px 4px; + border-radius: 3px; + border: 1px solid rgba(28, 117, 219, 0.3); +} + +.shell-message .clickable-url { + color: var(--blue-color); +} + +.tool-activity-card { + background: + radial-gradient( + circle at top right, + rgba(28, 117, 219, 0.14), + transparent 32% + ), + linear-gradient( + 180deg, + rgba(255, 255, 255, 0.04) 0%, + rgba(255, 255, 255, 0.02) 100% + ), + #15181a; +} + +.agent-skill-activity-card { + background: + radial-gradient( + circle at top right, + rgba(237, 41, 122, 0.14), + transparent 32% + ), + linear-gradient( + 180deg, + rgba(255, 255, 255, 0.04) 0%, + rgba(255, 255, 255, 0.02) 100% + ), + #15181a; +} + +.agent-skill-activity-card .tool-icon { + color: #ed297a; +} + +.tool-activity-header { + align-items: flex-start; +} + +.tool-activity-heading { + display: flex; + align-items: flex-start; + gap: 12px; + min-width: 0; + flex: 1; +} + +.tool-activity-title-block { + display: flex; + flex-direction: column; + min-width: 0; + gap: 2px; +} + +.tool-title { + color: var(--white-color); + font-size: 1rem; + font-weight: 700; + line-height: 1.2; +} + +.tool-subtitle { + color: rgba(255, 255, 255, 0.58); + font-size: 0.86rem; + line-height: 1.2; +} + +.tool-activity-meta { + display: flex; + align-items: center; + gap: 10px; + flex-shrink: 0; +} + +.tool-status-chip { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 72px; + padding: 5px 10px; + border-radius: 999px; + border: 1px solid transparent; + font-size: 0.76rem; + font-weight: 700; + letter-spacing: 0.02em; + text-transform: uppercase; +} + +.tool-status-chip.running { + color: #9fd2ff; + background-color: rgba(28, 117, 219, 0.14); + border-color: rgba(28, 117, 219, 0.28); +} + +.tool-status-chip.success { + color: #93f0c1; + background-color: rgba(36, 178, 101, 0.15); + border-color: rgba(36, 178, 101, 0.28); +} + +.tool-status-chip.selected { + color: #93f0c1; + background-color: rgba(36, 178, 101, 0.15); + border-color: rgba(36, 178, 101, 0.28); +} + +.tool-status-chip.observed { + color: #f5d48a; + background-color: rgba(210, 157, 38, 0.15); + border-color: rgba(210, 157, 38, 0.3); +} + +.tool-status-chip.error { + color: #ffb0b0; + background-color: rgba(237, 41, 122, 0.14); + border-color: rgba(237, 41, 122, 0.28); +} + +.tool-activity-summary { + padding: 16px 16px 4px; + color: rgba(255, 255, 255, 0.82); + font-size: 0.95rem; + line-height: 1.45; +} + +.tool-activity-sections { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + padding: 12px 16px 16px; +} + +.tool-activity-sections.single { + grid-template-columns: 1fr; +} + +.tool-activity-panel { + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 12px; + background-color: rgba(255, 255, 255, 0.025); + min-width: 0; +} + +.tool-panel-heading { + display: flex; + flex-direction: column; + gap: 2px; + padding: 12px 14px 10px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.tool-panel-title { + color: var(--white-color); + font-size: 0.84rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.tool-panel-description { + color: rgba(255, 255, 255, 0.5); + font-size: 0.78rem; +} + +.tool-panel-body { + padding: 12px 14px 14px; + min-height: 72px; +} + +.tool-output-summary { + margin-bottom: 10px; + color: rgba(255, 255, 255, 0.86); + line-height: 1.45; +} + +.tool-empty-state { + color: rgba(255, 255, 255, 0.45); + font-size: 0.88rem; + line-height: 1.4; +} + +.tool-kv-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.tool-kv-row { + display: flex; + flex-direction: column; + gap: 4px; +} + +.tool-kv-key { + color: rgba(255, 255, 255, 0.52); + font-size: 0.75rem; + font-weight: 700; + letter-spacing: 0.03em; + text-transform: uppercase; +} + +.tool-kv-value { + color: rgba(255, 255, 255, 0.88); + min-width: 0; +} + +.tool-rich-text { + color: rgba(255, 255, 255, 0.88); + line-height: 1.45; + word-break: break-word; +} + +.tool-command-output { + margin: 0; + max-height: 320px; + overflow: auto; + color: rgba(255, 255, 255, 0.86); + font-family: 'Courier New', Consolas, monospace; + font-size: 0.84rem; + line-height: 1.45; + white-space: pre-wrap; + word-break: break-word; +} + +.tool-rich-text .clickable-path { + color: var(--blue-color); + background-color: rgba(28, 117, 219, 0.1); + padding: 1px 4px; + border-radius: 3px; + border: 1px solid rgba(28, 117, 219, 0.3); +} + +.tool-rich-text .clickable-url { + color: var(--blue-color); +} + +.tool-value-list { + display: flex; + flex-direction: column; + gap: 8px; + margin-left: 18px; +} + +.tool-value-list li { + color: rgba(255, 255, 255, 0.88); + line-height: 1.4; +} + +.tool-raw-details { + margin: 0 16px 16px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + padding-top: 12px; +} + +.tool-raw-details summary { + cursor: pointer; + color: rgba(255, 255, 255, 0.62); + font-size: 0.82rem; + font-weight: 700; + letter-spacing: 0.03em; + text-transform: uppercase; + list-style: none; +} + +.tool-raw-details summary::-webkit-details-marker { + display: none; +} + +.tool-raw-content { + margin-top: 12px; + padding: 12px 14px; + border-radius: 10px; + background-color: rgba(0, 0, 0, 0.3); + color: rgba(255, 255, 255, 0.78); + font-family: 'Courier New', Consolas, monospace; + font-size: 0.84rem; + line-height: 1.45; + overflow-x: auto; +} + +@media screen and (max-width: 700px) { + .tool-activity-sections { + grid-template-columns: 1fr; + } + + .tool-activity-header { + gap: 10px; + } + + .tool-activity-meta { + align-items: flex-end; + } + + .tool-status-chip { + min-width: 64px; + padding: 5px 8px; + } +} diff --git a/app/src/css/voice-energy/_variables.scss b/app/src/css/voice-energy/_variables.scss new file mode 100644 index 0000000..dfbd53c --- /dev/null +++ b/app/src/css/voice-energy/_variables.scss @@ -0,0 +1,8 @@ +@use 'sass:color'; + +$voice-neon-pink-color: #ed297a; +$voice-neon-blue-color: #1c75db; +$voice-neon-shadow-color: color.mix( + $voice-neon-pink-color, + $voice-neon-blue-color +); diff --git a/app/src/css/voice-energy/base.scss b/app/src/css/voice-energy/base.scss new file mode 100644 index 0000000..07795d9 --- /dev/null +++ b/app/src/css/voice-energy/base.scss @@ -0,0 +1,162 @@ +/** + * Overlay and containers + */ + +body.voice-mode-enabled { + #voice-overlay-transitor, + #voice-overlay-bg { + visibility: visible; + } + #voice-overlay-bg { + opacity: 1; + } +} +#voice-overlay-transitor { + position: fixed; + background-color: var(--black-color); + z-index: 10; + width: 12px; + height: 12px; + border-radius: 50%; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + will-change: transform; + animation: scaleIn 1s; +} +@keyframes scaleIn { + 0% { + transform: scale3d(0, 0, 1); + } + 100% { + transform: scale3d(172, 172, 1); + } +} + +#voice-status, +#voice-tips { + color: var(--grey-color); + text-align: center; +} +#voice-status { + font-size: 17px; + font-style: italic; +} +#voice-tips { + margin-top: 32px; + line-height: 18px; + font-size: 15px; +} + +#voice-overlay-bg { + visibility: hidden; + cursor: pointer; + opacity: 0; + position: fixed; + width: 100vw; + height: 100vh; + z-index: 100; + will-change: opacity; + display: flex; + justify-content: center; + // backdrop-filter: saturate(140%) blur(5px); + /*background-color: rgba(0, 0, 0, .9);*/ + background-color: var(--black-color); +} +@keyframes skipFadeIn { + 0% { + opacity: 1; + } + 100% { + opacity: 1; + } +} + +#voice-container { + opacity: 0; + position: relative; + top: 64px; + display: flex; + flex-direction: column; + width: 1024px; + height: 756px; + align-items: center; + gap: 64px; + animation: fadeIn 1s 3s both; +} + +#voice-energy-container { + --neon-size: 228px; + + // animation: fadeIn 1s 1.5s both; + //opacity: 0; + overflow: hidden; + position: relative; + height: 400px; + border-radius: 50%; + display: flex; + justify-content: center; + align-items: center; +} +p#voice-speech { + width: 100%; + height: 100%; + flex: 1; + text-align: center; + font-size: 3rem; + font-weight: 600; +} + +/** + * Neons + */ + +.voice-neon { + position: absolute; + z-index: 10; + width: var(--neon-size); + height: var(--neon-size); +} + +#purple-neon-blur { + --neon-blur: calc(var(--neon-size) + 96px); + + position: absolute; + z-index: 0; + opacity: 0.7; + width: var(--neon-blur); + height: var(--neon-blur); +} + +#blue-neon-1 { + margin-top: -8px; + margin-left: 12px; +} + +#blue-neon-2 { + margin-top: 8px; + margin-right: 12px; +} + +/** + * Particles + */ + +.voice-particle { + position: absolute; + width: 3px; + height: 3px; + border-radius: 50%; + opacity: 1; + will-change: transform, opacity; + animation-duration: 1s; + animation-iteration-count: infinite; +} +.voice-particle.blue { + background-color: #c4e0ff; + box-shadow: 0 0 2px 2px var(--blue-color); +} +.voice-particle.pink { + background-color: #ffb9d7; + box-shadow: 0 0 2px 2px var(--pink-color); +} diff --git a/app/src/css/voice-energy/idle.scss b/app/src/css/voice-energy/idle.scss new file mode 100644 index 0000000..001e884 --- /dev/null +++ b/app/src/css/voice-energy/idle.scss @@ -0,0 +1,61 @@ +@use 'variables' as *; + +/** + * IDLE status + */ + +#voice-energy-container.idle { + .voice-particle { + visibility: hidden; + animation-play-state: paused; + opacity: 0; + } + .voice-neon { + margin: 0; + } + #purple-neon-blur { + transform: scale(1); + } + #purple-neon-blur circle { + filter: drop-shadow(0px 0px 64px $voice-neon-shadow-color); + animation: idleNeonBlurBreath 2.2s infinite alternate; + } + #pink-neon-1 { + transform: scale(1); + animation: idleBouncePinkNeon1 1.8s 1s infinite alternate; + } + #blue-neon-1 { + transform: scale(0.8); + animation: idleMoveBlueNeon1 1.8s infinite alternate; + } + #blue-neon-2 { + transform: scale(0.9); + animation: idleMoveBlueNeon2 1.8s 0.5s infinite alternate; + } +} + +@keyframes idleNeonBlurBreath { + 100% { + filter: drop-shadow(0px 0px 0px $voice-neon-shadow-color); + } +} +@keyframes idleBouncePurpleNeonBlur { + 100% { + transform: scale(1); + } +} +@keyframes idleBouncePinkNeon1 { + 100% { + transform: scale(1.1); + } +} +@keyframes idleMoveBlueNeon1 { + 100% { + transform: scale(0.9); + } +} +@keyframes idleMoveBlueNeon2 { + 100% { + transform: scale(1); + } +} diff --git a/app/src/css/voice-energy/listening.scss b/app/src/css/voice-energy/listening.scss new file mode 100644 index 0000000..f5a7f68 --- /dev/null +++ b/app/src/css/voice-energy/listening.scss @@ -0,0 +1,61 @@ +@use 'variables' as *; + +/** + * Listening status + */ + +#voice-energy-container.listening { + .voice-particle { + visibility: hidden; + animation-play-state: paused; + opacity: 0; + } + .voice-neon { + margin: 0; + } + #purple-neon-blur { + transform: scale(1); + } + #purple-neon-blur circle { + filter: drop-shadow(0px 0px 64px $voice-neon-shadow-color); + animation: listeningNeonBlurBreath 0.7s infinite alternate; + } + #pink-neon-1 { + transform: scale(1); + animation: listeningBouncePinkNeon1 0.3s 1s infinite alternate; + } + #blue-neon-1 { + transform: scale(0.8); + animation: listeningMoveBlueNeon1 0.3s infinite alternate; + } + #blue-neon-2 { + transform: scale(0.9); + animation: listeningMoveBlueNeon2 0.3s 0.5s infinite alternate; + } +} + +@keyframes listeningNeonBlurBreath { + 100% { + filter: drop-shadow(0px 0px 0px $voice-neon-shadow-color); + } +} +@keyframes listeningBouncePurpleNeonBlur { + 100% { + transform: scale(1); + } +} +@keyframes listeningBouncePinkNeon1 { + 100% { + transform: scale(1.1); + } +} +@keyframes listeningMoveBlueNeon1 { + 100% { + transform: scale(0.9); + } +} +@keyframes listeningMoveBlueNeon2 { + 100% { + transform: scale(1); + } +} diff --git a/app/src/css/voice-energy/main.scss b/app/src/css/voice-energy/main.scss new file mode 100644 index 0000000..e72ce4f --- /dev/null +++ b/app/src/css/voice-energy/main.scss @@ -0,0 +1,5 @@ +@use 'base'; +@use 'listening'; +@use 'idle'; +@use 'processing'; +@use 'talking'; diff --git a/app/src/css/voice-energy/processing.scss b/app/src/css/voice-energy/processing.scss new file mode 100644 index 0000000..93741fb --- /dev/null +++ b/app/src/css/voice-energy/processing.scss @@ -0,0 +1,88 @@ +@use 'sass:math'; + +/** + * Processing status + */ + +#voice-energy-container.processing { + #purple-neon-blur { + animation: processingBouncePurpleNeonBlur 1s infinite alternate; + } + #pink-neon-1 { + animation: processingBouncePinkNeon1 0.5s infinite alternate; + } + #blue-neon-1 { + animation: processingMoveBlueNeon1 0.5s infinite alternate; + } + #blue-neon-2 { + animation: processingMoveBlueNeon2 0.5s infinite alternate; + } +} + +@keyframes processingBouncePurpleNeonBlur { + 50% { + transform: scale(1.07); + } + 100% { + transform: scale(1); + } +} +@keyframes processingBouncePinkNeon1 { + 50% { + transform: scale(1.02); + } + 100% { + transform: scale(1); + } +} +@keyframes processingMoveBlueNeon1 { + 0% { + transform: translateX(0) translateY(0); + } + 33% { + transform: translateY(-3px) translateX(-2px); + } + 66% { + transform: translateY(-3px) translateX(3px); + } + 100% { + transform: translateY(-3px) translateX(1px); + } +} +@keyframes processingMoveBlueNeon2 { + 0% { + transform: translateX(0) translateY(0); + } + 33% { + transform: translateY(3px) translateX(2px); + } + 66% { + transform: translateY(3px) translateX(3px); + } + 100% { + transform: translateY(3px) translateX(-1px); + } +} + +@for $i from 0 through 31 { + .processing .voice-particle[data-particle='#{$i}'] { + animation-delay: #{$i * 0.1}s; + } + + .processing .voice-particle[data-particle='#{$i}'] { + animation-name: processingMoveParticle#{$i}; + } + + #voice-energy-container.processing { + @keyframes processingMoveParticle#{$i} { + 75% { + opacity: 0.1; + } + 100% { + opacity: 1; + transform: translateX(math.cos(11.25deg * $i) * 110px) + translateY(math.sin(11.25deg * $i) * 110px); + } + } + } +} diff --git a/app/src/css/voice-energy/talking.scss b/app/src/css/voice-energy/talking.scss new file mode 100644 index 0000000..1cd972e --- /dev/null +++ b/app/src/css/voice-energy/talking.scss @@ -0,0 +1,82 @@ +@use 'sass:math'; + +/** + * Talking status + */ + +#voice-energy-container.talking { + .voice-neon { + margin: 0; + } + #purple-neon-blur { + animation: talkingBouncePurpleNeonBlur 1s infinite alternate; + } + #pink-neon-1 { + transform: scale(1); + animation: talkingBouncePinkNeon1 0.5s 1s infinite alternate; + } + #blue-neon-1 { + transform: scale(0.8); + animation: talkingMoveBlueNeon1 0.5s infinite alternate; + } + #blue-neon-2 { + transform: scale(0.9); + animation: talkingMoveBlueNeon2 0.5s 0.3s infinite alternate; + } +} + +@keyframes talkingBouncePurpleNeonBlur { + 50% { + transform: scale(1.07); + } + 100% { + transform: scale(1); + } +} +@keyframes talkingBouncePinkNeon1 { + 100% { + transform: scale(1.1); + } +} +@keyframes talkingMoveBlueNeon1 { + 100% { + transform: scale(0.9); + } +} +@keyframes talkingMoveBlueNeon2 { + 100% { + transform: scale(1); + } +} + +.talking .voice-particle { + opacity: 0; + animation-duration: 2s; +} +@for $i from 0 through 31 { + .talking .voice-particle[data-particle='#{$i}'] { + animation-delay: #{$i * 0.2}s; + // animation-duration: #{$i * 0.5}s; + } + + .talking .voice-particle[data-particle='#{$i}'] { + animation-name: talkingMoveParticle#{$i}; + } + + #voice-energy-container.talking { + @keyframes talkingMoveParticle#{$i} { + 0% { + opacity: 1; + transform: translate(0); + } + 50% { + opacity: 0; + } + 100% { + opacity: 0; + transform: translateX(math.cos(math.random() * 360deg)) + translateY(math.sin(math.random() * 360deg)); + } + } + } +} diff --git a/app/src/custom-aurora-components/index.ts b/app/src/custom-aurora-components/index.ts new file mode 100644 index 0000000..4621391 --- /dev/null +++ b/app/src/custom-aurora-components/index.ts @@ -0,0 +1 @@ +export * from './timer' diff --git a/app/src/custom-aurora-components/timer/index.ts b/app/src/custom-aurora-components/timer/index.ts new file mode 100644 index 0000000..4621391 --- /dev/null +++ b/app/src/custom-aurora-components/timer/index.ts @@ -0,0 +1 @@ +export * from './timer' diff --git a/app/src/custom-aurora-components/timer/timer.tsx b/app/src/custom-aurora-components/timer/timer.tsx new file mode 100644 index 0000000..5a8396d --- /dev/null +++ b/app/src/custom-aurora-components/timer/timer.tsx @@ -0,0 +1,71 @@ +import { useState, useEffect } from 'react' + +import { CircularProgress, Flexbox, Text } from '@aurora' + +interface TimerProps { + initialTime: number + interval: number + totalTimeContent: string + initialProgress?: number + onEnd?: () => void +} + +function formatTime(seconds: number): string { + const minutes = seconds >= 60 ? Math.floor(seconds / 60) : 0 + const remainingSeconds = seconds % 60 + const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes + const formattedSeconds = + remainingSeconds < 10 ? `0${remainingSeconds}` : remainingSeconds + + return `${formattedMinutes}:${formattedSeconds}` +} + +export function Timer({ + initialTime, + initialProgress, + interval, + totalTimeContent, + onEnd +}: TimerProps) { + const [progress, setProgress] = useState(initialProgress || 0) + const [timeLeft, setTimeLeft] = useState(initialTime) + + useEffect(() => { + setTimeLeft(initialTime) + setProgress(progress) + }, [initialTime]) + + useEffect(() => { + if (timeLeft <= 0) { + return + } + + const timer = setInterval(() => { + setTimeLeft((prevTime) => { + const newTime = prevTime - 1 + + if (newTime <= 0 && onEnd) { + onEnd() + } + + return newTime + }) + setProgress((prevProgress) => prevProgress + 100 / initialTime) + }, interval) + + return () => clearInterval(timer) + }, [initialTime, interval, timeLeft]) + + return ( + + + + {formatTime(timeLeft)} + + + {totalTimeContent} + + + + ) +} diff --git a/app/src/img/favicon.png b/app/src/img/favicon.png new file mode 100644 index 0000000..b5e6f7b Binary files /dev/null and b/app/src/img/favicon.png differ diff --git a/app/src/img/logo.svg b/app/src/img/logo.svg new file mode 100644 index 0000000..92b2042 --- /dev/null +++ b/app/src/img/logo.svg @@ -0,0 +1,18 @@ + + + + logo + Created with Sketch. + + + + diff --git a/app/src/img/mic.svg b/app/src/img/mic.svg new file mode 100644 index 0000000..b2fa505 --- /dev/null +++ b/app/src/img/mic.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/index.html b/app/src/index.html new file mode 100644 index 0000000..0460604 --- /dev/null +++ b/app/src/index.html @@ -0,0 +1,366 @@ + + + + + + + Leon + + + +
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ It is recommended to use a headset for a better voice experience. +
+ Otherwise, if your microphone is too sensitive or speakers are too + loud, +
+ Leon may hear his own voice and get confused. +
+
+

+
+
+ +
+
+
+ +
+
+

+ You can start to interact with me, don't be shy. +

+
+
+
+
+
+
+
+
+ +
+
+ + +
    +
  • enter to submit.
  • +
  • shift + enter for new line.
  • +
  • + shift + / to browse history. +
  • +
  • alt / cmd + c to listen.
  • +
  • / for commands.
  • +
  • @ for files.
  • +
+
+
+ + + + diff --git a/app/src/js/built-in-commands/api.js b/app/src/js/built-in-commands/api.js new file mode 100644 index 0000000..0e2c66b --- /dev/null +++ b/app/src/js/built-in-commands/api.js @@ -0,0 +1,7 @@ +import axios from 'axios' + +export async function requestBuiltInCommand(serverUrl, payload) { + const response = await axios.post(`${serverUrl}/api/v1/command`, payload) + + return response.data +} diff --git a/app/src/js/built-in-commands/built-in-commands.jsx b/app/src/js/built-in-commands/built-in-commands.jsx new file mode 100644 index 0000000..6a823f2 --- /dev/null +++ b/app/src/js/built-in-commands/built-in-commands.jsx @@ -0,0 +1,750 @@ +import { createRef } from 'react' +import { createRoot } from 'react-dom/client' + +import { requestBuiltInCommand } from './api' +import { BuiltInCommandsModal } from './modal' +import FileSystemAutocomplete from '../file-system-autocomplete' + +const AUTOCOMPLETE_DELAY_MS = 90 +const CLOSE_ANIMATION_DURATION_MS = 180 +const ROOT_COMMAND_INPUT = '/' +const EDITABLE_ACTION_KEYS = new Set(['Backspace', 'Delete']) +const NAVIGATION_DIRECTIONS = { + next: 1, + previous: -1 +} + +function isEditableElement(element) { + if (!element) { + return false + } + + const tagName = element.tagName?.toLowerCase() + + return ( + tagName === 'input' || + tagName === 'textarea' || + element.isContentEditable === true + ) +} + +export default class BuiltInCommands { + constructor({ + serverUrl, + input, + onSubmitToChat, + getActiveSessionId, + onCommandExecuted + }) { + this.serverUrl = serverUrl + this.input = input + this.onSubmitToChat = onSubmitToChat + this.getActiveSessionId = getActiveSessionId + this.onCommandExecuted = onCommandExecuted + this.sessionId = null + this.origin = 'shortcut' + this.commandValue = '' + this.selectedSuggestionIndex = -1 + this.suggestions = [] + this.recentSuggestions = [] + this.result = null + this.loadingMessage = null + this.pendingInput = null + this.isOpen = false + this.isClosing = false + this.isLoading = false + this.hasSubmitted = false + this.autocompleteTimeout = null + this.closeTimeout = null + this.shouldFocusInput = false + this.modalInputRef = createRef() + this.fileSystemAutocomplete = new FileSystemAutocomplete({ + serverUrl, + onValueChange: (value) => { + this.handleCommandChange(value) + } + }) + } + + init() { + this.mount() + this.attachEvents() + this.render() + } + + mount() { + this.container = document.createElement('div') + document.body.appendChild(this.container) + this.root = createRoot(this.container) + } + + attachEvents() { + document.addEventListener('keydown', (event) => { + this.handleDocumentKeyDown(event) + }) + + this.input.addEventListener('input', () => { + this.handleMainInput() + }) + + this.input.addEventListener('focus', () => { + this.handleMainInput() + }) + } + + render() { + const focusedInputElement = this.modalInputRef.current + const shouldRestoreCommandInputFocus = + focusedInputElement && document.activeElement === focusedInputElement + const selectionStart = shouldRestoreCommandInputFocus + ? focusedInputElement.selectionStart + : null + const selectionEnd = shouldRestoreCommandInputFocus + ? focusedInputElement.selectionEnd + : null + const { recentSelectedSuggestionIndex, suggestionSelectedSuggestionIndex } = + this.getSelectedSuggestionIndices() + + this.root.render( + { + this.handleCommandChange(value) + }} + onMaskClick={() => { + this.close() + }} + onSuggestionSelect={(suggestion) => { + this.handleSuggestionSelect(suggestion) + }} + onReturn={() => { + this.returnToSuggestions() + }} + /> + ) + + if (this.shouldFocusInput) { + this.shouldFocusInput = false + + window.requestAnimationFrame(() => { + this.focusCommandInput() + }) + } else if (shouldRestoreCommandInputFocus) { + window.requestAnimationFrame(() => { + this.restoreCommandInputFocus(selectionStart, selectionEnd) + }) + } + + if ( + this.isOpen && + !this.hasSubmitted && + !this.result && + this.selectedSuggestionIndex >= 0 + ) { + window.requestAnimationFrame(() => { + this.scrollSelectedSuggestionIntoView() + }) + } + + window.requestAnimationFrame(() => { + this.attachFileSystemAutocomplete() + }) + } + + attachFileSystemAutocomplete() { + const inputElement = this.modalInputRef.current + + if (!inputElement) { + return + } + + this.fileSystemAutocomplete.attach(inputElement) + } + + handleDocumentKeyDown(event) { + if (this.isOpen) { + if (event.metaKey || event.ctrlKey || event.altKey) { + return + } + + if (event.key === 'Escape') { + event.preventDefault() + this.close() + return + } + + if (event.key === 'ArrowDown') { + event.preventDefault() + this.blurCommandInput() + this.moveSelection(NAVIGATION_DIRECTIONS.next) + return + } + + if (event.key === 'ArrowUp') { + event.preventDefault() + this.blurCommandInput() + this.moveSelection(NAVIGATION_DIRECTIONS.previous) + return + } + + if (event.key === 'Tab') { + const suggestion = + this.selectedSuggestionIndex >= 0 + ? this.getVisibleSuggestions()[this.selectedSuggestionIndex] + : null + + if (suggestion) { + event.preventDefault() + this.applySuggestion(suggestion, { + appendTrailingSpace: true + }) + } + + return + } + + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault() + + if (this.selectedSuggestionIndex >= 0) { + const suggestion = + this.getVisibleSuggestions()[this.selectedSuggestionIndex] + + if (suggestion) { + this.applySuggestion(suggestion) + void this.submit() + return + } + } + + this.submit() + return + } + + if (this.shouldHandleDetachedInputKey(event)) { + event.preventDefault() + this.handleDetachedInputKey(event) + return + } + + return + } + + if ( + event.key !== '/' || + event.metaKey || + event.ctrlKey || + event.altKey || + event.shiftKey + ) { + return + } + + const activeElement = document.activeElement + + if ( + activeElement === this.input || + (activeElement && isEditableElement(activeElement)) + ) { + return + } + + event.preventDefault() + this.open({ + origin: 'shortcut', + rawInput: '/' + }) + } + + handleMainInput() { + if (document.activeElement !== this.input) { + return + } + + const rawValue = this.input.value || '' + + if (!rawValue.startsWith('/')) { + return + } + + this.open({ + origin: 'input', + rawInput: rawValue + }) + } + + handleCommandChange(value) { + this.commandValue = value + this.hasSubmitted = false + if (!this.pendingInput) { + this.result = null + this.loadingMessage = null + this.queueAutocomplete() + } + this.render() + } + + open({ origin, rawInput }) { + window.clearTimeout(this.closeTimeout) + + if (this.isOpen) { + this.origin = origin + this.commandValue = this.normalizeCommandValue(rawInput) + this.result = null + this.loadingMessage = null + this.pendingInput = null + this.hasSubmitted = false + this.shouldFocusInput = true + this.input.value = '' + this.queueAutocomplete() + this.render() + return + } + + this.origin = origin + this.sessionId = null + this.commandValue = this.normalizeCommandValue(rawInput) + this.suggestions = [] + this.result = null + this.loadingMessage = null + this.pendingInput = null + this.selectedSuggestionIndex = -1 + this.hasSubmitted = false + this.isOpen = true + this.isClosing = false + this.shouldFocusInput = true + this.input.value = '' + + if (this.origin === 'input') { + this.input.blur() + } + + this.queueAutocomplete() + this.render() + } + + close() { + if (!this.isOpen || this.isClosing) { + return + } + + this.isClosing = true + this.isOpen = false + this.fileSystemAutocomplete.close() + this.render() + + this.closeTimeout = window.setTimeout(() => { + this.resetState() + this.render() + this.focusMainInput() + }, CLOSE_ANIMATION_DURATION_MS) + } + + queueAutocomplete() { + window.clearTimeout(this.autocompleteTimeout) + this.isLoading = true + + this.autocompleteTimeout = window.setTimeout(() => { + void this.fetchAutocomplete() + }, AUTOCOMPLETE_DELAY_MS) + } + + async fetchAutocomplete() { + try { + const data = await requestBuiltInCommand(this.serverUrl, { + mode: 'autocomplete', + input: this.buildCommandInput(), + session_id: this.sessionId, + conversation_session_id: this.getActiveSessionId?.() + }) + + if (!this.isOpen || this.hasSubmitted) { + return + } + + this.sessionId = data.session.id + this.suggestions = data.suggestions || [] + this.recentSuggestions = data.recent_suggestions || [] + this.loadingMessage = data.session.loading_message || null + this.pendingInput = data.session.pending_input || null + this.selectedSuggestionIndex = + this.getVisibleSuggestions().length > 0 ? 0 : -1 + this.isLoading = false + this.render() + } catch (error) { + if (!this.isOpen || this.hasSubmitted) { + return + } + + this.isLoading = false + this.result = { + title: 'Command Error', + tone: 'error', + blocks: [ + { + type: 'list', + items: [ + { + label: error.message || 'Failed to load built-in commands.', + tone: 'error' + } + ] + } + ] + } + this.loadingMessage = null + this.render() + } + } + + async submit() { + const commandInput = this.buildCommandInput() + + if (commandInput === ROOT_COMMAND_INPUT) { + return + } + + window.clearTimeout(this.autocompleteTimeout) + this.autocompleteTimeout = null + + await this.resolveLoadingMessageForSubmission(commandInput) + + this.isLoading = true + this.hasSubmitted = true + this.result = null + this.commandValue = '' + this.suggestions = [] + this.selectedSuggestionIndex = -1 + this.render() + + try { + const data = await requestBuiltInCommand(this.serverUrl, { + mode: 'execute', + input: commandInput, + session_id: this.sessionId, + conversation_session_id: this.getActiveSessionId?.() + }) + + if (data.client_action?.type === 'submit_to_chat') { + const wasSubmitted = this.onSubmitToChat?.(data.client_action) + + if (!wasSubmitted) { + throw new Error('Failed to submit the built-in command to chat.') + } + + this.isLoading = false + this.close() + return + } + + this.sessionId = data.session.id + this.isLoading = false + this.result = data.result + this.onCommandExecuted?.(commandInput, data) + this.loadingMessage = data.session.loading_message || null + this.recentSuggestions = data.recent_suggestions || [] + this.pendingInput = data.session.pending_input || null + this.commandValue = '' + this.render() + } catch (error) { + this.isLoading = false + this.result = { + title: 'Command Error', + tone: 'error', + blocks: [ + { + type: 'list', + items: [ + { + label: + error.message || 'Failed to execute the built-in command.', + tone: 'error' + } + ] + } + ] + } + this.loadingMessage = null + this.render() + } + } + + async resolveLoadingMessageForSubmission(commandInput) { + try { + const data = await requestBuiltInCommand(this.serverUrl, { + mode: 'autocomplete', + input: commandInput, + session_id: this.sessionId, + conversation_session_id: this.getActiveSessionId?.() + }) + + this.sessionId = data.session.id + this.loadingMessage = data.session.loading_message || null + } catch { + this.loadingMessage = null + } + } + + moveSelection(direction) { + if (this.hasSubmitted || this.result) { + return + } + + const visibleSuggestions = this.getVisibleSuggestions() + + if (visibleSuggestions.length === 0) { + return + } + + if (this.selectedSuggestionIndex === -1) { + this.selectedSuggestionIndex = 0 + } else { + this.selectedSuggestionIndex = + (this.selectedSuggestionIndex + + direction + + visibleSuggestions.length) % + visibleSuggestions.length + } + + this.render() + } + + handleSuggestionSelect(suggestion) { + const normalizedSuggestionValue = this.normalizeCommandValue(suggestion.value) + + if (normalizedSuggestionValue.trim() === this.commandValue.trim()) { + void this.submit() + return + } + + this.applySuggestion(suggestion, { + appendTrailingSpace: true + }) + } + + applySuggestion(suggestion, options = {}) { + this.commandValue = `${this.normalizeCommandValue(suggestion.value)}${ + options.appendTrailingSpace ? ' ' : '' + }` + this.loadingMessage = null + this.queueAutocomplete() + this.shouldFocusInput = true + this.render() + } + + returnToSuggestions() { + this.sessionId = null + this.hasSubmitted = false + this.result = null + this.loadingMessage = null + this.pendingInput = null + this.commandValue = '' + this.suggestions = [] + this.selectedSuggestionIndex = -1 + this.shouldFocusInput = true + this.queueAutocomplete() + this.render() + } + + focusCommandInput() { + const inputElement = this.modalInputRef.current + + if (!inputElement) { + return + } + + inputElement.focus() + + if (typeof inputElement.setSelectionRange === 'function') { + inputElement.setSelectionRange( + inputElement.value.length, + inputElement.value.length + ) + } + } + + restoreCommandInputFocus(selectionStart, selectionEnd) { + const inputElement = this.modalInputRef.current + + if (!inputElement) { + return + } + + if (document.activeElement !== inputElement) { + try { + inputElement.focus({ preventScroll: true }) + } catch { + inputElement.focus() + } + } + + if ( + typeof inputElement.setSelectionRange === 'function' && + selectionStart !== null && + selectionEnd !== null + ) { + inputElement.setSelectionRange(selectionStart, selectionEnd) + } + } + + blurCommandInput() { + const inputElement = this.modalInputRef.current + + if (!inputElement || document.activeElement !== inputElement) { + return + } + + inputElement.blur() + } + + focusMainInput() { + if (!this.input) { + return + } + + window.requestAnimationFrame(() => { + try { + this.input.focus({ preventScroll: true }) + } catch { + this.input.focus() + } + + if (typeof this.input.setSelectionRange === 'function') { + this.input.setSelectionRange( + this.input.value.length, + this.input.value.length + ) + } + }) + } + + scrollSelectedSuggestionIntoView() { + const selectedSuggestionElement = this.container?.querySelector( + '.aurora-list-item--selected' + ) + + if (!selectedSuggestionElement) { + return + } + + selectedSuggestionElement.scrollIntoView({ + block: 'nearest' + }) + } + + shouldHandleDetachedInputKey(event) { + const inputElement = this.modalInputRef.current + + if (!inputElement || document.activeElement === inputElement) { + return false + } + + return ( + event.key.length === 1 || + EDITABLE_ACTION_KEYS.has(event.key) + ) + } + + handleDetachedInputKey(event) { + if (event.key.length === 1) { + this.commandValue += event.key + } else if (event.key === 'Backspace') { + this.commandValue = this.commandValue.slice(0, -1) + } else if (event.key === 'Delete') { + this.commandValue = '' + } + + this.hasSubmitted = false + this.result = null + this.loadingMessage = null + this.queueAutocomplete() + this.shouldFocusInput = true + this.render() + } + + normalizeCommandValue(rawInput) { + const normalizedValue = String(rawInput || '').trim() + + if (!normalizedValue.startsWith('/')) { + return normalizedValue + } + + return normalizedValue.slice(1) + } + + buildCommandInput() { + if (this.pendingInput) { + return this.commandValue + } + + return `/${this.commandValue}`.trim() + } + + getVisibleSuggestions() { + if (this.commandValue.trim() === '') { + return [...this.recentSuggestions, ...this.suggestions] + } + + return this.suggestions + } + + getSelectedSuggestionIndices() { + if (this.commandValue.trim() !== '') { + return { + recentSelectedSuggestionIndex: -1, + suggestionSelectedSuggestionIndex: this.selectedSuggestionIndex + } + } + + const recentSuggestionsLength = this.recentSuggestions.length + + if (this.selectedSuggestionIndex < 0) { + return { + recentSelectedSuggestionIndex: -1, + suggestionSelectedSuggestionIndex: -1 + } + } + + if (this.selectedSuggestionIndex < recentSuggestionsLength) { + return { + recentSelectedSuggestionIndex: this.selectedSuggestionIndex, + suggestionSelectedSuggestionIndex: -1 + } + } + + return { + recentSelectedSuggestionIndex: -1, + suggestionSelectedSuggestionIndex: + this.selectedSuggestionIndex - recentSuggestionsLength + } + } + + resetState() { + window.clearTimeout(this.autocompleteTimeout) + this.isClosing = false + this.isLoading = false + this.sessionId = null + this.origin = 'shortcut' + this.commandValue = '' + this.suggestions = [] + this.result = null + this.loadingMessage = null + this.pendingInput = null + this.selectedSuggestionIndex = -1 + this.hasSubmitted = false + this.shouldFocusInput = false + this.autocompleteTimeout = null + } +} diff --git a/app/src/js/built-in-commands/index.js b/app/src/js/built-in-commands/index.js new file mode 100644 index 0000000..a3f47af --- /dev/null +++ b/app/src/js/built-in-commands/index.js @@ -0,0 +1,3 @@ +import '../../css/built-in-commands.scss' + +export { default as BuiltInCommands } from './built-in-commands.jsx' diff --git a/app/src/js/built-in-commands/modal.jsx b/app/src/js/built-in-commands/modal.jsx new file mode 100644 index 0000000..a7f0d63 --- /dev/null +++ b/app/src/js/built-in-commands/modal.jsx @@ -0,0 +1,263 @@ +import { + Button, + Flexbox, + Icon, + Input, + List, + ListHeader, + ListItem, + Loader, + ScrollContainer, + Text +} from '@aurora' + +import { BuiltInCommandResultRenderer } from './result-renderer' + +const SLASH_COMMAND_ICON_SVG = ( + + + +) + +function parseRemixIcon(rawIconName, rawIconType) { + const fallbackIcon = { + iconName: 'terminal-box', + type: 'line' + } + const normalizedIconName = String(rawIconName || '').trim() + const normalizedIconType = ['line', 'fill', 'notype'].includes(rawIconType) + ? rawIconType + : null + + if (!normalizedIconName) { + return fallbackIcon + } + + const iconWithoutPrefix = normalizedIconName.replace(/^ri-/, '') + + if (iconWithoutPrefix.endsWith('-line')) { + return { + iconName: iconWithoutPrefix.slice(0, -5), + type: 'line' + } + } + + if (iconWithoutPrefix.endsWith('-fill')) { + return { + iconName: iconWithoutPrefix.slice(0, -5), + type: 'fill' + } + } + + return { + iconName: iconWithoutPrefix, + type: normalizedIconType || 'notype' + } +} + +function SuggestionList({ + headerTitle, + suggestions, + selectedSuggestionIndex, + onSuggestionSelect +}) { + return ( + + {headerTitle} + {suggestions.map((suggestion, index) => { + const parsedIcon = parseRemixIcon( + suggestion.icon_name, + suggestion.icon_type + ) + + return ( + { + onSuggestionSelect(suggestion) + }} + > + + +
+ {suggestion.usage} + {suggestion.description} +
+
+
+ ) + })} +
+ ) +} + +function LoadingState({ loadingMessage }) { + return ( + + Working + + + + {loadingMessage || 'Working on it...'} + + + + ) +} + +function EmptyState() { + return ( + + Suggestions + + No matching built-in command. + + + ) +} + +export function BuiltInCommandsModal({ + isOpen, + isVisible, + isLoading, + loadingMessage, + commandValue, + suggestions, + recentSuggestions, + recentSelectedSuggestionIndex, + suggestionSelectedSuggestionIndex, + result, + pendingInput, + hasSubmitted, + inputRef, + onCommandChange, + onMaskClick, + onSuggestionSelect, + onReturn +}) { + const isCommandInputEmpty = commandValue.trim() === '' + const pendingInputIcon = pendingInput?.icon_name + ? parseRemixIcon(pendingInput.icon_name, pendingInput.icon_type) + : null + + return ( +
+
+
{ + event.stopPropagation() + }} + > +
+ + {hasSubmitted && result ? ( +
+
+ ) : null} +
+ +
+
+
+
+
+ + {isLoading ? ( + + ) : result ? ( + + ) : suggestions.length > 0 ? ( + + {isCommandInputEmpty && recentSuggestions.length > 0 ? ( + + ) : null} + + + ) : ( + + )} + +
+
+
+ + + navigate + + + tab complete + + + enter submit + + + esc close + + +
+
+
+ ) +} diff --git a/app/src/js/built-in-commands/result-renderer.jsx b/app/src/js/built-in-commands/result-renderer.jsx new file mode 100644 index 0000000..bfe8ffb --- /dev/null +++ b/app/src/js/built-in-commands/result-renderer.jsx @@ -0,0 +1,145 @@ +import { + Flexbox, + Icon, + Link, + List, + ListHeader, + ListItem, + Text +} from '@aurora' + +function InlineLabel({ item }) { + if (item.inline_link_label && item.inline_link_href) { + return ( + + {item.label}{' '} + + {item.inline_link_label} + . + + ) + } + + return {item.label} +} + +function ToneListItem({ item }) { + if (item.tone === 'success') { + return ( + + + + + + + ) + } + + if (item.tone === 'warning') { + return ( + + + + + + + ) + } + + if (item.tone === 'error') { + return ( + + + + + + + ) + } + + if (item.value || item.description) { + return ( + +
+
+ {item.label} + {item.description ? {item.description} : null} +
+ {item.value ? ( +
+ {item.href ? ( + + {item.value} + + ) : ( + + {item.value} + + )} +
+ ) : null} +
+
+ ) + } + + if (item.inline_link_label && item.inline_link_href) { + return ( + + + + ) + } + + return ( + + + + ) +} + +export function BuiltInCommandResultRenderer({ result }) { + const blocks = Array.isArray(result?.blocks) ? result.blocks : [] + + return ( + + {blocks.map((block, index) => { + if (block.type !== 'list') { + return null + } + + const header = block.header || (index === 0 ? result.title : '') + + return ( + + {header ? {header} : null} + {block.items.map((item, itemIndex) => ( + + ))} + + ) + })} + + ) +} diff --git a/app/src/js/chatbot.js b/app/src/js/chatbot.js new file mode 100644 index 0000000..3ce5cf3 --- /dev/null +++ b/app/src/js/chatbot.js @@ -0,0 +1,957 @@ +import { createElement } from 'react' +import { createRoot } from 'react-dom/client' +import axios from 'axios' + +import { WidgetWrapper, Flexbox, Loader, Text } from '@aurora' + +import renderAuroraComponent from './render-aurora-component' +import ToolUIHandler from './tool-ui-handler' + +const WIDGETS_TO_FETCH = [] +const WIDGETS_FETCH_CACHE = new Map() +const REPLACED_MESSAGES = new Set() +const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 24 +const MAXIMUM_BUBBLES_IN_MEMORY = 62 +const MAXIMUM_WIDGET_FETCH_CONCURRENCY = 4 +const SECONDS_PER_MINUTE = 60 + +function escapeHTML(value) { + return String(value || '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +export default class Chatbot { + constructor(socket, serverURL, sessionId = null) { + this.socket = socket + this.serverURL = serverURL + this.sessionId = sessionId + this.et = new EventTarget() + this.feed = document.querySelector('#feed') + this.typing = document.querySelector('#is-typing') + this.noBubbleMessage = document.querySelector('#no-bubble') + this.parsedBubbles = [] + this.reasoningBlocks = new Map() + this.feedAutoScrollEnabled = true + this.isProgrammaticFeedScroll = false + this.widgetHydrationPromise = null + + // Initialize tool UI handler + this.toolUIHandler = new ToolUIHandler( + this.feed, + this.scrollDown.bind(this), + this.formatMessage.bind(this) + ) + } + + async init() { + await this.loadFeed() + this.scrollDown() + + this.et.addEventListener('to-leon', (event) => { + this.createBubble({ + who: 'me', + string: event.detail.string, + sentAt: event.detail.sentAt + }) + }) + + this.et.addEventListener('me-received', (event) => { + this.createBubble({ + who: 'leon', + string: event.detail + }) + }) + + // Add event delegation for clickable paths + this.feed.addEventListener('click', (event) => { + if (event.target.classList.contains('clickable-path')) { + const path = event.target.getAttribute('data-path') + if (path) { + this.openPath(path) + } + } + }) + + this.feed.addEventListener( + 'scroll', + () => { + this.handleFeedScroll() + }, + { passive: true } + ) + } + + sendTo(who, string, sentAt = Date.now()) { + if (who === 'leon') { + this.et.dispatchEvent( + new CustomEvent('to-leon', { + detail: { + string, + sentAt + } + }) + ) + } + } + + receivedFrom(who, string) { + if (who === 'leon') { + this.et.dispatchEvent(new CustomEvent('me-received', { detail: string })) + } + } + + isTyping(who, value) { + if (who === 'leon') { + if (value) { + this.enableTyping() + } else if (value === false) { + this.disableTyping() + } + } + } + + enableTyping() { + if (!this.typing.classList.contains('on')) { + this.typing.classList.add('on') + } + } + + disableTyping() { + if (this.typing.classList.contains('on')) { + this.typing.classList.remove('on') + } + } + + isElementNearBottom(element) { + if (!element) { + return true + } + + const remainingScrollableDistance = + element.scrollHeight - (element.scrollTop + element.clientHeight) + + return remainingScrollableDistance <= AUTO_SCROLL_BOTTOM_THRESHOLD_PX + } + + handleFeedScroll() { + if (!this.feed || this.isProgrammaticFeedScroll) { + return + } + + this.feedAutoScrollEnabled = this.isElementNearBottom(this.feed) + } + + scrollDown(options = {}) { + if (!this.feed) { + return + } + + const { force = false } = options + + if (!force && !this.feedAutoScrollEnabled) { + return + } + + this.isProgrammaticFeedScroll = true + this.feed.scrollTo(0, this.feed.scrollHeight) + + requestAnimationFrame(() => { + this.isProgrammaticFeedScroll = false + this.feedAutoScrollEnabled = this.isElementNearBottom(this.feed) + }) + } + + scrollReasoningContentToBottom(reasoningBlock) { + if (!reasoningBlock?.content || !reasoningBlock.isAutoScrollEnabled) { + return + } + + reasoningBlock.isProgrammaticScroll = true + reasoningBlock.content.scrollTop = reasoningBlock.content.scrollHeight + + requestAnimationFrame(() => { + reasoningBlock.isProgrammaticScroll = false + reasoningBlock.isAutoScrollEnabled = this.isElementNearBottom( + reasoningBlock.content + ) + }) + } + + getWidgetPayload(formattedString) { + if ( + typeof formattedString !== 'string' || + !formattedString.includes('"component":"WidgetWrapper"') + ) { + return null + } + + try { + return JSON.parse(formattedString) + } catch { + return null + } + } + + getPlanWidgetInsertionPoint(widgetPayload) { + if (!widgetPayload || widgetPayload.widget !== 'PlanWidget') { + return null + } + + // Always append new plan widgets as new bubbles. + // Widget updates are handled via replaceMessageId targeting the same + // messageId, so insertion-point heuristics are unnecessary and can cause + // visual reuse across turns. + return null + } + + isPlanWidgetData(data) { + return Boolean(data && typeof data === 'object' && data.widget === 'PlanWidget') + } + + isSystemWidgetData(data) { + return Boolean( + data && + typeof data === 'object' && + data.historyMode && + data.historyMode === 'system_widget' + ) + } + + getTimelineItemWeight(item) { + if (item.who === 'owner') { + return 0 + } + + if (item.source === 'system_widget') { + return 1 + } + + return 2 + } + + async hydrateFetchedWidgets() { + if (this.widgetHydrationPromise) { + return this.widgetHydrationPromise + } + + const widgetContainers = [...WIDGETS_TO_FETCH].reverse() + WIDGETS_TO_FETCH.length = 0 + + if (widgetContainers.length === 0) { + return Promise.resolve() + } + + const hydrateWidgetContainer = async (widgetContainer) => { + const hasWidgetBeenFetched = WIDGETS_FETCH_CACHE.has( + widgetContainer.widgetId + ) + + if (hasWidgetBeenFetched) { + const fetchedWidget = WIDGETS_FETCH_CACHE.get(widgetContainer.widgetId) + widgetContainer.reactRootNode.render(fetchedWidget.reactNode) + + setTimeout(() => { + this.scrollDown() + }, 100) + + return + } + + const data = await axios.get( + `${this.serverURL}/api/v1/fetch-widget?skill_action=${widgetContainer.onFetch.actionName}&widget_id=${widgetContainer.widgetId}${this.sessionId ? `&session_id=${encodeURIComponent(this.sessionId)}` : ''}` + ) + const fetchedWidget = data.data.widget + const reactNode = fetchedWidget + ? renderAuroraComponent( + this.socket, + fetchedWidget.componentTree, + fetchedWidget.supportedEvents + ) + : createElement(WidgetWrapper, { + children: createElement(Flexbox, { + alignItems: 'center', + justifyContent: 'center', + children: createElement(Text, { + secondary: true, + children: 'This widget has been deleted.' + }) + }) + }) + + widgetContainer.reactRootNode.render(reactNode) + WIDGETS_FETCH_CACHE.set(widgetContainer.widgetId, { + ...fetchedWidget, + reactNode + }) + setTimeout(() => { + this.scrollDown() + }, 100) + } + + const workerCount = Math.min( + MAXIMUM_WIDGET_FETCH_CONCURRENCY, + widgetContainers.length + ) + let currentIndex = 0 + + this.widgetHydrationPromise = Promise.all( + Array.from({ length: workerCount }, async () => { + while (currentIndex < widgetContainers.length) { + const widgetContainer = widgetContainers[currentIndex] + currentIndex += 1 + + if (!widgetContainer) { + continue + } + + await hydrateWidgetContainer(widgetContainer) + } + }) + ) + .catch((error) => { + console.error('Failed to hydrate fetched widgets:', error) + }) + .finally(() => { + this.widgetHydrationPromise = null + }) + + return this.widgetHydrationPromise + } + + setSessionId(sessionId) { + this.sessionId = sessionId + } + + resetFeed() { + WIDGETS_TO_FETCH.length = 0 + this.feed.innerHTML = '' + this.noBubbleMessage = document.createElement('p') + this.noBubbleMessage.id = 'no-bubble' + this.noBubbleMessage.className = 'hide' + this.noBubbleMessage.textContent = + 'You can start to interact with me, don\'t be shy.' + this.feed.appendChild(this.noBubbleMessage) + this.parsedBubbles = [] + this.reasoningBlocks.clear() + this.feedAutoScrollEnabled = true + } + + async loadFeed() { + WIDGETS_TO_FETCH.length = 0 + this.resetFeed() + const sessionQuery = this.sessionId + ? `&session_id=${encodeURIComponent(this.sessionId)}` + : '' + + const [historyResponse, systemWidgetsResponse] = await Promise.all([ + axios.get( + `${this.serverURL}/api/v1/conversation-history?supports_widgets=true${sessionQuery}` + ), + axios.get( + `${this.serverURL}/api/v1/system-widgets?supports_widgets=true${sessionQuery}` + ) + ]) + const history = Array.isArray(historyResponse.data?.history) + ? historyResponse.data.history + : [] + const systemWidgets = Array.isArray(systemWidgetsResponse.data?.widgets) + ? systemWidgetsResponse.data.widgets + : [] + + const timelineItems = [...history, ...systemWidgets] + .map((item, index) => ({ + ...item, + sortIndex: index + })) + .sort((left, right) => { + if (left.sentAt !== right.sentAt) { + return left.sentAt - right.sentAt + } + + const leftWeight = this.getTimelineItemWeight(left) + const rightWeight = this.getTimelineItemWeight(right) + + if (leftWeight !== rightWeight) { + return leftWeight - rightWeight + } + + return left.sortIndex - right.sortIndex + }) + + this.parsedBubbles = history + + if (timelineItems.length === 0) { + this.noBubbleMessage.classList.remove('hide') + return + } + + for (let i = 0; i < timelineItems.length; i += 1) { + const bubble = timelineItems[i] + + if ( + bubble.originalString && + ToolUIHandler.isToolOutputMarker(bubble.originalString) + ) { + continue + } + + this.createBubble({ + who: bubble.who === 'owner' ? 'me' : bubble.who, + string: bubble.originalString ? bubble.originalString : bubble.string, + metrics: bubble.llmMetrics || null, + sentAt: bubble.sentAt, + save: false, + isCreatingFromLoadingFeed: true, + messageId: bubble.messageId + }) + } + + void this.hydrateFetchedWidgets() + } + + createBubble(params) { + const { + who, + string, + metrics = null, + save = true, + bubbleId, + isCreatingFromLoadingFeed = false, + messageId, + sentAt = null, + beforeElement = null + } = params + const container = document.createElement('div') + const bubble = document.createElement('p') + + if (!this.noBubbleMessage.classList.contains('hide')) { + this.noBubbleMessage.classList.add('hide') + } + + container.className = `bubble-container ${who}` + bubble.className = 'bubble' + + if (messageId) { + container.setAttribute('data-message-id', messageId) + } + + // Store original string before formatting + const originalString = string + const formattedString = this.formatMessage(string) + const widgetPayload = this.getWidgetPayload(formattedString) + const autoPlanInsertionPoint = this.getPlanWidgetInsertionPoint(widgetPayload) + const resolvedBeforeElement = beforeElement || autoPlanInsertionPoint + + bubble.innerHTML = formattedString + + if (bubbleId) { + container.classList.add(bubbleId) + } + + if (resolvedBeforeElement && resolvedBeforeElement.parentNode === this.feed) { + this.feed.insertBefore(container, resolvedBeforeElement) + } else { + this.feed.appendChild(container) + } + container.appendChild(bubble) + + if (who === 'leon' && metrics) { + container.appendChild(this.createMetricsElement(metrics, sentAt)) + } else if (who === 'me') { + const timestampElement = this.createTimestampElement(sentAt) + + if (timestampElement) { + container.appendChild(timestampElement) + } + } + + let widgetComponentTree = null + let widgetSupportedEvents = null + + /** + * Widget rendering + */ + if ( + formattedString.includes && + formattedString.includes('"component":"WidgetWrapper"') + ) { + const parsedWidget = widgetPayload || JSON.parse(formattedString) + container.setAttribute('data-widget-id', parsedWidget.id) + + /** + * On widget fetching, render the loader + */ + if (isCreatingFromLoadingFeed && parsedWidget.onFetch) { + const root = createRoot(container) + + root.render( + createElement(WidgetWrapper, { + children: createElement(Flexbox, { + alignItems: 'center', + justifyContent: 'center', + children: createElement(Loader) + }) + }) + ) + + WIDGETS_TO_FETCH.push({ + reactRootNode: root, + widgetId: parsedWidget.id, + onFetch: parsedWidget.onFetch + }) + + return container + } + + widgetComponentTree = parsedWidget.componentTree + widgetSupportedEvents = parsedWidget.supportedEvents + + /** + * On widget creation + */ + const root = createRoot(container) + + const reactNode = renderAuroraComponent( + this.socket, + widgetComponentTree, + widgetSupportedEvents + ) + + root.render(reactNode) + } + + if (save) { + this.saveBubble(who, originalString, formattedString, messageId, metrics, sentAt) + } + + return container + } + + formatReasoningPhaseTitle(phase) { + const normalizedPhase = + typeof phase === 'string' && phase.trim() + ? phase.replaceAll('_', ' ').toUpperCase() + : 'EXECUTION' + + return `REASONING - ${normalizedPhase}` + } + + createOrUpdateReasoningBlock(generationId, token, phase) { + if (!generationId || !token) { + return null + } + + if (!this.noBubbleMessage.classList.contains('hide')) { + this.noBubbleMessage.classList.add('hide') + } + + let reasoningBlock = this.reasoningBlocks.get(generationId) + + if (!reasoningBlock) { + const container = document.createElement('div') + const block = document.createElement('div') + const header = document.createElement('div') + const icon = document.createElement('i') + const title = document.createElement('span') + const content = document.createElement('div') + + container.className = 'reasoning-block-container leon' + container.setAttribute('data-reasoning-id', generationId) + block.className = 'reasoning-block' + header.className = 'reasoning-header' + icon.className = 'ri-brain-ai-3-line reasoning-icon' + title.className = 'reasoning-title' + title.textContent = this.formatReasoningPhaseTitle(phase) + content.className = 'reasoning-content' + + header.appendChild(icon) + header.appendChild(title) + block.appendChild(header) + block.appendChild(content) + container.appendChild(block) + this.feed.appendChild(container) + + reasoningBlock = { + container, + content, + text: '', + isAutoScrollEnabled: true, + isProgrammaticScroll: false + } + content.addEventListener( + 'scroll', + () => { + if (reasoningBlock.isProgrammaticScroll) { + return + } + + reasoningBlock.isAutoScrollEnabled = this.isElementNearBottom(content) + }, + { passive: true } + ) + this.reasoningBlocks.set(generationId, reasoningBlock) + } + + reasoningBlock.text += token + reasoningBlock.content.textContent = reasoningBlock.text + this.scrollReasoningContentToBottom(reasoningBlock) + + return reasoningBlock.container + } + + handleToolOutput(data) { + const result = this.toolUIHandler.handleToolOutput(data) + + // Save in memory if it's a new group + if (result && result.isNewGroup) { + const { toolkitName, toolName, answer } = data + const toolInfo = this.toolUIHandler.getToolGroupInfo( + result.groupId, + toolkitName, + toolName, + answer + ) + + this.saveBubble( + 'leon', + toolInfo.originalString, + toolInfo.formattedMessage, + toolInfo.messageId + ) + } + } + + saveBubble( + who, + originalString, + string, + messageId, + metrics = null, + sentAt = null + ) { + if (!this.noBubbleMessage.classList.contains('hide')) { + this.noBubbleMessage.classList.add('hide') + } + + if (this.parsedBubbles.length === MAXIMUM_BUBBLES_IN_MEMORY) { + this.parsedBubbles.shift() + } + + // Store both original and formatted strings + this.parsedBubbles.push({ + who, + sentAt, + string, + originalString, + messageId, + llmMetrics: metrics + }) + this.scrollDown() + } + + formatMessage(message) { + const isWidget = + message.includes && message.includes('"component":"WidgetWrapper"') + + if (typeof message === 'string' && !isWidget) { + message = escapeHTML(message) + message = message.replace(/\n/g, '
') + + // Handle HTTP/HTTPS URLs with simple regex + message = message.replace(/https?:\/\/[^\s<>"{}|\\^`[\]]+/gi, (match) => { + return `${match}` + }) + + // Handle file paths with delimiters for exact matching + message = message.replace( + /\[FILE_PATH\](.*?)\[\/FILE_PATH\]/g, + (match, filePath) => { + return `${filePath}` + } + ) + } + + return message + } + + formatMetricTimestamp(sentAt) { + if (typeof sentAt !== 'number' || !Number.isFinite(sentAt)) { + return '' + } + + const date = new Date(sentAt) + const now = new Date() + + if (Number.isNaN(date.getTime()) || Number.isNaN(now.getTime())) { + return '' + } + + const timeFormatter = new Intl.DateTimeFormat(undefined, { + hour: '2-digit', + minute: '2-digit', + hour12: false + }) + const formattedTime = timeFormatter.format(date) + const startOfToday = new Date( + now.getFullYear(), + now.getMonth(), + now.getDate() + ) + const startOfTargetDay = new Date( + date.getFullYear(), + date.getMonth(), + date.getDate() + ) + const dayDifference = Math.round( + (startOfToday.getTime() - startOfTargetDay.getTime()) / 86_400_000 + ) + + if (dayDifference === 0) { + return `Today, ${formattedTime}` + } + + if (dayDifference === 1) { + return `Yesterday, ${formattedTime}` + } + + if (dayDifference > 1 && dayDifference < 7) { + const weekdayFormatter = new Intl.DateTimeFormat(undefined, { + weekday: 'long' + }) + + return `${weekdayFormatter.format(date)}, ${formattedTime}` + } + + const monthDayFormatter = new Intl.DateTimeFormat(undefined, { + month: 'short', + day: 'numeric' + }) + + return `${monthDayFormatter.format(date)}, ${formattedTime}` + } + + formatFullMetricTimestamp(sentAt) { + if (typeof sentAt !== 'number' || !Number.isFinite(sentAt)) { + return '' + } + + const date = new Date(sentAt) + + if (Number.isNaN(date.getTime())) { + return '' + } + + const year = date.getFullYear() + const month = String(date.getMonth() + 1).padStart(2, '0') + const day = String(date.getDate()).padStart(2, '0') + const hours = String(date.getHours()).padStart(2, '0') + const minutes = String(date.getMinutes()).padStart(2, '0') + const seconds = String(date.getSeconds()).padStart(2, '0') + + return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` + } + + formatTimestampMarkup(sentAt) { + const formattedTimestamp = this.formatMetricTimestamp(sentAt) + const fullFormattedTimestamp = this.formatFullMetricTimestamp(sentAt) + + if (!formattedTimestamp) { + return '' + } + + return ` + + + ${formattedTimestamp} + + `.trim() + } + + formatTurnDuration(durationMs) { + const durationSeconds = Number(durationMs || 0) / 1_000 + const roundedDurationSeconds = Math.max(0, Number(durationSeconds.toFixed(1))) + + if (roundedDurationSeconds < SECONDS_PER_MINUTE) { + return `${roundedDurationSeconds.toFixed(1)}s` + } + + const minutes = Math.floor(roundedDurationSeconds / SECONDS_PER_MINUTE) + const seconds = roundedDurationSeconds % SECONDS_PER_MINUTE + + return `${minutes}m${seconds.toFixed(1)}s` + } + + formatMetrics(metrics, sentAt = null) { + if (!metrics) { + return '' + } + + const inputTokens = Number(metrics.inputTokens || 0) + const outputTokens = Number(metrics.outputTokens || 0) + const totalTokens = Number(metrics.totalTokens || inputTokens + outputTokens) + const turnDuration = this.formatTurnDuration(metrics.durationMs) + const tokensPerSecond = Number( + metrics.tokensPerSecond || metrics.averagedPhaseTokensPerSecond || 0 + ) + const tokenFormatter = new Intl.NumberFormat() + const timestampMarkup = this.formatTimestampMarkup(sentAt) + + return ` + + + ${tokenFormatter.format(totalTokens)} (i:${tokenFormatter.format(inputTokens)}/o:${tokenFormatter.format(outputTokens)}) tok + + + + ${turnDuration} + + + + ${tokensPerSecond.toFixed(2)} t/s + + ${timestampMarkup} + `.trim() + } + + createMetricsElement(metrics, sentAt = null) { + const metricsElement = document.createElement('div') + + metricsElement.className = 'bubble-metrics' + metricsElement.innerHTML = this.formatMetrics(metrics, sentAt) + + return metricsElement + } + + createTimestampElement(sentAt) { + const timestampMarkup = this.formatTimestampMarkup(sentAt) + + if (!timestampMarkup) { + return null + } + + const timestampElement = document.createElement('div') + + timestampElement.className = 'bubble-metrics' + timestampElement.innerHTML = timestampMarkup + + return timestampElement + } + + updateBubbleMetrics(container, metrics, sentAt = null) { + if (!container) { + return + } + + const existingMetricsElement = container.querySelector('.bubble-metrics') + + if (!metrics) { + if (existingMetricsElement) { + existingMetricsElement.remove() + } + + return + } + + if (existingMetricsElement) { + existingMetricsElement.innerHTML = this.formatMetrics(metrics, sentAt) + return + } + + container.appendChild(this.createMetricsElement(metrics, sentAt)) + } + + getLatestReasoningContainer() { + const reasoningContainers = this.feed.querySelectorAll( + '.reasoning-block-container' + ) + + if (reasoningContainers.length === 0) { + return null + } + + return reasoningContainers[reasoningContainers.length - 1] || null + } + + replaceMessage(replaceMessageId, newData) { + const existingBubble = document.querySelector( + `[data-message-id="${replaceMessageId}"]` + ) + const isPlanWidget = this.isPlanWidgetData(newData) + const nextSibling = existingBubble ? existingBubble.nextSibling : null + + if (existingBubble) { + existingBubble.remove() + + const bubbleIndex = this.parsedBubbles.findIndex( + (bubble) => bubble.messageId === replaceMessageId + ) + if (bubbleIndex !== -1) { + this.parsedBubbles.splice(bubbleIndex, 1) + } + } + + const isTextAnswerPayload = Boolean( + newData && + typeof newData === 'object' && + typeof newData.answer === 'string' && + !newData.widget && + !newData.componentTree + ) + const bubbleString = isTextAnswerPayload + ? newData.answer + : typeof newData === 'string' + ? newData + : JSON.stringify(newData) + const metrics = + isTextAnswerPayload && newData.llmMetrics ? newData.llmMetrics : null + + const shouldSaveMessage = !this.isSystemWidgetData(newData) + const beforeElement = isPlanWidget ? null : nextSibling + + this.createBubble({ + who: 'leon', + string: bubbleString, + save: shouldSaveMessage, + messageId: replaceMessageId, + beforeElement, + metrics, + sentAt: + newData && typeof newData === 'object' && typeof newData.sentAt === 'number' + ? newData.sentAt + : Date.now() + }) + + /** + * Only scroll down on the first replacement of this message + * to avoid repeating scrolling for every message replacement + */ + if (!REPLACED_MESSAGES.has(replaceMessageId)) { + REPLACED_MESSAGES.add(replaceMessageId) + this.scrollDown() + } + } + + openPath(filePath) { + // Send request to server to open the file path in system file explorer + fetch(`${this.serverURL}/api/v1/open-path`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ path: filePath }) + }) + .then((response) => response.json()) + .then((data) => { + if (!data.success) { + console.error('Failed to open path:', data.error) + } + }) + .catch((error) => { + console.error('Error opening path:', error) + }) + } +} diff --git a/app/src/js/client.js b/app/src/js/client.js new file mode 100644 index 0000000..18184ca --- /dev/null +++ b/app/src/js/client.js @@ -0,0 +1,651 @@ +import { io } from 'socket.io-client' + +import Chatbot from './chatbot' +import VoiceEnergy from './voice-energy' +import { ASR_DISABLED_MESSAGE, INIT_MESSAGES } from './constants' +import handleSuggestions from './suggestion-handler.js' + +const LEON_CLIENT_INTERFACE_PROTOCOL_VERSION = 1 +const LEON_EVENTS = { + init: 'leon:init', + utterance: 'leon:utterance', + ready: 'leon:ready', + answer: 'leon:answer', + isTyping: 'leon:is-typing', + suggest: 'leon:suggest', + llmToken: 'leon:llm-token', + llmReasoningToken: 'leon:llm-reasoning-token', + ownerUtterance: 'leon:owner-utterance', + error: 'leon:error' +} + +export default class Client { + constructor(client, serverUrl, input, options = {}) { + this.client = client + this._input = input + this.voiceSpeechElement = document.querySelector('#voice-speech') + this.serverUrl = serverUrl + this.socket = io(this.serverUrl) + this.activeSessionId = options.activeSessionId || null + this.history = localStorage.getItem('history') + this.parsedHistory = [] + this.chatbot = new Chatbot(this.socket, this.serverUrl, this.activeSessionId) + this.voiceEnergy = new VoiceEnergy(this) + this._recorder = {} + this._suggestions = [] + this._answerGenerationId = 'xxx' + this._activeStreamGenerationId = null + this._ttsAudioContext = null + this._isLeonGeneratingAnswer = false + this._isVoiceModeEnabled = false + this._hasSentInitMessages = false + this._chatbotInitPromise = null + // this._ttsAudioContextes = {} + } + + set input(newInput) { + if (typeof newInput !== 'undefined') { + this._input.value = newInput + } + } + + get input() { + return this._input + } + + set recorder(recorder) { + this._recorder = recorder + } + + get recorder() { + return this._recorder + } + + updateMood(mood) { + const moodContainer = document.querySelector('#mood') + + if (!moodContainer || !mood?.emoji || !mood?.type) { + return + } + + moodContainer.textContent = `Leon's mood: ${mood.emoji}` + moodContainer.setAttribute('title', mood.type) + } + + setSessionPanel(sessionPanel) { + this.sessionPanel = sessionPanel + } + + async setActiveSession(sessionId) { + if (!sessionId || sessionId === this.activeSessionId) { + return + } + + this.activeSessionId = sessionId + this.chatbot.setSessionId(sessionId) + this.socket.emit('session-change', sessionId) + await this.chatbot.loadFeed() + this.chatbot.scrollDown({ force: true }) + } + + async sendInitMessages() { + for (let i = 0; i < INIT_MESSAGES.length; i++) { + const messages = INIT_MESSAGES[i] + const message = messages[Math.floor(Math.random() * messages.length)] + const sendingDelay = Math.floor(Math.random() * 2000) + 1000 + const typingFactorDelay = Math.floor(Math.random() * 4) + 2 + + setTimeout(() => { + this.chatbot.isTyping('leon', true) + }, sendingDelay / typingFactorDelay) + + await new Promise((resolve) => setTimeout(resolve, sendingDelay)) + + this.chatbot.receivedFrom('leon', message) + this.chatbot.isTyping('leon', false) + } + } + + setInitStatus(statusName, statusType) { + window.leonInitStatusEvent.dispatchEvent( + new CustomEvent('initStatusChange', { + detail: { + statusName, + statusType + } + }) + ) + } + + waitForInitUICompletion() { + if (this._hasSentInitMessages || this.chatbot.parsedBubbles?.length > 0) { + return + } + + const trySendInitMessages = () => { + const initializedInitElement = document.querySelector('#init .initialized') + + if (!initializedInitElement) { + return false + } + + this._hasSentInitMessages = true + this.sendInitMessages() + return true + } + + if (trySendInitMessages()) { + return + } + + const interval = setInterval(() => { + if (trySendInitMessages()) { + clearInterval(interval) + } + }, 100) + } + + asrStartRecording() { + if (!window.leonConfigInfo.asr.enabled) { + alert(ASR_DISABLED_MESSAGE) + return + } + + if (!this._isVoiceModeEnabled) { + this.enableVoiceMode() + + this.voiceEnergy.status = 'listening' + + this.socket.emit('asr-start-record') + } + } + + init() { + this._chatbotInitPromise = this.chatbot.init() + this.voiceEnergy.init() + + if (window.leonConfigInfo?.tcpServer?.enabled === false) { + this.setInitStatus('tcpServerBoot', 'success') + } + + this.socket.on('connect', () => { + this.socket.emit(LEON_EVENTS.init, { + protocolVersion: LEON_CLIENT_INTERFACE_PROTOCOL_VERSION, + client: { + id: this.client, + type: 'web_app', + name: 'Leon Web App' + }, + sessionId: this.activeSessionId, + capabilities: { + supportsWidgets: true, + supportsTokenStreaming: true, + supportsVoice: true + } + }) + }) + + /** + * Init status listeners + */ + this.socket.on('init-llama-server-boot', (status) => { + this.setInitStatus('llamaServerBoot', status) + }) + + this.socket.on(LEON_EVENTS.ready, () => { + this.setInitStatus('clientCoreServerHandshake', 'success') + this.setInitStatus('tcpServerBoot', 'success') + + void this._chatbotInitPromise?.then(() => { + setTimeout(() => { + const body = document.querySelector('body') + body.classList.remove('settingup') + }, 250) + + this.waitForInitUICompletion() + }) + }) + + this.socket.on(LEON_EVENTS.answer, (data) => { + /*if (this._isVoiceModeEnabled) { + this.voiceEnergy.status = 'listening' + }*/ + + // Leon has finished to answer + this._isLeonGeneratingAnswer = false + + const isPlanWidget = + data && typeof data === 'object' && data.widget === 'PlanWidget' + + if (isPlanWidget) { + this.chatbot.isTyping('leon', false) + } + + /** + * Handle message replacement if replaceMessageId is provided + */ + if (data.replaceMessageId) { + this.chatbot.replaceMessage(data.replaceMessageId, data) + return + } + + /** + * Handle tool output messages + */ + if (data.isToolOutput) { + this.chatbot.handleToolOutput(data) + return + } + + /** + * Handle widget data directly + */ + if (data.widget || data.componentTree) { + const isSystemWidget = this.chatbot.isSystemWidgetData(data) + // Pass the entire widget data as JSON string for chatbot.js to handle + const widgetString = + typeof data === 'string' ? data : JSON.stringify(data) + + this.chatbot.createBubble({ + who: 'leon', + string: widgetString, + save: !isSystemWidget, + messageId: data.widget?.id || data.id || `msg-${Date.now()}` + }) + + return + } + + const answerText = typeof data === 'string' ? data : data.answer + const llmMetrics = + data && typeof data === 'object' && data.llmMetrics + ? data.llmMetrics + : null + + /** + * Just save the bubble if the newest bubble is from the streaming. + * Otherwise, create a new bubble + */ + const streamGenerationId = + this._activeStreamGenerationId || this._answerGenerationId + const streamedBubbleContainerElement = streamGenerationId + ? document.querySelector( + `.bubble-container.leon.${streamGenerationId}` + ) + : null + const isBubbleFromStreaming = Boolean(streamedBubbleContainerElement) + + if (isBubbleFromStreaming && streamedBubbleContainerElement) { + this.chatbot.saveBubble( + 'leon', + answerText, + answerText, + null, + llmMetrics, + data && typeof data === 'object' && typeof data.sentAt === 'number' + ? data.sentAt + : Date.now() + ) + + // Slightly delay the update to avoid the stream animation to be interrupted + setTimeout(() => { + // Update the text of the bubble (quick emoji fix) + streamedBubbleContainerElement.querySelector('p.bubble').innerHTML = + this.chatbot.formatMessage(answerText) + this.chatbot.updateBubbleMetrics( + streamedBubbleContainerElement, + llmMetrics, + data && typeof data === 'object' && typeof data.sentAt === 'number' + ? data.sentAt + : Date.now() + ) + }, 2_500) + } else { + this.chatbot.createBubble({ + who: 'leon', + string: answerText, + save: + !( + data && + typeof data === 'object' && + data.historyMode === 'system_widget' + ), + metrics: llmMetrics, + messageId: data && typeof data === 'object' ? data.messageId : null, + sentAt: + data && typeof data === 'object' && typeof data.sentAt === 'number' + ? data.sentAt + : Date.now() + }) + } + this.chatbot.scrollDown({ force: true }) + + this._activeStreamGenerationId = null + this._answerGenerationId = 'xxx' + void this.sessionPanel?.refresh() + }) + + this.socket.on(LEON_EVENTS.suggest, (data) => { + setTimeout(() => { + handleSuggestions(data, this.chatbot, this) + }, 400) + setTimeout(() => { + this.chatbot.scrollDown() + }, 450) + /*data?.forEach((suggestionText) => { + this.addSuggestion(suggestionText) + })*/ + }) + + this.socket.on(LEON_EVENTS.isTyping, (data) => { + this.chatbot.isTyping('leon', data) + }) + + this.socket.on(LEON_EVENTS.ownerUtterance, (data) => { + if (!data?.utterance) { + return + } + + this.chatbot.createBubble({ + who: 'me', + string: data.utterance, + messageId: data.messageId, + sentAt: typeof data.sentAt === 'number' ? data.sentAt : Date.now() + }) + }) + + this.socket.on('recognized', (data, cb) => { + this._input.value = data + this.send('utterance') + + cb('string-received') + }) + + this.socket.on('widget-send-utterance', (utterance) => { + this._input.value = utterance + this.send('utterance') + }) + + this.socket.on('new-mood', (mood) => { + this.updateMood(mood) + }) + + this.socket.on(LEON_EVENTS.llmToken, (data) => { + if (this._isVoiceModeEnabled) { + this.voiceEnergy.status = 'processing' + } + + this._isLeonGeneratingAnswer = true + const previousGenerationId = this._answerGenerationId + const newGenerationId = data.generationId + this._answerGenerationId = newGenerationId + this._activeStreamGenerationId = newGenerationId + const isSameGeneration = previousGenerationId === newGenerationId + let bubbleContainerElement = null + + if (!isSameGeneration) { + bubbleContainerElement = this.chatbot.createBubble({ + who: 'leon', + string: data.token, + save: false, + bubbleId: newGenerationId + }) + } else { + bubbleContainerElement = document.querySelector( + `.${previousGenerationId}` + ) + } + + const bubbleElement = bubbleContainerElement.querySelector('p.bubble') + + // Token is already appened when it's a new generation + if (isSameGeneration) { + // bubbleElement.textContent += data.token + + const tokenSpan = document.createElement('span') + tokenSpan.className = 'llm-token fade-in' + tokenSpan.textContent = data.token + + bubbleElement.appendChild(tokenSpan) + } + + this.chatbot.scrollDown() + }) + + this.socket.on(LEON_EVENTS.llmReasoningToken, (data) => { + if (!data?.generationId || !data?.token) { + return + } + + if (this._isVoiceModeEnabled) { + this.voiceEnergy.status = 'processing' + } + + this._isLeonGeneratingAnswer = true + this.chatbot.createOrUpdateReasoningBlock( + data.generationId, + data.token, + data.phase + ) + this.chatbot.scrollDown() + }) + + this.socket.on('asr-speech', (text) => { + if (!this._isVoiceModeEnabled) { + this.enableVoiceMode() + } + + this.voiceEnergy.status = 'listening' + this._input.value = text + + if (this.voiceSpeechElement) { + this.voiceSpeechElement.textContent = text + } + }) + + this.socket.on('asr-end-of-owner-speech', () => { + this.voiceEnergy.status = 'processing' + + setTimeout(() => { + this.send('utterance') + }, 200) + }) + + this.socket.on('asr-active-listening-disabled', () => { + this.voiceEnergy.status = 'idle' + }) + + /** + * Only used for "local" TTS provider as a PoC for now. + * Target to do a better implementation in the future + * with streaming support + */ + this.socket.on('tts-stream', (data) => { + this.voiceEnergy.status = 'talking' + + // const { audioId, chunk } = data + const { chunk } = data + this._ttsAudioContext = new AudioContext() + // this._ttsAudioContextes[audioId] = ctx + + const source = this._ttsAudioContext.createBufferSource() + this._ttsAudioContext.decodeAudioData(chunk, (buffer) => { + source.buffer = buffer + + source.connect(this._ttsAudioContext.destination) + source.start(0) + }) + }) + + /** + * When Leon got interrupted by the owner voice + * while he is speaking + */ + this.socket.on('tts-interruption', async () => { + if (this._ttsAudioContext) { + await this._ttsAudioContext.close() + } + }) + + this.socket.on('tts-end-of-speech', async () => { + this.voiceEnergy.status = 'listening' + + if (window.leonConfigInfo?.asr?.enabled) { + this.socket.emit('asr-start-record') + } + }) + + this.socket.on('audio-forwarded', (data, cb) => { + const ctx = new AudioContext() + const source = ctx.createBufferSource() + + ctx.decodeAudioData(data.buffer, (buffer) => { + source.buffer = buffer + + source.connect(ctx.destination) + source.start(0) + + /** + * When the after speech option is enabled and + * the answer is a final one + */ + if (window.leonConfigInfo.after_speech && data.is_final_answer) { + // Enable recording after the speech + 500ms + setTimeout(() => { + this._recorder.start() + this._recorder.enabled = true + + // Check every second if the recorder is enabled to stop it + const id = setInterval(() => { + if (this._recorder.enabled) { + if (this._recorder.countSilenceAfterTalk <= 8) { + // Stop recording if there was no noise for 8 seconds + if (this._recorder.countSilenceAfterTalk === 8) { + this._recorder.stop() + this._recorder.enabled = false + this._recorder.countSilenceAfterTalk = 0 + clearInterval(id) + } else if (!this._recorder.noiseDetected) { + this._recorder.countSilenceAfterTalk += 1 + } else { + clearInterval(id) + } + } + } + }, 1_000) + }, data.duration + 500) + } + }) + + cb('audio-received') + }) + + this.socket.on(LEON_EVENTS.error, (data) => { + console.error('Leon client interface error:', data) + }) + + if (this.history !== null) { + this.parsedHistory = JSON.parse(this.history) + } + } + + send(keyword) { + if (keyword === 'utterance') { + return this.sendUtterance(this._input.value) + } + + return false + } + + sendUtterance(value, options = {}) { + if (this._isLeonGeneratingAnswer) { + return false + } + + const trimmedValue = String(value || '').trim() + + if (trimmedValue === '') { + return false + } + + const sentAt = + typeof options.sentAt === 'number' ? options.sentAt : Date.now() + + this.socket.emit(LEON_EVENTS.utterance, { + value: trimmedValue, + sentAt, + sessionId: this.activeSessionId, + ...(options.commandContext + ? { commandContext: options.commandContext } + : {}) + }) + this.chatbot.sendTo('leon', trimmedValue, sentAt) + this.chatbot.scrollDown({ force: true }) + + this.save(trimmedValue) + + return true + } + + save(value = this._input.value) { + let val = value + + if (localStorage.getItem('history') === null) { + localStorage.setItem('history', JSON.stringify([])) + this.parsedHistory = JSON.parse(localStorage.getItem('history')) + } else if (this.parsedHistory.length >= 32) { + this.parsedHistory.shift() + } + + if (val[0] === ' ') { + val = val.substr(1, val.length - 1) + } + + if (this.parsedHistory[this.parsedHistory.length - 1] !== val) { + this.parsedHistory.push(val) + localStorage.setItem('history', JSON.stringify(this.parsedHistory)) + } + + this._input.value = '' + setTimeout(() => { + // Remove the last character to avoid the space + this._input.value = this._input.value.slice(0, -1) + }, 0) + } + + enableVoiceMode() { + if (!this._isVoiceModeEnabled) { + this._isVoiceModeEnabled = true + + const body = document.querySelector('body') + if (!body.classList.contains('voice-mode-enabled')) { + body.classList.add('voice-mode-enabled') + + const voiceOverlayTransitor = document.createElement('div') + voiceOverlayTransitor.id = 'voice-overlay-transitor' + body.appendChild(voiceOverlayTransitor) + voiceOverlayTransitor.addEventListener('animationend', () => { + voiceOverlayTransitor.removeEventListener('animationend', () => {}) + voiceOverlayTransitor.remove() + }) + } + } + } + disableVoiceMode() { + if (this._isVoiceModeEnabled) { + this._isVoiceModeEnabled = false + + const body = document.querySelector('body') + + const voiceContainer = document.querySelector('#voice-container') + if (voiceContainer) { + voiceContainer.style.animation = 'none' + voiceContainer.style.animation = null + } + + if (body.classList.contains('voice-mode-enabled')) { + body.classList.remove('voice-mode-enabled') + } + } + } +} diff --git a/app/src/js/constants.js b/app/src/js/constants.js new file mode 100644 index 0000000..3bfd4fe --- /dev/null +++ b/app/src/js/constants.js @@ -0,0 +1,22 @@ +export const INIT_MESSAGES = [ + [ + 'Hi, I\'m Leon, your open-source personal assistant. I\'m still evolving, but I\'m here to help.' + ], + [ + `Want to follow the project? + +- Regular progress updates: https://x.com/grenlouis +- Blog posts: https://blog.getleon.ai/ +- Email updates: https://leonai.substack.com/subscribe` + ], + [ + `Come hang out on Discord: https://discord.gg/MNQqqKg +That's where people will help shape the ecosystem and build what comes next.` + ], + [ + 'Leon is built independently in spare time. If you want to help accelerate development, you can support the project here: http://sponsor.getleon.ai/' + ] +] + +export const ASR_DISABLED_MESSAGE = + 'Voice mode is not enabled yet. Run /voice setup from the chat, wait for the resources to install, then restart Leon by using /restart.' diff --git a/app/src/js/file-system-autocomplete.js b/app/src/js/file-system-autocomplete.js new file mode 100644 index 0000000..bce3ff6 --- /dev/null +++ b/app/src/js/file-system-autocomplete.js @@ -0,0 +1,386 @@ +import axios from 'axios' + +const AUTOCOMPLETE_DELAY_MS = 80 +const CLOSE_DELAY_MS = 120 +const DROPDOWN_MARGIN_PX = 8 +const MINIMUM_DROPDOWN_HEIGHT_PX = 196 +const MAXIMUM_DROPDOWN_HEIGHT_PX = 280 +const FILE_SYSTEM_TRIGGER = '@' +const FOLDER_TYPE = 'folder' +const DEFAULT_FILE_ICON_NAME = 'file-line' +const DEFAULT_FOLDER_ICON_NAME = 'folder-3-line' +const NAVIGATION_DIRECTIONS = { + next: 1, + previous: -1 +} + +function isWhitespace(character) { + return character.trim() === '' +} + +function findPathToken(input) { + const selectionStart = input.selectionStart ?? input.value.length + let tokenStart = selectionStart + + while ( + tokenStart > 0 && + !isWhitespace(input.value.charAt(tokenStart - 1)) + ) { + tokenStart -= 1 + } + + if (input.value.charAt(tokenStart) !== FILE_SYSTEM_TRIGGER) { + return null + } + + return { + start: tokenStart, + end: selectionStart, + value: input.value.slice(tokenStart, selectionStart) + } +} + +export default class FileSystemAutocomplete { + constructor({ serverUrl, input = null, onValueChange = null }) { + this.serverUrl = serverUrl + this.input = null + this.onValueChange = onValueChange + this.dropdown = document.createElement('div') + this.dropdown.className = 'file-system-autocomplete file-system-autocomplete--hidden' + this.entries = [] + this.selectedEntryIndex = -1 + this.token = null + this.isOpen = false + this.requestCounter = 0 + this.autocompleteTimeout = null + this.closeTimeout = null + this.shouldScrollSelectedEntry = false + + this.handleInput = this.handleInput.bind(this) + this.handleKeyDown = this.handleKeyDown.bind(this) + this.handleFocus = this.handleFocus.bind(this) + this.handleClick = this.handleClick.bind(this) + this.handleBlur = this.handleBlur.bind(this) + this.handleWindowChange = this.handleWindowChange.bind(this) + + document.body.appendChild(this.dropdown) + + if (input) { + this.attach(input) + } + } + + attach(input) { + if (this.input === input) { + return + } + + window.clearTimeout(this.closeTimeout) + + if (this.input) { + this.removeInputListeners() + } + + this.input = input + this.input.addEventListener('input', this.handleInput) + this.input.addEventListener('keydown', this.handleKeyDown) + this.input.addEventListener('focus', this.handleFocus) + this.input.addEventListener('click', this.handleClick) + this.input.addEventListener('blur', this.handleBlur) + window.addEventListener('resize', this.handleWindowChange) + window.addEventListener('scroll', this.handleWindowChange, true) + } + + removeInputListeners() { + if (!this.input) { + return + } + + this.input.removeEventListener('input', this.handleInput) + this.input.removeEventListener('keydown', this.handleKeyDown) + this.input.removeEventListener('focus', this.handleFocus) + this.input.removeEventListener('click', this.handleClick) + this.input.removeEventListener('blur', this.handleBlur) + window.removeEventListener('resize', this.handleWindowChange) + window.removeEventListener('scroll', this.handleWindowChange, true) + this.input = null + } + + detach() { + this.removeInputListeners() + this.close() + } + + handleInput() { + window.clearTimeout(this.closeTimeout) + this.queueAutocomplete() + } + + handleFocus() { + window.clearTimeout(this.closeTimeout) + this.queueAutocomplete() + } + + handleClick() { + this.queueAutocomplete() + } + + handleBlur() { + this.queueClose() + } + + queueClose() { + window.clearTimeout(this.closeTimeout) + this.closeTimeout = window.setTimeout(() => { + this.close() + }, CLOSE_DELAY_MS) + } + + handleWindowChange() { + if (this.isOpen) { + this.positionDropdown() + } + } + + handleKeyDown(event) { + if (!this.isOpen) { + return + } + + if (event.key === 'Escape') { + event.preventDefault() + event.stopImmediatePropagation() + this.close() + return + } + + if (event.key === 'ArrowDown') { + event.preventDefault() + event.stopImmediatePropagation() + this.moveSelection(NAVIGATION_DIRECTIONS.next) + return + } + + if (event.key === 'ArrowUp') { + event.preventDefault() + event.stopImmediatePropagation() + this.moveSelection(NAVIGATION_DIRECTIONS.previous) + return + } + + if (event.key === 'Tab' || event.key === 'Enter') { + const selectedEntry = this.entries[this.selectedEntryIndex] + + if (selectedEntry) { + event.preventDefault() + event.stopImmediatePropagation() + this.applyEntry(selectedEntry) + } + } + } + + queueAutocomplete() { + window.clearTimeout(this.autocompleteTimeout) + this.autocompleteTimeout = window.setTimeout(() => { + void this.fetchAutocomplete() + }, AUTOCOMPLETE_DELAY_MS) + } + + async fetchAutocomplete() { + if (!this.input) { + this.close() + return + } + + if (document.activeElement !== this.input) { + this.queueClose() + return + } + + const token = findPathToken(this.input) + + if (!token) { + this.close() + return + } + + const requestId = this.requestCounter + 1 + this.requestCounter = requestId + this.token = token + + try { + const response = await axios.post( + `${this.serverUrl}/api/v1/file-system/list`, + { + value: token.value + } + ) + + if (requestId !== this.requestCounter) { + return + } + + this.entries = response.data.entries || [] + this.selectedEntryIndex = this.entries.length > 0 ? 0 : -1 + this.render() + } catch { + if (requestId !== this.requestCounter) { + return + } + + this.entries = [] + this.selectedEntryIndex = -1 + this.render() + } + } + + render() { + if (!this.input || !this.token) { + this.close() + return + } + + this.dropdown.innerHTML = '' + + if (this.entries.length === 0) { + const emptyElement = document.createElement('div') + emptyElement.className = 'file-system-autocomplete__empty' + emptyElement.textContent = 'No matching file system entry.' + this.dropdown.appendChild(emptyElement) + } else { + this.entries.forEach((entry, index) => { + const item = document.createElement('button') + const icon = document.createElement('i') + const label = document.createElement('span') + + item.type = 'button' + item.className = `file-system-autocomplete__item${ + index === this.selectedEntryIndex + ? ' file-system-autocomplete__item--selected' + : '' + }` + icon.className = `ri-${ + entry.iconName || + (entry.type === FOLDER_TYPE + ? DEFAULT_FOLDER_ICON_NAME + : DEFAULT_FILE_ICON_NAME) + }` + label.className = 'file-system-autocomplete__label' + label.textContent = entry.value + + item.addEventListener('mousedown', (event) => { + event.preventDefault() + }) + item.addEventListener('click', () => { + this.applyEntry(entry) + }) + + item.appendChild(icon) + item.appendChild(label) + this.dropdown.appendChild(item) + }) + } + + this.isOpen = true + this.dropdown.classList.remove('file-system-autocomplete--hidden') + this.positionDropdown() + + if (this.shouldScrollSelectedEntry) { + this.shouldScrollSelectedEntry = false + this.scrollSelectedEntryIntoView() + } + } + + positionDropdown() { + const inputRect = this.input.getBoundingClientRect() + const spaceBelow = window.innerHeight - inputRect.bottom + const spaceAbove = inputRect.top + const shouldOpenAbove = + spaceBelow < MINIMUM_DROPDOWN_HEIGHT_PX && spaceAbove > spaceBelow + const availableHeight = + (shouldOpenAbove ? spaceAbove : spaceBelow) - DROPDOWN_MARGIN_PX * 2 + const maxHeight = Math.min( + MAXIMUM_DROPDOWN_HEIGHT_PX, + Math.max(MINIMUM_DROPDOWN_HEIGHT_PX, availableHeight) + ) + + this.dropdown.style.left = `${inputRect.left}px` + this.dropdown.style.width = `${inputRect.width}px` + this.dropdown.style.maxHeight = `${maxHeight}px` + + if (shouldOpenAbove) { + this.dropdown.style.top = '' + this.dropdown.style.bottom = `${ + window.innerHeight - inputRect.top + DROPDOWN_MARGIN_PX + }px` + } else { + this.dropdown.style.top = `${inputRect.bottom + DROPDOWN_MARGIN_PX}px` + this.dropdown.style.bottom = '' + } + } + + moveSelection(direction) { + if (this.entries.length === 0) { + return + } + + this.selectedEntryIndex = + (this.selectedEntryIndex + direction + this.entries.length) % + this.entries.length + this.shouldScrollSelectedEntry = true + this.render() + } + + scrollSelectedEntryIntoView() { + const selectedEntryElement = this.dropdown.querySelector( + '.file-system-autocomplete__item--selected' + ) + + if (!selectedEntryElement) { + return + } + + selectedEntryElement.scrollIntoView({ + block: 'nearest' + }) + } + + applyEntry(entry) { + if (!this.input || !this.token) { + return + } + + const completedValue = entry.absolutePath || entry.value + const nextCharacter = this.input.value.charAt(this.token.end) + const shouldAddTrailingWhitespace = + nextCharacter === '' || !isWhitespace(nextCharacter) + const insertedValue = `${completedValue}${ + shouldAddTrailingWhitespace ? ' ' : '' + }` + const nextValue = `${this.input.value.slice(0, this.token.start)}${ + insertedValue + }${this.input.value.slice(this.token.end)}` + const nextCursorPosition = this.token.start + insertedValue.length + + this.input.value = nextValue + this.input.setSelectionRange(nextCursorPosition, nextCursorPosition) + this.input.dispatchEvent(new Event('input', { bubbles: true })) + + if (this.onValueChange) { + this.onValueChange(nextValue) + window.requestAnimationFrame(() => { + this.input?.setSelectionRange(nextCursorPosition, nextCursorPosition) + }) + } + + this.close() + } + + close() { + this.isOpen = false + this.entries = [] + this.selectedEntryIndex = -1 + this.token = null + this.dropdown.classList.add('file-system-autocomplete--hidden') + } +} diff --git a/app/src/js/init.jsx b/app/src/js/init.jsx new file mode 100644 index 0000000..1a2582f --- /dev/null +++ b/app/src/js/init.jsx @@ -0,0 +1,252 @@ +import { useEffect, useState, useRef } from 'react' +import { createRoot } from 'react-dom/client' +import { + WidgetWrapper, + Text, + Icon, + Flexbox, + List, + ListHeader, + ListItem, + Loader +} from '@aurora' + +const container = document.querySelector('#init') +const root = createRoot(container) +const LLAMA_SERVER_BOOT_STATUS = 'llamaServerBoot' +const INIT_ERROR_STATUS = 'error' +const INIT_ERROR_DISMISS_SECONDS = 10 +const INIT_ERROR_DISMISS_INTERVAL_MS = 1_000 + +function Item({ children, status }) { + if (status === 'error') { + return {children} + } + if (status === 'warning') { + return {children} + } + if (status === 'success') { + return {children} + } + if (status === 'loading') { + return {children} + } + + return {children} +} + +function LoadingListItem({ children }) { + return ( + + + + {children} + + + ) +} +function ErrorListItem({ children }) { + return ( + + + + {children} + + + ) +} +function WarningListItem({ children }) { + return ( + + + + {children} + + + ) +} +function SuccessListItem({ children }) { + return ( + + + + {children} + + + ) +} + +function Init() { + const parentRef = useRef(null) + const [config, setConfig] = useState(() => ({ ...window.leonConfigInfo })) + const usesLlamaCPP = + config.llm?.workflowProvider === 'llamacpp' || + config.llm?.agentProvider === 'llamacpp' + const [initErrorCountdown, setInitErrorCountdown] = useState(null) + const [areInitErrorsDismissed, setAreInitErrorsDismissed] = useState(false) + const [statusMap, setStatusMap] = useState({ + clientCoreServerHandshake: 'loading', + tcpServerBoot: + window.leonConfigInfo?.tcpServer?.enabled === false ? 'success' : 'loading', + [LLAMA_SERVER_BOOT_STATUS]: + window.leonConfigInfo?.llm?.workflowProvider === 'llamacpp' || + window.leonConfigInfo?.llm?.agentProvider === 'llamacpp' + ? 'loading' + : 'success' + }) + const hasInitError = Object.values(statusMap).some( + (status) => status === INIT_ERROR_STATUS + ) + + useEffect(() => { + setTimeout(() => { + if (parentRef.current) { + parentRef.current.classList.remove('not-initialized') + } + }, 250) + + function handleStatusChange(event) { + const { statusName, statusType } = event.detail + + if (statusType === INIT_ERROR_STATUS) { + setAreInitErrorsDismissed(false) + } + + setStatusMap((prev) => ({ ...prev, [statusName]: statusType })) + } + + window.leonInitStatusEvent.addEventListener( + 'initStatusChange', + handleStatusChange + ) + return () => + window.leonInitStatusEvent.removeEventListener( + 'initStatusChange', + handleStatusChange + ) + }, []) + + useEffect(() => { + if (!hasInitError || areInitErrorsDismissed) { + setInitErrorCountdown(null) + return + } + + let secondsLeft = INIT_ERROR_DISMISS_SECONDS + setInitErrorCountdown(secondsLeft) + + const interval = setInterval(() => { + secondsLeft -= 1 + setInitErrorCountdown(secondsLeft) + + if (secondsLeft <= 0) { + clearInterval(interval) + setAreInitErrorsDismissed(true) + } + }, INIT_ERROR_DISMISS_INTERVAL_MS) + + return () => clearInterval(interval) + }, [hasInitError, areInitErrorsDismissed]) + + const statuses = [] + for (let key of Object.keys(statusMap)) { + if (key === 'tcpServerBoot' && config.tcpServer?.enabled === false) { + statuses.push('success') + } else if (statusMap[key] === INIT_ERROR_STATUS && areInitErrorsDismissed) { + statuses.push('success') + } else if ( + key === LLAMA_SERVER_BOOT_STATUS && + !usesLlamaCPP + ) { + statuses.push('success') + } else { + statuses.push(statusMap[key]) + } + } + + const areAllStatusesSuccess = statuses.every((status) => status === 'success') + const getInitMessage = (status, defaultMessage) => { + if (status === INIT_ERROR_STATUS && initErrorCountdown !== null) { + return `An error occurred during the initialization. This message will disappear in ${initErrorCountdown} seconds` + } + + return defaultMessage + } + + useEffect(() => { + if (window.leonConfigInfo) { + setConfig({ ...window.leonConfigInfo }) + } + }, [window.leonConfigInfo]) + + return ( +
+
+ + + Leon is getting ready... + + {getInitMessage( + statusMap.clientCoreServerHandshake, + 'Client and core server handshaked' + )} + + {config.tcpServer?.enabled !== false && ( + + {getInitMessage(statusMap.tcpServerBoot, 'TCP server booted')} + + )} + {usesLlamaCPP && ( + + {getInitMessage( + statusMap[LLAMA_SERVER_BOOT_STATUS], + 'llama-server booted' + )} + + )} + + +
+
+ ) +} + +root.render() diff --git a/app/src/js/listener.js b/app/src/js/listener.js new file mode 100644 index 0000000..5b8f63f --- /dev/null +++ b/app/src/js/listener.js @@ -0,0 +1,44 @@ +const listener = {} + +listener.listening = ( + stream, + minDecibels, + maxBlankTime, + cbOnStart, + cbOnEnd +) => { + const ctx = new AudioContext() + const analyser = ctx.createAnalyser() + const streamNode = ctx.createMediaStreamSource(stream) + streamNode.connect(analyser) + analyser.minDecibels = minDecibels + + const data = new Uint8Array(analyser.frequencyBinCount) + let silenceStart = performance.now() + let triggered = false + + const loop = (time) => { + requestAnimationFrame(loop) + + analyser.getByteFrequencyData(data) + + if (data.some((v) => v)) { + if (triggered) { + triggered = false + + cbOnStart() + } + silenceStart = time + } + + if (!triggered && time - silenceStart > maxBlankTime) { + cbOnEnd() + + triggered = true + } + } + + loop() +} + +export default listener diff --git a/app/src/js/main.js b/app/src/js/main.js new file mode 100644 index 0000000..bd09a86 --- /dev/null +++ b/app/src/js/main.js @@ -0,0 +1,213 @@ +import axios from 'axios' +import '@aurora/style.css' + +window.leonInitStatusEvent = new EventTarget() + +import './init' +import Client from './client' +import { BuiltInCommands } from './built-in-commands' +import FileSystemAutocomplete from './file-system-autocomplete' +import SessionsPanel from './sessions' +// import Recorder from './recorder' +// import listener from './listener' +import { onkeydownstartrecording, onkeydowninput } from './onkeydown' + +const config = { + app: 'webapp', + server_host: import.meta.env.VITE_LEON_HOST, + server_port: import.meta.env.VITE_LEON_PORT, + min_decibels: -40, // Noise detection sensitivity + max_blank_time: 1_000 // Maximum time to consider a blank (ms) +} +const serverUrl = + import.meta.env.VITE_LEON_NODE_ENV === 'production' + ? '' + : `${config.server_host}:${config.server_port}` + +document.addEventListener('DOMContentLoaded', async () => { + try { + const [response, sessionsResponse] = await Promise.all([ + axios.get(`${serverUrl}/api/v1/info`), + axios.get(`${serverUrl}/api/v1/sessions`) + ]) + const input = document.querySelector('#utterance') + const mic = document.querySelector('#mic-button') + const v = document.querySelector('#version small') + const infoButton = document.querySelector('#info') + const client = new Client(config.app, serverUrl, input, { + activeSessionId: sessionsResponse.data.active_session_id + }) + const sessionsPanel = new SessionsPanel({ + serverUrl, + socket: client.socket, + activeSessionId: sessionsResponse.data.active_session_id, + initialPayload: sessionsResponse.data, + onSelect: (sessionId) => client.setActiveSession(sessionId) + }) + const fileSystemAutocomplete = new FileSystemAutocomplete({ + serverUrl, + input + }) + const builtInCommands = new BuiltInCommands({ + serverUrl, + input, + getActiveSessionId: () => sessionsPanel.getActiveSessionId(), + onCommandExecuted: (commandInput) => { + if (commandInput.trim().startsWith('/session')) { + void sessionsPanel.refresh() + } + }, + onSubmitToChat: (clientAction) => { + return client.sendUtterance(clientAction.utterance, { + commandContext: { + forcedRoutingMode: clientAction.command_context?.forced_routing_mode, + forcedSkillName: clientAction.command_context?.forced_skill_name, + forcedToolName: clientAction.command_context?.forced_tool_name + } + }) + } + }) + // let rec = {} + // let chunks = [] + + window.leonConfigInfo = response.data + const infoKeys = [ + 'timeZone', + 'telemetry', + 'gpu', + 'graphicsComputeAPI', + 'totalVRAM', + 'freeVRAM', + 'usedVRAM', + 'llm', + 'asr', + 'tts', + 'mood', + 'version' + ] + const infoToDisplay = {} + infoKeys.forEach((key) => { + infoToDisplay[key] = window.leonConfigInfo[key] + }) + + v.textContent += window.leonConfigInfo.version + + client.updateMood(window.leonConfigInfo.mood) + client.setSessionPanel(sessionsPanel) + sessionsPanel.init() + client.init() + fileSystemAutocomplete.attach(input) + builtInCommands.init() + + infoButton.addEventListener('click', () => { + alert(JSON.stringify(infoToDisplay, null, 2)) + }) + + /*if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { + navigator.mediaDevices + .getUserMedia({ audio: true }) + .then((stream) => { + if (MediaRecorder) { + rec = new Recorder(stream, mic, window.leonConfigInfo) + client.recorder = rec + + rec.ondataavailable((e) => { + chunks.push(e.data) + }) + + rec.onstart(() => { + /!* *!/ + }) + + rec.onstop(() => { + const blob = new Blob(chunks) + chunks = [] + rec.enabled = false + + // Ensure there are some data + if (blob.size >= 1_000) { + client.socket.emit('recognize', blob) + } + }) + + listener.listening( + stream, + config.min_decibels, + config.max_blank_time, + () => { + // Noise detected + rec.noiseDetected = true + }, + () => { + // Noise ended + + rec.noiseDetected = false + if (rec.enabled && !rec.hotwordTriggered) { + rec.stop() + rec.enabled = false + rec.hotwordTriggered = false + rec.countSilenceAfterTalk = 0 + } + } + ) + + client.socket.on('enable-record', () => { + rec.hotwordTriggered = true + rec.start() + setTimeout(() => { + rec.hotwordTriggered = false + }, config.max_blank_time) + rec.enabled = true + }) + } else { + console.error('MediaRecorder is not supported on your browser.') + } + }) + .catch((err) => { + console.error( + 'MediaDevices.getUserMedia() threw the following error:', + err + ) + }) + } else { + console.error( + 'MediaDevices.getUserMedia() is not supported on your browser.' + ) + }*/ + + document.addEventListener('keydown', (e) => { + onkeydownstartrecording(e, () => { + client.asrStartRecording() + /*if (rec.enabled === false) { + input.value = '' + rec.start() + rec.enabled = true + } else { + rec.stop() + rec.enabled = false + }*/ + }) + }) + + input.addEventListener('keydown', (e) => { + onkeydowninput(e, client) + }) + + mic.addEventListener('click', (e) => { + e.preventDefault() + + client.asrStartRecording() + + /*if (rec.enabled === false) { + rec.start() + rec.enabled = true + } else { + rec.stop() + rec.enabled = false + }*/ + }) + } catch (e) { + alert(`Error: ${e.message}; ${JSON.stringify(e.response?.data)}`) + console.error(e) + } +}) diff --git a/app/src/js/onkeydown.js b/app/src/js/onkeydown.js new file mode 100644 index 0000000..6152b50 --- /dev/null +++ b/app/src/js/onkeydown.js @@ -0,0 +1,38 @@ +let index = -1 +let parsedHistory = null + +const onkeydowninput = (e, client) => { + const key = e.which || e.keyCode + + if (localStorage.getItem('history') !== null && (key === 38 || key === 40)) { + parsedHistory = JSON.parse(localStorage.getItem('history')).reverse() + } + + if (key === 13 && !e.shiftKey) { + if (client.send('utterance')) { + parsedHistory = JSON.parse(localStorage.getItem('history')).reverse() + index = -1 + } + } else if (localStorage.getItem('history') !== null) { + if (e.shiftKey) { + if (key === 38 && index < parsedHistory.length - 1) { + index += 1 + client.input = parsedHistory[index] + } else if (key === 40 && index - 1 >= 0) { + index -= 1 + client.input = parsedHistory[index] + } else if (key === 40 && index - 1 < 0) { + client.input = '' + index = -1 + } + } + } +} + +const onkeydownstartrecording = (e, cb) => { + if ((e.metaKey || e.altKey) && e.key === 'c') { + cb() + } +} + +export { onkeydowninput, onkeydownstartrecording } diff --git a/app/src/js/recorder.js b/app/src/js/recorder.js new file mode 100644 index 0000000..7db714c --- /dev/null +++ b/app/src/js/recorder.js @@ -0,0 +1,63 @@ +import on from '../sounds/on.mp3' +import off from '../sounds/off.mp3' + +export default class Recorder { + constructor(stream, el, info) { + this.recorder = new MediaRecorder(stream, { audioBitsPerSecond: 16000 }) + this.el = el + this.audioOn = new Audio(on) + this.audioOff = new Audio(off) + this.playSound = true + this.info = info + this.enabled = false + this.hotwordTriggered = false + this.noiseDetected = false + this.countSilenceAfterTalk = 0 + } + + start(playSound = true) { + if (this.info.asr.enabled === false) { + console.warn('ASR disabled') + } else { + this.playSound = playSound + this.recorder.start(playSound) + } + } + + stop(playSound = true) { + if (this.info.asr.enabled === false) { + console.warn('ASR disabled') + } else { + this.playSound = playSound + this.recorder.stop(playSound) + } + } + + onstart(cb) { + this.recorder.onstart = (e) => { + if (this.playSound) { + this.audioOn.play() + } + this.el.classList.add('enabled') + + cb(e) + } + } + + onstop(cb) { + this.recorder.onstop = (e) => { + if (this.playSound) { + this.audioOff.play() + } + this.el.classList.remove('enabled') + + cb(e) + } + } + + ondataavailable(cb) { + this.recorder.ondataavailable = (e) => { + cb(e) + } + } +} diff --git a/app/src/js/render-aurora-component.js b/app/src/js/render-aurora-component.js new file mode 100644 index 0000000..26390b3 --- /dev/null +++ b/app/src/js/render-aurora-component.js @@ -0,0 +1,56 @@ +import { createElement } from 'react' + +import * as auroraComponents from '@aurora' + +import * as customAuroraComponents from '../custom-aurora-components' + +export default function renderAuroraComponent( + socket, + component, + supportedEvents +) { + if (component) { + // `import/namespace` cannot statically validate dynamic component lookups. + // eslint-disable-next-line import/namespace + let reactComponent = auroraComponents[component.component] + /** + * Find custom component if a former component is not found + */ + if (!reactComponent) { + // eslint-disable-next-line import/namespace + reactComponent = customAuroraComponents[component.component] + } + + if (!reactComponent) { + console.error(`Component ${component.component} not found`) + return null + } + + // Check if the browsed component has a supported event and bind it + if (reactComponent && Array.isArray(component.events)) { + component.events.forEach((event) => { + if (supportedEvents.includes(event.type)) { + component.props[event.type] = (data) => { + const { method } = event + + socket.emit('widget-event', { method, data }) + } + } + }) + } + + // When children is a component, then wrap it in an array to render properly + const isComponent = !!component.props?.children?.component + if (isComponent) { + component.props.children = [component.props.children] + } + + if (component.props?.children && Array.isArray(component.props.children)) { + component.props.children = component.props.children.map((child) => { + return renderAuroraComponent(socket, child, supportedEvents) + }) + } + + return createElement(reactComponent, component.props) + } +} diff --git a/app/src/js/sessions.js b/app/src/js/sessions.js new file mode 100644 index 0000000..bc07d00 --- /dev/null +++ b/app/src/js/sessions.js @@ -0,0 +1,288 @@ +import axios from 'axios' + +const DAY_MS = 24 * 60 * 60 * 1_000 +const GROUP_DATE_FORMATTER = new Intl.DateTimeFormat(undefined, { + month: 'long', + day: 'numeric', + year: 'numeric' +}) + +function createElement(tagName, className, textContent = '') { + const element = document.createElement(tagName) + + if (className) { + element.className = className + } + + if (textContent) { + element.textContent = textContent + } + + return element +} + +function getDayKey(timestamp) { + const date = new Date(timestamp) + + return new Date( + date.getFullYear(), + date.getMonth(), + date.getDate() + ).getTime() +} + +function getGroupLabel(timestamp) { + const now = Date.now() + const todayKey = getDayKey(now) + const yesterdayKey = todayKey - DAY_MS + const itemKey = getDayKey(timestamp) + + if (itemKey === todayKey) { + return 'Today' + } + + if (itemKey === yesterdayKey) { + return 'Yesterday' + } + + return GROUP_DATE_FORMATTER.format(new Date(timestamp)) +} + +export default class SessionsPanel { + constructor({ + serverUrl, + socket, + activeSessionId, + initialPayload, + onSelect + }) { + this.serverUrl = serverUrl + this.socket = socket + this.activeSessionId = activeSessionId + this.sessions = initialPayload?.sessions || [] + this.supportedProviders = initialPayload?.supported_providers || [] + this.currentModelTarget = initialPayload?.current_model_target || '' + this.onSelect = onSelect + this.container = document.querySelector('#sessions-panel') + this.list = document.querySelector('#sessions-list') + this.newButton = document.querySelector('#new-session') + } + + init() { + this.newButton.addEventListener('click', () => { + void this.createSession() + }) + this.list.addEventListener('click', (event) => { + void this.handleClick(event) + }) + this.render() + } + + getActiveSessionId() { + return this.activeSessionId + } + + async refresh() { + const previousActiveSessionId = this.activeSessionId + const response = await axios.get(`${this.serverUrl}/api/v1/sessions`) + + this.applyPayload(response.data) + + if ( + response.data.active_session_id && + response.data.active_session_id !== previousActiveSessionId + ) { + await this.onSelect?.(response.data.active_session_id) + } + } + + async createSession() { + const response = await axios.post(`${this.serverUrl}/api/v1/sessions`) + + this.applyPayload(response.data) + await this.selectSession(response.data.session.id) + } + + async selectSession(sessionId) { + this.activeSessionId = sessionId + this.socket.emit('session-change', sessionId) + await this.onSelect?.(sessionId) + await axios.patch(`${this.serverUrl}/api/v1/sessions/${sessionId}`, { + is_active: true + }) + await this.refresh() + } + + async updateSession(sessionId, payload) { + const response = await axios.patch( + `${this.serverUrl}/api/v1/sessions/${sessionId}`, + payload + ) + + this.applyPayload(response.data) + } + + async deleteSession(sessionId) { + const wasActiveSession = this.activeSessionId === sessionId + const response = await axios.delete( + `${this.serverUrl}/api/v1/sessions/${sessionId}` + ) + + this.applyPayload(response.data) + + if (wasActiveSession) { + await this.selectSession(response.data.active_session_id) + } + } + + async handleClick(event) { + const button = event.target.closest('button') + const item = event.target.closest('.session-item') + + if (!item) { + return + } + + const sessionId = item.getAttribute('data-session-id') + + if (!button) { + await this.selectSession(sessionId) + return + } + + const action = button.getAttribute('data-action') + + if (action === 'rename') { + const currentTitle = item.getAttribute('data-session-title') || '' + const title = window.prompt('Session title', currentTitle) + + if (title && title.trim()) { + await this.updateSession(sessionId, { title: title.trim() }) + } + } else if (action === 'pin') { + await this.updateSession(sessionId, { + is_pinned: button.getAttribute('aria-pressed') !== 'true' + }) + } else if (action === 'delete') { + await this.deleteSession(sessionId) + } else if (action === 'model') { + await this.updateSessionModel(sessionId) + } + } + + async updateSessionModel(sessionId) { + const provider = window.prompt( + `Provider (${this.supportedProviders.join(', ')})` + ) + + if (!provider) { + return + } + + const model = window.prompt('Model') + + if (!model) { + return + } + + await this.updateSession(sessionId, { + provider: provider.trim(), + model: model.trim() + }) + } + + applyPayload(payload) { + this.sessions = payload.sessions || [] + this.supportedProviders = payload.supported_providers || [] + this.currentModelTarget = payload.current_model_target || '' + this.activeSessionId = payload.active_session_id || this.activeSessionId + this.render() + } + + render() { + this.list.innerHTML = '' + + const pinnedSessions = this.sessions.filter((session) => session.isPinned) + const unpinnedSessions = this.sessions.filter((session) => !session.isPinned) + + if (pinnedSessions.length > 0) { + this.renderGroup('Pinned', pinnedSessions) + } + + const groupedSessions = new Map() + + for (const session of unpinnedSessions) { + const timestamp = session.lastMessageAt || session.updatedAt + const groupLabel = getGroupLabel(timestamp) + const group = groupedSessions.get(groupLabel) || [] + + group.push(session) + groupedSessions.set(groupLabel, group) + } + + for (const [label, sessions] of groupedSessions.entries()) { + this.renderGroup(label, sessions) + } + } + + renderGroup(label, sessions) { + const group = createElement('section', 'session-group') + const heading = createElement('h2', 'session-group-title', label) + + group.appendChild(heading) + + for (const session of sessions) { + group.appendChild(this.createSessionItem(session)) + } + + this.list.appendChild(group) + } + + createSessionItem(session) { + const item = createElement('article', 'session-item') + const title = createElement('div', 'session-title', session.title) + const meta = createElement( + 'div', + 'session-meta', + session.modelTarget || this.currentModelTarget || 'Default model' + ) + const actions = createElement('div', 'session-actions') + + item.setAttribute('data-session-id', session.id) + item.setAttribute('data-session-title', session.title) + + if (session.id === this.activeSessionId) { + item.classList.add('session-item--active') + } + + actions.appendChild( + this.createActionButton( + 'pin', + session.isPinned ? 'ri-pushpin-fill' : 'ri-pushpin-line', + session.isPinned + ) + ) + actions.appendChild(this.createActionButton('rename', 'ri-edit-line')) + actions.appendChild(this.createActionButton('model', 'ri-brain-line')) + actions.appendChild(this.createActionButton('delete', 'ri-delete-bin-line')) + + item.appendChild(title) + item.appendChild(meta) + item.appendChild(actions) + + return item + } + + createActionButton(action, iconClassName, isPressed = false) { + const button = createElement('button', 'session-action') + const icon = createElement('i', iconClassName) + + button.type = 'button' + button.setAttribute('data-action', action) + button.setAttribute('aria-label', action) + button.setAttribute('aria-pressed', String(isPressed)) + button.appendChild(icon) + + return button + } +} diff --git a/app/src/js/suggestion-handler.js b/app/src/js/suggestion-handler.js new file mode 100644 index 0000000..89ef909 --- /dev/null +++ b/app/src/js/suggestion-handler.js @@ -0,0 +1,43 @@ +import { createElement } from 'react' +import { createRoot } from 'react-dom/client' + +import { WidgetWrapper, List, ListHeader, ListItem } from '@aurora' + +export default function handleSuggestions(data, chatbot, client) { + const container = document.createElement('div') + container.className = 'bubble-container leon' + + chatbot.feed.appendChild(container) + + const root = createRoot(container) + + root.render( + createElement(WidgetWrapper, { + noPadding: true, + children: createElement(List, { + children: [ + createElement(ListHeader, { + children: 'Suggestions' + }), + ...data.map((suggestionText) => { + return createElement(ListItem, { + children: suggestionText, + name: 'suggestion', + value: suggestionText, + onClick: (suggestion) => { + const parent = container.parentNode + + if (parent) { + parent.removeChild(container) + } + + client.input.value = suggestion.value + client.send('utterance') + } + }) + }) + ] + }) + }) + ) +} diff --git a/app/src/js/tool-ui-handler.js b/app/src/js/tool-ui-handler.js new file mode 100644 index 0000000..3942071 --- /dev/null +++ b/app/src/js/tool-ui-handler.js @@ -0,0 +1,1010 @@ +const COMMAND_OUTPUT_MAX_DISPLAY_CHARS = 80_000 +const ANSI_ESCAPE_PATTERN = + // eslint-disable-next-line no-control-regex + /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g + +/** + * Tool UI Handler + * Renders tool executions as expandable activity cards. + */ +export default class ToolUIHandler { + constructor(feedElement, scrollDownCallback, formatMessageCallback) { + this.feed = feedElement + this.scrollDown = scrollDownCallback + this.formatMessage = formatMessageCallback + this.toolGroups = new Map() + } + + /** + * Handle tool output messages with interactive activity cards. + */ + handleToolOutput(data) { + if (data.activityType === 'agent_skill') { + return this.handleAgentSkillActivity(data) + } + + const { + toolkitName, + toolName, + toolGroupId, + answer, + replaceMessageId, + key + } = data + + if (replaceMessageId) { + this.replaceToolMessage(replaceMessageId, data) + return + } + + const answerKey = key ? key.split('.').pop() : 'unknown' + const groupId = toolGroupId || `${toolkitName}_${toolName}_${Date.now()}` + const mode = + data.toolDisplayMode === 'activity_card' ? 'activity_card' : 'legacy' + + let toolGroupContainer = this.toolGroups.get(groupId) + + if (!toolGroupContainer) { + toolGroupContainer = this.createToolGroupContainer({ + groupId, + toolkitName, + toolName, + answerKey, + mode, + data + }) + this.toolGroups.set(groupId, toolGroupContainer) + } + + if (toolGroupContainer.mode === 'activity_card') { + this.updateActivityCard(toolGroupContainer, data, answerKey) + } else { + this.addLegacyToolMessage(toolGroupContainer, answer) + } + + this.scrollDown() + + return { + groupId, + isNewGroup: toolGroupContainer.isNew + } + } + + handleAgentSkillActivity(data) { + const agentSkill = data.agentSkill || {} + const skillId = agentSkill.id || agentSkill.name || 'agent-skill' + const groupId = data.toolGroupId || `agent_skill_${skillId}_${Date.now()}` + + let activityContainer = this.toolGroups.get(groupId) + + if (!activityContainer) { + activityContainer = this.createAgentSkillActivityCard({ + groupId, + agentSkill + }) + this.toolGroups.set(groupId, activityContainer) + } + + this.updateAgentSkillActivityCard(activityContainer, data) + this.scrollDown() + + return { + groupId, + isNewGroup: activityContainer.isNew + } + } + + createToolGroupContainer(params) { + return params.mode === 'activity_card' + ? this.createActivityCardContainer(params) + : this.createLegacyToolGroupContainer(params) + } + + getRemixIconClass(iconName) { + const fallbackIconName = 'ri-magic-line' + if (typeof iconName !== 'string') { + return fallbackIconName + } + + const trimmedIconName = iconName.trim() + if (!trimmedIconName || trimmedIconName.includes(' ')) { + return fallbackIconName + } + + return trimmedIconName.startsWith('ri-') + ? trimmedIconName + : `ri-${trimmedIconName}` + } + + getToolActivityIconClass(data) { + return this.getRemixIconClass(data.toolIconName || data.toolkitIconName) + } + + /** + * Create the legacy shell-like tool group container. + */ + createLegacyToolGroupContainer({ + groupId, + toolkitName, + toolName, + answerKey + }) { + const groupContainer = document.createElement('div') + groupContainer.className = 'tool-group-container' + groupContainer.setAttribute('data-tool-group-id', groupId) + + const toolHeader = document.createElement('button') + toolHeader.className = 'tool-header' + toolHeader.setAttribute('type', 'button') + toolHeader.innerHTML = ` + + ${toolkitName} toolkit → ${toolName} → ${answerKey} + + ` + + const toolContent = document.createElement('div') + toolContent.className = 'tool-content' + + const shellOutput = document.createElement('div') + shellOutput.className = 'shell-output' + + toolContent.appendChild(shellOutput) + groupContainer.appendChild(toolHeader) + groupContainer.appendChild(toolContent) + + this.addExpandCollapseHandler(toolHeader, toolContent) + this.feed.appendChild(groupContainer) + + return { + mode: 'legacy', + container: groupContainer, + toolHeader, + toolContent, + shellOutput, + isNew: true + } + } + + createActivityCardContainer({ + groupId, + toolkitName, + toolName, + answerKey, + data + }) { + const groupContainer = document.createElement('div') + groupContainer.className = 'tool-group-container tool-activity-card' + groupContainer.setAttribute('data-tool-group-id', groupId) + + const toolHeader = document.createElement('button') + toolHeader.className = 'tool-header tool-activity-header' + toolHeader.setAttribute('type', 'button') + + const heading = document.createElement('div') + heading.className = 'tool-activity-heading' + + const icon = document.createElement('i') + icon.className = `${this.getToolActivityIconClass(data)} tool-icon` + + const titleBlock = document.createElement('div') + titleBlock.className = 'tool-activity-title-block' + + const title = document.createElement('span') + title.className = 'tool-title' + title.textContent = data.stepLabel || this.humanizeFunctionName(answerKey) + + const subtitle = document.createElement('span') + subtitle.className = 'tool-subtitle' + subtitle.textContent = `${toolkitName} toolkit • ${toolName}` + + titleBlock.appendChild(title) + titleBlock.appendChild(subtitle) + heading.appendChild(icon) + heading.appendChild(titleBlock) + + const meta = document.createElement('div') + meta.className = 'tool-activity-meta' + + const statusChip = document.createElement('span') + statusChip.className = 'tool-status-chip running' + statusChip.textContent = 'Running' + + const expandIcon = document.createElement('i') + expandIcon.className = 'ri-arrow-down-s-line expand-icon' + + meta.appendChild(statusChip) + meta.appendChild(expandIcon) + toolHeader.appendChild(heading) + toolHeader.appendChild(meta) + + const toolContent = document.createElement('div') + toolContent.className = 'tool-content' + + const summary = document.createElement('div') + summary.className = 'tool-activity-summary' + summary.textContent = 'Preparing tool activity...' + + const sections = document.createElement('div') + sections.className = 'tool-activity-sections' + + const inputPanel = this.createActivityPanel( + 'Input', + 'Parameters sent to the function' + ) + const outputPanel = this.createActivityPanel( + 'Result', + 'What the function returned' + ) + + sections.appendChild(inputPanel.panel) + sections.appendChild(outputPanel.panel) + + const rawDetails = document.createElement('details') + rawDetails.className = 'tool-raw-details' + + const rawSummary = document.createElement('summary') + rawSummary.textContent = 'Raw data' + + const rawContent = document.createElement('div') + rawContent.className = 'tool-raw-content' + + rawDetails.appendChild(rawSummary) + rawDetails.appendChild(rawContent) + + toolContent.appendChild(summary) + toolContent.appendChild(sections) + toolContent.appendChild(rawDetails) + groupContainer.appendChild(toolHeader) + groupContainer.appendChild(toolContent) + + this.addExpandCollapseHandler(toolHeader, toolContent) + this.feed.appendChild(groupContainer) + + return { + mode: 'activity_card', + container: groupContainer, + toolHeader, + toolContent, + summary, + title, + subtitle, + statusChip, + inputBody: inputPanel.body, + outputBody: outputPanel.body, + rawContent, + rawDetails, + rawInput: null, + rawOutput: null, + commandOutputText: '', + preparationLog: [], + isNew: true + } + } + + createAgentSkillActivityCard({ groupId, agentSkill }) { + const groupContainer = document.createElement('div') + groupContainer.className = + 'tool-group-container tool-activity-card agent-skill-activity-card' + groupContainer.setAttribute('data-tool-group-id', groupId) + + const skillName = agentSkill.name || agentSkill.id || 'Agent Skill' + const skillPath = agentSkill.skillPath || 'SKILL.md' + + const toolHeader = document.createElement('button') + toolHeader.className = 'tool-header tool-activity-header' + toolHeader.setAttribute('type', 'button') + + const heading = document.createElement('div') + heading.className = 'tool-activity-heading' + + const icon = document.createElement('i') + icon.className = 'ri-book-ai-line tool-icon' + + const titleBlock = document.createElement('div') + titleBlock.className = 'tool-activity-title-block' + + const title = document.createElement('span') + title.className = 'tool-title' + title.textContent = `Agent Skill: ${skillName}` + + const subtitle = document.createElement('span') + subtitle.className = 'tool-subtitle' + subtitle.textContent = skillPath + subtitle.setAttribute('title', skillPath) + + titleBlock.appendChild(title) + titleBlock.appendChild(subtitle) + heading.appendChild(icon) + heading.appendChild(titleBlock) + + const meta = document.createElement('div') + meta.className = 'tool-activity-meta' + + const statusChip = document.createElement('span') + statusChip.className = 'tool-status-chip selected' + statusChip.textContent = 'In use' + + const expandIcon = document.createElement('i') + expandIcon.className = 'ri-arrow-down-s-line expand-icon' + + meta.appendChild(statusChip) + meta.appendChild(expandIcon) + toolHeader.appendChild(heading) + toolHeader.appendChild(meta) + + const toolContent = document.createElement('div') + toolContent.className = 'tool-content' + + const summary = document.createElement('div') + summary.className = 'tool-activity-summary' + summary.textContent = 'Following SKILL.md instructions for this step.' + + const sections = document.createElement('div') + sections.className = 'tool-activity-sections single' + + const skillPanel = this.createActivityPanel( + 'Skill', + 'Agent Skill context for this step' + ) + sections.appendChild(skillPanel.panel) + + toolContent.appendChild(summary) + toolContent.appendChild(sections) + groupContainer.appendChild(toolHeader) + groupContainer.appendChild(toolContent) + + this.addExpandCollapseHandler(toolHeader, toolContent) + this.feed.appendChild(groupContainer) + + return { + mode: 'agent_skill', + container: groupContainer, + title, + subtitle, + statusChip, + skillBody: skillPanel.body, + isNew: true + } + } + + /** + * Create a titled content panel used by the activity card sections. + */ + createActivityPanel(title, description) { + const panel = document.createElement('section') + panel.className = 'tool-activity-panel' + + const heading = document.createElement('div') + heading.className = 'tool-panel-heading' + + const titleElement = document.createElement('span') + titleElement.className = 'tool-panel-title' + titleElement.textContent = title + + const descriptionElement = document.createElement('span') + descriptionElement.className = 'tool-panel-description' + descriptionElement.textContent = description + + const body = document.createElement('div') + body.className = 'tool-panel-body' + + heading.appendChild(titleElement) + heading.appendChild(descriptionElement) + panel.appendChild(heading) + panel.appendChild(body) + + return { + panel, + body + } + } + + /** + * Add expand/collapse functionality to tool header. + */ + addExpandCollapseHandler(toolHeader, toolContent) { + toolHeader.addEventListener('click', () => { + const isExpanded = toolContent.classList.contains('expanded') + const expandIcon = toolHeader.querySelector('.expand-icon') + + if (isExpanded) { + toolContent.classList.remove('expanded') + expandIcon?.classList.remove('rotated') + } else { + toolContent.classList.add('expanded') + expandIcon?.classList.add('rotated') + } + }) + } + + /** + * Update the activity card with the latest input/output state. + */ + updateActivityCard(toolGroupContainer, data, answerKey) { + const title = + data.stepLabel || + this.humanizeFunctionName(data.functionName || answerKey) + toolGroupContainer.title.textContent = title + + if (data.functionName) { + const functionLabel = this.humanizeFunctionName(data.functionName) + toolGroupContainer.subtitle.textContent = + `${data.toolkitName} toolkit • ${data.toolName} • ${functionLabel}` + } + + if (data.toolPhase === 'input') { + toolGroupContainer.summary.textContent = + data.stepLabel || data.functionName + ? `Preparing ${title.toLowerCase()}...` + : 'Preparing tool activity...' + this.setStatusChip(toolGroupContainer.statusChip, 'running') + + const parsedInput = this.parseToolInput(data.toolInput) + toolGroupContainer.rawInput = parsedInput ?? data.toolInput ?? null + this.renderValuePreview( + toolGroupContainer.inputBody, + parsedInput ?? data.toolInput, + 'No input' + ) + + if (!toolGroupContainer.rawOutput) { + this.renderPlaceholder( + toolGroupContainer.outputBody, + 'Waiting for function output...' + ) + } + } + + if (data.toolPhase === 'preparation') { + const progressMessage = data.message || data.answer || '' + this.setStatusChip(toolGroupContainer.statusChip, 'running') + + if (progressMessage) { + toolGroupContainer.summary.textContent = progressMessage + toolGroupContainer.preparationLog.push(progressMessage) + this.renderPreparationLog( + toolGroupContainer.outputBody, + toolGroupContainer.preparationLog + ) + toolGroupContainer.rawOutput = { + preparation: toolGroupContainer.preparationLog + } + } + } + + if (data.toolPhase === 'output_delta') { + const outputDelta = data.outputDelta || data.answer || '' + this.setStatusChip(toolGroupContainer.statusChip, 'running') + + if (outputDelta) { + toolGroupContainer.summary.textContent = 'Receiving command output...' + toolGroupContainer.commandOutputText = this.mergeCommandOutput( + toolGroupContainer.commandOutputText, + outputDelta + ) + this.renderCommandOutputLog( + toolGroupContainer.outputBody, + toolGroupContainer.commandOutputText + ) + toolGroupContainer.rawOutput = { + output: toolGroupContainer.commandOutputText + } + } + } + + if (data.toolPhase === 'output') { + const isError = data.status === 'error' + const isObserved = data.status === 'observed' + toolGroupContainer.summary.textContent = + data.message || + (isError + ? 'The function failed.' + : isObserved + ? 'The function returned an observation.' + : 'The function completed.') + this.setStatusChip( + toolGroupContainer.statusChip, + isError ? 'error' : isObserved ? 'observed' : 'success' + ) + + const outputPayload = { + message: data.message, + output: data.output + } + toolGroupContainer.rawOutput = outputPayload + this.renderOutputPreview(toolGroupContainer.outputBody, data) + } + + this.renderRawData(toolGroupContainer) + + if (toolGroupContainer.isNew) { + toolGroupContainer.isNew = false + } + } + + updateAgentSkillActivityCard(activityContainer, data) { + const agentSkill = data.agentSkill || {} + const skillName = agentSkill.name || agentSkill.id || 'Agent Skill' + const skillPath = agentSkill.skillPath || '' + + activityContainer.title.textContent = `Agent Skill: ${skillName}` + activityContainer.subtitle.textContent = skillPath || 'SKILL.md' + activityContainer.subtitle.setAttribute( + 'title', + skillPath || 'SKILL.md' + ) + this.setStatusChip(activityContainer.statusChip, 'selected') + this.renderValuePreview( + activityContainer.skillBody, + { + name: skillName, + description: agentSkill.description || '', + root_path: agentSkill.rootPath || '', + skill_path: skillPath + }, + 'No Agent Skill metadata' + ) + + if (activityContainer.isNew) { + activityContainer.isNew = false + } + } + + /** + * Add a tool message to the legacy shell output. + */ + addLegacyToolMessage(toolGroupContainer, message) { + const messageElement = document.createElement('div') + messageElement.className = 'shell-message' + + const formattedMessage = this.formatMessage(message) + messageElement.innerHTML = `> ${formattedMessage}` + + toolGroupContainer.shellOutput.appendChild(messageElement) + + if (toolGroupContainer.isNew) { + toolGroupContainer.isNew = false + } + } + + /** + * Render the output preview block. + */ + renderOutputPreview(container, data) { + container.innerHTML = '' + + if (data.message) { + const summary = document.createElement('div') + summary.className = 'tool-output-summary' + summary.innerHTML = this.formatMessage(data.message) + container.appendChild(summary) + } + + if ( + typeof data.output === 'undefined' || + data.output === null || + (typeof data.output === 'object' && + !Array.isArray(data.output) && + Object.keys(data.output).length === 0) + ) { + if (!data.message) { + this.renderPlaceholder(container, 'No output') + } + return + } + + const preview = this.buildValueNode(data.output) + container.appendChild(preview) + } + + /** + * Render preparation progress before the final tool output is available. + */ + renderPreparationLog(container, messages) { + container.innerHTML = '' + + if (!messages.length) { + this.renderPlaceholder(container, 'Waiting for function output...') + return + } + + const list = document.createElement('ul') + list.className = 'tool-value-list' + + messages.forEach((message) => { + const item = document.createElement('li') + item.textContent = message + list.appendChild(item) + }) + + container.appendChild(list) + } + + /** + * Merge terminal output chunks while respecting carriage-return progress + * updates used by CLI tools to repaint the current line. + */ + mergeCommandOutput(currentOutput, nextChunk) { + const cleanChunk = this.cleanCommandOutputChunk(nextChunk) + if (!cleanChunk) { + return currentOutput || '' + } + + let output = currentOutput || '' + let replaceCurrentLine = false + + for (const char of cleanChunk) { + if (char === '\r') { + replaceCurrentLine = true + continue + } + + if (char === '\n') { + output += '\n' + replaceCurrentLine = false + continue + } + + if (replaceCurrentLine) { + const lineStartIndex = output.lastIndexOf('\n') + 1 + output = output.slice(0, lineStartIndex) + replaceCurrentLine = false + } + + output += char + } + + if (output.length <= COMMAND_OUTPUT_MAX_DISPLAY_CHARS) { + return output + } + + return output.slice(output.length - COMMAND_OUTPUT_MAX_DISPLAY_CHARS) + } + + /** + * Strip terminal control sequences that do not render usefully in HTML. + */ + cleanCommandOutputChunk(chunk) { + const withoutAnsi = String(chunk || '').replace(ANSI_ESCAPE_PATTERN, '') + const output = [] + + for (const char of withoutAnsi) { + if (char === '\b') { + output.pop() + continue + } + + output.push(char) + } + + return output.join('') + } + + /** + * Render live command output in the result panel. + */ + renderCommandOutputLog(container, outputText) { + container.innerHTML = '' + + if (!outputText) { + this.renderPlaceholder(container, 'Waiting for function output...') + return + } + + const output = document.createElement('pre') + output.className = 'tool-command-output' + output.textContent = outputText + container.appendChild(output) + output.scrollTop = output.scrollHeight + } + + /** + * Render a value preview block. + */ + renderValuePreview(container, value, emptyLabel) { + container.innerHTML = '' + + if ( + value === null || + typeof value === 'undefined' || + value === '' || + (Array.isArray(value) && value.length === 0) || + (typeof value === 'object' && + !Array.isArray(value) && + Object.keys(value).length === 0) + ) { + this.renderPlaceholder(container, emptyLabel) + return + } + + container.appendChild(this.buildValueNode(value)) + } + + /** + * Render an empty state placeholder. + */ + renderPlaceholder(container, text) { + container.innerHTML = '' + const placeholder = document.createElement('div') + placeholder.className = 'tool-empty-state' + placeholder.textContent = text + container.appendChild(placeholder) + } + + /** + * Build the most appropriate preview node for a value. + */ + buildValueNode(value) { + if (Array.isArray(value)) { + return this.buildArrayNode(value) + } + + if (value && typeof value === 'object') { + return this.buildObjectNode(value) + } + + return this.buildScalarNode(value) + } + + /** + * Build a list preview for array values. + */ + buildArrayNode(value) { + const list = document.createElement('ul') + list.className = 'tool-value-list' + + value.slice(0, 8).forEach((item) => { + const itemElement = document.createElement('li') + itemElement.appendChild(this.buildScalarNode(this.stringifyCompact(item))) + list.appendChild(itemElement) + }) + + if (value.length > 8) { + const more = document.createElement('li') + more.className = 'tool-empty-state' + more.textContent = `+${value.length - 8} more item(s)` + list.appendChild(more) + } + + return list + } + + /** + * Build a key/value preview for object values. + */ + buildObjectNode(value) { + const entries = Object.entries(value) + if (entries.length === 0) { + const empty = document.createElement('div') + empty.className = 'tool-empty-state' + empty.textContent = 'No data' + return empty + } + + const wrapper = document.createElement('div') + wrapper.className = 'tool-kv-list' + + entries.slice(0, 8).forEach(([key, itemValue]) => { + const row = document.createElement('div') + row.className = 'tool-kv-row' + + const keyElement = document.createElement('span') + keyElement.className = 'tool-kv-key' + keyElement.textContent = this.humanizeFunctionName(key) + + const valueElement = document.createElement('div') + valueElement.className = 'tool-kv-value' + valueElement.appendChild( + this.buildScalarNode(this.stringifyCompact(itemValue)) + ) + + row.appendChild(keyElement) + row.appendChild(valueElement) + wrapper.appendChild(row) + }) + + if (entries.length > 8) { + const more = document.createElement('div') + more.className = 'tool-empty-state' + more.textContent = `+${entries.length - 8} more field(s)` + wrapper.appendChild(more) + } + + return wrapper + } + + /** + * Build a formatted scalar value preview. + */ + buildScalarNode(value) { + const wrapper = document.createElement('div') + wrapper.className = 'tool-rich-text' + wrapper.innerHTML = this.formatMessage( + typeof value === 'string' ? value : String(value ?? '') + ) + return wrapper + } + + /** + * Render raw input/output payloads behind a disclosure block. + */ + renderRawData(toolGroupContainer) { + const payload = {} + + if (toolGroupContainer.rawInput !== null) { + payload['input'] = toolGroupContainer.rawInput + } + + if (toolGroupContainer.rawOutput !== null) { + payload['result'] = toolGroupContainer.rawOutput + } + + if (Object.keys(payload).length === 0) { + toolGroupContainer.rawDetails.removeAttribute('open') + toolGroupContainer.rawContent.innerHTML = '' + return + } + + toolGroupContainer.rawContent.innerHTML = this.formatMessage( + JSON.stringify(payload, null, 2) + ) + } + + /** + * Parse tool input JSON when possible. + */ + parseToolInput(toolInput) { + if (typeof toolInput !== 'string' || !toolInput.trim()) { + return null + } + + try { + return JSON.parse(toolInput) + } catch { + return toolInput + } + } + + /** + * Update the status chip for the activity card. + */ + setStatusChip(chip, status) { + chip.classList.remove('running', 'success', 'error', 'selected', 'observed') + + if (status === 'error') { + chip.classList.add('error') + chip.textContent = 'Failed' + return + } + + if (status === 'success') { + chip.classList.add('success') + chip.textContent = 'Done' + return + } + + if (status === 'selected') { + chip.classList.add('selected') + chip.textContent = 'In use' + return + } + + if (status === 'observed') { + chip.classList.add('observed') + chip.textContent = 'Observed' + return + } + + chip.classList.add('running') + chip.textContent = 'Running' + } + + /** + * Humanize function and field names for display. + */ + humanizeFunctionName(value) { + return String(value || 'unknown') + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/[_-]+/g, ' ') + .replace(/\s+/g, ' ') + .trim() + .replace(/^\w/, (char) => char.toUpperCase()) + } + + /** + * Produce a compact preview string for nested values. + */ + stringifyCompact(value) { + if (typeof value === 'string') { + const trimmed = value.trim() + if (!trimmed) { + return '(empty)' + } + + return trimmed.length > 180 ? `${trimmed.slice(0, 177)}...` : trimmed + } + + if (value === null || typeof value === 'undefined') { + return '(empty)' + } + + if (typeof value === 'object') { + try { + const serialized = JSON.stringify(value) + return serialized.length > 180 + ? `${serialized.slice(0, 177)}...` + : serialized + } catch { + return String(value) + } + } + + return String(value) + } + + /** + * Replace a tool message (for progress updates, etc.). + */ + replaceToolMessage(replaceMessageId, newData) { + const existingMessage = document.querySelector( + `[data-message-id="${replaceMessageId}"]` + ) + + if (existingMessage && existingMessage.closest('.tool-group-container')) { + const formattedMessage = this.formatMessage(newData.answer) + existingMessage.innerHTML = `> ${formattedMessage}` + } else { + this.handleToolOutput(newData) + } + } + + /** + * Get tool group info for saving to localStorage. + */ + getToolGroupInfo(groupId, toolkitName, toolName, message) { + return { + originalString: `[TOOL_OUTPUT:${groupId}] ${toolkitName} → ${toolName}`, + messageId: `tool-${groupId}`, + formattedMessage: this.formatMessage(message) + } + } + + /** + * Check if a message is a tool output marker. + */ + static isToolOutputMarker(messageString) { + return messageString && messageString.startsWith('[TOOL_OUTPUT:') + } + + /** + * Clear all tool groups. + */ + clearToolGroups() { + this.toolGroups.clear() + } + + /** + * Get the number of active tool groups. + */ + getToolGroupCount() { + return this.toolGroups.size + } + + /** + * Get a specific tool group by ID. + */ + getToolGroup(groupId) { + return this.toolGroups.get(groupId) + } + + /** + * Remove a tool group. + */ + removeToolGroup(groupId) { + const toolGroup = this.toolGroups.get(groupId) + if (toolGroup) { + toolGroup.container.remove() + this.toolGroups.delete(groupId) + } + } +} diff --git a/app/src/js/voice-energy.js b/app/src/js/voice-energy.js new file mode 100644 index 0000000..e85c47a --- /dev/null +++ b/app/src/js/voice-energy.js @@ -0,0 +1,74 @@ +const STATUS = { + listening: 'Listening...', + processing: 'Processing...', + talking: 'Talking...', + idle: 'Idle' +} + +export default class VoiceEnergy { + constructor(client) { + this.client = client + this.voiceEnergyContainerElement = document.querySelector( + '#voice-energy-container' + ) + this.voiceOverlayElement = document.querySelector('#voice-overlay-bg') + this.statusElement = document.querySelector('#voice-status') + this._status = 'idle' + } + + get status() { + return this._status + } + + set status(newStatus) { + if (this._status !== newStatus) { + this._status = newStatus + + if (this.statusElement) { + this.statusElement.textContent = STATUS[newStatus] + } + + // Clean up speech text when listening + if (newStatus === 'listening' && this.client.voiceSpeechElement) { + this.client.voiceSpeechElement.textContent = '' + } + + if (this.voiceEnergyContainerElement) { + this.voiceEnergyContainerElement.className = '' + this.voiceEnergyContainerElement.classList.add(newStatus) + } + } + } + + init() { + if (this.voiceEnergyContainerElement) { + if (this.voiceOverlayElement) { + this.voiceOverlayElement.addEventListener('click', (e) => { + e.preventDefault() + this.client.disableVoiceMode() + }) + } + + const particles = new Set() + const particleColors = ['blue', 'pink'] + + for (let i = 0; i < 32; i += 1) { + const particle = document.createElement('div') + const randomColor = Math.floor(Math.random() * 2) + let random = Math.floor(Math.random() * 32) + + while (particles.has(random)) { + random = Math.floor(Math.random() * 32) + } + + particles.add(random) + particle.setAttribute('data-particle', String(random)) + particle.classList.add('voice-particle', particleColors[randomColor]) + particle.style.transform = `rotate(${ + i * 11.25 + }deg) translate(110px) rotate(-${i * 11.25}deg)` + this.voiceEnergyContainerElement.appendChild(particle) + } + } + } +} diff --git a/app/src/sounds/off.mp3 b/app/src/sounds/off.mp3 new file mode 100644 index 0000000..d3d5b7b Binary files /dev/null and b/app/src/sounds/off.mp3 differ diff --git a/app/src/sounds/on.mp3 b/app/src/sounds/on.mp3 new file mode 100644 index 0000000..985e532 Binary files /dev/null and b/app/src/sounds/on.mp3 differ diff --git a/app/tsconfig.json b/app/tsconfig.json new file mode 100644 index 0000000..470851e --- /dev/null +++ b/app/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "noEmit": true + }, + "include": ["./src/**/*", "../aurora/src/**/*", "../aurora/global.d.ts"], + "exclude": ["./dist", "../node_modules"] +} diff --git a/app/vite.config.js b/app/vite.config.js new file mode 100644 index 0000000..aac1793 --- /dev/null +++ b/app/vite.config.js @@ -0,0 +1,143 @@ +import dns from 'node:dns' +import fs from 'node:fs' +import { fileURLToPath } from 'node:url' + +import dotenv from 'dotenv' +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import YAML from 'yaml' + +import { + PROFILE_CONFIG_PATH, + PROFILE_DOT_ENV_PATH +} from '../server/src/leon-roots.ts' + +const APP_DEV_SERVER_PORT = 5_173 +const NODE_MODULES_PATH_SEGMENT = '/node_modules/' +const REACT_VENDOR_PACKAGES = ['react', 'react-dom', 'scheduler'] +const REALTIME_VENDOR_PACKAGES = [ + 'socket.io-client', + 'socket.io-parser', + 'engine.io-client', + 'engine.io-parser' +] +const UI_VENDOR_PACKAGE_PREFIXES = ['@ark-ui/', '@zag-js/', '@floating-ui/'] + +dotenv.config({ path: PROFILE_DOT_ENV_PATH }) + +dns.setDefaultResultOrder('verbatim') + +function readAppLeonConfig() { + if (!fs.existsSync(PROFILE_CONFIG_PATH)) { + throw new Error(`Profile config file not found at "${PROFILE_CONFIG_PATH}".`) + } + + const config = YAML.parse(fs.readFileSync(PROFILE_CONFIG_PATH, 'utf8')) + const server = config?.server + + if ( + !server || + typeof server.host !== 'string' || + !Number.isInteger(server.port) + ) { + throw new Error( + `Profile config file "${PROFILE_CONFIG_PATH}" must define server.host and server.port.` + ) + } + + return { + host: server.host, + port: server.port + } +} + +function normalizeModuleId(moduleId) { + return moduleId.replaceAll('\\', '/') +} + +function isNodeModule(moduleId) { + return normalizeModuleId(moduleId).includes(NODE_MODULES_PATH_SEGMENT) +} + +function includesVendorPackage(moduleId, packageName) { + return normalizeModuleId(moduleId).includes( + `${NODE_MODULES_PATH_SEGMENT}${packageName}/` + ) +} + +function includesVendorPackagePrefix(moduleId, packagePrefix) { + return normalizeModuleId(moduleId).includes( + `${NODE_MODULES_PATH_SEGMENT}${packagePrefix}` + ) +} + +// Map necessary Leon's env vars as Vite only expose VITE_* +const leonConfig = readAppLeonConfig() +process.env.VITE_LEON_NODE_ENV = process.env.LEON_NODE_ENV +process.env.VITE_LEON_HOST = leonConfig.host +process.env.VITE_LEON_PORT = String(leonConfig.port) + +export default defineConfig({ + root: 'app/src', + resolve: { + alias: [ + { + find: '@aurora/style.css', + replacement: fileURLToPath( + new URL('../aurora/style.css', import.meta.url) + ) + }, + { + find: '@aurora', + replacement: fileURLToPath( + new URL('../aurora/src/index.ts', import.meta.url) + ) + } + ] + }, + build: { + outDir: '../dist', + emptyOutDir: true, + rolldownOptions: { + output: { + codeSplitting: { + groups: [ + { + name: 'react-vendor', + test: (moduleId) => + REACT_VENDOR_PACKAGES.some((packageName) => + includesVendorPackage(moduleId, packageName) + ), + priority: 30 + }, + { + name: 'realtime-vendor', + test: (moduleId) => + REALTIME_VENDOR_PACKAGES.some((packageName) => + includesVendorPackage(moduleId, packageName) + ), + priority: 20 + }, + { + name: 'ui-vendor', + test: (moduleId) => + UI_VENDOR_PACKAGE_PREFIXES.some((packagePrefix) => + includesVendorPackagePrefix(moduleId, packagePrefix) + ), + priority: 10 + }, + { + name: 'vendor', + test: isNodeModule, + priority: 0 + } + ] + } + } + } + }, + server: { + port: APP_DEV_SERVER_PORT + }, + plugins: [react()] +}) diff --git a/aurora/global.d.ts b/aurora/global.d.ts new file mode 100644 index 0000000..5c53896 --- /dev/null +++ b/aurora/global.d.ts @@ -0,0 +1,3 @@ +declare module '*.css' +declare module '*.scss' +declare module '*.sass' diff --git a/aurora/preview/App.tsx b/aurora/preview/App.tsx new file mode 100644 index 0000000..c1c07c4 --- /dev/null +++ b/aurora/preview/App.tsx @@ -0,0 +1,1839 @@ +import { useState, useEffect } from 'react' + +import { + Button, + Card, + Checkbox, + CircularProgress, + Flexbox, + Form, + Icon, + IconButton, + Image, + Input, + Link, + List, + ListHeader, + ListItem, + Loader, + Progress, + Radio, + RadioGroup, + RangeSlider, + ScrollContainer, + Select, + SelectOption, + Status, + Switch, + Tab, + TabContent, + TabGroup, + TabList, + Text, + WidgetWrapper +} from '../src' + +interface SectionProps extends React.PropsWithChildren { + title: string +} + +const Section: React.FC = (props) => { + const { title, children } = props + + return ( +
+

{title}

+ {children} +
+ ) +} + +function formatTime(seconds: number): string { + const minutes = Math.floor(seconds / 60) + const remainingSeconds = seconds % 60 + const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes + const formattedSeconds = + remainingSeconds < 10 ? `0${remainingSeconds}` : remainingSeconds + + return `${formattedMinutes}:${formattedSeconds}` +} + +function Timer({ + value, + initialTime, + interval +}: { + value: number + initialTime: number + interval: number +}) { + const [progress, setProgress] = useState(0) + const [timeLeft, setTimeLeft] = useState(initialTime) + + useEffect(() => { + setTimeLeft(initialTime) + setProgress(0) + }, [initialTime, value]) + + useEffect(() => { + if (timeLeft === 0) { + return + } + + const timer = setInterval(() => { + setTimeLeft((prevTime) => prevTime - 1) + setProgress((prevProgress) => prevProgress + 100 / initialTime) + }, interval) + + return () => clearInterval(timer) + }, [initialTime, interval, timeLeft]) + + return ( + + + + {formatTime(timeLeft)} + + + Total 10 minutes + + + + ) +} + +export const App: React.FC = () => { + const [isSending, setIsSending] = useState(false) + const [isSendingIconButton, setIsSendingIconButton] = useState(false) + const [isPlayButtonActivated, setIsPlayButtonActivated] = useState(false) + const [isPlayButton2Activated, setIsPlayButton2Activated] = useState(false) + + return ( + <> +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + + Hello world + + + + Text 1 + Text 2 + + + + +
+
+ + + alert(JSON.stringify(data))} + /> + alert(JSON.stringify(data))} + /> + + + +
+
+ + + + + + + + + + + + +
+
+ WIP (+ search with chip)... N.B. create example with LLM list/search +
+
+ + + + + 1 + + + 2 + + + 3 + + + 4 + + + 5 + + + + + + 1 + + + + + 2 + + + + + 3 + + + + + + + 1 + + + + + +
+
+ +
{ + alert(JSON.stringify(data)) + }} + > + + + + + + + + + + + + Random size + + + + + + + + + + + + + +
+
+
+
+ + + + Test here + + + + + + + + + + + + +
+
+ + + + + { + setIsSendingIconButton(true) + + alert(JSON.stringify(data)) + + setTimeout(() => { + setIsSendingIconButton(false) + }, 2_000) + }} + /> + + + + + + + + + + + + + + + console.log('data', data)} + /> + console.log('data', data)} + /> + + + + console.log('data', data)} + /> + console.log('data', data)} + /> + + + + + + + console.log('Shuffle', data.isActivated)} + /> + + + { + console.log('Play', data.isActivated) + setIsPlayButtonActivated(data.isActivated) + }} + /> + + + console.log('Repeat', data.isActivated)} + /> + + + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + +
+
+ + + + Docs + + + Docs + + + Next + + + + + + Docs + + + + Docs + + + Next + + + + + +
+
+ + + + Shopping List + + console.log('Checkbox', data)} + /> + + + + + + + + + + + + + + + + + + + + + You are all set + + + + Installation is done + + + + + + Configuration is done + + + + + + Leon is now ready to use + + + + + + + + + + The voice provider is missing + + + + + + NLP models are broken + + + + + + Leon cannot run properly + + + + + + + Select your music provider + alert(JSON.stringify(data))} + > + + + alert(JSON.stringify(data))} + > + + + alert(JSON.stringify(data))} + > + + + alert(JSON.stringify(data))} + > + + + + + + + + + + Pancakes Ingredients + + + + + + Flour + 1 ½ cups + + + + + + + + Baking powder + 3 ½ teaspoons + + + + + + + + Sugar + 1 tablespoon + + + + + + + + Salt + ¼ teaspoon + + + + + + + + Milk + 1 ¼ cups + + + + + + + + Butter + 3 tablespoons butter + + + + + + + + Egg + 1 egg + + + + + + +
+
+ + + +
+
+ WIP (need methods from SDK to control)... N.B. make blurred bg +
+
+ + + + + + + + + + + + + + + + +
+
+ + alert(JSON.stringify(data))} + > + + + + + + + + +
+
+ + + + console.log(data)} + /> + console.log(data)} + /> + console.log(data)} + /> + + + + + console.log(data)} + /> + console.log(data)} + /> + + + +
+
+ + + + + + Card 1 + + + Card 2 + + + Card 3 + + + Card 4 + + + Card 5 + + + + + + + + + Card 1 + + + Card 2 + + + Card 3 + + + Card 4 + + + Card 5 + + + + + +
+
+ + + + + + +
+
+ + + Normal + Edited + Warning + + Danger + + + Success + + + +
+
+ + + alert(JSON.stringify(data))} + /> + alert(JSON.stringify(data))} + /> + alert(JSON.stringify(data))} + /> + + +
+
+ + + + Tab 1 + Tab 2 + + Tab 3 + + + + Tab 1 content + + + Tab 2 content + + + Tab 3 content + + + +
+
+ + + Text xs + Text sm + Text md + Text lg + Text xl + Text + Text regular + Text semi-bold + Text secondary + + +
+
+ + + + console.log('Text input value:', value)} + /> + + + + + + + + + + +
+
WIP (need methods from SDK to control)...
+
+ + + + + 42 + + + + + + + + Paris + + Thursday, 1 June + + + + + + + + + + + + + + + + + } + /> + + + + 18° + + Thunderstorms + + + + + + + + + + + + + + } + /> + + 1 + + + UV Index + + + + + + + + + + + + + } + /> + + 10 m/s + + + Wind + + + + + + + + + + + + + } + /> + + 98% + + + Humidity + + + + + + + Today + Tomorrow + Next 7 days + + + + + + + + 10:00 + + + + + + + + + + + + + + + + } + /> + + 15° + + + + + + + 11:00 + + + + + + + + + + + + + + + + } + /> + + 15° + + + + + + + 12:00 + + + + + + + + + + + + + + + + } + /> + + 15° + + + + + + + 13:00 + + + + + + + + + + + + + + + + } + /> + + 15° + + + + + + + 14:00 + + + + + + + + + + + + + + + + } + /> + + 15° + + + + + + + + Tab 2 content + + + Tab 3 content + + + + + + + + + + Mockingbird + + Eminem + + + + + + 1:44 + + + 4:12 + + + + + console.log('Shuffle', data.isActivated)} + /> + + + { + console.log('Play', data.isActivated) + setIsPlayButton2Activated(data.isActivated) + }} + /> + + + console.log('Repeat', data.isActivated)} + /> + + + + +
+ + ) +} diff --git a/aurora/preview/index.html b/aurora/preview/index.html new file mode 100644 index 0000000..5c3569e --- /dev/null +++ b/aurora/preview/index.html @@ -0,0 +1,31 @@ + + + + + + Aurora + + +
+ + + + diff --git a/aurora/preview/main.tsx b/aurora/preview/main.tsx new file mode 100644 index 0000000..e268d9b --- /dev/null +++ b/aurora/preview/main.tsx @@ -0,0 +1,24 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' + +import '@fontsource/source-sans-pro/200.css' +import '@fontsource/source-sans-pro/300.css' +import '@fontsource/source-sans-pro/400.css' +import '@fontsource/source-sans-pro/600.css' +import '@fontsource/source-sans-pro/700.css' +import '@fontsource/source-sans-pro/900.css' +import 'remixicon/fonts/remixicon.css' +import '../src/styles/main.sass' +import { App } from './App.tsx' + +const rootElement = document.getElementById('root') + +if (rootElement != null) { + ReactDOM.createRoot(rootElement).render( + + + + ) +} else { + console.error('Error: Root element not found!') +} diff --git a/aurora/preview/public/apple-music.svg b/aurora/preview/public/apple-music.svg new file mode 100644 index 0000000..74cabe3 --- /dev/null +++ b/aurora/preview/public/apple-music.svg @@ -0,0 +1,3 @@ + + + diff --git a/aurora/preview/public/baking-powder.jpeg b/aurora/preview/public/baking-powder.jpeg new file mode 100644 index 0000000..0a262d2 Binary files /dev/null and b/aurora/preview/public/baking-powder.jpeg differ diff --git a/aurora/preview/public/butter.jpeg b/aurora/preview/public/butter.jpeg new file mode 100644 index 0000000..9c8c5de Binary files /dev/null and b/aurora/preview/public/butter.jpeg differ diff --git a/aurora/preview/public/deezer.svg b/aurora/preview/public/deezer.svg new file mode 100644 index 0000000..52fdd94 --- /dev/null +++ b/aurora/preview/public/deezer.svg @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/aurora/preview/public/egg.webp b/aurora/preview/public/egg.webp new file mode 100644 index 0000000..6ddef5c Binary files /dev/null and b/aurora/preview/public/egg.webp differ diff --git a/aurora/preview/public/flour.jpeg b/aurora/preview/public/flour.jpeg new file mode 100644 index 0000000..c06552c Binary files /dev/null and b/aurora/preview/public/flour.jpeg differ diff --git a/aurora/preview/public/milk.jpeg b/aurora/preview/public/milk.jpeg new file mode 100644 index 0000000..6c16b8c Binary files /dev/null and b/aurora/preview/public/milk.jpeg differ diff --git a/aurora/preview/public/mockingbird.jpg b/aurora/preview/public/mockingbird.jpg new file mode 100644 index 0000000..f834c46 Binary files /dev/null and b/aurora/preview/public/mockingbird.jpg differ diff --git a/aurora/preview/public/pancakes.jpeg b/aurora/preview/public/pancakes.jpeg new file mode 100644 index 0000000..14543fa Binary files /dev/null and b/aurora/preview/public/pancakes.jpeg differ diff --git a/aurora/preview/public/salt.jpg b/aurora/preview/public/salt.jpg new file mode 100644 index 0000000..4d1e9ac Binary files /dev/null and b/aurora/preview/public/salt.jpg differ diff --git a/aurora/preview/public/spotify.svg b/aurora/preview/public/spotify.svg new file mode 100644 index 0000000..a1370d0 --- /dev/null +++ b/aurora/preview/public/spotify.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/aurora/preview/public/sugar.jpg b/aurora/preview/public/sugar.jpg new file mode 100644 index 0000000..14d0c70 Binary files /dev/null and b/aurora/preview/public/sugar.jpg differ diff --git a/aurora/preview/public/youtube-music.svg b/aurora/preview/public/youtube-music.svg new file mode 100644 index 0000000..62e2175 --- /dev/null +++ b/aurora/preview/public/youtube-music.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/aurora/preview/style.css b/aurora/preview/style.css new file mode 100644 index 0000000..bfbf7bd --- /dev/null +++ b/aurora/preview/style.css @@ -0,0 +1,36 @@ +.aurora-preview-page { + min-height: 100vh; + padding: 32px; + background: + radial-gradient(circle at top left, rgba(28, 117, 219, 0.16), transparent 30%), + radial-gradient(circle at top right, rgba(237, 41, 122, 0.14), transparent 30%), + var(--black-color); + color: var(--white-color); +} + +.aurora-preview-shell { + width: min(1_440px, 100%); + margin: 0 auto; +} + +.aurora-preview-header { + margin-bottom: 24px; +} + +.aurora-preview-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: 20px; +} + +.aurora-preview-section { + display: flex; + flex-direction: column; + gap: 16px; +} + +.aurora-preview-widget { + display: flex; + flex-direction: column; + gap: 16px; +} diff --git a/aurora/preview/vite.config.js b/aurora/preview/vite.config.js new file mode 100644 index 0000000..8cef38b --- /dev/null +++ b/aurora/preview/vite.config.js @@ -0,0 +1,26 @@ +import { fileURLToPath } from 'node:url' + +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +const AURORA_PREVIEW_DEV_SERVER_PORT = 5_175 + +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + resolve: { + alias: [ + { + find: '@aurora/style.css', + replacement: fileURLToPath(new URL('../style.css', import.meta.url)) + }, + { + find: '@aurora', + replacement: fileURLToPath(new URL('../src/index.ts', import.meta.url)) + } + ] + }, + server: { + port: AURORA_PREVIEW_DEV_SERVER_PORT + }, + plugins: [react()] +}) diff --git a/aurora/src/components/button/button.sass b/aurora/src/components/button/button.sass new file mode 100644 index 0000000..f4bf657 --- /dev/null +++ b/aurora/src/components/button/button.sass @@ -0,0 +1,61 @@ +@use '../../styles/main.sass' as * + +.aurora-button + position: relative + display: inline-block + font-size: var(--a-font-size-md) + line-height: var(--a-line-height-md) + font-weight: var(--a-font-weight-semi-bold) + border-radius: var(--a-border-radius-md) + height: var(--a-button-size-md) + border: none + cursor: pointer + padding: 0 var(--a-space-lg) + box-shadow: 0 0 10px 2px transparent + transition: opacity var(--a-transition-duration-main) var(--a-transition-timing-main), transform var(--a-transition-duration-main), background-color var(--a-transition-duration-main) var(--a-transition-timing-main), border-color var(--a-transition-duration-main) var(--a-transition-timing-main), color var(--a-transition-duration-main) var(--a-transition-timing-main), box-shadow var(--a-transition-duration-main) var(--a-transition-timing-main) + &:hover:not(&--disabled, &--loading) + transform: scale3d(1.01, 1.01, 1.01) + &:active:not(&--disabled, &--loading) + transform: scale3d(.96, .96, .96) + + &--primary + color: var(--a-color-text) + background-color: var(--a-color-accent) + &:hover:not(.aurora-button--disabled, .aurora-button--loading) + background-color: var(--a-color-accent-hover) + + &--secondary + background-color: transparent + color: var(--a-color-accent) + border: 1px solid var(--a-color-accent) + &:hover:not(.aurora-button--disabled, .aurora-button--loading), &:hover:not(.aurora-button--disabled, .aurora-button--loading) .aurora-icon + border-color: var(--a-color-accent-hover) + color: var(--a-color-accent-hover) + .aurora-icon + color: var(--a-color-accent) + + &--danger + background-color: var(--a-color-background-danger) + color: var(--a-color-text-danger) + &:hover:not(.aurora-button--disabled, .aurora-button--loading) + background-color: var(--a-color-danger-hover) + + &--light + background-color: transparent + color: var(--a-color-accent) + &:hover:not(.aurora-button--disabled, .aurora-button--loading), &:hover:not(.aurora-button--disabled, .aurora-button--loading) .aurora-icon + color: var(--a-color-accent-hover) + .aurora-icon + color: var(--a-color-accent) + + &--disabled + opacity: var(--a-opacity-disabled) + cursor: not-allowed + + &--loading + opacity: var(--a-opacity-disabled) + cursor: wait + + .aurora-loader + &::before, &::after + background-color: var(--a-color-white) diff --git a/aurora/src/components/button/button.tsx b/aurora/src/components/button/button.tsx new file mode 100644 index 0000000..f27f10d --- /dev/null +++ b/aurora/src/components/button/button.tsx @@ -0,0 +1,114 @@ +import classNames from 'clsx' + +import { generateKeyId } from '../../lib/utils' +import { Flexbox, Icon, Loader } from '../..' + +import './button.sass' + +interface ButtonOnClickData { + name: string | undefined + value: string | number | undefined +} + +export interface ButtonProps { + /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ + children?: any + // children?: React.ReactNode + type?: 'button' | 'submit' + iconName?: string + iconPosition?: 'left' | 'right' + secondary?: boolean + danger?: boolean + light?: boolean + disabled?: boolean + loading?: boolean + name?: string + value?: string | number | undefined + onClick?: (data: ButtonOnClickData) => void +} + +export function Button({ + children, + type = 'button', + iconName, + iconPosition = 'left', + secondary, + danger, + light, + disabled, + loading, + name, + value, + onClick +}: ButtonProps) { + let variant = 'primary' + + if (secondary) { + variant = 'secondary' + } else if (danger) { + variant = 'danger' + } else if (light) { + variant = 'light' + } + + return ( + + ) +} diff --git a/aurora/src/components/button/index.ts b/aurora/src/components/button/index.ts new file mode 100644 index 0000000..14757e7 --- /dev/null +++ b/aurora/src/components/button/index.ts @@ -0,0 +1 @@ +export * from './button' diff --git a/aurora/src/components/card/card.sass b/aurora/src/components/card/card.sass new file mode 100644 index 0000000..7feacf5 --- /dev/null +++ b/aurora/src/components/card/card.sass @@ -0,0 +1,12 @@ +@use '../../styles/main.sass' as * + +.aurora-card + position: relative + display: inline-block + width: auto + padding: var(--a-space-md) + background-color: var(--a-color-background-surface-secondary) + border-radius: var(--a-border-radius-md) + + &--full-width + width: 100% diff --git a/aurora/src/components/card/card.tsx b/aurora/src/components/card/card.tsx new file mode 100644 index 0000000..a29be03 --- /dev/null +++ b/aurora/src/components/card/card.tsx @@ -0,0 +1,25 @@ +import classNames from 'clsx' + +import { generateKeyId } from '../../lib/utils' + +import './card.sass' + +export interface CardProps { + /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ + children: any + // children: React.ReactNode + fullWidth?: boolean +} + +export function Card({ children, fullWidth }: CardProps) { + return ( +
+ {children} +
+ ) +} diff --git a/aurora/src/components/card/index.ts b/aurora/src/components/card/index.ts new file mode 100644 index 0000000..efb3293 --- /dev/null +++ b/aurora/src/components/card/index.ts @@ -0,0 +1 @@ +export * from './card' diff --git a/aurora/src/components/checkbox/checkbox.sass b/aurora/src/components/checkbox/checkbox.sass new file mode 100644 index 0000000..59f1d90 --- /dev/null +++ b/aurora/src/components/checkbox/checkbox.sass @@ -0,0 +1,39 @@ +@use '../../styles/main.sass' as * + +.aurora-checkbox + display: flex + align-items: center + gap: var(--a-space-sm) + cursor: pointer + &[data-disabled] + cursor: not-allowed + +.aurora-checkbox-placeholder + width: var(--a-checkbox-radio-size) + height: var(--a-checkbox-radio-size) + +.aurora-checkbox-control + display: flex + justify-content: center + align-items: center + width: var(--a-checkbox-radio-size) + height: var(--a-checkbox-radio-size) + border-radius: var(--a-border-radius-xs) + border: 1px solid var(--a-color-input-border) + background-color: var(--a-color-input-background) + transition: background-color var(--a-transition-duration-main) var(--a-transition-timing-main), border-color var(--a-transition-duration-main) var(--a-transition-timing-main) + + &[data-hover]:not([data-state="checked"]) + border-color: var(--a-color-input-border-hover) + background-color: var(--a-color-input-background-hover) + &[data-state="checked"] + border-color: transparent + background-color: var(--a-color-input-border-focus) + &[data-disabled] + opacity: var(--a-opacity-disabled) + +.aurora-checkbox-label + color: var(--a-color-text) + font-size: var(--a-font-size-md) + &[data-disabled] + opacity: var(--a-opacity-disabled) diff --git a/aurora/src/components/checkbox/checkbox.tsx b/aurora/src/components/checkbox/checkbox.tsx new file mode 100644 index 0000000..609fdbc --- /dev/null +++ b/aurora/src/components/checkbox/checkbox.tsx @@ -0,0 +1,74 @@ +import { useState } from 'react' +import { + Checkbox as ArkCheckbox, + type CheckboxCheckedChangeDetails, + type CheckboxRootProps as ArkCheckboxProps +} from '@ark-ui/react/checkbox' + +import { Icon } from '../icon' + +import './checkbox.sass' + +interface CheckboxOnChangeData { + name: string + value: string | undefined + isChecked: boolean +} + +export interface CheckboxProps + extends Pick< + ArkCheckboxProps, + 'value' | 'checked' | 'disabled' | 'required' + > { + name: string + label?: string + onChange?: (data: CheckboxOnChangeData) => void +} + +export function Checkbox({ + name, + label, + checked, + value, + disabled, + required, + onChange +}: CheckboxProps) { + const [isChecked, setIsChecked] = useState(checked) + + return ( + { + setIsChecked(event.checked as boolean) + + const data = { + name, + value, + isChecked: !!event.checked + } + + if (onChange) { + onChange(data) + } + }} + > + + + {isChecked ? ( + + ) : ( +
+ )} + + + {label} + + + ) +} diff --git a/aurora/src/components/checkbox/index.ts b/aurora/src/components/checkbox/index.ts new file mode 100644 index 0000000..31d7689 --- /dev/null +++ b/aurora/src/components/checkbox/index.ts @@ -0,0 +1 @@ +export * from './checkbox' diff --git a/aurora/src/components/circular-progress/circular-progress.sass b/aurora/src/components/circular-progress/circular-progress.sass new file mode 100644 index 0000000..cc7b82f --- /dev/null +++ b/aurora/src/components/circular-progress/circular-progress.sass @@ -0,0 +1,28 @@ +.aurora-circular-progress + position: relative + + &--sm + width: 64px + height: 64px + &--md + width: 128px + height: 128px + &--lg + width: 256px + height: 256px + + path + transition: stroke-dashoffset var(--a-transition-duration-main) var(--a-transition-timing-main) + &:nth-child(1) + stroke: var(--a-color-background-surface-secondary) + stroke-width: 32px + &:nth-child(2) + stroke: var(--a-color-accent) + stroke-width: 12px + stroke-linecap: round + +.aurora-circular-progress-content + position: absolute + top: 50% + left: 50% + transform: translate(-50%, -50%) diff --git a/aurora/src/components/circular-progress/circular-progress.tsx b/aurora/src/components/circular-progress/circular-progress.tsx new file mode 100644 index 0000000..9cdece2 --- /dev/null +++ b/aurora/src/components/circular-progress/circular-progress.tsx @@ -0,0 +1,41 @@ +import classNames from 'clsx' + +import { generateKeyId } from '../../lib/utils' + +import './circular-progress.sass' + +export interface CircularProgressProps { + value: number + /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ + children?: any + // children?: React.ReactNode + size?: 'sm' | 'md' | 'lg' +} + +export function CircularProgress({ + value, + children, + size = 'md' +}: CircularProgressProps) { + const total = 100 + + return ( +
+ + + + +
{children}
+
+ ) +} diff --git a/aurora/src/components/circular-progress/index.ts b/aurora/src/components/circular-progress/index.ts new file mode 100644 index 0000000..985e8a5 --- /dev/null +++ b/aurora/src/components/circular-progress/index.ts @@ -0,0 +1 @@ +export * from './circular-progress' diff --git a/aurora/src/components/flexbox/flexbox.sass b/aurora/src/components/flexbox/flexbox.sass new file mode 100644 index 0000000..6dc395f --- /dev/null +++ b/aurora/src/components/flexbox/flexbox.sass @@ -0,0 +1,92 @@ +@use '../../styles/main.sass' as * + +.aurora-flexbox + position: relative + display: flex + flex-direction: column + height: 100% + + &--padding + padding: var(--a-space-xl) var(--a-space-md) + &--padding-x + padding-left: var(--a-space-md) + padding-right: var(--a-space-md) + &--padding-y + padding-top: var(--a-space-xl) + padding-bottom: var(--a-space-xl) + + &--full-width + width: 100% + + &--flex + display: flex + &--inline-flex + display: inline-flex + + &--row + flex-direction: row + &--row-reverse + flex-direction: row-reverse + &--column + flex-direction: column + &--column-reverse + flex-direction: column-reverse + + &--align-flex-start + align-items: flex-start + &--align-center + align-items: center + &--align-flex-end + align-items: flex-end + &--align-stretch + align-items: stretch + &--align-baseline + align-items: baseline + + &--justify-flex-start + justify-content: flex-start + &--justify-center + justify-content: center + &--justify-flex-end + justify-content: flex-end + &--justify-space-between + justify-content: space-between + &--justify-space-around + justify-content: space-around + &--justify-space-evenly + justify-content: space-evenly + &--justify-stretch + justify-content: stretch + + &--gap-xs + gap: var(--a-space-xs) + &--gap-sm + gap: var(--a-space-sm) + &--gap-md + gap: var(--a-space-md) + &--gap-lg + gap: var(--a-space-lg) + &--gap-xl + gap: var(--a-space-xl) + + &--row-gap-xs + row-gap: var(--a-space-xs) + &--row-gap-sm + row-gap: var(--a-space-sm) + &--row-gap-md + row-gap: var(--a-space-md) + &--row-gap-lg + row-gap: var(--a-space-lg) + &--row-gap-xl + row-gap: var(--a-space-xl) + + &--column-gap-xs + column-gap: var(--a-space-xs) + &--column-gap-sm + column-gap: var(--a-space-sm) + &--column-gap-md + column-gap: var(--a-space-md) + &--column-gap-lg + column-gap: var(--a-space-lg) + &--column-gap-xl + column-gap: var(--a-space-xl) diff --git a/aurora/src/components/flexbox/flexbox.tsx b/aurora/src/components/flexbox/flexbox.tsx new file mode 100644 index 0000000..77171ff --- /dev/null +++ b/aurora/src/components/flexbox/flexbox.tsx @@ -0,0 +1,66 @@ +import classNames from 'clsx' + +import { type Size } from '../../lib/types' +import { generateKeyId } from '../../lib/utils' + +import './flexbox.sass' + +export interface FlexboxProps { + /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ + children: any + // children: React.ReactNode + fullWidth?: boolean + display?: 'flex' | 'inline-flex' + alignItems?: 'center' | 'flex-start' | 'flex-end' | 'baseline' | 'stretch' + justifyContent?: + | 'center' + | 'flex-start' + | 'flex-end' + | 'space-between' + | 'space-around' + | 'space-evenly' + | 'stretch' + flexDirection?: 'row' | 'row-reverse' | 'column' | 'column-reverse' + gap?: Size + rowGap?: Size + columnGap?: Size + padding?: boolean + paddingX?: boolean + paddingY?: boolean +} + +export function Flexbox({ + children, + fullWidth, + display, + alignItems, + justifyContent, + flexDirection, + gap, + rowGap, + columnGap, + padding, + paddingX, + paddingY +}: FlexboxProps) { + return ( +
+ {children} +
+ ) +} diff --git a/aurora/src/components/flexbox/index.ts b/aurora/src/components/flexbox/index.ts new file mode 100644 index 0000000..b258a66 --- /dev/null +++ b/aurora/src/components/flexbox/index.ts @@ -0,0 +1 @@ +export * from './flexbox' diff --git a/aurora/src/components/form/form.sass b/aurora/src/components/form/form.sass new file mode 100644 index 0000000..e829832 --- /dev/null +++ b/aurora/src/components/form/form.sass @@ -0,0 +1,4 @@ +@use '../../styles/main.sass' as * + +.aurora-form + position: relative diff --git a/aurora/src/components/form/form.tsx b/aurora/src/components/form/form.tsx new file mode 100644 index 0000000..99460e2 --- /dev/null +++ b/aurora/src/components/form/form.tsx @@ -0,0 +1,51 @@ +import { generateKeyId } from '../../lib/utils' + +import './form.sass' + +export interface FormProps { + /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ + children?: any + // children?: React.ReactNode + onSubmit: (data: Record) => void +} + +export function Form({ children, onSubmit }: FormProps) { + const handleSubmit = (event: React.FormEvent) => { + event.preventDefault() + + const form = event.currentTarget + const formData = new FormData(form) + const data: Record = {} + + for (const [key, value] of formData.entries()) { + if (data[key] && key.endsWith('[]')) { + if (Array.isArray(data[key])) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + ;(data[key] as []).push(value) + } else { + data[key] = [data[key], value] + } + } else { + if (key.endsWith('[]')) { + data[key] = [value] + } else { + data[key] = value + } + } + } + + onSubmit(data) + } + + return ( +
+ {children} +
+ ) +} diff --git a/aurora/src/components/form/index.ts b/aurora/src/components/form/index.ts new file mode 100644 index 0000000..5415177 --- /dev/null +++ b/aurora/src/components/form/index.ts @@ -0,0 +1 @@ +export * from './form' diff --git a/aurora/src/components/icon-button/icon-button.sass b/aurora/src/components/icon-button/icon-button.sass new file mode 100644 index 0000000..1bf83e9 --- /dev/null +++ b/aurora/src/components/icon-button/icon-button.sass @@ -0,0 +1,70 @@ +@use '../../styles/main.sass' as * + +.aurora-icon-button + position: relative + width: var(--a-button-size-md) + height: var(--a-button-size-md) + display: flex + align-items: center + justify-content: center + padding: 0 + text-align: center + &.aurora-button:hover:not(.aurora-button--disabled, .aurora-button--loading) + transform: scale3d(1.03, 1.03, 1.03) + &.aurora-button:active:not(.aurora-button--disabled, .aurora-button--loading) + transform: scale3d(.96, .96, .96) + &.aurora-button.aurora-button--light:hover:not(.aurora-button--disabled, .aurora-button--loading) + transform: scale3d(1.06, 1.06, 1.06) + &.aurora-button.aurora-button--light:active:not(.aurora-button--disabled, .aurora-button--loading) + transform: scale3d(.96, .96, .96) + + &--square + width: var(--a-button-size-md) + height: var(--a-button-size-md) + border-radius: var(--a-border-radius-md) + &--circle + width: var(--a-button-size-md) + height: var(--a-button-size-md) + border-radius: 50% + + &--xs + width: 22px + height: 22px + &--sm + width: 30px + height: 30px + &--md + width: var(--a-button-size-md) + height: var(--a-button-size-md) + &--lg + width: 56px + height: 56px + &--xl + width: 96px + height: 96px + &--xxl + width: 164px + height: 164px + + &.aurora-button--light .aurora-icon + color: var(--a-color-text) + + &.aurora-button--secondary:hover, &.aurora-button--light:hover + background-color: transparent + + + &.aurora-button--light:hover .aurora-icon + color: var(--a-color-text) + + &.aurora-button--light.aurora-button--secondary + background-color: transparent + border: none + .aurora-icon + color: var(--a-color-white-secondary) + &:hover:not(.aurora-button--disabled, .aurora-button--loading) .aurora-icon + color: var(--a-color-text) + &:hover.aurora-icon-button--activated .aurora-icon + color: var(--a-color-accent) + + &.aurora-button--light.aurora-icon-button--activated .aurora-icon + color: var(--a-color-accent) diff --git a/aurora/src/components/icon-button/icon-button.tsx b/aurora/src/components/icon-button/icon-button.tsx new file mode 100644 index 0000000..b65614a --- /dev/null +++ b/aurora/src/components/icon-button/icon-button.tsx @@ -0,0 +1,113 @@ +import { useState } from 'react' +import classNames from 'clsx' + +import { Icon, Loader } from '../..' +import { type IconProps } from '../icon' +import { generateKeyId } from '../../lib/utils' + +import './icon-button.sass' + +interface IconButtonOnClickData { + name: string | undefined + value: string | number | undefined + isActivated: boolean +} + +export interface IconButtonProps { + iconName: string + name?: string + value?: string | number | undefined + type?: 'button' | 'submit' + iconType?: IconProps['type'] + size?: IconProps['size'] + shape?: IconProps['bgShape'] + activated?: boolean + secondary?: boolean + danger?: boolean + light?: boolean + disabled?: boolean + loading?: boolean + onClick?: (data: IconButtonOnClickData) => void +} + +export function IconButton({ + iconName, + name, + value, + type = 'button', + iconType = 'line', + size, + shape, + activated, + secondary, + danger, + light, + disabled, + loading, + onClick +}: IconButtonProps) { + const [isActivated, setIsActivated] = useState(activated || false) + + let variant = 'primary' + + if (danger) { + variant = 'danger' + } + + return ( + + ) +} diff --git a/aurora/src/components/icon-button/index.ts b/aurora/src/components/icon-button/index.ts new file mode 100644 index 0000000..876ec6f --- /dev/null +++ b/aurora/src/components/icon-button/index.ts @@ -0,0 +1 @@ +export * from './icon-button' diff --git a/aurora/src/components/icon/icon.sass b/aurora/src/components/icon/icon.sass new file mode 100644 index 0000000..4b0a417 --- /dev/null +++ b/aurora/src/components/icon/icon.sass @@ -0,0 +1,115 @@ +@use '../../styles/main.sass' as * + +.aurora-icon + position: relative + display: inline-flex + align-items: center + justify-content: center + border-radius: var(--a-border-radius-xs) + color: var(--a-color-white) + font-size: var(--a-font-size-md) + background-color: transparent + padding: var(--a-space-xs) + transition: opacity var(--a-transition-duration-main) var(--a-transition-timing-main), color var(--a-transition-duration-main) var(--a-transition-timing-main), background-color var(--a-transition-duration-main) var(--a-transition-timing-main), transform var(--a-transition-duration-main) var(--a-transition-timing-main) + + &--animated + opacity: 0 + animation: aurora-animation-fade-in var(--a-transition-duration-main) var(--a-transition-timing-main) var(--a-transition-duration-main) forwards + + &--xs + width: 12px + height: 12px + font-size: var(--a-font-size-xs) + border-radius: var(--a-border-radius-xs) + &--sm + width: 20px + height: 20px + font-size: var(--a-font-size-sm) + border-radius: var(--a-border-radius-xs) + &--md + width: 28px + height: 28px + font-size: var(--a-font-size-md) + border-radius: var(--a-border-radius-xs) + &--lg + width: 56px + height: 56px + font-size: var(--a-font-size-lg) + border-radius: var(--a-border-radius-md) + &--xl + width: 96px + height: 96px + font-size: var(--a-font-size-xl) + border-radius: var(--a-border-radius-md) + &--xxl + width: 128px + height: 128px + font-size: var(--a-font-size-xxl) + border-radius: var(--a-border-radius-md) + + &--square + border-radius: var(--a-border-radius-xs) + &--circle + border-radius: var(--a-border-radius-circle) + + &--white + color: var(--a-color-white) + &--transparent-white + color: var(--a-color-transparent-white) + &--black + color: var(--a-color-black) + &--blue + color: var(--a-color-blue) + &--secondary-blue + color: var(--a-color-secondary-blue) + &--transparent-blue + color: var(--a-color-transparent-blue) + &--red + color: var(--a-color-red) + &--secondary-red + color: var(--a-color-secondary-red) + &--transparent-red + color: var(--a-color-transparent-red) + &--green + color: var(--a-color-green) + &--secondary-green + color: var(--a-color-secondary-green) + &--transparent-green + color: var(--a-color-transparent-green) + &--yellow + color: var(--a-color-yellow) + &--secondary-yellow + color: var(--a-color-secondary-yellow) + &--transparent-yellow + color: var(--a-color-transparent-yellow) + + &--bg-white + background-color: var(--a-color-white) + &--bg-transparent-white + background-color: var(--a-color-transparent-white) + &--bg-black + background-color: var(--a-color-black) + &--bg-blue + background-color: var(--a-color-blue) + &--bg-secondary-blue + background-color: var(--a-color-secondary-blue) + &--bg-transparent-blue + background-color: var(--a-color-transparent-blue) + &--bg-red + background-color: var(--a-color-red) + &--bg-secondary-red + background-color: var(--a-color-secondary-red) + &--bg-transparent-red + background-color: var(--a-color-transparent-red) + &--bg-green + background-color: var(--a-color-green) + &--bg-secondary-green + background-color: var(--a-color-secondary-green) + &--bg-transparent-green + background-color: var(--a-color-transparent-green) + &--bg-yellow + background-color: var(--a-color-yellow) + &--bg-secondary-yellow + background-color: var(--a-color-secondary-yellow) + &--bg-transparent-yellow + background-color: var(--a-color-transparent-yellow) diff --git a/aurora/src/components/icon/icon.tsx b/aurora/src/components/icon/icon.tsx new file mode 100644 index 0000000..f6a5170 --- /dev/null +++ b/aurora/src/components/icon/icon.tsx @@ -0,0 +1,75 @@ +import classNames from 'clsx' + +import type { Color, Size, IconType } from '../../lib/types' +import { generateKeyId } from '../../lib/utils' + +import './icon.sass' + +export interface IconProps { + iconName?: string + /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ + svg?: any + // svg?: React.ReactNode + type?: IconType + color?: Color + size?: Size | 'xxl' + bgShape?: 'square' | 'circle' + bgColor?: Color + animated?: boolean +} + +const REMIX_SIZE_MAPPING = { + xs: 'xs', + sm: 'sm', + md: '1x', + lg: 'lg', + xl: 'xl', + xxl: '2x' +} +const REMIX_ICON_TYPE_SUFFIXES = ['-line', '-fill'] + +/** + * @see https://remixicon.com/ + */ +export function Icon({ + iconName, + svg, + type = 'line', + color, + size = 'md', + bgShape, + bgColor, + animated +}: IconProps) { + let iconClassName = `ri-${iconName}` + const hasExplicitTypeSuffix = REMIX_ICON_TYPE_SUFFIXES.some((suffix) => + iconName?.endsWith(suffix) + ) + + if (type && type !== 'notype' && !hasExplicitTypeSuffix) { + iconClassName = `${iconClassName}-${type}` + } + + return ( + + {svg ? ( + svg + ) : ( + + )} + + ) +} diff --git a/aurora/src/components/icon/index.ts b/aurora/src/components/icon/index.ts new file mode 100644 index 0000000..0af8038 --- /dev/null +++ b/aurora/src/components/icon/index.ts @@ -0,0 +1 @@ +export * from './icon' diff --git a/aurora/src/components/image/image.sass b/aurora/src/components/image/image.sass new file mode 100644 index 0000000..3277f96 --- /dev/null +++ b/aurora/src/components/image/image.sass @@ -0,0 +1,76 @@ +@use '../../styles/main.sass' as * + +.aurora-image + position: relative + border-radius: var(--a-border-radius-md) + background-repeat: no-repeat + background-size: cover + background-position: center center + + &--overlay + &::before + content: '' + position: absolute + width: 100% + height: 100% + background-color: rgba(0, 0, 0, .2) + transition: background-color var(--a-transition-duration-main) var(--a-transition-timing-main) + &:hover + &::before + background-color: rgba(0, 0, 0, 0) + + &--gradient + &::after + content: '' + position: absolute + top: auto + bottom: 0 + width: 100% + height: 64px + background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0), var(--a-color-background-surface)) + &--gradient-top + &::after + top: 0 + bottom: auto + background-image: linear-gradient(to top, rgba(0, 0, 0, 0), var(--a-color-background-surface)) + &--gradient-bottom + &::after + top: auto + bottom: 0 + background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0), var(--a-color-background-surface)) + &--gradient-left + &::after + left: 0 + top: 0 + bottom: 0 + width: 64px + height: 100% + background-image: linear-gradient(to left, rgba(0, 0, 0, 0), var(--a-color-background-surface)) + &--gradient-right + &::after + right: 0 + top: 0 + bottom: 0 + width: 64px + height: 100% + background-image: linear-gradient(to right, rgba(0, 0, 0, 0), var(--a-color-background-surface)) + + &--cover + background-size: cover + &--contain + background-size: contain + + &--square + border-radius: var(--a-border-radius-md) + &--circle + border-radius: var(--a-border-radius-circle) + + &--blue-border + border: 1px solid var(--a-color-blue) + &--white-border + border: 1px solid var(--a-color-white) + + &--radius-top + border-radius: var(--a-border-radius-md) var(--a-border-radius-md) 0 0 + &--radius-bottom + border-radius: 0 0 var(--a-border-radius-md) var(--a-border-radius-md) diff --git a/aurora/src/components/image/image.tsx b/aurora/src/components/image/image.tsx new file mode 100644 index 0000000..5cb490c --- /dev/null +++ b/aurora/src/components/image/image.tsx @@ -0,0 +1,54 @@ +import classNames from 'clsx' + +import { generateKeyId } from '../../lib/utils' + +import './image.sass' + +export interface ImageProps { + src: string + width?: number | string + height?: number | string + shape?: 'circle' | 'square' + borderColor?: 'white' | 'blue' + backgroundSize?: 'cover' | 'contain' + radiusTop?: boolean + radiusBottom?: boolean + overlay?: boolean + gradient?: boolean + gradientPosition?: 'top' | 'bottom' | 'left' | 'right' +} + +export function Image({ + src, + width, + height, + shape, + borderColor, + backgroundSize, + radiusTop, + radiusBottom, + overlay, + gradient, + gradientPosition +}: ImageProps) { + return ( +
+ ) +} diff --git a/aurora/src/components/image/index.ts b/aurora/src/components/image/index.ts new file mode 100644 index 0000000..556dbfd --- /dev/null +++ b/aurora/src/components/image/index.ts @@ -0,0 +1 @@ +export * from './image' diff --git a/aurora/src/components/input/index.ts b/aurora/src/components/input/index.ts new file mode 100644 index 0000000..114afe8 --- /dev/null +++ b/aurora/src/components/input/index.ts @@ -0,0 +1 @@ +export * from './input' diff --git a/aurora/src/components/input/input.sass b/aurora/src/components/input/input.sass new file mode 100644 index 0000000..be56fe9 --- /dev/null +++ b/aurora/src/components/input/input.sass @@ -0,0 +1,87 @@ +@use '../../styles/main.sass' as * + +.aurora-input-container + --a-icon-container-width: calc(var(--a-input-size-md) + var(--a-space-sm)) + + position: relative + display: flex + flex-direction: column + +.aurora-input + position: relative + display: inline-block + color: var(--a-color-text) + background-color: var(--a-color-input-background) + font-size: var(--a-font-size-md) + border: 1px solid var(--a-color-input-border) + border-radius: var(--a-border-radius-md) + height: var(--a-input-size-md) + padding: 0 var(--a-space-md) + width: 100% + outline: none + transition: background-color var(--a-transition-duration-main) var(--a-transition-timing-main), border-color var(--a-transition-duration-main) var(--a-transition-timing-main) + &::-webkit-calendar-picker-indicator + cursor: pointer + background-color: var(--a-color-grey-blue-dark) + border-radius: var(--a-border-radius-xs) + &:hover + border-color: var(--a-color-input-border-hover) + background-color: var(--a-color-input-background-hover) + &:hover:not([disabled]) ~ .aurora-input-icon-container + border-color: var(--a-color-input-border-hover) + &:focus + border-color: var(--a-color-input-border-focus) + background-color: var(--a-color-input-background-hover) + &:focus:not([disabled]) + &~ .aurora-input-icon-container + border-color: var(--a-color-input-border-focus) + i + color: var(--a-color-accent) + &:placeholder-shown ~ .aurora-input-icon-container i + color: var(--color-secondary-white) + + &--multiline + height: calc(var(--a-input-size-md) * 2) + padding: var(--a-space-sm) var(--a-space-md) + resize: vertical + min-height: calc(var(--a-input-size-md) * 2) + max-height: 512px + &~ .aurora-input-icon-container + height: 100% + + &--disabled, &--disabled:hover + opacity: var(--a-opacity-disabled) + color: inherit + background-color: var(--a-color-input-background) + border-color: var(--a-color-input-border) + cursor: not-allowed + &--disabled ~ .aurora-input-icon-container + opacity: var(--a-opacity-disabled) + i + color: inherit + opacity: var(--a-opacity-disabled) + + &--with-icon + padding-left: calc(var(--a-icon-container-width) + var(--a-space-md)) + +.aurora-input-icon-container + position: absolute + left: 0 + top: 0 + bottom: 0 + display: flex + align-items: center + justify-content: center + color: var(--a-color-text) + pointer-events: none + border-right: 1px solid var(--a-color-input-border) + width: var(--a-icon-container-width) + height: var(--a-input-size-md) + transition: background-color var(--a-transition-duration-main) var(--a-transition-timing-main), border-color var(--a-transition-duration-main) var(--a-transition-timing-main) + i + color: var(--a-color-text) + transition: color var(--a-transition-duration-main) var(--a-transition-timing-main) + +.aurora-input-hint-container + padding-left: var(--a-space-md) + margin-top: var(--a-space-xs) diff --git a/aurora/src/components/input/input.tsx b/aurora/src/components/input/input.tsx new file mode 100644 index 0000000..9ef4ef8 --- /dev/null +++ b/aurora/src/components/input/input.tsx @@ -0,0 +1,167 @@ +import { useEffect, useState } from 'react' +import classNames from 'clsx' + +import { Text, Icon } from '../..' +import type { IconProps } from '../icon' + +import './input.sass' + +export interface InputProps { + name: string + placeholder: string + required?: boolean + value?: string + type?: + | 'text' + | 'password' + | 'email' + | 'tel' + | 'url' + | 'number' + | 'date' + | 'time' + | 'datetime-local' + | 'month' + | 'week' + | 'color' + iconName?: string + iconSVG?: IconProps['svg'] + iconType?: IconProps['type'] + iconSize?: IconProps['size'] + hint?: string + disabled?: boolean + height?: number | 'auto' + minLength?: number + maxLength?: number + min?: number + max?: number + step?: number + pattern?: string + multiline?: boolean + autofocus?: boolean + onFocus?: () => void + onBlur?: () => void + onKeyDown?: (event: React.KeyboardEvent) => void + inputRef?: React.Ref + onChange?: (value: string) => void +} + +export function Input({ + name, + placeholder, + required = false, + type = 'text', + iconName, + iconSVG, + iconType = 'fill', + iconSize = 'md', + hint, + value, + disabled, + height = 'auto', + minLength, + maxLength, + pattern, + multiline, + autofocus, + onFocus, + onBlur, + onKeyDown, + inputRef, + onChange +}: InputProps) { + const [inputValue, setInputValue] = useState(value || '') + + useEffect(() => { + setInputValue(value || '') + }, [value]) + + if (!multiline) { + if (!maxLength) { + maxLength = 64 + } + + if (height !== 'auto') { + height = 'auto' + } + } + + return ( +
+ {multiline ? ( +