Repository: pickle-com/glass
Branch: main
Commit: 71bc3dce7c92
Files: 153
Total size: 1.3 MB
Directory structure:
gitextract_d8n6n_v9/
├── .firebaserc
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ └── feature_request.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── workflows/
│ ├── assign-on-comment.yml
│ └── build.yml
├── .gitignore
├── .gitmodules
├── .npmrc
├── .prettierignore
├── .prettierrc
├── .vscode/
│ └── settings.json
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── build.js
├── docs/
│ ├── DESIGN_PATTERNS.md
│ └── refactor-plan.md
├── electron-builder.yml
├── entitlements.plist
├── firebase.json
├── firestore.indexes.json
├── functions/
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── index.js
│ └── package.json
├── notarize.js
├── package.json
├── pickleglass_web/
│ ├── app/
│ │ ├── activity/
│ │ │ ├── details/
│ │ │ │ └── page.tsx
│ │ │ └── page.tsx
│ │ ├── download/
│ │ │ └── page.tsx
│ │ ├── globals.css
│ │ ├── help/
│ │ │ └── page.tsx
│ │ ├── layout.tsx
│ │ ├── login/
│ │ │ └── page.tsx
│ │ ├── page.tsx
│ │ ├── personalize/
│ │ │ └── page.tsx
│ │ └── settings/
│ │ ├── billing/
│ │ │ └── page.tsx
│ │ ├── page.tsx
│ │ └── privacy/
│ │ └── page.tsx
│ ├── backend_node/
│ │ ├── index.js
│ │ ├── ipcBridge.js
│ │ ├── middleware/
│ │ │ └── auth.js
│ │ └── routes/
│ │ ├── auth.js
│ │ ├── conversations.js
│ │ ├── presets.js
│ │ └── user.js
│ ├── components/
│ │ ├── ClientLayout.tsx
│ │ ├── SearchPopup.tsx
│ │ └── Sidebar.tsx
│ ├── next-env.d.ts
│ ├── next.config.js
│ ├── package.json
│ ├── postcss.config.js
│ ├── public/
│ │ └── README.md
│ ├── requirements.txt
│ ├── tailwind.config.js
│ ├── tsconfig.json
│ └── utils/
│ ├── api.ts
│ ├── auth.ts
│ ├── firebase.ts
│ └── firestore.ts
├── preload.js
└── src/
├── bridge/
│ ├── featureBridge.js
│ ├── internalBridge.js
│ └── windowBridge.js
├── features/
│ ├── ask/
│ │ ├── askService.js
│ │ └── repositories/
│ │ ├── firebase.repository.js
│ │ ├── index.js
│ │ └── sqlite.repository.js
│ ├── common/
│ │ ├── ai/
│ │ │ ├── factory.js
│ │ │ └── providers/
│ │ │ ├── anthropic.js
│ │ │ ├── deepgram.js
│ │ │ ├── gemini.js
│ │ │ ├── ollama.js
│ │ │ ├── openai.js
│ │ │ └── whisper.js
│ │ ├── config/
│ │ │ ├── checksums.js
│ │ │ ├── config.js
│ │ │ └── schema.js
│ │ ├── prompts/
│ │ │ ├── promptBuilder.js
│ │ │ └── promptTemplates.js
│ │ ├── repositories/
│ │ │ ├── firestoreConverter.js
│ │ │ ├── ollamaModel/
│ │ │ │ ├── index.js
│ │ │ │ └── sqlite.repository.js
│ │ │ ├── permission/
│ │ │ │ ├── index.js
│ │ │ │ └── sqlite.repository.js
│ │ │ ├── preset/
│ │ │ │ ├── firebase.repository.js
│ │ │ │ ├── index.js
│ │ │ │ └── sqlite.repository.js
│ │ │ ├── providerSettings/
│ │ │ │ ├── index.js
│ │ │ │ └── sqlite.repository.js
│ │ │ ├── session/
│ │ │ │ ├── firebase.repository.js
│ │ │ │ ├── index.js
│ │ │ │ └── sqlite.repository.js
│ │ │ ├── user/
│ │ │ │ ├── firebase.repository.js
│ │ │ │ ├── index.js
│ │ │ │ └── sqlite.repository.js
│ │ │ └── whisperModel/
│ │ │ └── index.js
│ │ ├── services/
│ │ │ ├── authService.js
│ │ │ ├── databaseInitializer.js
│ │ │ ├── encryptionService.js
│ │ │ ├── firebaseClient.js
│ │ │ ├── localAIManager.js
│ │ │ ├── migrationService.js
│ │ │ ├── modelStateService.js
│ │ │ ├── ollamaService.js
│ │ │ ├── permissionService.js
│ │ │ ├── sqliteClient.js
│ │ │ └── whisperService.js
│ │ └── utils/
│ │ └── spawnHelper.js
│ ├── listen/
│ │ ├── listenService.js
│ │ ├── stt/
│ │ │ ├── repositories/
│ │ │ │ ├── firebase.repository.js
│ │ │ │ ├── index.js
│ │ │ │ └── sqlite.repository.js
│ │ │ └── sttService.js
│ │ └── summary/
│ │ ├── repositories/
│ │ │ ├── firebase.repository.js
│ │ │ ├── index.js
│ │ │ └── sqlite.repository.js
│ │ └── summaryService.js
│ ├── settings/
│ │ ├── repositories/
│ │ │ ├── firebase.repository.js
│ │ │ ├── index.js
│ │ │ └── sqlite.repository.js
│ │ └── settingsService.js
│ └── shortcuts/
│ ├── repositories/
│ │ ├── index.js
│ │ └── sqlite.repository.js
│ └── shortcutsService.js
├── index.js
├── preload.js
├── ui/
│ ├── app/
│ │ ├── ApiKeyHeader.js
│ │ ├── HeaderController.js
│ │ ├── MainHeader.js
│ │ ├── PermissionHeader.js
│ │ ├── PickleGlassApp.js
│ │ ├── WelcomeHeader.js
│ │ ├── content.html
│ │ └── header.html
│ ├── ask/
│ │ └── AskView.js
│ ├── assets/
│ │ ├── SystemAudioDump
│ │ ├── logo.icns
│ │ └── smd.js
│ ├── listen/
│ │ ├── ListenView.js
│ │ ├── audioCore/
│ │ │ ├── aec.js
│ │ │ ├── listenCapture.js
│ │ │ └── renderer.js
│ │ ├── stt/
│ │ │ └── SttView.js
│ │ └── summary/
│ │ └── SummaryView.js
│ ├── settings/
│ │ ├── SettingsView.js
│ │ └── ShortCutSettingsView.js
│ └── styles/
│ └── glass-bypass.css
└── window/
├── smoothMovementManager.js
├── windowLayoutManager.js
└── windowManager.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .firebaserc
================================================
{
"projects": {
"default": "pickle-3651a"
}
}
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug Report
about: Create a report to help us improve
title: "[BUG] "
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):**
- OS: [e.g. macOS, Windows]
- App Version [e.g. 1.0.0]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature Request
about: Suggest an idea for this project
title: "[FEAT] "
labels: feature
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
---
name: Pull Request
about: Propose a change to the codebase
---
## Summary of Changes
Please provide a brief, high-level summary of the changes in this pull request.
## Related Issue
- Closes #XXX
*Please replace `XXX` with the issue number that this pull request resolves. If it does not resolve a specific issue, please explain why this change is needed.*
## Contributor's Self-Review Checklist
Please check the boxes that apply. This is a reminder of what we look for in a good pull request.
- [ ] I have read the [CONTRIBUTING.md](https://github.com/your-org/your-repo/blob/main/CONTRIBUTING.md) document.
- [ ] My code follows the project's coding style and architectural patterns as described in [DESIGN_PATTERNS.md](https://github.com/your-org/your-repo/blob/main/docs/DESIGN_PATTERNS.md).
- [ ] I have added or updated relevant tests for my changes.
- [ ] I have updated the documentation to reflect my changes (if applicable).
- [ ] My changes have been tested locally and are working as expected.
## Additional Context (Optional)
Add any other context or screenshots about the pull request here.
================================================
FILE: .github/workflows/assign-on-comment.yml
================================================
name: Assign on Comment
on:
issue_comment:
types: [created]
jobs:
# Job 1: Any contributor can self-assign
self-assign:
# Only run if the comment is exactly '/assign'
if: startsWith(github.event.comment.body, '/assign') && !contains(github.event.comment.body, '@')
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: Assign commenter to the issue
uses: actions/github-script@v7
with:
script: |
// Assign the commenter as the assignee
await github.rest.issues.addAssignees({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
assignees: [context.actor]
});
// Add a rocket (🚀) reaction to indicate success
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'rocket'
});
# Job 2: Admin can assign others
assign-others:
# Only run if the comment starts with '/assign @' and the commenter is in the admin group
if: startsWith(github.event.comment.body, '/assign @') && contains(fromJson('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association)
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: Assign mentioned user
uses: actions/github-script@v7
with:
script: |
const mention = context.payload.comment.body.split(' ')[1];
const assignee = mention.substring(1); // Remove '@'
// Assign the mentioned user as the assignee
await github.rest.issues.addAssignees({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
assignees: [assignee]
});
// Add a thumbs up (+1) reaction to indicate success
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: '+1'
});
================================================
FILE: .github/workflows/build.yml
================================================
name: Build & Verify
on:
push:
branches: [ "main" ] # Runs on every push to main branch
jobs:
build:
# Currently runs on macOS only, can add windows-latest later
runs-on: macos-latest
steps:
- name: 🚚 Checkout code
uses: actions/checkout@v4
- name: ⚙️ Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: '20.x' # Node.js version compatible with project
cache: 'npm' # npm dependency caching for speed improvement
- name: 📦 Install root dependencies
run: npm install
- name: 🌐 Install and build web (Renderer) part
# Move to pickleglass_web directory and run commands
working-directory: ./pickleglass_web
run: |
npm install
npm run build
- name: 🖥️ Build Electron app
# Run Electron build script from root directory
run: npm run build
- name: 🚨 Send failure notification to Slack
if: failure()
uses: rtCamp/action-slack-notify@v2
env:
SLACK_CHANNEL: general
SLACK_TITLE: "🚨 Build Failed"
SLACK_MESSAGE: "😭 Build failed for `${{ github.repository }}` repo on main branch."
SLACK_COLOR: 'danger'
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
================================================
FILE: .gitignore
================================================
# Logs
src/data
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
.DS_Store
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# Webpack
.webpack/
# Vite
.vite/
# Electron-Forge
out/
.specstory
.specstory/
data/pickleglass.db
pickleglass_web/backend/__pycache__/
pickleglass_web/venv/
# Node / JS
node_modules/
npm-debug.log
yarn-error.log
# Database
data/*.db
data/*.db-journal
data/*.db-shm
data/*.db-wal
# Build output
out/
dist/
build/
================================================
FILE: .gitmodules
================================================
[submodule "aec"]
path = aec
url = https://github.com/samtiz/aec.git
================================================
FILE: .npmrc
================================================
better-sqlite3:ignore-scripts=true
sharp:ignore-scripts=true
================================================
FILE: .prettierignore
================================================
src/ui/assets
node_modules
================================================
FILE: .prettierrc
================================================
{
"semi": true,
"tabWidth": 4,
"printWidth": 150,
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "avoid",
"endOfLine": "lf"
}
================================================
FILE: .vscode/settings.json
================================================
{
"search.useIgnoreFiles": true
}
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Glass
Thank you for considering contributing to **Glass by Pickle**! Contributions make the open-source community vibrant, innovative, and collaborative. We appreciate every contribution you make—big or small.
This document guides you through the entire contribution process, from finding an issue to getting your pull request merged.
---
## 🚀 Contribution Workflow
To ensure a smooth and effective workflow, all contributions must go through the following process. Please follow these steps carefully.
### 1. Find or Create an Issue
All work begins with an issue. This is the central place to discuss new ideas and track progress.
- Browse our existing [**Issues**](https://github.com/pickle-com/glass/issues) to find something you'd like to work on. We recommend looking for issues labeled `good first issue` if you're new!
- If you have a new idea or find a bug that hasn't been reported, please **create a new issue** using our templates.
### 2. Claim the Issue
To avoid duplicate work, you must claim an issue before you start coding.
- On the issue you want to work on, leave a comment with the command:
```
/assign
```
- Our GitHub bot will automatically assign the issue to you. Once your profile appears in the **`Assignees`** section on the right, you are ready to start development.
### 3. Fork & Create a Branch
Now it's time to set up your local environment.
1. **Fork** the repository to your own GitHub account.
2. **Clone** your forked repository to your local machine.
3. **Create a new branch** from `main`. A clear branch name is recommended.
- For new features: `feat/short-description` (e.g., `feat/user-login-ui`)
- For bug fixes: `fix/short-description` (e.g., `fix/header-rendering-bug`)
### 4. Develop
Write your code! As you work, please adhere to our quality standards.
- **Code Style & Quality**: Our project uses `Prettier` and `ESLint` to maintain a consistent code style.
- **Architecture & Design Patterns**: All new code must be consistent with the project's architecture. Please read our **[Design Patterns Guide](https://github.com/pickle-com/glass/blob/main/docs/DESIGN_PATTERNS.md)** before making significant changes.
### 5. Create a Pull Request (PR)
Once your work is ready, create a Pull Request to the `main` branch of the original repository.
- **Fill out the PR Template**: Our template will appear automatically. Please provide a clear summary of your changes.
- **Link the Issue**: In the PR description, include the line `Closes #XXX` (e.g., `Closes #123`) to link it to the issue you resolved. This is mandatory.
- **Code Review**: A maintainer will review your code, provide feedback, and merge it.
---
# Developing
### Prerequisites
Ensure the following are installed:
- [Node.js v20.x.x](https://nodejs.org/en/download)
- [Python](https://www.python.org/downloads/)
- (Windows users) [Build Tools for Visual Studio](https://visualstudio.microsoft.com/downloads/)
Ensure you're using Node.js version 20.x.x to avoid build errors with native dependencies.
```bash
# Check your Node.js version
node --version
# If you need to install Node.js 20.x.x, we recommend using nvm:
# curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# nvm install 20
# nvm use 20
```
## Setup and Build
```bash
npm run setup
```
Please ensure that you can make a full production build before pushing code.
## Linting
```bash
npm run lint
```
If you get errors, be sure to fix them before committing.
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
Glass by Pickle: Digital Mind Extension 🧠
> This project is a fork of [CheatingDaddy](https://github.com/sohzm/cheating-daddy) with modifications and enhancements. Thanks to [Soham](https://x.com/soham_btw) and all the open-source contributors who made this possible!
🤖 **Fast, light & open-source**—Glass lives on your desktop, sees what you see, listens in real time, understands your context, and turns every moment into structured knowledge.
💬 **Proactive in meetings**—it surfaces action items, summaries, and answers the instant you need them.
🫥️ **Truly invisible**—never shows up in screen recordings, screenshots, or your dock; no always-on capture or hidden sharing.
To have fun building with us, join our [Discord](https://discord.gg/UCZH5B5Hpd)!
## Instant Launch
⚡️ Skip the setup—launch instantly with our ready-to-run macOS app. [[Download Here]](https://www.dropbox.com/scl/fi/znid09apxiwtwvxer6oc9/Glass_latest.dmg?rlkey=gwvvyb3bizkl25frhs4k1zwds&st=37q31b4w&dl=1)
## Quick Start (Local Build)
### Prerequisites
First download & install [Python](https://www.python.org/downloads/) and [Node](https://nodejs.org/en/download).
If you are using Windows, you need to also install [Build Tools for Visual Studio](https://visualstudio.microsoft.com/downloads/)
Ensure you're using Node.js version 20.x.x to avoid build errors with native dependencies.
```bash
# Check your Node.js version
node --version
# If you need to install Node.js 20.x.x, we recommend using nvm:
# curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# nvm install 20
# nvm use 20
```
### Installation
```bash
npm run setup
```
## Highlights
### Ask: get answers based on all your previous screen actions & audio
### Meetings: real-time meeting notes, live summaries, session records
### Use your own API key, or sign up to use ours (free)
**Currently Supporting:**
- OpenAI API: Get OpenAI API Key [here](https://platform.openai.com/api-keys)
- Gemini API: Get Gemini API Key [here](https://aistudio.google.com/apikey)
- Local LLM Ollama & Whisper
### Liquid Glass Design (coming soon)
for a more detailed guide, please refer to this video.
we don't waste money on fancy vids; we just code.
## Keyboard Shortcuts
`Ctrl/Cmd + \` : show and hide main window
`Ctrl/Cmd + Enter` : ask AI using all your previous screen and audio
`Ctrl/Cmd + Arrows` : move main window position
## Repo Activity

## Contributing
We love contributions! Feel free to open issues for bugs or feature requests. For detailed guide, please see our [contributing guide](/CONTRIBUTING.md).
> Currently, we're working on a full code refactor and modularization. Once that's completed, we'll jump into addressing the major issues.
### Contributors
### Help Wanted Issues
We have a list of [help wanted](https://github.com/pickle-com/glass/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22%F0%9F%99%8B%E2%80%8D%E2%99%82%EF%B8%8Fhelp%20wanted%22) that contain small features and bugs which have a relatively limited scope. This is a great place to get started, gain experience, and get familiar with our contribution process.
### 🛠 Current Issues & Improvements
| Status | Issue | Description |
|--------|--------------------------------|---------------------------------------------------|
| 🚧 WIP | Liquid Glass | Liquid Glass UI for MacOS 26 |
### Changelog
- Jul 5: Now support Gemini, Intel Mac supported
- Jul 6: Full code refactoring has done.
- Jul 7: Now support Claude, LLM/STT model selection
- Jul 8: Now support Windows(beta), Improved AEC by Rust(to seperate mic/system audio), shortcut editing(beta)
- Jul 8: Now support Local LLM & STT, Firebase Data Storage
## About Pickle
**Our mission is to build a living digital clone for everyone.** Glass is part of Step 1—a trusted pipeline that transforms your daily data into a scalable clone. Visit [pickle.com](https://pickle.com) to learn more.
## Star History
[](https://www.star-history.com/#pickle-com/glass&Date)
================================================
FILE: build.js
================================================
const esbuild = require('esbuild');
const path = require('path');
const baseConfig = {
bundle: true,
platform: 'browser',
format: 'esm',
loader: { '.js': 'jsx' },
sourcemap: true,
external: ['electron'],
define: {
'process.env.NODE_ENV': `"${process.env.NODE_ENV || 'development'}"`,
},
};
const entryPoints = [
{ in: 'src/ui/app/HeaderController.js', out: 'public/build/header' },
{ in: 'src/ui/app/PickleGlassApp.js', out: 'public/build/content' },
];
async function build() {
try {
console.log('Building renderer process code...');
await Promise.all(entryPoints.map(point => esbuild.build({
...baseConfig,
entryPoints: [point.in],
outfile: `${point.out}.js`,
})));
console.log('✅ Renderer builds successful!');
} catch (e) {
console.error('Renderer build failed:', e);
process.exit(1);
}
}
async function watch() {
try {
const contexts = await Promise.all(entryPoints.map(point => esbuild.context({
...baseConfig,
entryPoints: [point.in],
outfile: `${point.out}.js`,
})));
console.log('Watching for changes...');
await Promise.all(contexts.map(context => context.watch()));
} catch (e) {
console.error('Watch mode failed:', e);
process.exit(1);
}
}
if (process.argv.includes('--watch')) {
watch();
} else {
build();
}
================================================
FILE: docs/DESIGN_PATTERNS.md
================================================
# Glass: Design Patterns and Architectural Overview
Welcome to the Glass project! This document is the definitive guide to the architectural patterns, conventions, and design philosophy that guide our development. Adhering to these principles is essential for building new features, maintaining the quality of our codebase, and ensuring a stable, consistent developer experience.
The architecture is designed to be modular, robust, and clear, with a strict separation of concerns.
---
## Core Architectural Principles
These are the fundamental rules that govern the entire application.
1. **Centralized Data Logic**: All data persistence logic (reading from or writing to a database) is centralized within the **Electron Main Process**. The UI layers (both Electron's renderer and the web dashboard) are forbidden from accessing data sources directly.
2. **Feature-Based Modularity**: Code is organized by feature (`src/features`) to promote encapsulation and separation of concerns. A new feature should be self-contained within its own directory.
3. **Dual-Database Repositories**: The data access layer uses a **Repository Pattern** that abstracts away the underlying database. Every repository that handles user data **must** have two implementations: one for the local `SQLite` database and one for the cloud `Firebase` database. Both must expose an identical interface.
4. **AI Provider Abstraction**: AI model interactions are abstracted using a **Factory Pattern**. To add a new provider (e.g., a new LLM), you only need to create a new provider module that conforms to the base interface in `src/common/ai/providers/` and register it in the `factory.js`.
5. **Single Source of Truth for Schema**: The schema for the local SQLite database is defined in a single location: `src/common/config/schema.js`. Any change to the database structure **must** be updated here.
6. **Encryption by Default**: All sensitive user data **must** be encrypted before being persisted to Firebase. This includes, but is not limited to, API keys, conversation titles, transcription text, and AI-generated summaries. This is handled automatically by the `createEncryptedConverter` Firestore helper.
---
## I. Electron Application Architecture (`src/`)
This section details the architecture of the core desktop application.
### 1. Overall Pattern: Service-Repository
The Electron app's logic is primarily built on a **Service-Repository** pattern, with the Views being the HTML/JS files in the `src/app` and `src/features` directories.
- **Views** (`*.html`, `*View.js`): The UI layer. Views are responsible for rendering the interface and capturing user interactions. They are intentionally kept "dumb" and delegate all significant logic to a corresponding Service.
- **Services** (`*Service.js`): Services contain the application's business logic. They act as the intermediary between Views and Repositories. For example, `sttService` contains the logic for STT, while `summaryService` handles the logic for generating summaries.
- **Repositories** (`*.repository.js`): Repositories are responsible for all data access. They are the *only* part of the application that directly interacts with `sqliteClient` or `firebaseClient`.
**Location of Modules:**
- **Feature-Specific**: If a service or repository is used by only one feature, it should reside within that feature's directory (e.g., `src/features/listen/summary/summaryService.js`).
- **Common**: If a service or repository is shared across multiple features (like `authService` or `userRepository`), it must be placed in `src/common/services/` or `src/common/repositories/` respectively.
### 2. Data Persistence: The Dual Repository Factory
The application dynamically switches between using the local SQLite database and the cloud-based Firebase Firestore.
- **SQLite**: The default data store for all users, especially those not logged in. This ensures full offline functionality. The low-level client is `src/common/services/sqliteClient.js`.
- **Firebase**: Used exclusively for users who are authenticated. This enables data synchronization across devices and with the web dashboard.
The selection mechanism is a sophisticated **Factory and Adapter Pattern** located in the `index.js` file of each repository directory (e.g., `src/common/repositories/session/index.js`).
**How it works:**
1. **Service Call**: A service makes a call to a high-level repository function, like `sessionRepository.create('ask')`. The service is unaware of the user's state or the underlying database.
2. **Repository Selection (Factory)**: The `index.js` adapter logic first determines which underlying repository to use. It imports and calls `authService.getCurrentUser()` to check the login state. If the user is logged in, it selects `firebase.repository.js`; otherwise, it defaults to `sqlite.repository.js`.
3. **UID Injection (Adapter)**: The adapter then retrieves the current user's ID (`uid`) from `authService.getCurrentUserId()`. It injects this `uid` into the actual, low-level repository call (e.g., `firebaseRepository.create(uid, 'ask')`).
4. **Execution**: The selected repository (`sqlite` or `firebase`) executes the data operation.
This powerful pattern accomplishes two critical goals:
- It makes the services completely agnostic about the underlying data source.
- It frees the services from the responsibility of managing and passing user IDs for every database query.
**Visualizing the Data Flow**
```mermaid
graph TD
subgraph "Electron Main Process"
A -- User Action --> B[Service Layer];
B -- Data Request --> C[Repository Factory];
C -- Check Login Status --> D{Decision};
D -- No --> E[SQLite Repository];
D -- Yes --> F[Firebase Repository];
E -- Access Local DB --> G[(SQLite)];
F -- Access Cloud DB --> H[(Firebase)];
G -- Return Data --> B;
H -- Return Data --> B;
B -- Update UI --> A;
end
style A fill:#D6EAF8,stroke:#3498DB
style G fill:#E8DAEF,stroke:#8E44AD
style H fill:#FADBD8,stroke:#E74C3C
```
---
## II. Web Dashboard Architecture (`pickleglass_web/`)
This section details the architecture of the Next.js web application, which serves as the user-facing dashboard for account management and cloud data viewing.
### 1. Frontend, Backend, and Main Process Communication
The web dashboard has a more complex, three-part architecture:
1. **Next.js Frontend (`app/`):** The React-based user interface.
2. **Node.js Backend (`backend_node/`):** An Express.js server that acts as an intermediary.
3. **Electron Main Process (`src/`):** The ultimate authority for all local data access.
Crucially, **the web dashboard's backend cannot access the local SQLite database directly**. It must communicate with the Electron main process to request data.
### 2. The IPC Data Flow
When the web frontend needs data that resides in the local SQLite database (e.g., viewing a non-synced session), it follows this precise flow:
1. **HTTP Request**: The Next.js frontend makes a standard API call to its own Node.js backend (e.g., `GET /api/conversations`).
2. **IPC Request**: The Node.js backend receives the HTTP request. It **does not** contain any database logic. Instead, it uses the `ipcRequest` helper from `backend_node/ipcBridge.js`.
3. **IPC Emission**: `ipcRequest` sends an event to the Electron main process over an IPC channel (`web-data-request`). It passes three things: the desired action (e.g., `'get-sessions'`), a unique channel name for the response, and a payload.
4. **Main Process Listener**: The Electron main process has a listener (`ipcMain.on('web-data-request', ...)`) that receives this request. It identifies the action and calls the appropriate **Service** or **Repository** to fetch the data from the SQLite database.
5. **IPC Response**: Once the data is retrieved, the main process sends it back to the web backend using the unique response channel provided in the request.
6. **HTTP Response**: The web backend's `ipcRequest` promise resolves with the data, and the backend sends it back to the Next.js frontend as a standard JSON HTTP response.
This round-trip ensures our core principle of centralizing data logic in the main process is never violated.
**Visualizing the IPC Data Flow**
```mermaid
sequenceDiagram
participant FE as Next.js Frontend
participant BE as Node.js Backend
participant Main as Electron Main Process
FE->>+BE: 1. HTTP GET /api/local-data
Note over BE: Receives local data request
BE->>+Main: 2. ipcRequest('get-data', responseChannel)
Note over Main: Receives request, fetches data from SQLite via Service/Repository
Main-->>-BE: 3. ipcResponse on responseChannel (data)
Note over BE: Receives data, prepares HTTP response
BE-->>-FE: 4. HTTP 200 OK (JSON data)
```
================================================
FILE: docs/refactor-plan.md
================================================
# Refactor Plan: Non-Window Logic Migration from windowManager.js
## Goal
`windowManager.js`를 순수 창 관리 모듈로 만들기 위해 비즈니스 로직을 해당 서비스와 `featureBridge.js`로 이전.
## Steps (based on initial plan)
1. **Shortcuts**: Completed. Logic moved to `shortcutsService.js` and IPC to `featureBridge.js`. Used `internalBridge` for coordination.
2. **Screenshot**: Next. Move `captureScreenshot` function and related IPC handlers from `windowManager.js` to `askService.js` (since it's primarily used there). Update `askService.js` to use its own screenshot method. Add IPC handlers to `featureBridge.js` if needed.
3. **System Permissions**: Create new `permissionService.js` in `src/features/common/services/`. Move all permission-related logic (check, request, open preferences, mark completed, etc.) and IPC handlers from `windowManager.js` to the new service and `featureBridge.js`.
4. **API Key / Model State**: Completely remove from `windowManager.js` (e.g., `setupApiKeyIPC` and helpers). Ensure all usages (e.g., in `askService.js`) directly require and use `modelStateService.js` instead.
## Notes
- Maintain original logic without changes.
- Break circular dependencies if found.
- Use `internalBridge` for inter-module communication where appropriate.
- After each step, verify no errors and test functionality.
================================================
FILE: electron-builder.yml
================================================
# electron-builder.yml
# The unique application ID
appId: com.pickle.glass
# The user-facing application name
productName: Glass
# Publish configuration for GitHub releases
publish:
provider: github
owner: pickle-com
repo: glass
releaseType: draft
# Protocols configuration for deep linking
protocols:
name: PickleGlass Protocol
schemes:
- pickleglass
# List of files to be included in the app package
files:
- src/**/*
- package.json
- pickleglass_web/backend_node/**/*
- '!**/node_modules/electron/**'
- public/build/**/*
# Additional resources to be copied into the app's resources directory
extraResources:
- from: pickleglass_web/out
to: out
asarUnpack:
- "src/ui/assets/SystemAudioDump"
- "**/node_modules/sharp/**/*"
- "**/node_modules/@img/**/*"
# Windows configuration
win:
icon: src/ui/assets/logo.ico
target:
- target: nsis
arch: x64
- target: portable
arch: x64
requestedExecutionLevel: asInvoker
signAndEditExecutable: true
cscLink: build\certs\glass-dev.pfx
cscKeyPassword: "${env.CSC_KEY_PASSWORD}"
signtoolOptions:
certificateSubjectName: "Glass Dev Code Signing"
# NSIS installer configuration for Windows
nsis:
oneClick: false
perMachine: false
allowToChangeInstallationDirectory: true
deleteAppDataOnUninstall: true
createDesktopShortcut: always
createStartMenuShortcut: true
shortcutName: Glass
# macOS specific configuration
mac:
# The application category type
category: public.app-category.utilities
# Path to the .icns icon file
icon: src/ui/assets/logo.icns
# Minimum macOS version (supports both Intel and Apple Silicon)
minimumSystemVersion: '11.0'
hardenedRuntime: true
entitlements: entitlements.plist
entitlementsInherit: entitlements.plist
target:
- target: dmg
arch: universal
- target: zip
arch: universal
================================================
FILE: entitlements.plist
================================================
com.apple.security.cs.allow-jit
com.apple.security.cs.allow-unsigned-executable-memory
com.apple.security.cs.debugger
com.apple.security.cs.disable-library-validation
com.apple.security.device.audio-input
com.apple.security.device.microphone
com.apple.security.network.client
com.apple.security.network.server
com.apple.security.temporary-exception.mach-lookup.global-name
com.deeplink.pickleglass.MachPortRendezvousServer.*
com.apple.security.app-sandbox
================================================
FILE: firebase.json
================================================
{
"functions": [
{
"source": "functions",
"codebase": "pickle-glass",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log",
"*.local"
],
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
]
}
],
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"hosting": {
"public": "pickleglass_web/out",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
================================================
FILE: firestore.indexes.json
================================================
{
"indexes": [],
"fieldOverrides": []
}
================================================
FILE: functions/.eslintrc.js
================================================
module.exports = {
env: {
es6: true,
node: true,
},
parserOptions: {
"ecmaVersion": 2018,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
"no-restricted-globals": ["error", "name", "length"],
"prefer-arrow-callback": "error",
"quotes": ["error", "double", {"allowTemplateLiterals": true}],
},
overrides: [
{
files: ["**/*.spec.*"],
env: {
mocha: true,
},
rules: {},
},
],
globals: {},
};
================================================
FILE: functions/.gitignore
================================================
node_modules/
*.local
================================================
FILE: functions/index.js
================================================
/**
* Import function triggers from their respective submodules:
*
* const {onCall} = require("firebase-functions/v2/https");
* const {onDocumentWritten} = require("firebase-functions/v2/firestore");
*
* See a full list of supported triggers at https://firebase.google.com/docs/functions
*/
const {onRequest} = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
const admin = require("firebase-admin");
const cors = require("cors")({origin: true});
admin.initializeApp();
// Create and deploy your first functions
// https://firebase.google.com/docs/functions/get-started
// exports.helloWorld = onRequest((request, response) => {
// logger.info("Hello logs!", {structuredData: true});
// response.send("Hello from Firebase!");
// });
/**
* @name pickleGlassAuthCallback
* @description
* Validate Firebase ID token and return custom token.
* On success, return success response with user information.
* On failure, return error message.
*
* @param {object} request - HTTPS request object. { token: "..." } in body.
* @param {object} response - HTTPS response object.
*/
const authCallbackHandler = (request, response) => {
cors(request, response, async () => {
try {
logger.info("pickleGlassAuthCallback function triggered", {
body: request.body,
});
if (request.method !== "POST") {
response.status(405).send("Method Not Allowed");
return;
}
if (!request.body || !request.body.token) {
logger.error("Token is missing from the request body");
response.status(400).send({
success: false,
error: "ID token is required.",
});
return;
}
const idToken = request.body.token;
const decodedToken = await admin.auth().verifyIdToken(idToken);
const uid = decodedToken.uid;
logger.info("Successfully verified token for UID:", uid);
const customToken = await admin.auth().createCustomToken(uid);
response.status(200).send({
success: true,
message: "Authentication successful.",
user: {
uid: decodedToken.uid,
email: decodedToken.email,
name: decodedToken.name,
picture: decodedToken.picture,
},
customToken,
});
} catch (error) {
logger.error("Authentication failed:", error);
response.status(401).send({
success: false,
error: "Invalid token or authentication failed.",
details: error.message,
});
}
});
};
exports.pickleGlassAuthCallback = onRequest(
{region: "us-west1"},
authCallbackHandler,
);
================================================
FILE: functions/package.json
================================================
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint . --fix",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "20"
},
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"firebase-admin": "^12.7.0",
"firebase-functions": "^6.0.1"
},
"devDependencies": {
"eslint": "^8.15.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^3.1.0"
},
"private": true
}
================================================
FILE: notarize.js
================================================
const { notarize } = require('@electron/notarize');
exports.notarizeApp = async function (context) {
if (context.electronPlatformName !== 'darwin') {
return;
}
console.log(' notarizing a macOS build!');
const { appOutDir } = context;
const appName = context.packager.appInfo.productFilename;
const appPath = `${appOutDir}/${appName}.app`;
if (!process.env.APPLE_ID || !process.env.APPLE_ID_PASSWORD || !process.env.APPLE_TEAM_ID) {
throw new Error('APPLE_ID, APPLE_ID_PASSWORD, and APPLE_TEAM_ID environment variables are required for notarization.');
}
await notarize({
appBundleId: 'com.pickle.glass',
appPath: appPath,
appleId: process.env.APPLE_ID,
appleIdPassword: process.env.APPLE_ID_PASSWORD,
teamId: process.env.APPLE_TEAM_ID,
});
console.log(`Successfully notarized ${appName}`);
};
================================================
FILE: package.json
================================================
{
"name": "pickle-glass",
"productName": "Glass",
"version": "0.2.4",
"description": "Cl*ely for Free",
"main": "src/index.js",
"scripts": {
"setup": "npm install && cd pickleglass_web && npm install && npm run build && cd .. && npm start",
"start": "npm run build:renderer && electron .",
"package": "npm run build:all && electron-builder --dir",
"make": "npm run build:renderer && electron-forge make",
"build": "npm run build:all && electron-builder --config electron-builder.yml --publish never",
"build:win": "npm run build:all && electron-builder --win --x64 --publish never",
"publish": "npm run build:all && electron-builder --config electron-builder.yml --publish always",
"lint": "eslint --ext .ts,.tsx,.js .",
"postinstall": "electron-builder install-app-deps",
"build:renderer": "node build.js",
"build:web": "cd pickleglass_web && npm run build && cd ..",
"build:all": "npm run build:renderer && npm run build:web",
"watch:renderer": "node build.js --watch"
},
"keywords": [
"glass",
"pickle glass",
"ai assistant",
"real-time",
"live summary",
"contextual ai"
],
"author": {
"name": "Pickle Team"
},
"license": "GPL-3.0",
"dependencies": {
"@anthropic-ai/sdk": "^0.56.0",
"@deepgram/sdk": "^4.9.1",
"@google/genai": "^1.8.0",
"@google/generative-ai": "^0.24.1",
"axios": "^1.10.0",
"better-sqlite3": "^9.6.0",
"cors": "^2.8.5",
"dotenv": "^17.0.0",
"electron-squirrel-startup": "^1.0.1",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"express": "^4.18.2",
"firebase": "^11.10.0",
"firebase-admin": "^13.4.0",
"jsonwebtoken": "^9.0.2",
"keytar": "^7.9.0",
"node-fetch": "^2.7.0",
"openai": "^4.70.0",
"portkey-ai": "^1.10.1",
"react-hot-toast": "^2.5.2",
"sharp": "^0.34.2",
"validator": "^13.11.0",
"wait-on": "^8.0.3",
"ws": "^8.18.0"
},
"devDependencies": {
"@electron/fuses": "^1.8.0",
"@electron/notarize": "^2.5.0",
"electron": "^30.5.1",
"electron-builder": "^26.0.12",
"electron-reloader": "^1.2.3",
"esbuild": "^0.25.5",
"prettier": "^3.6.2"
},
"optionalDependencies": {
"electron-liquid-glass": "^1.0.1"
}
}
================================================
FILE: pickleglass_web/app/activity/details/page.tsx
================================================
'use client'
import { useState, useEffect, Suspense } from 'react'
import { useRedirectIfNotAuth } from '@/utils/auth'
import { useSearchParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import {
UserProfile,
SessionDetails,
Transcript,
AiMessage,
getSessionDetails,
deleteSession,
} from '@/utils/api'
type ConversationItem = (Transcript & { type: 'transcript' }) | (AiMessage & { type: 'ai_message' });
const Section = ({ title, children }: { title: string, children: React.ReactNode }) => (
);
function SessionDetailsContent() {
const userInfo = useRedirectIfNotAuth() as UserProfile | null;
const [sessionDetails, setSessionDetails] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const searchParams = useSearchParams();
const sessionId = searchParams.get('sessionId');
const router = useRouter();
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (userInfo && sessionId) {
const fetchDetails = async () => {
setIsLoading(true);
try {
const details = await getSessionDetails(sessionId as string);
setSessionDetails(details);
} catch (error) {
console.error('Failed to load session details:', error);
} finally {
setIsLoading(false);
}
};
fetchDetails();
}
}, [userInfo, sessionId]);
const handleDelete = async () => {
if (!sessionId) return;
if (!window.confirm('Are you sure you want to delete this activity? This cannot be undone.')) return;
setDeleting(true);
try {
await deleteSession(sessionId);
router.push('/activity');
} catch (error) {
alert('Failed to delete activity.');
setDeleting(false);
console.error(error);
}
};
if (!userInfo || isLoading) {
return (
Loading session details...
);
}
if (!sessionDetails) {
return (
Session Not Found
The requested session could not be found.
← Back to Activity
)
}
const askMessages = sessionDetails.ai_messages || [];
return (
{sessionDetails.session.title || `Conversation on ${new Date(sessionDetails.session.started_at * 1000).toLocaleDateString()}`}
{new Date(sessionDetails.session.started_at * 1000).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}
{new Date(sessionDetails.session.started_at * 1000).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true })}
{sessionDetails.session.session_type}
{deleting ? 'Deleting...' : 'Delete Activity'}
{sessionDetails.summary && (
"{sessionDetails.summary.tldr}"
{sessionDetails.summary.bullet_json && JSON.parse(sessionDetails.summary.bullet_json).length > 0 &&
Key Points:
{JSON.parse(sessionDetails.summary.bullet_json).map((point: string, index: number) => (
{point}
))}
}
{sessionDetails.summary.action_json && JSON.parse(sessionDetails.summary.action_json).length > 0 &&
Action Items:
{JSON.parse(sessionDetails.summary.action_json).map((action: string, index: number) => (
{action}
))}
}
)}
{sessionDetails.transcripts && sessionDetails.transcripts.length > 0 && (
{sessionDetails.transcripts.map((item) => (
{item.speaker}:
{item.text}
))}
)}
{askMessages.length > 0 && (
{askMessages.map((item) => (
{item.role === 'user' ? 'You' : 'AI'}
{item.content}
))}
)}
);
}
export default function SessionDetailsPage() {
return (
}>
);
}
================================================
FILE: pickleglass_web/app/activity/page.tsx
================================================
'use client'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useRedirectIfNotAuth } from '@/utils/auth'
import {
UserProfile,
Session,
getSessions,
deleteSession,
} from '@/utils/api'
export default function ActivityPage() {
const userInfo = useRedirectIfNotAuth() as UserProfile | null;
const [sessions, setSessions] = useState([])
const [isLoading, setIsLoading] = useState(true)
const [deletingId, setDeletingId] = useState(null)
const fetchSessions = async () => {
try {
const fetchedSessions = await getSessions();
setSessions(fetchedSessions);
} catch (error) {
console.error('Failed to fetch conversations:', error)
} finally {
setIsLoading(false)
}
}
useEffect(() => {
fetchSessions()
}, [])
if (!userInfo) {
return (
)
}
const getGreeting = () => {
const hour = new Date().getHours()
if (hour < 12) return 'Good morning'
if (hour < 18) return 'Good afternoon'
return 'Good evening'
}
const handleDelete = async (sessionId: string) => {
if (!window.confirm('Are you sure you want to delete this activity? This cannot be undone.')) return;
setDeletingId(sessionId);
try {
await deleteSession(sessionId);
setSessions(sessions => sessions.filter(s => s.id !== sessionId));
} catch (error) {
alert('Failed to delete activity.');
console.error(error);
} finally {
setDeletingId(null);
}
}
return (
{getGreeting()}, {userInfo.display_name}
Your Past Activity
{isLoading ? (
) : sessions.length > 0 ? (
{sessions.map((session) => (
{session.title || `Conversation - ${new Date(session.started_at * 1000).toLocaleDateString()}`}
{new Date(session.started_at * 1000).toLocaleString()}
handleDelete(session.id)}
disabled={deletingId === session.id}
className={`ml-4 px-3 py-1 rounded text-xs font-medium border border-red-200 text-red-700 bg-red-50 hover:bg-red-100 transition-colors ${deletingId === session.id ? 'opacity-50 cursor-not-allowed' : ''}`}
>
{deletingId === session.id ? 'Deleting...' : 'Delete'}
{session.session_type || 'ask'}
))}
) : (
No conversations yet. Start a conversation in the desktop app to see your activity here.
💡 Tip: Use the desktop app to have AI-powered conversations that will appear here automatically.
)}
)
}
================================================
FILE: pickleglass_web/app/download/page.tsx
================================================
'use client'
import { Download, Smartphone, Monitor, Tablet } from 'lucide-react'
import { useRedirectIfNotAuth } from '@/utils/auth'
export default function DownloadPage() {
const userInfo = useRedirectIfNotAuth()
if (!userInfo) {
return (
)
}
return (
Download pickleglass
Use pickleglass on various platforms
Desktop
Windows, macOS, Linux
Download Desktop
Mobile
iOS, Android
App Store
Google Play
Tablet
iPad, Android Tablet
Download Tablet
System Requirements
Windows
• Windows 10 or later
• 4GB RAM
• 100MB Storage
macOS
• macOS 11.0 or later
• 4GB RAM
• 100MB Storage
Mobile
• iOS 14.0 or later
• Android 8.0 or later
• 50MB Storage
)
}
================================================
FILE: pickleglass_web/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
letter-spacing: -0.03em;
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
================================================
FILE: pickleglass_web/app/help/page.tsx
================================================
'use client'
import { HelpCircle, Book, MessageCircle, Mail } from 'lucide-react'
import { useRedirectIfNotAuth } from '@/utils/auth'
export default function HelpPage() {
const userInfo = useRedirectIfNotAuth()
if (!userInfo) {
return (
)
}
return (
Help Center
Getting Started
New to pickleglass? Learn about basic features and setup methods.
• Setting up personalized contexts
• Selecting presets and creating custom contexts
• Checking activity records
• Changing settings
Frequently Asked Questions
Check out frequently asked questions and answers from other users.
How do I change the context?
On the Personalize page, select a preset or enter a custom context, then click the Save button.
Where can I check my activity history?
You can check your past activity records on the My Activity page.
Community
Connect with other users and share tips.
Join Community →
Contact Us
Couldn't find a solution? Contact us directly.
Contact via Email →
💡 Tip
Each context is optimized for different situations.
Choose the appropriate preset for your work environment,
or create your own custom context!
)
}
================================================
FILE: pickleglass_web/app/layout.tsx
================================================
import './globals.css'
import { Inter } from 'next/font/google'
import ClientLayout from '@/components/ClientLayout'
const inter = Inter({ subsets: ['latin'] })
export const metadata = {
title: 'pickleglass - AI Assistant',
description: 'Personalized AI Assistant for various contexts',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
{children}
)
}
================================================
FILE: pickleglass_web/app/login/page.tsx
================================================
'use client'
import { useRouter } from 'next/navigation'
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth'
import { auth } from '@/utils/firebase'
import { Chrome } from 'lucide-react'
import { useState, useEffect } from 'react'
export default function LoginPage() {
const router = useRouter()
const [isLoading, setIsLoading] = useState(false)
const [isElectronMode, setIsElectronMode] = useState(false)
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search)
const mode = urlParams.get('mode')
setIsElectronMode(mode === 'electron')
}, [])
const handleGoogleSignIn = async () => {
const provider = new GoogleAuthProvider()
setIsLoading(true)
try {
const result = await signInWithPopup(auth, provider)
const user = result.user
if (user) {
console.log('✅ Google login successful:', user.uid)
if (isElectronMode) {
try {
const idToken = await user.getIdToken()
const deepLinkUrl = `pickleglass://auth-success?` + new URLSearchParams({
uid: user.uid,
email: user.email || '',
displayName: user.displayName || '',
token: idToken
}).toString()
console.log('🔗 Return to electron app via deep link:', deepLinkUrl)
window.location.href = deepLinkUrl
// Maybe we don't need this
// setTimeout(() => {
// alert('Login completed. Please return to Pickle Glass app.')
// }, 1000)
} catch (error) {
console.error('❌ Deep link processing failed:', error)
alert('Login was successful but failed to return to app. Please check the app.')
}
}
else if (typeof window !== 'undefined' && window.require) {
try {
const { ipcRenderer } = window.require('electron')
const idToken = await user.getIdToken()
ipcRenderer.send('firebase-auth-success', {
uid: user.uid,
displayName: user.displayName,
email: user.email,
idToken
})
console.log('📡 Auth info sent to electron successfully')
} catch (error) {
console.error('❌ Electron communication failed:', error)
}
}
else {
router.push('/settings')
}
}
} catch (error: any) {
console.error('❌ Google login failed:', error)
if (error.code !== 'auth/popup-closed-by-user') {
alert('An error occurred during login. Please try again.')
}
} finally {
setIsLoading(false)
}
}
return (
Welcome to Pickle Glass
Sign in with your Google account to sync your data across all devices.
{isElectronMode ? (
🔗 Login requested from Electron app
) : (
Local mode will run if you don't sign in.
)}
{isLoading ? 'Signing in...' : 'Sign in with Google'}
{
if (isElectronMode) {
window.location.href = 'pickleglass://auth-success?uid=default_user&email=contact@pickle.com&displayName=Default%20User'
} else {
router.push('/settings')
}
}}
className="text-sm text-gray-500 hover:text-gray-700 underline"
>
Continue in local mode
By signing in, you agree to our Terms of Service and Privacy Policy.
)
}
================================================
FILE: pickleglass_web/app/page.tsx
================================================
'use client'
import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
export default function Home() {
const router = useRouter()
useEffect(() => {
router.push('/personalize')
}, [router])
return (
)
}
================================================
FILE: pickleglass_web/app/personalize/page.tsx
================================================
'use client'
import { useState, useEffect } from 'react'
import { ChevronDown, Plus, Copy } from 'lucide-react'
import { getPresets, updatePreset, createPreset, PromptPreset } from '@/utils/api'
export default function PersonalizePage() {
const [allPresets, setAllPresets] = useState([]);
const [selectedPreset, setSelectedPreset] = useState(null);
const [showPresets, setShowPresets] = useState(true);
const [editorContent, setEditorContent] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [isDirty, setIsDirty] = useState(false);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const presetsData = await getPresets();
setAllPresets(presetsData);
if (presetsData.length > 0) {
const firstUserPreset = presetsData.find(p => p.is_default === 0) || presetsData[0];
setSelectedPreset(firstUserPreset);
setEditorContent(firstUserPreset.prompt);
}
} catch (error) {
console.error("Failed to fetch presets:", error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
const handlePresetClick = (preset: PromptPreset) => {
if (isDirty && !window.confirm("You have unsaved changes. Are you sure you want to switch?")) {
return;
}
setSelectedPreset(preset);
setEditorContent(preset.prompt);
setIsDirty(false);
};
const handleEditorChange = (e: React.ChangeEvent) => {
setEditorContent(e.target.value);
setIsDirty(true);
};
const handleSave = async () => {
if (!selectedPreset || saving || !isDirty) return;
if (selectedPreset.is_default === 1) {
alert("Default presets cannot be modified.");
return;
}
try {
setSaving(true);
await updatePreset(selectedPreset.id, {
title: selectedPreset.title,
prompt: editorContent
});
setAllPresets(prev =>
prev.map(p =>
p.id === selectedPreset.id
? { ...p, prompt: editorContent }
: p
)
);
setIsDirty(false);
} catch (error) {
console.error("Save failed:", error);
alert("Failed to save preset. See console for details.");
} finally {
setSaving(false);
}
};
const handleCreateNewPreset = async () => {
const title = prompt("Enter a title for the new preset:");
if (!title) return;
try {
setSaving(true);
const { id } = await createPreset({
title,
prompt: "Enter your custom prompt here..."
});
const newPreset: PromptPreset = {
id,
uid: 'current_user',
title,
prompt: "Enter your custom prompt here...",
is_default: 0,
created_at: Date.now(),
sync_state: 'clean'
};
setAllPresets(prev => [...prev, newPreset]);
setSelectedPreset(newPreset);
setEditorContent(newPreset.prompt);
setIsDirty(false);
} catch (error) {
console.error("Failed to create preset:", error);
alert("Failed to create preset. See console for details.");
} finally {
setSaving(false);
}
};
const handleDuplicatePreset = async () => {
if (!selectedPreset) return;
const title = prompt("Enter a title for the duplicated preset:", `${selectedPreset.title} (Copy)`);
if (!title) return;
try {
setSaving(true);
const { id } = await createPreset({
title,
prompt: editorContent
});
const newPreset: PromptPreset = {
id,
uid: 'current_user',
title,
prompt: editorContent,
is_default: 0,
created_at: Date.now(),
sync_state: 'clean'
};
setAllPresets(prev => [...prev, newPreset]);
setSelectedPreset(newPreset);
setIsDirty(false);
} catch (error) {
console.error("Failed to duplicate preset:", error);
alert("Failed to duplicate preset. See console for details.");
} finally {
setSaving(false);
}
};
if (loading) {
return (
);
}
return (
New Preset
{selectedPreset && (
Duplicate
)}
{!isDirty && !saving ? 'Saved' : saving ? 'Saving...' : 'Save'}
setShowPresets(!showPresets)}
className="flex items-center gap-2 text-gray-600 hover:text-gray-800 text-sm font-medium transition-colors"
>
{showPresets ? 'Hide Presets' : 'Show Presets'}
{showPresets && (
{allPresets.map((preset) => (
handlePresetClick(preset)}
className={`
p-4 rounded-lg cursor-pointer transition-all duration-200 bg-white
h-48 flex flex-col shadow-sm hover:shadow-md relative
${selectedPreset?.id === preset.id
? 'border-2 border-blue-500 shadow-md'
: 'border border-gray-200 hover:border-gray-300'
}
`}
>
{preset.is_default === 1 && (
Default
)}
{preset.title}
{preset.prompt.substring(0, 100) + (preset.prompt.length > 100 ? '...' : '')}
))}
)}
{selectedPreset?.is_default === 1 && (
This is a default preset and cannot be edited.
Use the "Duplicate" button above to create an editable copy, or create a new preset.
)}
);
}
================================================
FILE: pickleglass_web/app/settings/billing/page.tsx
================================================
'use client'
import { useRedirectIfNotAuth } from '@/utils/auth'
export default function BillingPage() {
const userInfo = useRedirectIfNotAuth()
if (!userInfo) {
return (
)
}
const tabs = [
{ id: 'profile', name: 'Personal profile', href: '/settings' },
{ id: 'privacy', name: 'Data & privacy', href: '/settings/privacy' },
{ id: 'billing', name: 'Billing', href: '/settings/billing' },
]
return (
Settings
Personal settings
Cl*ely For Free
)
}
================================================
FILE: pickleglass_web/app/settings/page.tsx
================================================
'use client'
import { useState, useEffect } from 'react'
import { Check, ExternalLink, Cloud, HardDrive } from 'lucide-react'
import { useAuth } from '@/utils/auth'
import {
UserProfile,
getUserProfile,
updateUserProfile,
checkApiKeyStatus,
saveApiKey,
deleteAccount,
logout
} from '@/utils/api'
import { useRouter } from 'next/navigation'
declare global {
interface Window {
ipcRenderer?: any;
}
}
type Tab = 'profile' | 'privacy' | 'billing'
type BillingCycle = 'monthly' | 'annually'
export default function SettingsPage() {
const { user: userInfo, isLoading, mode } = useAuth()
const [activeTab, setActiveTab] = useState('profile')
const [billingCycle, setBillingCycle] = useState('monthly')
const [profile, setProfile] = useState(null)
const [hasApiKey, setHasApiKey] = useState(false)
const [apiKeyInput, setApiKeyInput] = useState('')
const [isSaving, setIsSaving] = useState(false)
const [displayNameInput, setDisplayNameInput] = useState('')
const router = useRouter()
const fetchApiKeyStatus = async () => {
try {
const apiKeyStatus = await checkApiKeyStatus()
setHasApiKey(apiKeyStatus.hasApiKey)
} catch (error) {
console.error("Failed to fetch API key status:", error);
}
}
useEffect(() => {
if (!userInfo) return
const fetchProfileData = async () => {
try {
const userProfile = await getUserProfile()
setProfile(userProfile)
setDisplayNameInput(userProfile.display_name)
await fetchApiKeyStatus();
} catch (error) {
console.error("Failed to fetch profile data:", error)
}
}
fetchProfileData()
if (window.ipcRenderer) {
window.ipcRenderer.on('api-key-updated', () => {
console.log('Received api-key-updated event from main process.');
fetchApiKeyStatus();
});
}
return () => {
if (window.ipcRenderer) {
window.ipcRenderer.removeAllListeners('api-key-updated');
}
}
}, [userInfo])
if (isLoading) {
return (
)
}
if (!userInfo) {
router.push('/login')
return null
}
const isFirebaseMode = mode === 'firebase'
const tabs = [
{ id: 'profile' as Tab, name: 'Personal Profile', href: '/settings' },
{ id: 'privacy' as Tab, name: 'Data & Privacy', href: '/settings/privacy' },
{ id: 'billing' as Tab, name: 'Billing', href: '/settings/billing' },
]
const handleSaveApiKey = async () => {
setIsSaving(true)
try {
await saveApiKey(apiKeyInput)
setHasApiKey(true)
setApiKeyInput('')
if (window.ipcRenderer) {
window.ipcRenderer.invoke('save-api-key', apiKeyInput);
}
} catch (error) {
console.error("Failed to save API key:", error)
} finally {
setIsSaving(false)
}
}
const handleUpdateDisplayName = async () => {
if (!profile || displayNameInput === profile.display_name) return;
setIsSaving(true);
try {
await updateUserProfile({ displayName: displayNameInput });
setProfile(prev => prev ? { ...prev, display_name: displayNameInput } : null);
} catch (error) {
console.error("Failed to update display name:", error);
} finally {
setIsSaving(false);
}
}
const handleDeleteAccount = async () => {
const confirmMessage = isFirebaseMode
? "Are you sure you want to delete your account? This action cannot be undone and all data stored in Firebase will be deleted."
: "Are you sure you want to delete your account? This action cannot be undone and all data will be deleted."
if (window.confirm(confirmMessage)) {
try {
await deleteAccount()
router.push('/login');
} catch (error) {
console.error("Failed to delete account:", error)
}
}
}
const handleLogout = async () => {
try {
await logout()
} catch (error) {
console.error("Logout failed:", error)
}
}
const renderBillingContent = () => (
{isFirebaseMode ? (
) : (
)}
{isFirebaseMode ? 'Firebase Hosting Mode' : 'Local Execution Mode'}
{isFirebaseMode
? 'All data is safely stored and synchronized in Firebase Cloud.'
: 'Data is stored in local database and you can use personal API keys.'
}
setBillingCycle('monthly')}
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
billingCycle === 'monthly'
? 'bg-gray-200 text-gray-900'
: 'text-gray-600 hover:text-gray-900'
}`}
>
Monthly
setBillingCycle('annually')}
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
billingCycle === 'annually'
? 'bg-gray-200 text-gray-900'
: 'text-gray-600 hover:text-gray-900'
}`}
>
Annually
Experience how Pickle Glass works with unlimited responses.
Daily unlimited responses
Unlimited access to free models
Unlimited text output
Screen viewing, audio listening
Custom system prompts
Community support only
Current Plan
Use latest models, get full response output, and work with custom prompts.
Unlimited pro responses
Unlimited access to latest models
Full access to conversation dashboard
Priority support
All features from free plan
Coming Soon
Specially crafted for teams that need complete customization.
Custom integrations
User provisioning & role-based access
Advanced post-call analytics
Single sign-on
Advanced security features
Centralized billing
Usage analytics & reporting dashboard
Coming Soon
All features are currently free!
{isFirebaseMode
? 'Enjoy all Pickle Glass features for free in Firebase hosting mode. Pro and Enterprise plans will be released soon with additional premium features.'
: 'Enjoy all Pickle Glass features for free in local mode. You can use personal API keys or continue using the free system.'
}
)
const renderTabContent = () => {
switch (activeTab) {
case 'billing':
return renderBillingContent()
case 'profile':
return (
{isFirebaseMode ? (
) : (
)}
{isFirebaseMode ? 'Firebase Hosting Mode' : 'Local Execution Mode'}
{isFirebaseMode
? `Logged in with Google account (${userInfo.email})`
: 'Running as local user'
}
{isFirebaseMode && (
Logout
)}
Display Name
Enter your full name or a display name you're comfortable using.
Update
{!isFirebaseMode && (
API Key
If you want to use your own LLM API key, you can add it here. It will be used for all requests made by the local application.
API Key
setApiKeyInput(e.target.value)}
className="flex-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm text-black"
placeholder="Enter new API key or existing API key"
/>
{hasApiKey ? (
API key is currently set.
) : (
No API key set. Using free system.
)}
{isSaving ? 'Saving...' : 'Save'}
)}
{(isFirebaseMode || (!isFirebaseMode && !hasApiKey)) && (
Delete Account
{isFirebaseMode
? 'Permanently remove your Firebase account and all content. This action cannot be undone, so please proceed carefully.'
: 'Permanently remove your personal account and all content from the Pickle Glass platform. This action cannot be undone, so please proceed carefully.'
}
Delete
)}
)
case 'privacy':
return null
default:
return renderBillingContent()
}
}
return (
Settings
Personal Settings
{renderTabContent()}
)
}
================================================
FILE: pickleglass_web/app/settings/privacy/page.tsx
================================================
'use client'
import { ExternalLink } from 'lucide-react'
import { useRedirectIfNotAuth } from '@/utils/auth'
export default function PrivacySettingsPage() {
const userInfo = useRedirectIfNotAuth()
if (!userInfo) {
return (
)
}
const tabs = [
{ id: 'profile', name: 'Personal profile', href: '/settings' },
{ id: 'privacy', name: 'Data & privacy', href: '/settings/privacy' },
{ id: 'billing', name: 'Billing', href: '/settings/billing' },
]
return (
Settings
Personal settings
Privacy Policy
Understand how we collect, use, and protect your personal information.
window.open('https://www.pickle.com/ko/privacy-policy', '_blank')}
className="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-md text-sm font-medium transition-colors"
>
Privacy
Terms of Service
Understand your rights and responsibilities when using our platform.
window.open('https://www.pickle.com/ko/terms-of-service', '_blank')}
className="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-md text-sm font-medium transition-colors"
>
Terms
)
}
================================================
FILE: pickleglass_web/backend_node/index.js
================================================
const express = require('express');
const cors = require('cors');
// const db = require('./db'); // No longer needed
const { identifyUser } = require('./middleware/auth');
function createApp(eventBridge) {
const app = express();
const webUrl = process.env.pickleglass_WEB_URL || 'http://localhost:3000';
console.log(`🔧 Backend CORS configured for: ${webUrl}`);
app.use(cors({
origin: webUrl,
credentials: true,
}));
app.use(express.json());
app.get('/', (req, res) => {
res.json({ message: "pickleglass API is running" });
});
app.use((req, res, next) => {
req.bridge = eventBridge;
next();
});
app.use('/api', identifyUser);
app.use('/api/auth', require('./routes/auth'));
app.use('/api/user', require('./routes/user'));
app.use('/api/conversations', require('./routes/conversations'));
app.use('/api/presets', require('./routes/presets'));
app.get('/api/sync/status', (req, res) => {
res.json({
status: 'online',
timestamp: new Date().toISOString(),
version: '1.0.0'
});
});
app.post('/api/desktop/set-user', (req, res) => {
res.json({
success: true,
message: "Direct IPC communication is now used. This endpoint is deprecated.",
user: req.body,
deprecated: true
});
});
app.get('/api/desktop/status', (req, res) => {
res.json({
connected: true,
current_user: null,
communication_method: "IPC",
file_based_deprecated: true
});
});
return app;
}
module.exports = createApp;
================================================
FILE: pickleglass_web/backend_node/ipcBridge.js
================================================
const crypto = require('crypto');
function ipcRequest(req, channel, payload) {
return new Promise((resolve, reject) => {
// Immediately check bridge status and fail if it's not available.
if (!req.bridge || typeof req.bridge.emit !== 'function') {
reject(new Error('IPC bridge is not available'));
return;
}
const responseChannel = `${channel}-${crypto.randomUUID()}`;
req.bridge.once(responseChannel, (response) => {
if (!response) {
reject(new Error(`No response received from ${channel}`));
return;
}
if (response.success) {
resolve(response.data);
} else {
reject(new Error(response.error || `IPC request to ${channel} failed`));
}
});
try {
req.bridge.emit('web-data-request', channel, responseChannel, payload);
} catch (error) {
req.bridge.removeAllListeners(responseChannel);
reject(new Error(`Failed to emit IPC request: ${error.message}`));
}
});
}
module.exports = { ipcRequest };
================================================
FILE: pickleglass_web/backend_node/middleware/auth.js
================================================
function identifyUser(req, res, next) {
const userId = req.get('X-User-ID');
if (userId) {
req.uid = userId;
} else {
req.uid = 'default_user';
}
next();
}
module.exports = { identifyUser };
================================================
FILE: pickleglass_web/backend_node/routes/auth.js
================================================
const express = require('express');
const router = express.Router();
const { ipcRequest } = require('../ipcBridge');
router.get('/status', async (req, res) => {
try {
const user = await ipcRequest(req, 'get-user-profile');
if (!user) {
return res.status(500).json({ error: 'Default user not initialized' });
}
res.json({
authenticated: true,
user: {
id: user.uid,
name: user.display_name
}
});
} catch (error) {
console.error('Failed to get auth status via IPC:', error);
res.status(500).json({ error: 'Failed to retrieve auth status' });
}
});
module.exports = router;
================================================
FILE: pickleglass_web/backend_node/routes/conversations.js
================================================
const express = require('express');
const router = express.Router();
const { ipcRequest } = require('../ipcBridge');
router.get('/', async (req, res) => {
try {
const sessions = await ipcRequest(req, 'get-sessions');
res.json(sessions);
} catch (error) {
console.error('Failed to get sessions via IPC:', error);
res.status(500).json({ error: 'Failed to retrieve sessions' });
}
});
router.post('/', async (req, res) => {
try {
const result = await ipcRequest(req, 'create-session', req.body);
res.status(201).json({ ...result, message: 'Session created successfully' });
} catch (error) {
console.error('Failed to create session via IPC:', error);
res.status(500).json({ error: 'Failed to create session' });
}
});
router.get('/:session_id', async (req, res) => {
try {
const details = await ipcRequest(req, 'get-session-details', req.params.session_id);
if (!details) {
return res.status(404).json({ error: 'Session not found' });
}
res.json(details);
} catch (error) {
console.error(`Failed to get session details via IPC for ${req.params.session_id}:`, error);
res.status(500).json({ error: 'Failed to retrieve session details' });
}
});
router.delete('/:session_id', async (req, res) => {
try {
await ipcRequest(req, 'delete-session', req.params.session_id);
res.status(200).json({ message: 'Session deleted successfully' });
} catch (error) {
console.error(`Failed to delete session via IPC for ${req.params.session_id}:`, error);
res.status(500).json({ error: 'Failed to delete session' });
}
});
// The search functionality will be more complex to move to IPC.
// For now, we can disable it or leave it as is, knowing it's a future task.
router.get('/search', (req, res) => {
res.status(501).json({ error: 'Search not implemented for IPC bridge yet.' });
});
module.exports = router;
================================================
FILE: pickleglass_web/backend_node/routes/presets.js
================================================
const express = require('express');
const router = express.Router();
const { ipcRequest } = require('../ipcBridge');
router.get('/', async (req, res) => {
try {
const presets = await ipcRequest(req, 'get-presets');
res.json(presets);
} catch (error) {
console.error('Failed to get presets via IPC:', error);
res.status(500).json({ error: 'Failed to retrieve presets' });
}
});
router.post('/', async (req, res) => {
try {
const result = await ipcRequest(req, 'create-preset', req.body);
res.status(201).json({ ...result, message: 'Preset created successfully' });
} catch (error) {
console.error('Failed to create preset via IPC:', error);
res.status(500).json({ error: 'Failed to create preset' });
}
});
router.put('/:id', async (req, res) => {
try {
await ipcRequest(req, 'update-preset', { id: req.params.id, data: req.body });
res.json({ message: 'Preset updated successfully' });
} catch (error) {
console.error('Failed to update preset via IPC:', error);
res.status(500).json({ error: 'Failed to update preset' });
}
});
router.delete('/:id', async (req, res) => {
try {
await ipcRequest(req, 'delete-preset', req.params.id);
res.json({ message: 'Preset deleted successfully' });
} catch (error) {
console.error('Failed to delete preset via IPC:', error);
res.status(500).json({ error: 'Failed to delete preset' });
}
});
module.exports = router;
================================================
FILE: pickleglass_web/backend_node/routes/user.js
================================================
const express = require('express');
const router = express.Router();
const { ipcRequest } = require('../ipcBridge');
router.put('/profile', async (req, res) => {
try {
await ipcRequest(req, 'update-user-profile', req.body);
res.json({ message: 'Profile updated successfully' });
} catch (error) {
console.error('Failed to update profile via IPC:', error);
res.status(500).json({ error: 'Failed to update profile' });
}
});
router.get('/profile', async (req, res) => {
try {
const user = await ipcRequest(req, 'get-user-profile');
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
} catch (error) {
console.error('Failed to get profile via IPC:', error);
res.status(500).json({ error: 'Failed to get profile' });
}
});
router.post('/find-or-create', async (req, res) => {
try {
console.log('[API] find-or-create request received:', req.body);
if (!req.body || !req.body.uid) {
return res.status(400).json({ error: 'User data with uid is required' });
}
const user = await ipcRequest(req, 'find-or-create-user', req.body);
console.log('[API] find-or-create response:', user);
res.status(200).json(user);
} catch (error) {
console.error('Failed to find or create user via IPC:', error);
console.error('Request body:', req.body);
res.status(500).json({
error: 'Failed to find or create user',
details: error.message
});
}
});
router.post('/api-key', async (req, res) => {
try {
const { apiKey, provider = 'openai' } = req.body;
await ipcRequest(req, 'save-api-key', { apiKey, provider });
res.json({ message: 'API key saved successfully' });
} catch (error) {
console.error('Failed to save API key via IPC:', error);
res.status(500).json({ error: 'Failed to save API key' });
}
});
router.get('/api-key-status', async (req, res) => {
try {
const status = await ipcRequest(req, 'check-api-key-status');
res.json(status);
} catch (error) {
console.error('Failed to get API key status via IPC:', error);
res.status(500).json({ error: 'Failed to get API key status' });
}
});
router.delete('/profile', async (req, res) => {
try {
await ipcRequest(req, 'delete-account');
res.status(200).json({ message: 'User account and all data deleted successfully.' });
} catch (error) {
console.error('Failed to delete user account via IPC:', error);
res.status(500).json({ error: 'Failed to delete user account' });
}
});
router.get('/batch', async (req, res) => {
try {
const result = await ipcRequest(req, 'get-batch-data', req.query.include);
res.json(result);
} catch(error) {
console.error('Failed to get batch data via IPC:', error);
res.status(500).json({ error: 'Failed to get batch data' });
}
});
module.exports = router;
================================================
FILE: pickleglass_web/components/ClientLayout.tsx
================================================
'use client'
import { useState, useEffect } from 'react'
import Sidebar from '@/components/Sidebar'
import SearchPopup from '@/components/SearchPopup'
export default function ClientLayout({
children,
}: {
children: React.ReactNode
}) {
const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false)
const [isSearchOpen, setIsSearchOpen] = useState(false)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault()
setIsSearchOpen(true)
}
}
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}, [])
return (
setIsSearchOpen(true)}
/>
{children}
setIsSearchOpen(false)}
/>
)
}
================================================
FILE: pickleglass_web/components/SearchPopup.tsx
================================================
'use client'
import { useState, useEffect, useRef } from 'react'
import { useRouter } from 'next/navigation'
import { Search, X } from 'lucide-react'
import { searchConversations, Session } from '@/utils/api'
import { MessageSquare } from 'lucide-react'
interface SearchPopupProps {
isOpen: boolean
onClose: () => void
}
export default function SearchPopup({ isOpen, onClose }: SearchPopupProps) {
const [searchQuery, setSearchQuery] = useState('')
const [searchResults, setSearchResults] = useState([])
const [isLoading, setIsLoading] = useState(false)
const inputRef = useRef(null)
const router = useRouter()
useEffect(() => {
if (isOpen && inputRef.current) {
inputRef.current.focus()
}
}, [isOpen])
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen) {
onClose()
}
}
document.addEventListener('keydown', handleEscape)
return () => document.removeEventListener('keydown', handleEscape)
}, [isOpen, onClose])
const handleSearch = async (query: string) => {
if (!query.trim()) {
setSearchResults([])
return
}
setIsLoading(true)
try {
const results = await searchConversations(query)
setSearchResults(results)
} catch (error) {
console.error('Search failed:', error)
setSearchResults([])
} finally {
setIsLoading(false)
}
}
const handleInputChange = (e: React.ChangeEvent) => {
const query = e.target.value
setSearchQuery(query)
handleSearch(query)
}
const handleBackgroundClick = (e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onClose()
}
}
if (!isOpen) return null
return (
Type
#
to access summaries,
?
for help.
{searchQuery && (
{isLoading ? (
) : searchResults.length > 0 ? (
{searchResults.map((result) => {
const timestamp = new Date(result.started_at * 1000).toLocaleString()
return (
{
router.push(`/activity/${result.id}`)
onClose()
}}
>
{result.title || 'Untitled Conversation'}
{timestamp}
)
})}
) : (
No results found for "{searchQuery}"
)}
)}
)
}
================================================
FILE: pickleglass_web/components/Sidebar.tsx
================================================
'use client';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import Image from 'next/image';
import { useState, createElement, useEffect, useMemo, useCallback, memo } from 'react';
import { Search, Activity, HelpCircle, Download, ChevronDown, User, Shield, Database, CreditCard, LogOut, LucideIcon } from 'lucide-react';
import { logout, UserProfile, checkApiKeyStatus } from '@/utils/api';
import { useAuth } from '@/utils/auth';
const ANIMATION_DURATION = {
SIDEBAR: 500,
TEXT: 300,
SUBMENU: 500,
ICON_HOVER: 200,
COLOR_TRANSITION: 200,
HOVER_SCALE: 200,
} as const;
const DIMENSIONS = {
SIDEBAR_EXPANDED: 220,
SIDEBAR_COLLAPSED: 64,
ICON_SIZE: 18,
USER_AVATAR_SIZE: 32,
HEADER_HEIGHT: 64,
} as const;
const ANIMATION_DELAYS = {
BASE: 0,
INCREMENT: 50,
TEXT_BASE: 250,
SUBMENU_INCREMENT: 30,
} as const;
interface NavigationItem {
name: string;
href?: string;
action?: () => void;
icon: LucideIcon | string;
isLucide: boolean;
hasSubmenu?: boolean;
ariaLabel?: string;
}
interface SubmenuItem {
name: string;
href: string;
icon: LucideIcon | string;
isLucide: boolean;
ariaLabel?: string;
}
interface SidebarProps {
isCollapsed: boolean;
onToggle: (collapsed: boolean) => void;
onSearchClick?: () => void;
}
interface AnimationStyles {
text: React.CSSProperties;
submenu: React.CSSProperties;
sidebarContainer: React.CSSProperties;
textContainer: React.CSSProperties;
}
const useAnimationStyles = (isCollapsed: boolean) => {
const [isAnimating, setIsAnimating] = useState(false);
useEffect(() => {
setIsAnimating(true);
const timer = setTimeout(() => setIsAnimating(false), ANIMATION_DURATION.SIDEBAR);
return () => clearTimeout(timer);
}, [isCollapsed]);
const getTextAnimationStyle = useCallback(
(delay = 0): React.CSSProperties => ({
willChange: 'opacity',
transition: `opacity ${ANIMATION_DURATION.TEXT}ms ease-out`,
transitionDelay: `${delay}ms`,
opacity: isCollapsed ? 0 : 1,
pointerEvents: isCollapsed ? 'none' : 'auto',
}),
[isCollapsed]
);
const getSubmenuAnimationStyle = useCallback(
(isExpanded: boolean): React.CSSProperties => ({
willChange: 'opacity, max-height',
transition: `all ${ANIMATION_DURATION.SUBMENU}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`,
maxHeight: isCollapsed || !isExpanded ? '0px' : '400px',
opacity: isCollapsed || !isExpanded ? 0 : 1,
}),
[isCollapsed]
);
const sidebarContainerStyle: React.CSSProperties = useMemo(
() => ({
willChange: 'width',
transition: `width ${ANIMATION_DURATION.SIDEBAR}ms cubic-bezier(0.4, 0, 0.2, 1)`,
}),
[]
);
const getTextContainerStyle = useCallback(
(): React.CSSProperties => ({
width: isCollapsed ? '0px' : '150px',
overflow: 'hidden',
transition: `width ${ANIMATION_DURATION.SIDEBAR}ms cubic-bezier(0.4, 0, 0.2, 1)`,
}),
[isCollapsed]
);
const getUniformTextStyle = useCallback(
(): React.CSSProperties => ({
willChange: 'opacity',
opacity: isCollapsed ? 0 : 1,
transition: `opacity 300ms ease ${isCollapsed ? '0ms' : '200ms'}`,
whiteSpace: 'nowrap' as const,
}),
[isCollapsed]
);
return {
isAnimating,
getTextAnimationStyle,
getSubmenuAnimationStyle,
sidebarContainerStyle,
getTextContainerStyle,
getUniformTextStyle,
};
};
const IconComponent = memo<{
icon: LucideIcon | string;
isLucide: boolean;
alt: string;
className?: string;
}>(({ icon, isLucide, alt, className = 'h-[18px] w-[18px] transition-transform duration-200' }) => {
if (isLucide) {
return createElement(icon as LucideIcon, { className, 'aria-hidden': true });
}
return ;
});
IconComponent.displayName = 'IconComponent';
const SidebarComponent = ({ isCollapsed, onToggle, onSearchClick }: SidebarProps) => {
const pathname = usePathname();
const router = useRouter();
const [isSettingsExpanded, setIsSettingsExpanded] = useState(pathname.startsWith('/settings'));
const { user: userInfo, isLoading: authLoading } = useAuth();
const [hasApiKey, setHasApiKey] = useState(null);
const { isAnimating, getTextAnimationStyle, getSubmenuAnimationStyle, sidebarContainerStyle, getTextContainerStyle, getUniformTextStyle } =
useAnimationStyles(isCollapsed);
useEffect(() => {
checkApiKeyStatus()
.then(status => setHasApiKey(status.hasApiKey))
.catch(err => {
console.error('Failed to check API key status:', err);
setHasApiKey(null); // Set to null on error
});
}, []);
useEffect(() => {
if (pathname.startsWith('/settings')) {
setIsSettingsExpanded(true);
}
}, [pathname]);
const navigation = useMemo(
() => [
{
name: 'Search',
action: onSearchClick,
icon: '/search.svg',
isLucide: false,
ariaLabel: 'Open search',
},
{
name: 'My Activity',
href: '/activity',
icon: '/activity.svg',
isLucide: false,
ariaLabel: 'View my activity',
},
{
name: 'Personalize',
href: '/personalize',
icon: '/book.svg',
isLucide: false,
ariaLabel: 'Personalization settings',
},
{
name: 'Settings',
href: '/settings',
icon: '/setting.svg',
isLucide: false,
hasSubmenu: true,
ariaLabel: 'Settings menu',
},
],
[onSearchClick]
);
const settingsSubmenu = useMemo(
() => [
{ name: 'Personal Profile', href: '/settings', icon: '/user.svg', isLucide: false, ariaLabel: 'Personal profile settings' },
{ name: 'Data & privacy', href: '/settings/privacy', icon: '/privacy.svg', isLucide: false, ariaLabel: 'Data and privacy settings' },
{ name: 'Billing', href: '/settings/billing', icon: '/credit-card.svg', isLucide: false, ariaLabel: 'Billing settings' },
],
[]
);
const bottomItems = useMemo(
() => [
{
href: 'https://discord.gg/UCZH5B5Hpd',
icon: '/linkout.svg',
text: 'Join Discord',
ariaLabel: 'Help Center (new window)',
},
{
href: 'https://www.dropbox.com/scl/fi/esk4h8z45sryvbremy57v/Pickle_latest.dmg?rlkey=92y535bz6p6gov6vd17x6q53b&st=9kl0annj&dl=1',
icon: '/download.svg',
text: 'Download Pickle Camera',
ariaLabel: 'Download Pickle Camera (new window)',
},
{
href: 'hhttps://www.dropbox.com/scl/fi/znid09apxiwtwvxer6oc9/Glass_latest.dmg?rlkey=gwvvyb3bizkl25frhs4k1zwds&st=37q31b4w&dl=1',
icon: '/download.svg',
text: 'Download Pickle Glass',
ariaLabel: 'Download Pickle Glass (new window)',
},
],
[]
);
const toggleSidebar = useCallback(() => {
onToggle(!isCollapsed);
}, [isCollapsed, onToggle]);
const toggleSettings = useCallback(() => {
if (!pathname.startsWith('/settings')) {
setIsSettingsExpanded(prev => !prev);
}
}, [pathname]);
const handleLogout = useCallback(async () => {
try {
await logout();
} catch (error) {
console.error('An error occurred during logout:', error);
}
}, []);
const handleKeyDown = useCallback((event: React.KeyboardEvent, action?: () => void) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
action?.();
}
}, []);
const renderNavigationItem = useCallback(
(item: NavigationItem, index: number) => {
const isActive = item.href ? pathname.startsWith(item.href) : false;
const animationDelay = 0;
const baseButtonClasses = `
group flex items-center rounded-[8px] px-[12px] py-[10px] text-[14px] text-[#282828] w-full relative
transition-colors duration-${ANIMATION_DURATION.COLOR_TRANSITION} ease-out
focus:outline-none
`;
const getStateClasses = (isActive: boolean) =>
isActive ? 'bg-[#f2f2f2] text-[#282828]' : 'text-[#282828] hover:text-[#282828] hover:bg-[#f7f7f7]';
if (item.action) {
return (
handleKeyDown(e, item.action)}
className={`${baseButtonClasses} ${getStateClasses(false)}`}
title={isCollapsed ? item.name : undefined}
aria-label={item.ariaLabel || item.name}
style={{ willChange: 'background-color, color' }}
>
{item.name}
);
}
if (item.hasSubmenu) {
return (
handleKeyDown(e, toggleSettings)}
className={`${baseButtonClasses} ${getStateClasses(isActive)}`}
title={isCollapsed ? item.name : undefined}
aria-label={item.ariaLabel || item.name}
aria-expanded={isSettingsExpanded}
aria-controls="settings-submenu"
style={{ willChange: 'background-color, color' }}
>
{item.name}
);
}
return (
{item.name}
);
},
[
pathname,
isCollapsed,
isSettingsExpanded,
toggleSettings,
handleLogout,
handleKeyDown,
getUniformTextStyle,
getTextContainerStyle,
getSubmenuAnimationStyle,
settingsSubmenu,
]
);
const getUserDisplayName = useCallback(() => {
if (authLoading) return 'Loading...';
return userInfo?.display_name || 'Guest';
}, [userInfo, authLoading]);
const getUserInitial = useCallback(() => {
if (authLoading) return 'L';
return userInfo?.display_name ? userInfo.display_name.charAt(0).toUpperCase() : 'G';
}, [userInfo, authLoading]);
const isFirebaseUser = userInfo && userInfo.uid !== 'default_user';
return (
);
};
const Sidebar = memo(SidebarComponent);
Sidebar.displayName = 'Sidebar';
export default Sidebar;
================================================
FILE: pickleglass_web/next-env.d.ts
================================================
///
///
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
================================================
FILE: pickleglass_web/next.config.js
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
output: 'export',
images: { unoptimized: true },
}
module.exports = nextConfig
================================================
FILE: pickleglass_web/package.json
================================================
{
"name": "pickleglass-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@headlessui/react": "^1.7.17",
"autoprefixer": "^10.4.16",
"axios": "^1.6.0",
"firebase": "^11.10.0",
"lucide-react": "^0.294.0",
"next": "^14.2.30",
"postcss": "^8.4.32",
"react": "^18",
"react-dom": "^18",
"react-hot-toast": "^2.5.2",
"tailwindcss": "^3.3.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.0.4",
"typescript": "^5"
}
}
================================================
FILE: pickleglass_web/postcss.config.js
================================================
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
================================================
FILE: pickleglass_web/public/README.md
================================================
# Public Assets
This folder contains static files.
## Logo Image
**@symbol.svg** - Logo image for the pickleglass application
### Requirements:
- Filename: `symbol.png`
- Recommended size: 32x32px or 64x64px
- Format: PNG
- Transparent background recommended
### Usage:
- Used as logo in sidebar header
- Loaded optimized through Next.js Image component
Currently there is a placeholder file, please replace it with the actual logo image.
================================================
FILE: pickleglass_web/requirements.txt
================================================
fastapi==0.104.1
uvicorn[standard]==0.24.0
aiosqlite==0.19.0
pydantic==2.5.0
python-dotenv==1.0.0
python-multipart==0.0.6
bcrypt==4.1.2
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-dateutil==2.8.2
email-validator==2.1.0
fastapi-cors==0.0.6
PyJWT==2.8.0
================================================
FILE: pickleglass_web/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
primary: '#3b82f6',
secondary: '#64748b',
accent: '#06b6d4',
'subtle-bg': '#f8f7f4',
'subtle-active-bg': '#e7e5e4',
},
},
},
plugins: [],
}
================================================
FILE: pickleglass_web/tsconfig.json
================================================
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "es6"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
================================================
FILE: pickleglass_web/utils/api.ts
================================================
import { auth as firebaseAuth } from './firebase';
import {
FirestoreUserService,
FirestoreSessionService,
FirestoreTranscriptService,
FirestoreAiMessageService,
FirestoreSummaryService,
FirestorePromptPresetService,
FirestoreSession,
FirestoreTranscript,
FirestoreAiMessage,
FirestoreSummary,
FirestorePromptPreset
} from './firestore';
import { Timestamp } from 'firebase/firestore';
export interface UserProfile {
uid: string;
display_name: string;
email: string;
}
export interface Session {
id: string;
uid: string;
title: string;
session_type: string;
started_at: number;
ended_at?: number;
sync_state: 'clean' | 'dirty';
updated_at: number;
}
export interface Transcript {
id: string;
session_id: string;
start_at: number;
end_at?: number;
speaker?: string;
text: string;
lang?: string;
created_at: number;
sync_state: 'clean' | 'dirty';
}
export interface AiMessage {
id: string;
session_id: string;
sent_at: number;
role: 'user' | 'assistant';
content: string;
tokens?: number;
model?: string;
created_at: number;
sync_state: 'clean' | 'dirty';
}
export interface Summary {
session_id: string;
generated_at: number;
model?: string;
text: string;
tldr: string;
bullet_json: string;
action_json: string;
tokens_used?: number;
updated_at: number;
sync_state: 'clean' | 'dirty';
}
export interface PromptPreset {
id: string;
uid: string;
title: string;
prompt: string;
is_default: 0 | 1;
created_at: number;
sync_state: 'clean' | 'dirty';
}
export interface SessionDetails {
session: Session;
transcripts: Transcript[];
ai_messages: AiMessage[];
summary: Summary | null;
}
const isFirebaseMode = (): boolean => {
// The web frontend can no longer directly access Firebase state,
// so we assume communication always goes through the backend API.
// In the future, we can create an endpoint like /api/auth/status
// in the backend to retrieve the authentication state.
return false;
};
const timestampToUnix = (timestamp: Timestamp): number => {
return timestamp.seconds * 1000 + Math.floor(timestamp.nanoseconds / 1000000);
};
const unixToTimestamp = (unix: number): Timestamp => {
return Timestamp.fromMillis(unix);
};
const convertFirestoreSession = (session: { id: string } & FirestoreSession, uid: string): Session => {
return {
id: session.id,
uid,
title: session.title,
session_type: session.session_type,
started_at: timestampToUnix(session.startedAt),
ended_at: session.endedAt ? timestampToUnix(session.endedAt) : undefined,
sync_state: 'clean',
updated_at: timestampToUnix(session.startedAt)
};
};
const convertFirestoreTranscript = (transcript: { id: string } & FirestoreTranscript): Transcript => {
return {
id: transcript.id,
session_id: '',
start_at: timestampToUnix(transcript.startAt),
end_at: transcript.endAt ? timestampToUnix(transcript.endAt) : undefined,
speaker: transcript.speaker,
text: transcript.text,
lang: transcript.lang,
created_at: timestampToUnix(transcript.createdAt),
sync_state: 'clean'
};
};
const convertFirestoreAiMessage = (message: { id: string } & FirestoreAiMessage): AiMessage => {
return {
id: message.id,
session_id: '',
sent_at: timestampToUnix(message.sentAt),
role: message.role,
content: message.content,
tokens: message.tokens,
model: message.model,
created_at: timestampToUnix(message.createdAt),
sync_state: 'clean'
};
};
const convertFirestoreSummary = (summary: FirestoreSummary, sessionId: string): Summary => {
return {
session_id: sessionId,
generated_at: timestampToUnix(summary.generatedAt),
model: summary.model,
text: summary.text,
tldr: summary.tldr,
bullet_json: JSON.stringify(summary.bulletPoints),
action_json: JSON.stringify(summary.actionItems),
tokens_used: summary.tokensUsed,
updated_at: timestampToUnix(summary.generatedAt),
sync_state: 'clean'
};
};
const convertFirestorePreset = (preset: { id: string } & FirestorePromptPreset, uid: string): PromptPreset => {
return {
id: preset.id,
uid,
title: preset.title,
prompt: preset.prompt,
is_default: preset.isDefault ? 1 : 0,
created_at: timestampToUnix(preset.createdAt),
sync_state: 'clean'
};
};
let API_ORIGIN = process.env.NODE_ENV === 'development'
? 'http://localhost:9001'
: '';
const loadRuntimeConfig = async (): Promise => {
try {
const response = await fetch('/runtime-config.json');
if (response.ok) {
const config = await response.json();
console.log('✅ Runtime config loaded:', config);
return config.API_URL;
}
} catch (error) {
console.log('⚠️ Failed to load runtime config:', error);
}
return null;
};
let apiUrlInitialized = false;
let initializationPromise: Promise | null = null;
const initializeApiUrl = async () => {
if (apiUrlInitialized) return;
// Electron IPC 관련 코드를 모두 제거하고 runtime-config.json 또는 fallback에만 의존합니다.
const runtimeUrl = await loadRuntimeConfig();
if (runtimeUrl) {
API_ORIGIN = runtimeUrl;
apiUrlInitialized = true;
return;
}
console.log('📍 Using fallback API URL:', API_ORIGIN);
apiUrlInitialized = true;
};
if (typeof window !== 'undefined') {
initializationPromise = initializeApiUrl();
}
const userInfoListeners: Array<(userInfo: UserProfile | null) => void> = [];
export const getUserInfo = (): UserProfile | null => {
if (typeof window === 'undefined') return null;
const storedUserInfo = localStorage.getItem('pickleglass_user');
if (storedUserInfo) {
try {
return JSON.parse(storedUserInfo);
} catch (error) {
console.error('Failed to parse user info:', error);
localStorage.removeItem('pickleglass_user');
}
}
return null;
};
export const setUserInfo = (userInfo: UserProfile | null, skipEvents: boolean = false) => {
if (typeof window === 'undefined') return;
if (userInfo) {
localStorage.setItem('pickleglass_user', JSON.stringify(userInfo));
} else {
localStorage.removeItem('pickleglass_user');
}
if (!skipEvents) {
userInfoListeners.forEach(listener => listener(userInfo));
window.dispatchEvent(new Event('userInfoChanged'));
}
};
export const onUserInfoChange = (listener: (userInfo: UserProfile | null) => void) => {
userInfoListeners.push(listener);
return () => {
const index = userInfoListeners.indexOf(listener);
if (index > -1) {
userInfoListeners.splice(index, 1);
}
};
};
export const getApiHeaders = (): HeadersInit => {
const headers: HeadersInit = {
'Content-Type': 'application/json',
};
const userInfo = getUserInfo();
if (userInfo?.uid) {
headers['X-User-ID'] = userInfo.uid;
}
return headers;
};
export const apiCall = async (path: string, options: RequestInit = {}) => {
if (!apiUrlInitialized && initializationPromise) {
await initializationPromise;
}
if (!apiUrlInitialized) {
await initializeApiUrl();
}
const url = `${API_ORIGIN}${path}`;
console.log('🌐 apiCall (Local Mode):', {
path,
API_ORIGIN,
fullUrl: url,
initialized: apiUrlInitialized,
timestamp: new Date().toISOString()
});
const defaultOpts: RequestInit = {
headers: {
'Content-Type': 'application/json',
...getApiHeaders(),
...(options.headers || {}),
},
...options,
};
return fetch(url, defaultOpts);
};
export const searchConversations = async (query: string): Promise => {
if (!query.trim()) {
return [];
}
if (isFirebaseMode()) {
const sessions = await getSessions();
return sessions.filter(session =>
session.title.toLowerCase().includes(query.toLowerCase())
);
} else {
const response = await apiCall(`/api/conversations/search?q=${encodeURIComponent(query)}`, {
method: 'GET',
});
if (!response.ok) {
throw new Error('Failed to search conversations');
}
return response.json();
}
};
export const getSessions = async (): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
const firestoreSessions = await FirestoreSessionService.getSessions(uid);
return firestoreSessions.map(session => convertFirestoreSession(session, uid));
} else {
const response = await apiCall(`/api/conversations`, { method: 'GET' });
if (!response.ok) throw new Error('Failed to fetch sessions');
return response.json();
}
};
export const getSessionDetails = async (sessionId: string): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
const [session, transcripts, aiMessages, summary] = await Promise.all([
FirestoreSessionService.getSession(uid, sessionId),
FirestoreTranscriptService.getTranscripts(uid, sessionId),
FirestoreAiMessageService.getAiMessages(uid, sessionId),
FirestoreSummaryService.getSummary(uid, sessionId)
]);
if (!session) {
throw new Error('Session not found');
}
return {
session: convertFirestoreSession({ id: sessionId, ...session }, uid),
transcripts: transcripts.map(t => ({ ...convertFirestoreTranscript(t), session_id: sessionId })),
ai_messages: aiMessages.map(m => ({ ...convertFirestoreAiMessage(m), session_id: sessionId })),
summary: summary ? convertFirestoreSummary(summary, sessionId) : null
};
} else {
const response = await apiCall(`/api/conversations/${sessionId}`, { method: 'GET' });
if (!response.ok) throw new Error('Failed to fetch session details');
return response.json();
}
};
export const createSession = async (title?: string): Promise<{ id: string }> => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
const sessionId = await FirestoreSessionService.createSession(uid, {
title: title || 'New Session',
session_type: 'ask',
endedAt: undefined
});
return { id: sessionId };
} else {
const response = await apiCall(`/api/conversations`, {
method: 'POST',
body: JSON.stringify({ title }),
});
if (!response.ok) throw new Error('Failed to create session');
return response.json();
}
};
export const deleteSession = async (sessionId: string): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
await FirestoreSessionService.deleteSession(uid, sessionId);
} else {
const response = await apiCall(`/api/conversations/${sessionId}`, { method: 'DELETE' });
if (!response.ok) throw new Error('Failed to delete session');
}
};
export const getUserProfile = async (): Promise => {
if (isFirebaseMode()) {
const user = firebaseAuth.currentUser!;
const firestoreProfile = await FirestoreUserService.getUser(user.uid);
return {
uid: user.uid,
display_name: firestoreProfile?.displayName || user.displayName || 'User',
email: firestoreProfile?.email || user.email || 'no-email@example.com'
};
} else {
const response = await apiCall(`/api/user/profile`, { method: 'GET' });
if (!response.ok) throw new Error('Failed to fetch user profile');
return response.json();
}
};
export const updateUserProfile = async (data: { displayName: string }): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
await FirestoreUserService.updateUser(uid, { displayName: data.displayName });
} else {
const response = await apiCall(`/api/user/profile`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('Failed to update user profile');
}
};
export const findOrCreateUser = async (user: UserProfile): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
const existingUser = await FirestoreUserService.getUser(uid);
if (!existingUser) {
await FirestoreUserService.createUser(uid, {
displayName: user.display_name,
email: user.email
});
}
return user;
} else {
const response = await apiCall(`/api/user/find-or-create`, {
method: 'POST',
body: JSON.stringify(user),
});
if (!response.ok) throw new Error('Failed to find or create user');
return response.json();
}
};
export const saveApiKey = async (apiKey: string): Promise => {
if (isFirebaseMode()) {
console.log('API key is not needed in Firebase mode');
return;
} else {
const response = await apiCall(`/api/user/api-key`, {
method: 'POST',
body: JSON.stringify({ apiKey }),
});
if (!response.ok) throw new Error('Failed to save API key');
}
};
export const checkApiKeyStatus = async (): Promise<{ hasApiKey: boolean }> => {
if (isFirebaseMode()) {
return { hasApiKey: true };
} else {
const response = await apiCall(`/api/user/api-key-status`, { method: 'GET' });
if (!response.ok) throw new Error('Failed to check API key status');
return response.json();
}
};
export const deleteAccount = async (): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
await FirestoreUserService.deleteUser(uid);
await firebaseAuth.currentUser!.delete();
} else {
const response = await apiCall(`/api/user/profile`, { method: 'DELETE' });
if (!response.ok) throw new Error('Failed to delete account');
}
};
export const getPresets = async (): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
const firestorePresets = await FirestorePromptPresetService.getPresets(uid);
return firestorePresets.map(preset => convertFirestorePreset(preset, uid));
} else {
const response = await apiCall(`/api/presets`, { method: 'GET' });
if (!response.ok) throw new Error('Failed to fetch presets');
return response.json();
}
};
export const createPreset = async (data: { title: string, prompt: string }): Promise<{ id: string }> => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
const presetId = await FirestorePromptPresetService.createPreset(uid, {
title: data.title,
prompt: data.prompt,
isDefault: false
});
return { id: presetId };
} else {
const response = await apiCall(`/api/presets`, {
method: 'POST',
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('Failed to create preset');
return response.json();
}
};
export const updatePreset = async (id: string, data: { title: string, prompt: string }): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
await FirestorePromptPresetService.updatePreset(uid, id, {
title: data.title,
prompt: data.prompt
});
} else {
const response = await apiCall(`/api/presets/${id}`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to update preset: ${response.status} ${errorText}`);
}
}
};
export const deletePreset = async (id: string): Promise => {
if (isFirebaseMode()) {
const uid = firebaseAuth.currentUser!.uid;
await FirestorePromptPresetService.deletePreset(uid, id);
} else {
const response = await apiCall(`/api/presets/${id}`, { method: 'DELETE' });
if (!response.ok) throw new Error('Failed to delete preset');
}
};
export interface BatchData {
profile?: UserProfile;
presets?: PromptPreset[];
sessions?: Session[];
}
export const getBatchData = async (includes: ('profile' | 'presets' | 'sessions')[]): Promise => {
if (isFirebaseMode()) {
const result: BatchData = {};
const promises: Promise[] = [];
if (includes.includes('profile')) {
promises.push(getUserProfile().then(profile => ({ type: 'profile', data: profile })));
}
if (includes.includes('presets')) {
promises.push(getPresets().then(presets => ({ type: 'presets', data: presets })));
}
if (includes.includes('sessions')) {
promises.push(getSessions().then(sessions => ({ type: 'sessions', data: sessions })));
}
const results = await Promise.all(promises);
results.forEach(({ type, data }) => {
result[type as keyof BatchData] = data;
});
return result;
} else {
const response = await apiCall(`/api/user/batch?include=${includes.join(',')}`, { method: 'GET' });
if (!response.ok) throw new Error('Failed to fetch batch data');
return response.json();
}
};
export const logout = async () => {
if (isFirebaseMode()) {
const { signOut } = await import('firebase/auth');
await signOut(firebaseAuth);
}
setUserInfo(null);
localStorage.removeItem('openai_api_key');
localStorage.removeItem('user_info');
window.location.href = '/login';
};
================================================
FILE: pickleglass_web/utils/auth.ts
================================================
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { UserProfile, setUserInfo, findOrCreateUser } from './api'
import { auth as firebaseAuth } from './firebase'
import { onAuthStateChanged, User as FirebaseUser } from 'firebase/auth'
const defaultLocalUser: UserProfile = {
uid: 'default_user',
display_name: 'Default User',
email: 'contact@pickle.com',
};
export const useAuth = () => {
const [user, setUser] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const [mode, setMode] = useState<'local' | 'firebase' | null>(null)
useEffect(() => {
const unsubscribe = onAuthStateChanged(firebaseAuth, async (firebaseUser: FirebaseUser | null) => {
if (firebaseUser) {
console.log('🔥 Firebase mode activated:', firebaseUser.uid);
setMode('firebase');
let profile: UserProfile = {
uid: firebaseUser.uid,
display_name: firebaseUser.displayName || 'User',
email: firebaseUser.email || 'no-email@example.com',
};
try {
profile = await findOrCreateUser(profile);
console.log('✅ Firestore user created/verified:', profile);
} catch (error) {
console.error('❌ Firestore user creation/verification failed:', error);
}
setUser(profile);
setUserInfo(profile);
} else {
console.log('🏠 Local mode activated');
setMode('local');
setUser(defaultLocalUser);
setUserInfo(defaultLocalUser);
}
setIsLoading(false);
});
return () => unsubscribe();
}, [])
return { user, isLoading, mode }
}
export const useRedirectIfNotAuth = () => {
const { user, isLoading } = useAuth()
const router = useRouter()
useEffect(() => {
// This hook is now simplified. It doesn't redirect for local mode.
// If you want to force login for hosting mode, you'd add logic here.
// For example: if (!isLoading && !user) router.push('/login');
// But for now, we allow both modes.
}, [user, isLoading, router])
return user
}
================================================
FILE: pickleglass_web/utils/firebase.ts
================================================
// Import the functions you need from the SDKs you need
import { initializeApp, getApp, getApps } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
// import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
apiKey: "AIzaSyAgtJrmsFWG1C7m9S55HyT1laICEzuUS2g",
authDomain: "pickle-3651a.firebaseapp.com",
projectId: "pickle-3651a",
storageBucket: "pickle-3651a.firebasestorage.app",
messagingSenderId: "904706892885",
appId: "1:904706892885:web:0e42b3dda796674ead20dc",
measurementId: "G-SQ0WM6S28T"
};
// Initialize Firebase
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
const auth = getAuth(app);
const firestore = getFirestore(app);
// const analytics = getAnalytics(app);
export { app, auth, firestore };
================================================
FILE: pickleglass_web/utils/firestore.ts
================================================
import {
doc,
collection,
addDoc,
getDoc,
getDocs,
setDoc,
updateDoc,
deleteDoc,
query,
where,
orderBy,
serverTimestamp,
Timestamp,
writeBatch
} from 'firebase/firestore';
import { firestore } from './firebase';
export interface FirestoreUserProfile {
displayName: string;
email: string;
createdAt: Timestamp;
}
export interface FirestoreSession {
title: string;
session_type: string;
startedAt: Timestamp;
endedAt?: Timestamp;
}
export interface FirestoreTranscript {
startAt: Timestamp;
endAt: Timestamp;
speaker: 'me' | 'other';
text: string;
lang?: string;
createdAt: Timestamp;
}
export interface FirestoreAiMessage {
sentAt: Timestamp;
role: 'user' | 'assistant';
content: string;
tokens?: number;
model?: string;
createdAt: Timestamp;
}
export interface FirestoreSummary {
generatedAt: Timestamp;
model: string;
text: string;
tldr: string;
bulletPoints: string[];
actionItems: Array<{ owner: string; task: string; due: string }>;
tokensUsed?: number;
}
export interface FirestorePromptPreset {
title: string;
prompt: string;
isDefault: boolean;
createdAt: Timestamp;
}
export class FirestoreUserService {
static async createUser(uid: string, profile: Omit) {
const userRef = doc(firestore, 'users', uid);
await setDoc(userRef, {
...profile,
createdAt: serverTimestamp()
});
}
static async getUser(uid: string): Promise {
const userRef = doc(firestore, 'users', uid);
const userSnap = await getDoc(userRef);
return userSnap.exists() ? userSnap.data() as FirestoreUserProfile : null;
}
static async updateUser(uid: string, updates: Partial) {
const userRef = doc(firestore, 'users', uid);
await updateDoc(userRef, updates);
}
static async deleteUser(uid: string) {
const batch = writeBatch(firestore);
const sessionsRef = collection(firestore, 'users', uid, 'sessions');
const sessionsSnap = await getDocs(sessionsRef);
for (const sessionDoc of sessionsSnap.docs) {
const sessionId = sessionDoc.id;
const transcriptsRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'transcripts');
const transcriptsSnap = await getDocs(transcriptsRef);
transcriptsSnap.docs.forEach(doc => batch.delete(doc.ref));
const aiMessagesRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'aiMessages');
const aiMessagesSnap = await getDocs(aiMessagesRef);
aiMessagesSnap.docs.forEach(doc => batch.delete(doc.ref));
const summaryRef = doc(firestore, 'users', uid, 'sessions', sessionId, 'summary', 'data');
batch.delete(summaryRef);
batch.delete(sessionDoc.ref);
}
const presetsRef = collection(firestore, 'users', uid, 'promptPresets');
const presetsSnap = await getDocs(presetsRef);
presetsSnap.docs.forEach(doc => batch.delete(doc.ref));
const userRef = doc(firestore, 'users', uid);
batch.delete(userRef);
await batch.commit();
}
}
export class FirestoreSessionService {
static async createSession(uid: string, session: Omit): Promise {
const sessionsRef = collection(firestore, 'users', uid, 'sessions');
const docRef = await addDoc(sessionsRef, {
...session,
startedAt: serverTimestamp()
});
return docRef.id;
}
static async getSession(uid: string, sessionId: string): Promise {
const sessionRef = doc(firestore, 'users', uid, 'sessions', sessionId);
const sessionSnap = await getDoc(sessionRef);
return sessionSnap.exists() ? sessionSnap.data() as FirestoreSession : null;
}
static async getSessions(uid: string): Promise> {
const sessionsRef = collection(firestore, 'users', uid, 'sessions');
const q = query(sessionsRef, orderBy('startedAt', 'desc'));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data() as FirestoreSession
}));
}
static async updateSession(uid: string, sessionId: string, updates: Partial) {
const sessionRef = doc(firestore, 'users', uid, 'sessions', sessionId);
await updateDoc(sessionRef, updates);
}
static async deleteSession(uid: string, sessionId: string) {
const batch = writeBatch(firestore);
const transcriptsRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'transcripts');
const transcriptsSnap = await getDocs(transcriptsRef);
transcriptsSnap.docs.forEach(doc => batch.delete(doc.ref));
const aiMessagesRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'aiMessages');
const aiMessagesSnap = await getDocs(aiMessagesRef);
aiMessagesSnap.docs.forEach(doc => batch.delete(doc.ref));
const summaryRef = doc(firestore, 'users', uid, 'sessions', sessionId, 'summary', 'data');
batch.delete(summaryRef);
const sessionRef = doc(firestore, 'users', uid, 'sessions', sessionId);
batch.delete(sessionRef);
await batch.commit();
}
}
export class FirestoreTranscriptService {
static async addTranscript(uid: string, sessionId: string, transcript: Omit): Promise {
const transcriptsRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'transcripts');
const docRef = await addDoc(transcriptsRef, {
...transcript,
createdAt: serverTimestamp()
});
return docRef.id;
}
static async getTranscripts(uid: string, sessionId: string): Promise> {
const transcriptsRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'transcripts');
const q = query(transcriptsRef, orderBy('startAt', 'asc'));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data() as FirestoreTranscript
}));
}
}
export class FirestoreAiMessageService {
static async addAiMessage(uid: string, sessionId: string, message: Omit): Promise {
const aiMessagesRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'aiMessages');
const docRef = await addDoc(aiMessagesRef, {
...message,
createdAt: serverTimestamp()
});
return docRef.id;
}
static async getAiMessages(uid: string, sessionId: string): Promise> {
const aiMessagesRef = collection(firestore, 'users', uid, 'sessions', sessionId, 'aiMessages');
const q = query(aiMessagesRef, orderBy('sentAt', 'asc'));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data() as FirestoreAiMessage
}));
}
}
export class FirestoreSummaryService {
static async setSummary(uid: string, sessionId: string, summary: FirestoreSummary) {
const summaryRef = doc(firestore, 'users', uid, 'sessions', sessionId, 'summary', 'data');
await setDoc(summaryRef, summary);
}
static async getSummary(uid: string, sessionId: string): Promise {
const summaryRef = doc(firestore, 'users', uid, 'sessions', sessionId, 'summary', 'data');
const summarySnap = await getDoc(summaryRef);
return summarySnap.exists() ? summarySnap.data() as FirestoreSummary : null;
}
}
export class FirestorePromptPresetService {
static async createPreset(uid: string, preset: Omit): Promise {
const presetsRef = collection(firestore, 'users', uid, 'promptPresets');
const docRef = await addDoc(presetsRef, {
...preset,
createdAt: serverTimestamp()
});
return docRef.id;
}
static async getPresets(uid: string): Promise> {
const presetsRef = collection(firestore, 'users', uid, 'promptPresets');
const q = query(presetsRef, orderBy('createdAt', 'desc'));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data() as FirestorePromptPreset
}));
}
static async updatePreset(uid: string, presetId: string, updates: Partial) {
const presetRef = doc(firestore, 'users', uid, 'promptPresets', presetId);
await updateDoc(presetRef, updates);
}
static async deletePreset(uid: string, presetId: string) {
const presetRef = doc(firestore, 'users', uid, 'promptPresets', presetId);
await deleteDoc(presetRef);
}
}
================================================
FILE: preload.js
================================================
================================================
FILE: src/bridge/featureBridge.js
================================================
// src/bridge/featureBridge.js
const { ipcMain, app, BrowserWindow } = require('electron');
const settingsService = require('../features/settings/settingsService');
const authService = require('../features/common/services/authService');
const whisperService = require('../features/common/services/whisperService');
const ollamaService = require('../features/common/services/ollamaService');
const modelStateService = require('../features/common/services/modelStateService');
const shortcutsService = require('../features/shortcuts/shortcutsService');
const presetRepository = require('../features/common/repositories/preset');
const localAIManager = require('../features/common/services/localAIManager');
const askService = require('../features/ask/askService');
const listenService = require('../features/listen/listenService');
const permissionService = require('../features/common/services/permissionService');
const encryptionService = require('../features/common/services/encryptionService');
module.exports = {
// Renderer로부터의 요청을 수신하고 서비스로 전달
initialize() {
// Settings Service
ipcMain.handle('settings:getPresets', async () => await settingsService.getPresets());
ipcMain.handle('settings:get-auto-update', async () => await settingsService.getAutoUpdateSetting());
ipcMain.handle('settings:set-auto-update', async (event, isEnabled) => await settingsService.setAutoUpdateSetting(isEnabled));
ipcMain.handle('settings:get-model-settings', async () => await settingsService.getModelSettings());
ipcMain.handle('settings:clear-api-key', async (e, { provider }) => await settingsService.clearApiKey(provider));
ipcMain.handle('settings:set-selected-model', async (e, { type, modelId }) => await settingsService.setSelectedModel(type, modelId));
ipcMain.handle('settings:get-ollama-status', async () => await settingsService.getOllamaStatus());
ipcMain.handle('settings:ensure-ollama-ready', async () => await settingsService.ensureOllamaReady());
ipcMain.handle('settings:shutdown-ollama', async () => await settingsService.shutdownOllama());
// Shortcuts
ipcMain.handle('settings:getCurrentShortcuts', async () => await shortcutsService.loadKeybinds());
ipcMain.handle('shortcut:getDefaultShortcuts', async () => await shortcutsService.handleRestoreDefaults());
ipcMain.handle('shortcut:closeShortcutSettingsWindow', async () => await shortcutsService.closeShortcutSettingsWindow());
ipcMain.handle('shortcut:openShortcutSettingsWindow', async () => await shortcutsService.openShortcutSettingsWindow());
ipcMain.handle('shortcut:saveShortcuts', async (event, newKeybinds) => await shortcutsService.handleSaveShortcuts(newKeybinds));
ipcMain.handle('shortcut:toggleAllWindowsVisibility', async () => await shortcutsService.toggleAllWindowsVisibility());
// Permissions
ipcMain.handle('check-system-permissions', async () => await permissionService.checkSystemPermissions());
ipcMain.handle('request-microphone-permission', async () => await permissionService.requestMicrophonePermission());
ipcMain.handle('open-system-preferences', async (event, section) => await permissionService.openSystemPreferences(section));
ipcMain.handle('mark-keychain-completed', async () => await permissionService.markKeychainCompleted());
ipcMain.handle('check-keychain-completed', async () => await permissionService.checkKeychainCompleted());
ipcMain.handle('initialize-encryption-key', async () => {
const userId = authService.getCurrentUserId();
await encryptionService.initializeKey(userId);
return { success: true };
});
// User/Auth
ipcMain.handle('get-current-user', () => authService.getCurrentUser());
ipcMain.handle('start-firebase-auth', async () => await authService.startFirebaseAuthFlow());
ipcMain.handle('firebase-logout', async () => await authService.signOut());
// App
ipcMain.handle('quit-application', () => app.quit());
// Whisper
ipcMain.handle('whisper:download-model', async (event, modelId) => await whisperService.handleDownloadModel(modelId));
ipcMain.handle('whisper:get-installed-models', async () => await whisperService.handleGetInstalledModels());
// General
ipcMain.handle('get-preset-templates', () => presetRepository.getPresetTemplates());
ipcMain.handle('get-web-url', () => process.env.pickleglass_WEB_URL || 'http://localhost:3000');
// Ollama
ipcMain.handle('ollama:get-status', async () => await ollamaService.handleGetStatus());
ipcMain.handle('ollama:install', async () => await ollamaService.handleInstall());
ipcMain.handle('ollama:start-service', async () => await ollamaService.handleStartService());
ipcMain.handle('ollama:ensure-ready', async () => await ollamaService.handleEnsureReady());
ipcMain.handle('ollama:get-models', async () => await ollamaService.handleGetModels());
ipcMain.handle('ollama:get-model-suggestions', async () => await ollamaService.handleGetModelSuggestions());
ipcMain.handle('ollama:pull-model', async (event, modelName) => await ollamaService.handlePullModel(modelName));
ipcMain.handle('ollama:is-model-installed', async (event, modelName) => await ollamaService.handleIsModelInstalled(modelName));
ipcMain.handle('ollama:warm-up-model', async (event, modelName) => await ollamaService.handleWarmUpModel(modelName));
ipcMain.handle('ollama:auto-warm-up', async () => await ollamaService.handleAutoWarmUp());
ipcMain.handle('ollama:get-warm-up-status', async () => await ollamaService.handleGetWarmUpStatus());
ipcMain.handle('ollama:shutdown', async (event, force = false) => await ollamaService.handleShutdown(force));
// Ask
ipcMain.handle('ask:sendQuestionFromAsk', async (event, userPrompt) => await askService.sendMessage(userPrompt));
ipcMain.handle('ask:sendQuestionFromSummary', async (event, userPrompt) => await askService.sendMessage(userPrompt));
ipcMain.handle('ask:toggleAskButton', async () => await askService.toggleAskButton());
ipcMain.handle('ask:closeAskWindow', async () => await askService.closeAskWindow());
// Listen
ipcMain.handle('listen:sendMicAudio', async (event, { data, mimeType }) => await listenService.handleSendMicAudioContent(data, mimeType));
ipcMain.handle('listen:sendSystemAudio', async (event, { data, mimeType }) => {
const result = await listenService.sttService.sendSystemAudioContent(data, mimeType);
if(result.success) {
listenService.sendToRenderer('system-audio-data', { data });
}
return result;
});
ipcMain.handle('listen:startMacosSystemAudio', async () => await listenService.handleStartMacosAudio());
ipcMain.handle('listen:stopMacosSystemAudio', async () => await listenService.handleStopMacosAudio());
ipcMain.handle('update-google-search-setting', async (event, enabled) => await listenService.handleUpdateGoogleSearchSetting(enabled));
ipcMain.handle('listen:isSessionActive', async () => await listenService.isSessionActive());
ipcMain.handle('listen:changeSession', async (event, listenButtonText) => {
console.log('[FeatureBridge] listen:changeSession from mainheader', listenButtonText);
try {
await listenService.handleListenRequest(listenButtonText);
return { success: true };
} catch (error) {
console.error('[FeatureBridge] listen:changeSession failed', error.message);
return { success: false, error: error.message };
}
});
// ModelStateService
ipcMain.handle('model:validate-key', async (e, { provider, key }) => await modelStateService.handleValidateKey(provider, key));
ipcMain.handle('model:get-all-keys', async () => await modelStateService.getAllApiKeys());
ipcMain.handle('model:set-api-key', async (e, { provider, key }) => await modelStateService.setApiKey(provider, key));
ipcMain.handle('model:remove-api-key', async (e, provider) => await modelStateService.handleRemoveApiKey(provider));
ipcMain.handle('model:get-selected-models', async () => await modelStateService.getSelectedModels());
ipcMain.handle('model:set-selected-model', async (e, { type, modelId }) => await modelStateService.handleSetSelectedModel(type, modelId));
ipcMain.handle('model:get-available-models', async (e, { type }) => await modelStateService.getAvailableModels(type));
ipcMain.handle('model:are-providers-configured', async () => await modelStateService.areProvidersConfigured());
ipcMain.handle('model:get-provider-config', () => modelStateService.getProviderConfig());
ipcMain.handle('model:re-initialize-state', async () => await modelStateService.initialize());
// LocalAIManager 이벤트를 모든 윈도우에 브로드캐스트
localAIManager.on('install-progress', (service, data) => {
const event = { service, ...data };
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('localai:install-progress', event);
}
});
});
localAIManager.on('installation-complete', (service) => {
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('localai:installation-complete', { service });
}
});
});
localAIManager.on('error', (error) => {
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('localai:error-occurred', error);
}
});
});
// Handle error-occurred events from LocalAIManager's error handling
localAIManager.on('error-occurred', (error) => {
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('localai:error-occurred', error);
}
});
});
localAIManager.on('model-ready', (data) => {
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('localai:model-ready', data);
}
});
});
localAIManager.on('state-changed', (service, state) => {
const event = { service, ...state };
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('localai:service-status-changed', event);
}
});
});
// 주기적 상태 동기화 시작
localAIManager.startPeriodicSync();
// ModelStateService 이벤트를 모든 윈도우에 브로드캐스트
modelStateService.on('state-updated', (state) => {
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('model-state:updated', state);
}
});
});
modelStateService.on('settings-updated', () => {
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('settings-updated');
}
});
});
modelStateService.on('force-show-apikey-header', () => {
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed()) {
win.webContents.send('force-show-apikey-header');
}
});
});
// LocalAI 통합 핸들러 추가
ipcMain.handle('localai:install', async (event, { service, options }) => {
return await localAIManager.installService(service, options);
});
ipcMain.handle('localai:get-status', async (event, service) => {
return await localAIManager.getServiceStatus(service);
});
ipcMain.handle('localai:start-service', async (event, service) => {
return await localAIManager.startService(service);
});
ipcMain.handle('localai:stop-service', async (event, service) => {
return await localAIManager.stopService(service);
});
ipcMain.handle('localai:install-model', async (event, { service, modelId, options }) => {
return await localAIManager.installModel(service, modelId, options);
});
ipcMain.handle('localai:get-installed-models', async (event, service) => {
return await localAIManager.getInstalledModels(service);
});
ipcMain.handle('localai:run-diagnostics', async (event, service) => {
return await localAIManager.runDiagnostics(service);
});
ipcMain.handle('localai:repair-service', async (event, service) => {
return await localAIManager.repairService(service);
});
// 에러 처리 핸들러
ipcMain.handle('localai:handle-error', async (event, { service, errorType, details }) => {
return await localAIManager.handleError(service, errorType, details);
});
// 전체 상태 조회
ipcMain.handle('localai:get-all-states', async (event) => {
return await localAIManager.getAllServiceStates();
});
console.log('[FeatureBridge] Initialized with all feature handlers.');
},
// Renderer로 상태를 전송
sendAskProgress(win, progress) {
win.webContents.send('feature:ask:progress', progress);
},
};
================================================
FILE: src/bridge/internalBridge.js
================================================
// src/bridge/internalBridge.js
const { EventEmitter } = require('events');
// FeatureCore와 WindowCore를 잇는 내부 이벤트 버스
const internalBridge = new EventEmitter();
module.exports = internalBridge;
// 예시 이벤트
// internalBridge.on('content-protection-changed', (enabled) => {
// // windowManager에서 처리
// });
================================================
FILE: src/bridge/windowBridge.js
================================================
// src/bridge/windowBridge.js
const { ipcMain, shell } = require('electron');
// Bridge는 단순히 IPC 핸들러를 등록하는 역할만 함 (비즈니스 로직 없음)
module.exports = {
initialize() {
// initialize 시점에 windowManager를 require하여 circular dependency 문제 해결
const windowManager = require('../window/windowManager');
// 기존 IPC 핸들러들
ipcMain.handle('toggle-content-protection', () => windowManager.toggleContentProtection());
ipcMain.handle('resize-header-window', (event, args) => windowManager.resizeHeaderWindow(args));
ipcMain.handle('get-content-protection-status', () => windowManager.getContentProtectionStatus());
ipcMain.on('show-settings-window', () => windowManager.showSettingsWindow());
ipcMain.on('hide-settings-window', () => windowManager.hideSettingsWindow());
ipcMain.on('cancel-hide-settings-window', () => windowManager.cancelHideSettingsWindow());
ipcMain.handle('open-login-page', () => windowManager.openLoginPage());
ipcMain.handle('open-personalize-page', () => windowManager.openLoginPage());
ipcMain.handle('move-window-step', (event, direction) => windowManager.moveWindowStep(direction));
ipcMain.handle('open-external', (event, url) => shell.openExternal(url));
// Newly moved handlers from windowManager
ipcMain.on('header-state-changed', (event, state) => windowManager.handleHeaderStateChanged(state));
ipcMain.on('header-animation-finished', (event, state) => windowManager.handleHeaderAnimationFinished(state));
ipcMain.handle('get-header-position', () => windowManager.getHeaderPosition());
ipcMain.handle('move-header-to', (event, newX, newY) => windowManager.moveHeaderTo(newX, newY));
ipcMain.handle('adjust-window-height', (event, { winName, height }) => windowManager.adjustWindowHeight(winName, height));
},
notifyFocusChange(win, isFocused) {
win.webContents.send('window:focus-change', isFocused);
}
};
================================================
FILE: src/features/ask/askService.js
================================================
const { BrowserWindow } = require('electron');
const { createStreamingLLM } = require('../common/ai/factory');
// Lazy require helper to avoid circular dependency issues
const getWindowManager = () => require('../../window/windowManager');
const internalBridge = require('../../bridge/internalBridge');
const getWindowPool = () => {
try {
return getWindowManager().windowPool;
} catch {
return null;
}
};
const sessionRepository = require('../common/repositories/session');
const askRepository = require('./repositories');
const { getSystemPrompt } = require('../common/prompts/promptBuilder');
const path = require('node:path');
const fs = require('node:fs');
const os = require('os');
const util = require('util');
const execFile = util.promisify(require('child_process').execFile);
const { desktopCapturer } = require('electron');
const modelStateService = require('../common/services/modelStateService');
// Try to load sharp, but don't fail if it's not available
let sharp;
try {
sharp = require('sharp');
console.log('[AskService] Sharp module loaded successfully');
} catch (error) {
console.warn('[AskService] Sharp module not available:', error.message);
console.warn('[AskService] Screenshot functionality will work with reduced image processing capabilities');
sharp = null;
}
let lastScreenshot = null;
async function captureScreenshot(options = {}) {
if (process.platform === 'darwin') {
try {
const tempPath = path.join(os.tmpdir(), `screenshot-${Date.now()}.jpg`);
await execFile('screencapture', ['-x', '-t', 'jpg', tempPath]);
const imageBuffer = await fs.promises.readFile(tempPath);
await fs.promises.unlink(tempPath);
if (sharp) {
try {
// Try using sharp for optimal image processing
const resizedBuffer = await sharp(imageBuffer)
.resize({ height: 384 })
.jpeg({ quality: 80 })
.toBuffer();
const base64 = resizedBuffer.toString('base64');
const metadata = await sharp(resizedBuffer).metadata();
lastScreenshot = {
base64,
width: metadata.width,
height: metadata.height,
timestamp: Date.now(),
};
return { success: true, base64, width: metadata.width, height: metadata.height };
} catch (sharpError) {
console.warn('Sharp module failed, falling back to basic image processing:', sharpError.message);
}
}
// Fallback: Return the original image without resizing
console.log('[AskService] Using fallback image processing (no resize/compression)');
const base64 = imageBuffer.toString('base64');
lastScreenshot = {
base64,
width: null, // We don't have metadata without sharp
height: null,
timestamp: Date.now(),
};
return { success: true, base64, width: null, height: null };
} catch (error) {
console.error('Failed to capture screenshot:', error);
return { success: false, error: error.message };
}
}
try {
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: {
width: 1920,
height: 1080,
},
});
if (sources.length === 0) {
throw new Error('No screen sources available');
}
const source = sources[0];
const buffer = source.thumbnail.toJPEG(70);
const base64 = buffer.toString('base64');
const size = source.thumbnail.getSize();
return {
success: true,
base64,
width: size.width,
height: size.height,
};
} catch (error) {
console.error('Failed to capture screenshot using desktopCapturer:', error);
return {
success: false,
error: error.message,
};
}
}
/**
* @class
* @description
*/
class AskService {
constructor() {
this.abortController = null;
this.state = {
isVisible: false,
isLoading: false,
isStreaming: false,
currentQuestion: '',
currentResponse: '',
showTextInput: true,
};
console.log('[AskService] Service instance created.');
}
_broadcastState() {
const askWindow = getWindowPool()?.get('ask');
if (askWindow && !askWindow.isDestroyed()) {
askWindow.webContents.send('ask:stateUpdate', this.state);
}
}
async toggleAskButton(inputScreenOnly = false) {
const askWindow = getWindowPool()?.get('ask');
let shouldSendScreenOnly = false;
if (inputScreenOnly && this.state.showTextInput && askWindow && askWindow.isVisible()) {
shouldSendScreenOnly = true;
await this.sendMessage('', []);
return;
}
const hasContent = this.state.isLoading || this.state.isStreaming || (this.state.currentResponse && this.state.currentResponse.length > 0);
if (askWindow && askWindow.isVisible() && hasContent) {
this.state.showTextInput = !this.state.showTextInput;
this._broadcastState();
} else {
if (askWindow && askWindow.isVisible()) {
internalBridge.emit('window:requestVisibility', { name: 'ask', visible: false });
this.state.isVisible = false;
} else {
console.log('[AskService] Showing hidden Ask window');
internalBridge.emit('window:requestVisibility', { name: 'ask', visible: true });
this.state.isVisible = true;
}
if (this.state.isVisible) {
this.state.showTextInput = true;
this._broadcastState();
}
}
}
async closeAskWindow () {
if (this.abortController) {
this.abortController.abort('Window closed by user');
this.abortController = null;
}
this.state = {
isVisible : false,
isLoading : false,
isStreaming : false,
currentQuestion: '',
currentResponse: '',
showTextInput : true,
};
this._broadcastState();
internalBridge.emit('window:requestVisibility', { name: 'ask', visible: false });
return { success: true };
}
/**
*
* @param {string[]} conversationTexts
* @returns {string}
* @private
*/
_formatConversationForPrompt(conversationTexts) {
if (!conversationTexts || conversationTexts.length === 0) {
return 'No conversation history available.';
}
return conversationTexts.slice(-30).join('\n');
}
/**
*
* @param {string} userPrompt
* @returns {Promise<{success: boolean, response?: string, error?: string}>}
*/
async sendMessage(userPrompt, conversationHistoryRaw=[]) {
internalBridge.emit('window:requestVisibility', { name: 'ask', visible: true });
this.state = {
...this.state,
isLoading: true,
isStreaming: false,
currentQuestion: userPrompt,
currentResponse: '',
showTextInput: false,
};
this._broadcastState();
if (this.abortController) {
this.abortController.abort('New request received.');
}
this.abortController = new AbortController();
const { signal } = this.abortController;
let sessionId;
try {
console.log(`[AskService] 🤖 Processing message: ${userPrompt.substring(0, 50)}...`);
sessionId = await sessionRepository.getOrCreateActive('ask');
await askRepository.addAiMessage({ sessionId, role: 'user', content: userPrompt.trim() });
console.log(`[AskService] DB: Saved user prompt to session ${sessionId}`);
const modelInfo = await modelStateService.getCurrentModelInfo('llm');
if (!modelInfo || !modelInfo.apiKey) {
throw new Error('AI model or API key not configured.');
}
console.log(`[AskService] Using model: ${modelInfo.model} for provider: ${modelInfo.provider}`);
const screenshotResult = await captureScreenshot({ quality: 'medium' });
const screenshotBase64 = screenshotResult.success ? screenshotResult.base64 : null;
const conversationHistory = this._formatConversationForPrompt(conversationHistoryRaw);
const systemPrompt = getSystemPrompt('pickle_glass_analysis', conversationHistory, false);
const messages = [
{ role: 'system', content: systemPrompt },
{
role: 'user',
content: [
{ type: 'text', text: `User Request: ${userPrompt.trim()}` },
],
},
];
if (screenshotBase64) {
messages[1].content.push({
type: 'image_url',
image_url: { url: `data:image/jpeg;base64,${screenshotBase64}` },
});
}
const streamingLLM = createStreamingLLM(modelInfo.provider, {
apiKey: modelInfo.apiKey,
model: modelInfo.model,
temperature: 0.7,
maxTokens: 2048,
usePortkey: modelInfo.provider === 'openai-glass',
portkeyVirtualKey: modelInfo.provider === 'openai-glass' ? modelInfo.apiKey : undefined,
});
try {
const response = await streamingLLM.streamChat(messages);
const askWin = getWindowPool()?.get('ask');
if (!askWin || askWin.isDestroyed()) {
console.error("[AskService] Ask window is not available to send stream to.");
response.body.getReader().cancel();
return { success: false, error: 'Ask window is not available.' };
}
const reader = response.body.getReader();
signal.addEventListener('abort', () => {
console.log(`[AskService] Aborting stream reader. Reason: ${signal.reason}`);
reader.cancel(signal.reason).catch(() => { /* 이미 취소된 경우의 오류는 무시 */ });
});
await this._processStream(reader, askWin, sessionId, signal);
return { success: true };
} catch (multimodalError) {
// 멀티모달 요청이 실패했고 스크린샷이 포함되어 있다면 텍스트만으로 재시도
if (screenshotBase64 && this._isMultimodalError(multimodalError)) {
console.log(`[AskService] Multimodal request failed, retrying with text-only: ${multimodalError.message}`);
// 텍스트만으로 메시지 재구성
const textOnlyMessages = [
{ role: 'system', content: systemPrompt },
{
role: 'user',
content: `User Request: ${userPrompt.trim()}`
}
];
const fallbackResponse = await streamingLLM.streamChat(textOnlyMessages);
const askWin = getWindowPool()?.get('ask');
if (!askWin || askWin.isDestroyed()) {
console.error("[AskService] Ask window is not available for fallback response.");
fallbackResponse.body.getReader().cancel();
return { success: false, error: 'Ask window is not available.' };
}
const fallbackReader = fallbackResponse.body.getReader();
signal.addEventListener('abort', () => {
console.log(`[AskService] Aborting fallback stream reader. Reason: ${signal.reason}`);
fallbackReader.cancel(signal.reason).catch(() => {});
});
await this._processStream(fallbackReader, askWin, sessionId, signal);
return { success: true };
} else {
// 다른 종류의 에러이거나 스크린샷이 없었다면 그대로 throw
throw multimodalError;
}
}
} catch (error) {
console.error('[AskService] Error during message processing:', error);
this.state = {
...this.state,
isLoading: false,
isStreaming: false,
showTextInput: true,
};
this._broadcastState();
const askWin = getWindowPool()?.get('ask');
if (askWin && !askWin.isDestroyed()) {
const streamError = error.message || 'Unknown error occurred';
askWin.webContents.send('ask-response-stream-error', { error: streamError });
}
return { success: false, error: error.message };
}
}
/**
*
* @param {ReadableStreamDefaultReader} reader
* @param {BrowserWindow} askWin
* @param {number} sessionId
* @param {AbortSignal} signal
* @returns {Promise}
* @private
*/
async _processStream(reader, askWin, sessionId, signal) {
const decoder = new TextDecoder();
let fullResponse = '';
try {
this.state.isLoading = false;
this.state.isStreaming = true;
this._broadcastState();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(line => line.trim() !== '');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.substring(6);
if (data === '[DONE]') {
return;
}
try {
const json = JSON.parse(data);
const token = json.choices[0]?.delta?.content || '';
if (token) {
fullResponse += token;
this.state.currentResponse = fullResponse;
this._broadcastState();
}
} catch (error) {
}
}
}
}
} catch (streamError) {
if (signal.aborted) {
console.log(`[AskService] Stream reading was intentionally cancelled. Reason: ${signal.reason}`);
} else {
console.error('[AskService] Error while processing stream:', streamError);
if (askWin && !askWin.isDestroyed()) {
askWin.webContents.send('ask-response-stream-error', { error: streamError.message });
}
}
} finally {
this.state.isStreaming = false;
this.state.currentResponse = fullResponse;
this._broadcastState();
if (fullResponse) {
try {
await askRepository.addAiMessage({ sessionId, role: 'assistant', content: fullResponse });
console.log(`[AskService] DB: Saved partial or full assistant response to session ${sessionId} after stream ended.`);
} catch(dbError) {
console.error("[AskService] DB: Failed to save assistant response after stream ended:", dbError);
}
}
}
}
/**
* 멀티모달 관련 에러인지 판단
* @private
*/
_isMultimodalError(error) {
const errorMessage = error.message?.toLowerCase() || '';
return (
errorMessage.includes('vision') ||
errorMessage.includes('image') ||
errorMessage.includes('multimodal') ||
errorMessage.includes('unsupported') ||
errorMessage.includes('image_url') ||
errorMessage.includes('400') || // Bad Request often for unsupported features
errorMessage.includes('invalid') ||
errorMessage.includes('not supported')
);
}
}
const askService = new AskService();
module.exports = askService;
================================================
FILE: src/features/ask/repositories/firebase.repository.js
================================================
const { collection, addDoc, query, getDocs, orderBy, Timestamp } = require('firebase/firestore');
const { getFirestoreInstance } = require('../../common/services/firebaseClient');
const { createEncryptedConverter } = require('../../common/repositories/firestoreConverter');
const aiMessageConverter = createEncryptedConverter(['content']);
function aiMessagesCol(sessionId) {
if (!sessionId) throw new Error("Session ID is required to access AI messages.");
const db = getFirestoreInstance();
return collection(db, `sessions/${sessionId}/ai_messages`).withConverter(aiMessageConverter);
}
async function addAiMessage({ uid, sessionId, role, content, model = 'unknown' }) {
const now = Timestamp.now();
const newMessage = {
uid, // To identify the author of the message
session_id: sessionId,
sent_at: now,
role,
content,
model,
created_at: now,
};
const docRef = await addDoc(aiMessagesCol(sessionId), newMessage);
return { id: docRef.id };
}
async function getAllAiMessagesBySessionId(sessionId) {
const q = query(aiMessagesCol(sessionId), orderBy('sent_at', 'asc'));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => doc.data());
}
module.exports = {
addAiMessage,
getAllAiMessagesBySessionId,
};
================================================
FILE: src/features/ask/repositories/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
const firebaseRepository = require('./firebase.repository');
const authService = require('../../common/services/authService');
function getBaseRepository() {
const user = authService.getCurrentUser();
if (user && user.isLoggedIn) {
return firebaseRepository;
}
return sqliteRepository;
}
// The adapter layer that injects the UID
const askRepositoryAdapter = {
addAiMessage: ({ sessionId, role, content, model }) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().addAiMessage({ uid, sessionId, role, content, model });
},
getAllAiMessagesBySessionId: (sessionId) => {
// This function does not require a UID at the service level.
return getBaseRepository().getAllAiMessagesBySessionId(sessionId);
}
};
module.exports = askRepositoryAdapter;
================================================
FILE: src/features/ask/repositories/sqlite.repository.js
================================================
const sqliteClient = require('../../common/services/sqliteClient');
function addAiMessage({ uid, sessionId, role, content, model = 'unknown' }) {
// uid is ignored in the SQLite implementation
const db = sqliteClient.getDb();
const messageId = require('crypto').randomUUID();
const now = Math.floor(Date.now() / 1000);
const query = `INSERT INTO ai_messages (id, session_id, sent_at, role, content, model, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`;
try {
db.prepare(query).run(messageId, sessionId, now, role, content, model, now);
return { id: messageId };
} catch (err) {
console.error('SQLite: Failed to add AI message:', err);
throw err;
}
}
function getAllAiMessagesBySessionId(sessionId) {
const db = sqliteClient.getDb();
const query = "SELECT * FROM ai_messages WHERE session_id = ? ORDER BY sent_at ASC";
return db.prepare(query).all(sessionId);
}
module.exports = {
addAiMessage,
getAllAiMessagesBySessionId
};
================================================
FILE: src/features/common/ai/factory.js
================================================
// factory.js
/**
* @typedef {object} ModelOption
* @property {string} id
* @property {string} name
*/
/**
* @typedef {object} Provider
* @property {string} name
* @property {() => any} handler
* @property {ModelOption[]} llmModels
* @property {ModelOption[]} sttModels
*/
/**
* @type {Object.}
*/
const PROVIDERS = {
'openai': {
name: 'OpenAI',
handler: () => require("./providers/openai"),
llmModels: [
{ id: 'gpt-4.1', name: 'GPT-4.1' },
],
sttModels: [
{ id: 'gpt-4o-mini-transcribe', name: 'GPT-4o Mini Transcribe' }
],
},
'openai-glass': {
name: 'OpenAI (Glass)',
handler: () => require("./providers/openai"),
llmModels: [
{ id: 'gpt-4.1-glass', name: 'GPT-4.1 (glass)' },
],
sttModels: [
{ id: 'gpt-4o-mini-transcribe-glass', name: 'GPT-4o Mini Transcribe (glass)' }
],
},
'gemini': {
name: 'Gemini',
handler: () => require("./providers/gemini"),
llmModels: [
{ id: 'gemini-2.5-flash', name: 'Gemini 2.5 Flash' },
],
sttModels: [
{ id: 'gemini-live-2.5-flash-preview', name: 'Gemini Live 2.5 Flash' }
],
},
'anthropic': {
name: 'Anthropic',
handler: () => require("./providers/anthropic"),
llmModels: [
{ id: 'claude-3-5-sonnet-20241022', name: 'Claude 3.5 Sonnet' },
],
sttModels: [],
},
'deepgram': {
name: 'Deepgram',
handler: () => require("./providers/deepgram"),
llmModels: [],
sttModels: [
{ id: 'nova-3', name: 'Nova-3 (General)' },
],
},
'ollama': {
name: 'Ollama (Local)',
handler: () => require("./providers/ollama"),
llmModels: [], // Dynamic models populated from installed Ollama models
sttModels: [], // Ollama doesn't support STT yet
},
'whisper': {
name: 'Whisper (Local)',
handler: () => {
// This needs to remain a function due to its conditional logic for renderer/main process
if (typeof window === 'undefined') {
const { WhisperProvider } = require("./providers/whisper");
return new WhisperProvider();
}
// Return a dummy object for the renderer process
return {
validateApiKey: async () => ({ success: true }), // Mock validate for renderer
createSTT: () => { throw new Error('Whisper STT is only available in main process'); },
};
},
llmModels: [],
sttModels: [
{ id: 'whisper-tiny', name: 'Whisper Tiny (39M)' },
{ id: 'whisper-base', name: 'Whisper Base (74M)' },
{ id: 'whisper-small', name: 'Whisper Small (244M)' },
{ id: 'whisper-medium', name: 'Whisper Medium (769M)' },
],
},
};
function sanitizeModelId(model) {
return (typeof model === 'string') ? model.replace(/-glass$/, '') : model;
}
function createSTT(provider, opts) {
if (provider === 'openai-glass') provider = 'openai';
const handler = PROVIDERS[provider]?.handler();
if (!handler?.createSTT) {
throw new Error(`STT not supported for provider: ${provider}`);
}
if (opts && opts.model) {
opts = { ...opts, model: sanitizeModelId(opts.model) };
}
return handler.createSTT(opts);
}
function createLLM(provider, opts) {
if (provider === 'openai-glass') provider = 'openai';
const handler = PROVIDERS[provider]?.handler();
if (!handler?.createLLM) {
throw new Error(`LLM not supported for provider: ${provider}`);
}
if (opts && opts.model) {
opts = { ...opts, model: sanitizeModelId(opts.model) };
}
return handler.createLLM(opts);
}
function createStreamingLLM(provider, opts) {
if (provider === 'openai-glass') provider = 'openai';
const handler = PROVIDERS[provider]?.handler();
if (!handler?.createStreamingLLM) {
throw new Error(`Streaming LLM not supported for provider: ${provider}`);
}
if (opts && opts.model) {
opts = { ...opts, model: sanitizeModelId(opts.model) };
}
return handler.createStreamingLLM(opts);
}
function getProviderClass(providerId) {
const providerConfig = PROVIDERS[providerId];
if (!providerConfig) return null;
// Handle special cases for glass providers
let actualProviderId = providerId;
if (providerId === 'openai-glass') {
actualProviderId = 'openai';
}
// The handler function returns the module, from which we get the class.
const module = providerConfig.handler();
// Map provider IDs to their actual exported class names
const classNameMap = {
'openai': 'OpenAIProvider',
'anthropic': 'AnthropicProvider',
'gemini': 'GeminiProvider',
'deepgram': 'DeepgramProvider',
'ollama': 'OllamaProvider',
'whisper': 'WhisperProvider'
};
const className = classNameMap[actualProviderId];
return className ? module[className] : null;
}
function getAvailableProviders() {
const stt = [];
const llm = [];
for (const [id, provider] of Object.entries(PROVIDERS)) {
if (provider.sttModels.length > 0) stt.push(id);
if (provider.llmModels.length > 0) llm.push(id);
}
return { stt: [...new Set(stt)], llm: [...new Set(llm)] };
}
module.exports = {
PROVIDERS,
createSTT,
createLLM,
createStreamingLLM,
getProviderClass,
getAvailableProviders,
};
================================================
FILE: src/features/common/ai/providers/anthropic.js
================================================
const { Anthropic } = require("@anthropic-ai/sdk")
class AnthropicProvider {
static async validateApiKey(key) {
if (!key || typeof key !== 'string' || !key.startsWith('sk-ant-')) {
return { success: false, error: 'Invalid Anthropic API key format.' };
}
try {
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": key,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify({
model: "claude-3-haiku-20240307",
max_tokens: 1,
messages: [{ role: "user", content: "Hi" }],
}),
});
if (response.ok || response.status === 400) { // 400 is a valid response for a bad request, not a bad key
return { success: true };
} else {
const errorData = await response.json().catch(() => ({}));
return { success: false, error: errorData.error?.message || `Validation failed with status: ${response.status}` };
}
} catch (error) {
console.error(`[AnthropicProvider] Network error during key validation:`, error);
return { success: false, error: 'A network error occurred during validation.' };
}
}
}
/**
* Creates an Anthropic STT session
* Note: Anthropic doesn't have native real-time STT, so this is a placeholder
* You might want to use a different STT service or implement a workaround
* @param {object} opts - Configuration options
* @param {string} opts.apiKey - Anthropic API key
* @param {string} [opts.language='en'] - Language code
* @param {object} [opts.callbacks] - Event callbacks
* @returns {Promise} STT session placeholder
*/
async function createSTT({ apiKey, language = "en", callbacks = {}, ...config }) {
console.warn("[Anthropic] STT not natively supported. Consider using OpenAI or Gemini for STT.")
// Return a mock STT session that doesn't actually do anything
// You might want to fallback to another provider for STT
return {
sendRealtimeInput: async (audioData) => {
console.warn("[Anthropic] STT sendRealtimeInput called but not implemented")
},
close: async () => {
console.log("[Anthropic] STT session closed")
},
}
}
/**
* Creates an Anthropic LLM instance
* @param {object} opts - Configuration options
* @param {string} opts.apiKey - Anthropic API key
* @param {string} [opts.model='claude-3-5-sonnet-20241022'] - Model name
* @param {number} [opts.temperature=0.7] - Temperature
* @param {number} [opts.maxTokens=4096] - Max tokens
* @returns {object} LLM instance
*/
function createLLM({ apiKey, model = "claude-3-5-sonnet-20241022", temperature = 0.7, maxTokens = 4096, ...config }) {
const client = new Anthropic({ apiKey })
return {
generateContent: async (parts) => {
const messages = []
let systemPrompt = ""
const userContent = []
for (const part of parts) {
if (typeof part === "string") {
if (systemPrompt === "" && part.includes("You are")) {
systemPrompt = part
} else {
userContent.push({ type: "text", text: part })
}
} else if (part.inlineData) {
userContent.push({
type: "image",
source: {
type: "base64",
media_type: part.inlineData.mimeType,
data: part.inlineData.data,
},
})
}
}
if (userContent.length > 0) {
messages.push({ role: "user", content: userContent })
}
try {
const response = await client.messages.create({
model: model,
max_tokens: maxTokens,
temperature: temperature,
system: systemPrompt || undefined,
messages: messages,
})
return {
response: {
text: () => response.content[0].text,
},
raw: response,
}
} catch (error) {
console.error("Anthropic API error:", error)
throw error
}
},
// For compatibility with chat-style interfaces
chat: async (messages) => {
let systemPrompt = ""
const anthropicMessages = []
for (const msg of messages) {
if (msg.role === "system") {
systemPrompt = msg.content
} else {
// Handle multimodal content
let content
if (Array.isArray(msg.content)) {
content = []
for (const part of msg.content) {
if (typeof part === "string") {
content.push({ type: "text", text: part })
} else if (part.type === "text") {
content.push({ type: "text", text: part.text })
} else if (part.type === "image_url" && part.image_url) {
// Convert base64 image to Anthropic format
const imageUrl = part.image_url.url
const [mimeInfo, base64Data] = imageUrl.split(",")
// Extract the actual MIME type from the data URL
const mimeType = mimeInfo.match(/data:([^;]+)/)?.[1] || "image/jpeg"
content.push({
type: "image",
source: {
type: "base64",
media_type: mimeType,
data: base64Data,
},
})
}
}
} else {
content = [{ type: "text", text: msg.content }]
}
anthropicMessages.push({
role: msg.role === "user" ? "user" : "assistant",
content: content,
})
}
}
const response = await client.messages.create({
model: model,
max_tokens: maxTokens,
temperature: temperature,
system: systemPrompt || undefined,
messages: anthropicMessages,
})
return {
content: response.content[0].text,
raw: response,
}
},
}
}
/**
* Creates an Anthropic streaming LLM instance
* @param {object} opts - Configuration options
* @param {string} opts.apiKey - Anthropic API key
* @param {string} [opts.model='claude-3-5-sonnet-20241022'] - Model name
* @param {number} [opts.temperature=0.7] - Temperature
* @param {number} [opts.maxTokens=4096] - Max tokens
* @returns {object} Streaming LLM instance
*/
function createStreamingLLM({
apiKey,
model = "claude-3-5-sonnet-20241022",
temperature = 0.7,
maxTokens = 4096,
...config
}) {
const client = new Anthropic({ apiKey })
return {
streamChat: async (messages) => {
console.log("[Anthropic Provider] Starting streaming request")
let systemPrompt = ""
const anthropicMessages = []
for (const msg of messages) {
if (msg.role === "system") {
systemPrompt = msg.content
} else {
// Handle multimodal content
let content
if (Array.isArray(msg.content)) {
content = []
for (const part of msg.content) {
if (typeof part === "string") {
content.push({ type: "text", text: part })
} else if (part.type === "text") {
content.push({ type: "text", text: part.text })
} else if (part.type === "image_url" && part.image_url) {
// Convert base64 image to Anthropic format
const imageUrl = part.image_url.url
const [mimeInfo, base64Data] = imageUrl.split(",")
// Extract the actual MIME type from the data URL
const mimeType = mimeInfo.match(/data:([^;]+)/)?.[1] || "image/jpeg"
console.log(`[Anthropic] Processing image with MIME type: ${mimeType}`)
content.push({
type: "image",
source: {
type: "base64",
media_type: mimeType,
data: base64Data,
},
})
}
}
} else {
content = [{ type: "text", text: msg.content }]
}
anthropicMessages.push({
role: msg.role === "user" ? "user" : "assistant",
content: content,
})
}
}
// Create a ReadableStream to handle Anthropic's streaming
const stream = new ReadableStream({
async start(controller) {
try {
console.log("[Anthropic Provider] Processing messages:", anthropicMessages.length, "messages")
let chunkCount = 0
let totalContent = ""
// Stream the response
const stream = await client.messages.create({
model: model,
max_tokens: maxTokens,
temperature: temperature,
system: systemPrompt || undefined,
messages: anthropicMessages,
stream: true,
})
for await (const chunk of stream) {
if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
chunkCount++
const chunkText = chunk.delta.text || ""
totalContent += chunkText
// Format as SSE data
const data = JSON.stringify({
choices: [
{
delta: {
content: chunkText,
},
},
],
})
controller.enqueue(new TextEncoder().encode(`data: ${data}\n\n`))
}
}
console.log(
`[Anthropic Provider] Streamed ${chunkCount} chunks, total length: ${totalContent.length} chars`,
)
// Send the final done message
controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n"))
controller.close()
console.log("[Anthropic Provider] Streaming completed successfully")
} catch (error) {
console.error("[Anthropic Provider] Streaming error:", error)
controller.error(error)
}
},
})
// Create a Response object with the stream
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
})
},
}
}
module.exports = {
AnthropicProvider,
createSTT,
createLLM,
createStreamingLLM
};
================================================
FILE: src/features/common/ai/providers/deepgram.js
================================================
// providers/deepgram.js
const { createClient, LiveTranscriptionEvents } = require('@deepgram/sdk');
const WebSocket = require('ws');
/**
* Deepgram Provider 클래스. API 키 유효성 검사를 담당합니다.
*/
class DeepgramProvider {
/**
* Deepgram API 키의 유효성을 검사합니다.
* @param {string} key - 검사할 Deepgram API 키
* @returns {Promise<{success: boolean, error?: string}>}
*/
static async validateApiKey(key) {
if (!key || typeof key !== 'string') {
return { success: false, error: 'Invalid Deepgram API key format.' };
}
try {
// ✨ 변경점: SDK 대신 직접 fetch로 API를 호출하여 안정성 확보 (openai.js 방식)
const response = await fetch('https://api.deepgram.com/v1/projects', {
headers: { 'Authorization': `Token ${key}` }
});
if (response.ok) {
return { success: true };
} else {
const errorData = await response.json().catch(() => ({}));
const message = errorData.err_msg || `Validation failed with status: ${response.status}`;
return { success: false, error: message };
}
} catch (error) {
console.error(`[DeepgramProvider] Network error during key validation:`, error);
return { success: false, error: error.message || 'A network error occurred during validation.' };
}
}
}
function createSTT({
apiKey,
language = 'en-US',
sampleRate = 24000,
callbacks = {},
}) {
const qs = new URLSearchParams({
model: 'nova-3',
encoding: 'linear16',
sample_rate: sampleRate.toString(),
language,
smart_format: 'true',
interim_results: 'true',
channels: '1',
});
const url = `wss://api.deepgram.com/v1/listen?${qs}`;
const ws = new WebSocket(url, {
headers: { Authorization: `Token ${apiKey}` },
});
ws.binaryType = 'arraybuffer';
return new Promise((resolve, reject) => {
const to = setTimeout(() => {
ws.terminate();
reject(new Error('DG open timeout (10 s)'));
}, 10_000);
ws.on('open', () => {
clearTimeout(to);
resolve({
sendRealtimeInput: (buf) => ws.send(buf),
close: () => ws.close(1000, 'client'),
});
});
ws.on('message', raw => {
let msg;
try { msg = JSON.parse(raw.toString()); } catch { return; }
if (msg.channel?.alternatives?.[0]?.transcript !== undefined) {
callbacks.onmessage?.({ provider: 'deepgram', ...msg });
}
});
ws.on('close', (code, reason) =>
callbacks.onclose?.({ code, reason: reason.toString() })
);
ws.on('error', err => {
clearTimeout(to);
callbacks.onerror?.(err);
reject(err);
});
});
}
// ... (LLM 관련 Placeholder 함수들은 그대로 유지) ...
function createLLM(opts) {
console.warn("[Deepgram] LLM not supported.");
return { generateContent: async () => { throw new Error("Deepgram does not support LLM functionality."); } };
}
function createStreamingLLM(opts) {
console.warn("[Deepgram] Streaming LLM not supported.");
return { streamChat: async () => { throw new Error("Deepgram does not support Streaming LLM functionality."); } };
}
module.exports = {
DeepgramProvider,
createSTT,
createLLM,
createStreamingLLM
};
================================================
FILE: src/features/common/ai/providers/gemini.js
================================================
const { GoogleGenerativeAI } = require("@google/generative-ai")
const { GoogleGenAI } = require("@google/genai")
class GeminiProvider {
static async validateApiKey(key) {
if (!key || typeof key !== 'string') {
return { success: false, error: 'Invalid Gemini API key format.' };
}
try {
const validationUrl = `https://generativelanguage.googleapis.com/v1beta/models?key=${key}`;
const response = await fetch(validationUrl);
if (response.ok) {
return { success: true };
} else {
const errorData = await response.json().catch(() => ({}));
const message = errorData.error?.message || `Validation failed with status: ${response.status}`;
return { success: false, error: message };
}
} catch (error) {
console.error(`[GeminiProvider] Network error during key validation:`, error);
return { success: false, error: 'A network error occurred during validation.' };
}
}
}
/**
* Creates a Gemini STT session
* @param {object} opts - Configuration options
* @param {string} opts.apiKey - Gemini API key
* @param {string} [opts.language='en-US'] - Language code
* @param {object} [opts.callbacks] - Event callbacks
* @returns {Promise} STT session
*/
async function createSTT({ apiKey, language = "en-US", callbacks = {}, ...config }) {
const liveClient = new GoogleGenAI({ vertexai: false, apiKey })
// Language code BCP-47 conversion
const lang = language.includes("-") ? language : `${language}-US`
const session = await liveClient.live.connect({
model: 'gemini-live-2.5-flash-preview',
callbacks: {
...callbacks,
onMessage: (msg) => {
if (!msg || typeof msg !== 'object') return;
msg.provider = 'gemini';
callbacks.onmessage?.(msg);
}
},
config: {
inputAudioTranscription: {},
speechConfig: { languageCode: lang },
},
})
return {
sendRealtimeInput: async (payload) => session.sendRealtimeInput(payload),
close: async () => session.close(),
}
}
/**
* Creates a Gemini LLM instance with proper text response handling
*/
function createLLM({ apiKey, model = "gemini-2.5-flash", temperature = 0.7, maxTokens = 8192, ...config }) {
const client = new GoogleGenerativeAI(apiKey)
return {
generateContent: async (parts) => {
const geminiModel = client.getGenerativeModel({
model: model,
generationConfig: {
temperature,
maxOutputTokens: maxTokens,
// Ensure we get text responses, not JSON
responseMimeType: "text/plain",
},
})
const systemPrompt = ""
const userContent = []
for (const part of parts) {
if (typeof part === "string") {
// Don't automatically assume strings starting with "You are" are system prompts
// Check if it's explicitly marked as a system instruction
userContent.push(part)
} else if (part.inlineData) {
userContent.push({
inlineData: {
mimeType: part.inlineData.mimeType,
data: part.inlineData.data,
},
})
}
}
try {
const result = await geminiModel.generateContent(userContent)
const response = await result.response
// Return plain text, not wrapped in JSON structure
return {
response: {
text: () => response.text(),
},
}
} catch (error) {
console.error("Gemini API error:", error)
throw error
}
},
chat: async (messages) => {
// Filter out any system prompts that might be causing JSON responses
let systemInstruction = ""
const history = []
let lastMessage
messages.forEach((msg, index) => {
if (msg.role === "system") {
// Clean system instruction - avoid JSON formatting requests
systemInstruction = msg.content
.replace(/respond in json/gi, "")
.replace(/format.*json/gi, "")
.replace(/return.*json/gi, "")
// Add explicit instruction for natural text
if (!systemInstruction.includes("respond naturally")) {
systemInstruction += "\n\nRespond naturally in plain text, not in JSON or structured format."
}
return
}
const role = msg.role === "user" ? "user" : "model"
if (index === messages.length - 1) {
lastMessage = msg
} else {
history.push({ role, parts: [{ text: msg.content }] })
}
})
const geminiModel = client.getGenerativeModel({
model: model,
systemInstruction:
systemInstruction ||
"Respond naturally in plain text format. Do not use JSON or structured responses unless specifically requested.",
generationConfig: {
temperature: temperature,
maxOutputTokens: maxTokens,
// Force plain text responses
responseMimeType: "text/plain",
},
})
const chat = geminiModel.startChat({
history: history,
})
let content = lastMessage.content
// Handle multimodal content
if (Array.isArray(content)) {
const geminiContent = []
for (const part of content) {
if (typeof part === "string") {
geminiContent.push(part)
} else if (part.type === "text") {
geminiContent.push(part.text)
} else if (part.type === "image_url" && part.image_url) {
const base64Data = part.image_url.url.split(",")[1]
geminiContent.push({
inlineData: {
mimeType: "image/png",
data: base64Data,
},
})
}
}
content = geminiContent
}
const result = await chat.sendMessage(content)
const response = await result.response
// Return plain text content
return {
content: response.text(),
raw: result,
}
},
}
}
/**
* Creates a Gemini streaming LLM instance with text response fix
*/
function createStreamingLLM({ apiKey, model = "gemini-2.5-flash", temperature = 0.7, maxTokens = 8192, ...config }) {
const client = new GoogleGenerativeAI(apiKey)
return {
streamChat: async (messages) => {
console.log("[Gemini Provider] Starting streaming request")
let systemInstruction = ""
const nonSystemMessages = []
for (const msg of messages) {
if (msg.role === "system") {
// Clean and modify system instruction
systemInstruction = msg.content
.replace(/respond in json/gi, "")
.replace(/format.*json/gi, "")
.replace(/return.*json/gi, "")
if (!systemInstruction.includes("respond naturally")) {
systemInstruction += "\n\nRespond naturally in plain text, not in JSON or structured format."
}
} else {
nonSystemMessages.push(msg)
}
}
const geminiModel = client.getGenerativeModel({
model: model,
systemInstruction:
systemInstruction ||
"Respond naturally in plain text format. Do not use JSON or structured responses unless specifically requested.",
generationConfig: {
temperature,
maxOutputTokens: maxTokens || 8192,
// Force plain text responses
responseMimeType: "text/plain",
},
})
const stream = new ReadableStream({
async start(controller) {
try {
const lastMessage = nonSystemMessages[nonSystemMessages.length - 1]
let geminiContent = []
if (Array.isArray(lastMessage.content)) {
for (const part of lastMessage.content) {
if (typeof part === "string") {
geminiContent.push(part)
} else if (part.type === "text") {
geminiContent.push(part.text)
} else if (part.type === "image_url" && part.image_url) {
const base64Data = part.image_url.url.split(",")[1]
geminiContent.push({
inlineData: {
mimeType: "image/png",
data: base64Data,
},
})
}
}
} else {
geminiContent = [lastMessage.content]
}
const contentParts = geminiContent.map((part) => {
if (typeof part === "string") {
return { text: part }
} else if (part.inlineData) {
return { inlineData: part.inlineData }
}
return part
})
const result = await geminiModel.generateContentStream({
contents: [
{
role: "user",
parts: contentParts,
},
],
})
for await (const chunk of result.stream) {
const chunkText = chunk.text() || ""
// Format as SSE data - this should now be plain text
const data = JSON.stringify({
choices: [
{
delta: {
content: chunkText,
},
},
],
})
controller.enqueue(new TextEncoder().encode(`data: ${data}\n\n`))
}
controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n"))
controller.close()
} catch (error) {
console.error("[Gemini Provider] Streaming error:", error)
controller.error(error)
}
},
})
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
})
},
}
}
module.exports = {
GeminiProvider,
createSTT,
createLLM,
createStreamingLLM
};
================================================
FILE: src/features/common/ai/providers/ollama.js
================================================
const http = require('http');
const fetch = require('node-fetch');
// Request Queue System for Ollama API (only for non-streaming requests)
class RequestQueue {
constructor() {
this.queue = [];
this.processing = false;
this.streamingActive = false;
}
async addStreamingRequest(requestFn) {
// Streaming requests have priority - wait for current processing to finish
while (this.processing) {
await new Promise(resolve => setTimeout(resolve, 50));
}
this.streamingActive = true;
console.log('[Ollama Queue] Starting streaming request (priority)');
try {
const result = await requestFn();
return result;
} finally {
this.streamingActive = false;
console.log('[Ollama Queue] Streaming request completed');
}
}
async add(requestFn) {
return new Promise((resolve, reject) => {
this.queue.push({ requestFn, resolve, reject });
this.process();
});
}
async process() {
if (this.processing || this.queue.length === 0) {
return;
}
// Wait if streaming is active
if (this.streamingActive) {
setTimeout(() => this.process(), 100);
return;
}
this.processing = true;
while (this.queue.length > 0) {
// Check if streaming started while processing queue
if (this.streamingActive) {
this.processing = false;
setTimeout(() => this.process(), 100);
return;
}
const { requestFn, resolve, reject } = this.queue.shift();
try {
console.log(`[Ollama Queue] Processing queued request (${this.queue.length} remaining)`);
const result = await requestFn();
resolve(result);
} catch (error) {
console.error('[Ollama Queue] Request failed:', error);
reject(error);
}
}
this.processing = false;
}
}
// Global request queue instance
const requestQueue = new RequestQueue();
class OllamaProvider {
static async validateApiKey() {
try {
const response = await fetch('http://localhost:11434/api/tags');
if (response.ok) {
return { success: true };
} else {
return { success: false, error: 'Ollama service is not running. Please start Ollama first.' };
}
} catch (error) {
return { success: false, error: 'Cannot connect to Ollama. Please ensure Ollama is installed and running.' };
}
}
}
function convertMessagesToOllamaFormat(messages) {
return messages.map(msg => {
if (Array.isArray(msg.content)) {
let textContent = '';
const images = [];
for (const part of msg.content) {
if (part.type === 'text') {
textContent += part.text;
} else if (part.type === 'image_url') {
const base64 = part.image_url.url.replace(/^data:image\/[^;]+;base64,/, '');
images.push(base64);
}
}
return {
role: msg.role,
content: textContent,
...(images.length > 0 && { images })
};
} else {
return msg;
}
});
}
function createLLM({
model,
temperature = 0.7,
maxTokens = 2048,
baseUrl = 'http://localhost:11434',
...config
}) {
if (!model) {
throw new Error('Model parameter is required for Ollama LLM. Please specify a model name (e.g., "llama3.2:latest", "gemma3:4b")');
}
return {
generateContent: async (parts) => {
let systemPrompt = '';
const userContent = [];
for (const part of parts) {
if (typeof part === 'string') {
if (systemPrompt === '' && part.includes('You are')) {
systemPrompt = part;
} else {
userContent.push(part);
}
} else if (part.inlineData) {
userContent.push({
type: 'image',
image: `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`
});
}
}
const messages = [];
if (systemPrompt) {
messages.push({ role: 'system', content: systemPrompt });
}
messages.push({ role: 'user', content: userContent.join('\n') });
// Use request queue to prevent concurrent API calls
return await requestQueue.add(async () => {
try {
const response = await fetch(`${baseUrl}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model,
messages,
stream: false,
options: {
temperature,
num_predict: maxTokens,
}
})
});
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
}
const result = await response.json();
return {
response: {
text: () => result.message.content
},
raw: result
};
} catch (error) {
console.error('Ollama LLM error:', error);
throw error;
}
});
},
chat: async (messages) => {
const ollamaMessages = convertMessagesToOllamaFormat(messages);
// Use request queue to prevent concurrent API calls
return await requestQueue.add(async () => {
try {
const response = await fetch(`${baseUrl}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model,
messages: ollamaMessages,
stream: false,
options: {
temperature,
num_predict: maxTokens,
}
})
});
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
}
const result = await response.json();
return {
content: result.message.content,
raw: result
};
} catch (error) {
console.error('Ollama chat error:', error);
throw error;
}
});
}
};
}
function createStreamingLLM({
model,
temperature = 0.7,
maxTokens = 2048,
baseUrl = 'http://localhost:11434',
...config
}) {
if (!model) {
throw new Error('Model parameter is required for Ollama streaming LLM. Please specify a model name (e.g., "llama3.2:latest", "gemma3:4b")');
}
return {
streamChat: async (messages) => {
console.log('[Ollama Provider] Starting streaming request');
const ollamaMessages = convertMessagesToOllamaFormat(messages);
console.log('[Ollama Provider] Converted messages for Ollama:', ollamaMessages);
// Streaming requests have priority over queued requests
return await requestQueue.addStreamingRequest(async () => {
try {
const response = await fetch(`${baseUrl}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model,
messages: ollamaMessages,
stream: true,
options: {
temperature,
num_predict: maxTokens,
}
})
});
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
}
console.log('[Ollama Provider] Got streaming response');
const stream = new ReadableStream({
async start(controller) {
let buffer = '';
try {
response.body.on('data', (chunk) => {
buffer += chunk.toString();
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.trim() === '') continue;
try {
const data = JSON.parse(line);
if (data.message?.content) {
const sseData = JSON.stringify({
choices: [{
delta: {
content: data.message.content
}
}]
});
controller.enqueue(new TextEncoder().encode(`data: ${sseData}\n\n`));
}
if (data.done) {
controller.enqueue(new TextEncoder().encode('data: [DONE]\n\n'));
}
} catch (e) {
console.error('[Ollama Provider] Failed to parse chunk:', e);
}
}
});
response.body.on('end', () => {
controller.close();
console.log('[Ollama Provider] Streaming completed');
});
response.body.on('error', (error) => {
console.error('[Ollama Provider] Streaming error:', error);
controller.error(error);
});
} catch (error) {
console.error('[Ollama Provider] Streaming setup error:', error);
controller.error(error);
}
}
});
return {
ok: true,
body: stream
};
} catch (error) {
console.error('[Ollama Provider] Request error:', error);
throw error;
}
});
}
};
}
module.exports = {
OllamaProvider,
createLLM,
createStreamingLLM,
convertMessagesToOllamaFormat
};
================================================
FILE: src/features/common/ai/providers/openai.js
================================================
const OpenAI = require('openai');
const WebSocket = require('ws');
const { Portkey } = require('portkey-ai');
const { Readable } = require('stream');
const { getProviderForModel } = require('../factory.js');
class OpenAIProvider {
static async validateApiKey(key) {
if (!key || typeof key !== 'string' || !key.startsWith('sk-')) {
return { success: false, error: 'Invalid OpenAI API key format.' };
}
try {
const response = await fetch('https://api.openai.com/v1/models', {
headers: { 'Authorization': `Bearer ${key}` }
});
if (response.ok) {
return { success: true };
} else {
const errorData = await response.json().catch(() => ({}));
const message = errorData.error?.message || `Validation failed with status: ${response.status}`;
return { success: false, error: message };
}
} catch (error) {
console.error(`[OpenAIProvider] Network error during key validation:`, error);
return { success: false, error: 'A network error occurred during validation.' };
}
}
}
/**
* Creates an OpenAI STT session
* @param {object} opts - Configuration options
* @param {string} opts.apiKey - OpenAI API key
* @param {string} [opts.language='en'] - Language code
* @param {object} [opts.callbacks] - Event callbacks
* @param {boolean} [opts.usePortkey=false] - Whether to use Portkey
* @param {string} [opts.portkeyVirtualKey] - Portkey virtual key
* @returns {Promise} STT session
*/
async function createSTT({ apiKey, language = 'en', callbacks = {}, usePortkey = false, portkeyVirtualKey, ...config }) {
const keyType = usePortkey ? 'vKey' : 'apiKey';
const key = usePortkey ? (portkeyVirtualKey || apiKey) : apiKey;
const wsUrl = keyType === 'apiKey'
? 'wss://api.openai.com/v1/realtime?intent=transcription'
: 'wss://api.portkey.ai/v1/realtime?intent=transcription';
const headers = keyType === 'apiKey'
? {
'Authorization': `Bearer ${key}`,
'OpenAI-Beta': 'realtime=v1',
}
: {
'x-portkey-api-key': 'gRv2UGRMq6GGLJ8aVEB4e7adIewu',
'x-portkey-virtual-key': key,
'OpenAI-Beta': 'realtime=v1',
};
const ws = new WebSocket(wsUrl, { headers });
return new Promise((resolve, reject) => {
ws.onopen = () => {
console.log("WebSocket session opened.");
const sessionConfig = {
type: 'transcription_session.update',
session: {
input_audio_format: 'pcm16',
input_audio_transcription: {
model: 'gpt-4o-mini-transcribe',
prompt: config.prompt || '',
language: language || 'en'
},
turn_detection: {
type: 'server_vad',
threshold: 0.5,
prefix_padding_ms: 200,
silence_duration_ms: 100,
},
input_audio_noise_reduction: {
type: 'near_field'
}
}
};
ws.send(JSON.stringify(sessionConfig));
// Helper to periodically keep the websocket alive
const keepAlive = () => {
try {
if (ws.readyState === WebSocket.OPEN) {
// The ws library supports native ping frames which are ideal for heart-beats
ws.ping();
}
} catch (err) {
console.error('[OpenAI STT] keepAlive error:', err.message);
}
};
resolve({
sendRealtimeInput: (audioData) => {
if (ws.readyState === WebSocket.OPEN) {
const message = {
type: 'input_audio_buffer.append',
audio: audioData
};
ws.send(JSON.stringify(message));
}
},
// Expose keepAlive so higher-level services can schedule heart-beats
keepAlive,
close: () => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'session.close' }));
ws.onmessage = ws.onerror = () => {}; // 핸들러 제거
ws.close(1000, 'Client initiated close.');
}
}
});
};
ws.onmessage = (event) => {
// ── 종료·하트비트 패킷 필터링 ──────────────────────────────
if (!event.data || event.data === 'null' || event.data === '[DONE]') return;
let msg;
try { msg = JSON.parse(event.data); }
catch { return; } // JSON 파싱 실패 무시
if (!msg || typeof msg !== 'object') return;
msg.provider = 'openai'; // ← 항상 명시
callbacks.onmessage?.(msg);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error.message);
if (callbacks && callbacks.onerror) {
callbacks.onerror(error);
}
reject(error);
};
ws.onclose = (event) => {
console.log(`WebSocket closed: ${event.code} ${event.reason}`);
if (callbacks && callbacks.onclose) {
callbacks.onclose(event);
}
};
});
}
/**
* Creates an OpenAI LLM instance
* @param {object} opts - Configuration options
* @param {string} opts.apiKey - OpenAI API key
* @param {string} [opts.model='gpt-4.1'] - Model name
* @param {number} [opts.temperature=0.7] - Temperature
* @param {number} [opts.maxTokens=2048] - Max tokens
* @param {boolean} [opts.usePortkey=false] - Whether to use Portkey
* @param {string} [opts.portkeyVirtualKey] - Portkey virtual key
* @returns {object} LLM instance
*/
function createLLM({ apiKey, model = 'gpt-4.1', temperature = 0.7, maxTokens = 2048, usePortkey = false, portkeyVirtualKey, ...config }) {
const client = new OpenAI({ apiKey });
const callApi = async (messages) => {
if (!usePortkey) {
const response = await client.chat.completions.create({
model: model,
messages: messages,
temperature: temperature,
max_tokens: maxTokens
});
return {
content: response.choices[0].message.content.trim(),
raw: response
};
} else {
const fetchUrl = 'https://api.portkey.ai/v1/chat/completions';
const response = await fetch(fetchUrl, {
method: 'POST',
headers: {
'x-portkey-api-key': 'gRv2UGRMq6GGLJ8aVEB4e7adIewu',
'x-portkey-virtual-key': portkeyVirtualKey || apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: model,
messages,
temperature,
max_tokens: maxTokens,
}),
});
if (!response.ok) {
throw new Error(`Portkey API error: ${response.status} ${response.statusText}`);
}
const result = await response.json();
return {
content: result.choices[0].message.content.trim(),
raw: result
};
}
};
return {
generateContent: async (parts) => {
const messages = [];
let systemPrompt = '';
let userContent = [];
for (const part of parts) {
if (typeof part === 'string') {
if (systemPrompt === '' && part.includes('You are')) {
systemPrompt = part;
} else {
userContent.push({ type: 'text', text: part });
}
} else if (part.inlineData) {
userContent.push({
type: 'image_url',
image_url: { url: `data:${part.inlineData.mimeType};base64,${part.inlineData.data}` }
});
}
}
if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });
if (userContent.length > 0) messages.push({ role: 'user', content: userContent });
const result = await callApi(messages);
return {
response: {
text: () => result.content
},
raw: result.raw
};
},
// For compatibility with chat-style interfaces
chat: async (messages) => {
return await callApi(messages);
}
};
}
/**
* Creates an OpenAI streaming LLM instance
* @param {object} opts - Configuration options
* @param {string} opts.apiKey - OpenAI API key
* @param {string} [opts.model='gpt-4.1'] - Model name
* @param {number} [opts.temperature=0.7] - Temperature
* @param {number} [opts.maxTokens=2048] - Max tokens
* @param {boolean} [opts.usePortkey=false] - Whether to use Portkey
* @param {string} [opts.portkeyVirtualKey] - Portkey virtual key
* @returns {object} Streaming LLM instance
*/
function createStreamingLLM({ apiKey, model = 'gpt-4.1', temperature = 0.7, maxTokens = 2048, usePortkey = false, portkeyVirtualKey, ...config }) {
return {
streamChat: async (messages) => {
const fetchUrl = usePortkey
? 'https://api.portkey.ai/v1/chat/completions'
: 'https://api.openai.com/v1/chat/completions';
const headers = usePortkey
? {
'x-portkey-api-key': 'gRv2UGRMq6GGLJ8aVEB4e7adIewu',
'x-portkey-virtual-key': portkeyVirtualKey || apiKey,
'Content-Type': 'application/json',
}
: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
};
const response = await fetch(fetchUrl, {
method: 'POST',
headers,
body: JSON.stringify({
model: model,
messages,
temperature,
max_tokens: maxTokens,
stream: true,
}),
});
if (!response.ok) {
throw new Error(`OpenAI API error: ${response.status} ${response.statusText}`);
}
return response;
}
};
}
module.exports = {
OpenAIProvider,
createSTT,
createLLM,
createStreamingLLM
};
================================================
FILE: src/features/common/ai/providers/whisper.js
================================================
let spawn, path, EventEmitter;
if (typeof window === 'undefined') {
spawn = require('child_process').spawn;
path = require('path');
EventEmitter = require('events').EventEmitter;
} else {
class DummyEventEmitter {
on() {}
emit() {}
removeAllListeners() {}
}
EventEmitter = DummyEventEmitter;
}
class WhisperSTTSession extends EventEmitter {
constructor(model, whisperService, sessionId) {
super();
this.model = model;
this.whisperService = whisperService;
this.sessionId = sessionId || `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
this.process = null;
this.isRunning = false;
this.audioBuffer = Buffer.alloc(0);
this.processingInterval = null;
this.lastTranscription = '';
}
async initialize() {
try {
await this.whisperService.ensureModelAvailable(this.model);
this.isRunning = true;
this.startProcessingLoop();
return true;
} catch (error) {
console.error('[WhisperSTT] Initialization error:', error);
this.emit('error', error);
return false;
}
}
startProcessingLoop() {
this.processingInterval = setInterval(async () => {
const minBufferSize = 16000 * 2 * 0.15;
if (this.audioBuffer.length >= minBufferSize && !this.process) {
console.log(`[WhisperSTT-${this.sessionId}] Processing audio chunk, buffer size: ${this.audioBuffer.length}`);
await this.processAudioChunk();
}
}, 1500);
}
async processAudioChunk() {
if (!this.isRunning || this.audioBuffer.length === 0) return;
const audioData = this.audioBuffer;
this.audioBuffer = Buffer.alloc(0);
try {
const tempFile = await this.whisperService.saveAudioToTemp(audioData, this.sessionId);
if (!tempFile || typeof tempFile !== 'string') {
console.error('[WhisperSTT] Invalid temp file path:', tempFile);
return;
}
const whisperPath = await this.whisperService.getWhisperPath();
const modelPath = await this.whisperService.getModelPath(this.model);
if (!whisperPath || !modelPath) {
console.error('[WhisperSTT] Invalid whisper or model path:', { whisperPath, modelPath });
return;
}
this.process = spawn(whisperPath, [
'-m', modelPath,
'-f', tempFile,
'--no-timestamps',
'--output-txt',
'--output-json',
'--language', 'auto',
'--threads', '4',
'--print-progress', 'false'
]);
let output = '';
let errorOutput = '';
this.process.stdout.on('data', (data) => {
output += data.toString();
});
this.process.stderr.on('data', (data) => {
errorOutput += data.toString();
});
this.process.on('close', async (code) => {
this.process = null;
if (code === 0 && output.trim()) {
const transcription = output.trim();
if (transcription && transcription !== this.lastTranscription) {
this.lastTranscription = transcription;
console.log(`[WhisperSTT-${this.sessionId}] Transcription: "${transcription}"`);
this.emit('transcription', {
text: transcription,
timestamp: Date.now(),
confidence: 1.0,
sessionId: this.sessionId
});
}
} else if (errorOutput) {
console.error(`[WhisperSTT-${this.sessionId}] Process error:`, errorOutput);
}
await this.whisperService.cleanupTempFile(tempFile);
});
} catch (error) {
console.error('[WhisperSTT] Processing error:', error);
this.emit('error', error);
}
}
sendRealtimeInput(audioData) {
if (!this.isRunning) {
console.warn(`[WhisperSTT-${this.sessionId}] Session not running, cannot accept audio`);
return;
}
if (typeof audioData === 'string') {
try {
audioData = Buffer.from(audioData, 'base64');
} catch (error) {
console.error('[WhisperSTT] Failed to decode base64 audio data:', error);
return;
}
} else if (audioData instanceof ArrayBuffer) {
audioData = Buffer.from(audioData);
} else if (!Buffer.isBuffer(audioData) && !(audioData instanceof Uint8Array)) {
console.error('[WhisperSTT] Invalid audio data type:', typeof audioData);
return;
}
if (!Buffer.isBuffer(audioData)) {
audioData = Buffer.from(audioData);
}
if (audioData.length > 0) {
this.audioBuffer = Buffer.concat([this.audioBuffer, audioData]);
// Log every 10th audio chunk to avoid spam
if (Math.random() < 0.1) {
console.log(`[WhisperSTT-${this.sessionId}] Received audio chunk: ${audioData.length} bytes, total buffer: ${this.audioBuffer.length} bytes`);
}
}
}
async close() {
console.log(`[WhisperSTT-${this.sessionId}] Closing session`);
this.isRunning = false;
if (this.processingInterval) {
clearInterval(this.processingInterval);
this.processingInterval = null;
}
if (this.process) {
this.process.kill('SIGTERM');
this.process = null;
}
this.removeAllListeners();
}
}
class WhisperProvider {
static async validateApiKey() {
// Whisper is a local service, no API key validation needed.
return { success: true };
}
constructor() {
this.whisperService = null;
}
async initialize() {
if (!this.whisperService) {
this.whisperService = require('../../services/whisperService');
if (!this.whisperService.isInitialized) {
await this.whisperService.initialize();
}
}
}
async createSTT(config) {
await this.initialize();
const model = config.model || 'whisper-tiny';
const sessionType = config.sessionType || 'unknown';
console.log(`[WhisperProvider] Creating ${sessionType} STT session with model: ${model}`);
// Create unique session ID based on type
const sessionId = `${sessionType}_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`;
const session = new WhisperSTTSession(model, this.whisperService, sessionId);
// Log session creation
console.log(`[WhisperProvider] Created session: ${sessionId}`);
const initialized = await session.initialize();
if (!initialized) {
throw new Error('Failed to initialize Whisper STT session');
}
if (config.callbacks) {
if (config.callbacks.onmessage) {
session.on('transcription', config.callbacks.onmessage);
}
if (config.callbacks.onerror) {
session.on('error', config.callbacks.onerror);
}
if (config.callbacks.onclose) {
session.on('close', config.callbacks.onclose);
}
}
return session;
}
async createLLM() {
throw new Error('Whisper provider does not support LLM functionality');
}
async createStreamingLLM() {
console.warn('[WhisperProvider] Streaming LLM is not supported by Whisper.');
throw new Error('Whisper does not support LLM.');
}
}
module.exports = {
WhisperProvider,
WhisperSTTSession
};
================================================
FILE: src/features/common/config/checksums.js
================================================
const DOWNLOAD_CHECKSUMS = {
ollama: {
dmg: {
url: 'https://ollama.com/download/Ollama.dmg',
sha256: null // TODO: 실제 체크섬 추가 필요 - null일 경우 체크섬 검증 스킵됨
},
exe: {
url: 'https://ollama.com/download/OllamaSetup.exe',
sha256: null // TODO: 실제 체크섬 추가 필요 - null일 경우 체크섬 검증 스킵됨
},
linux: {
url: 'curl -fsSL https://ollama.com/install.sh | sh',
sha256: null // TODO: 실제 체크섬 추가 필요 - null일 경우 체크섬 검증 스킵됨
}
},
whisper: {
models: {
'whisper-tiny': {
url: 'https://huggingface.co/ggml-org/whisper.cpp/resolve/main/ggml-tiny.bin',
sha256: 'be07e048e1e599ad46341c8d2a135645097a538221678b7acdd1b1919c6e1b21'
},
'whisper-base': {
url: 'https://huggingface.co/ggml-org/whisper.cpp/resolve/main/ggml-base.bin',
sha256: '60ed5bc3dd14eea856493d334349b405782ddcaf0028d4b5df4088345fba2efe'
},
'whisper-small': {
url: 'https://huggingface.co/ggml-org/whisper.cpp/resolve/main/ggml-small.bin',
sha256: '1be3a9b2063867b937e64e2ec7483364a79917e157fa98c5d94b5c1fffea987b'
},
'whisper-medium': {
url: 'https://huggingface.co/ggml-org/whisper.cpp/resolve/main/ggml-medium.bin',
sha256: '6c14d5adee5f86394037b4e4e8b59f1673b6cee10e3cf0b11bbdbee79c156208'
}
},
binaries: {
'v1.7.6': {
mac: {
url: 'https://github.com/ggml-org/whisper.cpp/releases/download/v1.7.6/whisper-cpp-v1.7.6-mac-x64.zip',
sha256: null // TODO: 실제 체크섬 추가 필요 - null일 경우 체크섬 검증 스킵됨
},
windows: {
url: 'https://github.com/ggml-org/whisper.cpp/releases/download/v1.7.6/whisper-cpp-v1.7.6-win-x64.zip',
sha256: null // TODO: 실제 체크섬 추가 필요 - null일 경우 체크섬 검증 스킵됨
},
linux: {
url: 'https://github.com/ggml-org/whisper.cpp/releases/download/v1.7.6/whisper-cpp-v1.7.6-linux-x64.tar.gz',
sha256: null // TODO: 실제 체크섬 추가 필요 - null일 경우 체크섬 검증 스킵됨
}
}
}
}
};
module.exports = { DOWNLOAD_CHECKSUMS };
================================================
FILE: src/features/common/config/config.js
================================================
// Configuration management for environment-based settings
const os = require('os');
const path = require('path');
const fs = require('fs');
class Config {
constructor() {
this.env = process.env.NODE_ENV || 'development';
this.defaults = {
apiUrl: process.env.pickleglass_API_URL || 'http://localhost:9001',
apiTimeout: 10000,
webUrl: process.env.pickleglass_WEB_URL || 'http://localhost:3000',
enableJWT: false,
fallbackToHeaderAuth: false,
cacheTimeout: 5 * 60 * 1000,
enableCaching: true,
syncInterval: 0,
healthCheckInterval: 30 * 1000,
defaultWindowWidth: 400,
defaultWindowHeight: 60,
enableOfflineMode: true,
enableFileBasedCommunication: false,
enableSQLiteStorage: true,
logLevel: 'info',
enableDebugLogging: false
};
this.config = { ...this.defaults };
this.loadEnvironmentConfig();
this.loadUserConfig();
}
loadEnvironmentConfig() {
if (process.env.pickleglass_API_URL) {
this.config.apiUrl = process.env.pickleglass_API_URL;
console.log(`[Config] API URL from env: ${this.config.apiUrl}`);
}
if (process.env.pickleglass_WEB_URL) {
this.config.webUrl = process.env.pickleglass_WEB_URL;
console.log(`[Config] Web URL from env: ${this.config.webUrl}`);
}
if (process.env.pickleglass_API_TIMEOUT) {
this.config.apiTimeout = parseInt(process.env.pickleglass_API_TIMEOUT);
}
if (process.env.pickleglass_ENABLE_JWT) {
this.config.enableJWT = process.env.pickleglass_ENABLE_JWT === 'true';
}
if (process.env.pickleglass_CACHE_TIMEOUT) {
this.config.cacheTimeout = parseInt(process.env.pickleglass_CACHE_TIMEOUT);
}
if (process.env.pickleglass_LOG_LEVEL) {
this.config.logLevel = process.env.pickleglass_LOG_LEVEL;
}
if (process.env.pickleglass_DEBUG) {
this.config.enableDebugLogging = process.env.pickleglass_DEBUG === 'true';
}
if (this.env === 'production') {
this.config.enableDebugLogging = false;
this.config.logLevel = 'warn';
} else if (this.env === 'development') {
this.config.enableDebugLogging = true;
this.config.logLevel = 'debug';
}
}
loadUserConfig() {
try {
const userConfigPath = this.getUserConfigPath();
if (fs.existsSync(userConfigPath)) {
const userConfig = JSON.parse(fs.readFileSync(userConfigPath, 'utf-8'));
this.config = { ...this.config, ...userConfig };
console.log('[Config] User config loaded from:', userConfigPath);
}
} catch (error) {
console.warn('[Config] Failed to load user config:', error.message);
}
}
getUserConfigPath() {
const configDir = path.join(os.homedir(), '.pickleglass');
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
return path.join(configDir, 'config.json');
}
get(key) {
return this.config[key];
}
set(key, value) {
this.config[key] = value;
}
getAll() {
return { ...this.config };
}
saveUserConfig() {
try {
const userConfigPath = this.getUserConfigPath();
const userConfig = { ...this.config };
Object.keys(this.defaults).forEach(key => {
if (userConfig[key] === this.defaults[key]) {
delete userConfig[key];
}
});
fs.writeFileSync(userConfigPath, JSON.stringify(userConfig, null, 2));
console.log('[Config] User config saved to:', userConfigPath);
} catch (error) {
console.error('[Config] Failed to save user config:', error);
}
}
reset() {
this.config = { ...this.defaults };
this.loadEnvironmentConfig();
}
isDevelopment() {
return this.env === 'development';
}
isProduction() {
return this.env === 'production';
}
shouldLog(level) {
const levels = ['debug', 'info', 'warn', 'error'];
const currentLevelIndex = levels.indexOf(this.config.logLevel);
const requestedLevelIndex = levels.indexOf(level);
return requestedLevelIndex >= currentLevelIndex;
}
}
const config = new Config();
module.exports = config;
================================================
FILE: src/features/common/config/schema.js
================================================
const LATEST_SCHEMA = {
users: {
columns: [
{ name: 'uid', type: 'TEXT PRIMARY KEY' },
{ name: 'display_name', type: 'TEXT NOT NULL' },
{ name: 'email', type: 'TEXT NOT NULL' },
{ name: 'created_at', type: 'INTEGER' },
{ name: 'auto_update_enabled', type: 'INTEGER DEFAULT 1' },
{ name: 'has_migrated_to_firebase', type: 'INTEGER DEFAULT 0' }
]
},
sessions: {
columns: [
{ name: 'id', type: 'TEXT PRIMARY KEY' },
{ name: 'uid', type: 'TEXT NOT NULL' },
{ name: 'title', type: 'TEXT' },
{ name: 'session_type', type: 'TEXT DEFAULT \'ask\'' },
{ name: 'started_at', type: 'INTEGER' },
{ name: 'ended_at', type: 'INTEGER' },
{ name: 'sync_state', type: 'TEXT DEFAULT \'clean\'' },
{ name: 'updated_at', type: 'INTEGER' }
]
},
transcripts: {
columns: [
{ name: 'id', type: 'TEXT PRIMARY KEY' },
{ name: 'session_id', type: 'TEXT NOT NULL' },
{ name: 'start_at', type: 'INTEGER' },
{ name: 'end_at', type: 'INTEGER' },
{ name: 'speaker', type: 'TEXT' },
{ name: 'text', type: 'TEXT' },
{ name: 'lang', type: 'TEXT' },
{ name: 'created_at', type: 'INTEGER' },
{ name: 'sync_state', type: 'TEXT DEFAULT \'clean\'' }
]
},
ai_messages: {
columns: [
{ name: 'id', type: 'TEXT PRIMARY KEY' },
{ name: 'session_id', type: 'TEXT NOT NULL' },
{ name: 'sent_at', type: 'INTEGER' },
{ name: 'role', type: 'TEXT' },
{ name: 'content', type: 'TEXT' },
{ name: 'tokens', type: 'INTEGER' },
{ name: 'model', type: 'TEXT' },
{ name: 'created_at', type: 'INTEGER' },
{ name: 'sync_state', type: 'TEXT DEFAULT \'clean\'' }
]
},
summaries: {
columns: [
{ name: 'session_id', type: 'TEXT PRIMARY KEY' },
{ name: 'generated_at', type: 'INTEGER' },
{ name: 'model', type: 'TEXT' },
{ name: 'text', type: 'TEXT' },
{ name: 'tldr', type: 'TEXT' },
{ name: 'bullet_json', type: 'TEXT' },
{ name: 'action_json', type: 'TEXT' },
{ name: 'tokens_used', type: 'INTEGER' },
{ name: 'updated_at', type: 'INTEGER' },
{ name: 'sync_state', type: 'TEXT DEFAULT \'clean\'' }
]
},
prompt_presets: {
columns: [
{ name: 'id', type: 'TEXT PRIMARY KEY' },
{ name: 'uid', type: 'TEXT NOT NULL' },
{ name: 'title', type: 'TEXT NOT NULL' },
{ name: 'prompt', type: 'TEXT NOT NULL' },
{ name: 'is_default', type: 'INTEGER NOT NULL' },
{ name: 'created_at', type: 'INTEGER' },
{ name: 'sync_state', type: 'TEXT DEFAULT \'clean\'' }
]
},
ollama_models: {
columns: [
{ name: 'name', type: 'TEXT PRIMARY KEY' },
{ name: 'size', type: 'TEXT NOT NULL' },
{ name: 'installed', type: 'INTEGER DEFAULT 0' },
{ name: 'installing', type: 'INTEGER DEFAULT 0' }
]
},
whisper_models: {
columns: [
{ name: 'id', type: 'TEXT PRIMARY KEY' },
{ name: 'name', type: 'TEXT NOT NULL' },
{ name: 'size', type: 'TEXT NOT NULL' },
{ name: 'installed', type: 'INTEGER DEFAULT 0' },
{ name: 'installing', type: 'INTEGER DEFAULT 0' }
]
},
provider_settings: {
columns: [
{ name: 'provider', type: 'TEXT NOT NULL' },
{ name: 'api_key', type: 'TEXT' },
{ name: 'selected_llm_model', type: 'TEXT' },
{ name: 'selected_stt_model', type: 'TEXT' },
{ name: 'is_active_llm', type: 'INTEGER DEFAULT 0' },
{ name: 'is_active_stt', type: 'INTEGER DEFAULT 0' },
{ name: 'created_at', type: 'INTEGER' },
{ name: 'updated_at', type: 'INTEGER' }
],
constraints: ['PRIMARY KEY (provider)']
},
shortcuts: {
columns: [
{ name: 'action', type: 'TEXT PRIMARY KEY' },
{ name: 'accelerator', type: 'TEXT NOT NULL' },
{ name: 'created_at', type: 'INTEGER' }
]
},
permissions: {
columns: [
{ name: 'uid', type: 'TEXT PRIMARY KEY' },
{ name: 'keychain_completed', type: 'INTEGER DEFAULT 0' }
]
}
};
module.exports = LATEST_SCHEMA;
================================================
FILE: src/features/common/prompts/promptBuilder.js
================================================
const { profilePrompts } = require('./promptTemplates.js');
function buildSystemPrompt(promptParts, customPrompt = '', googleSearchEnabled = true) {
const sections = [promptParts.intro, '\n\n', promptParts.formatRequirements];
if (googleSearchEnabled) {
sections.push('\n\n', promptParts.searchUsage);
}
sections.push('\n\n', promptParts.content, '\n\nUser-provided context\n-----\n', customPrompt, '\n-----\n\n', promptParts.outputInstructions);
return sections.join('');
}
function getSystemPrompt(profile, customPrompt = '', googleSearchEnabled = true) {
const promptParts = profilePrompts[profile] || profilePrompts.interview;
return buildSystemPrompt(promptParts, customPrompt, googleSearchEnabled);
}
module.exports = {
getSystemPrompt,
};
================================================
FILE: src/features/common/prompts/promptTemplates.js
================================================
const profilePrompts = {
interview: {
intro: `You are the user's live-meeting co-pilot called Pickle, developed and created by Pickle. Prioritize only the most recent context from the conversation.`,
formatRequirements: `**RESPONSE FORMAT REQUIREMENTS:**
- First section: Key topics as bullet points (≤10 words each)
- Second section: Analysis questions as bullet points (≤15 words each)
- Use clear section headers: "TOPICS:" and "QUESTIONS:"
- Focus on the most essential information only`,
searchUsage: `**ANALYSIS PROCESSING:**
- Extract key topics from conversation in chronological order
- Generate helpful analysis questions for deeper insights
- Keep responses concise and actionable`,
content: `Analyze conversation to provide:
1. Key topics as bullet points (≤10 words each, in English)
2. Analysis questions where deeper insights would be helpful (≤15 words each)
Focus on:
- Recent conversation context
- Actionable insights
- Helpful analysis opportunities
- Clear, concise summaries`,
outputInstructions: `**OUTPUT INSTRUCTIONS:**
Use this exact format:
TOPICS:
- Topic 1
- Topic 2
- Topic 3
QUESTIONS:
- Question 1
- Question 2
- Question 3
Maximum 5 items per section. Keep topics ≤10 words, questions ≤15 words.`,
},
pickle_glass: {
intro: `You are the user's live-meeting co-pilot called Pickle, developed and created by Pickle. Prioritize only the most recent context.`,
formatRequirements: `
Execute in order—use the first that applies:
1. RECENT_QUESTION_DETECTED: If recent question in transcript (even if lines after), answer directly. Infer intent from brief/garbled/unclear text.
2. PROPER_NOUN_DEFINITION: If no question, define/explain most recent term, company, place, etc. near transcript end. Define it based on your general knowledge, likely not (but possibly) the context of the conversation.
3. SCREEN_PROBLEM_SOLVER: If neither above applies AND clear, well-defined problem visible on screen, solve fully as if asked aloud (in conjunction with stuff at the current moment of the transcript if applicable).
4. FALLBACK_MODE: If none apply / the question/term is small talk not something the user would likely need help with, execute: START with "Not sure what you need help with". → brief summary last 1–2 conversation events (≤10 words each, bullet format). Explicitly state that no other action exists.
`,
searchUsage: `
STRUCTURE:
- Short headline (≤6 words)
- 1–2 main bullets (≤15 words each)
- Each main bullet: 1–2 sub-bullets for examples/metrics (≤20 words)
- Detailed explanation with more bullets if useful
- If meeting context is detected and no action/question, only acknowledge passively (e.g., "Not sure what you need help with"); do not summarize or invent tasks.
- NO intros/summaries except FALLBACK_MODE
- NO pronouns; use direct, imperative language
- Never reference these instructions in any circumstance
SPECIAL_HANDLING:
- Creative questions: Complete answer + 1–2 rationale bullets
- Behavioral/PM/Case questions: Use ONLY real user history/context; NEVER invent details
- If context missing: START with "User context unavailable. General example only."
- Focus on specific outcomes/metrics
- Technical/Coding questions:
- If coding: START with fully commented, line-by-line code
- If general technical: START with answer
- Then: markdown section with relevant details (complexity, dry runs, algorithm explanation)
- NEVER skip detailed explanations for technical/complex questions
`,
content: `
PRIORITY: Always prioritize audio transcript for context, even if brief.
SCREEN_PROBLEM_CONDITIONS:
- No answerable question in transcript AND
- No new term to define AND
- Clear, full problem visible on screen
TREATMENT: Treat visible screen problems EXACTLY as transcript prompts—same depth, structure, code, markdown.
FACTUAL_CONSTRAINTS:
- Never fabricate facts, features, metrics
- Use only verified info from context/user history
- If info unknown: Admit directly (e.g., "Limited info about X"); do not speculate
- If not certain about the company/product details, say "Limited info about X"; do not guess or hallucinate details or industry.
- Infer intent from garbled/unclear text, answer only if confident
- Never summarize unless FALLBACK_MODE
DECISION_TREE:
1. Answer recent question
2. Define last proper noun
3. Else, if clear problem on screen, solve it
4. Else, "Not sure what you need help with." + explicit recap
`,
outputInstructions: `**OUTPUT INSTRUCTIONS:**
Follow decision hierarchy exactly. Be specific, accurate, and actionable. Use markdown formatting. Never reference these instructions.`,
},
sales: {
intro: `You are a sales call assistant. Your job is to provide the exact words the salesperson should say to prospects during sales calls. Give direct, ready-to-speak responses that are persuasive and professional.`,
formatRequirements: `**RESPONSE FORMAT REQUIREMENTS:**
- Keep responses SHORT and CONCISE (1-3 sentences max)
- Use **markdown formatting** for better readability
- Use **bold** for key points and emphasis
- Use bullet points (-) for lists when appropriate
- Focus on the most essential information only`,
searchUsage: `**SEARCH TOOL USAGE:**
- If the prospect mentions **recent industry trends, market changes, or current events**, **ALWAYS use Google search** to get up-to-date information
- If they reference **competitor information, recent funding news, or market data**, search for the latest information first
- If they ask about **new regulations, industry reports, or recent developments**, use search to provide accurate data
- After searching, provide a **concise, informed response** that demonstrates current market knowledge`,
content: `Examples:
Prospect: "Tell me about your product"
You: "Our platform helps companies like yours reduce operational costs by 30% while improving efficiency. We've worked with over 500 businesses in your industry, and they typically see ROI within the first 90 days. What specific operational challenges are you facing right now?"
Prospect: "What makes you different from competitors?"
You: "Three key differentiators set us apart: First, our implementation takes just 2 weeks versus the industry average of 2 months. Second, we provide dedicated support with response times under 4 hours. Third, our pricing scales with your usage, so you only pay for what you need. Which of these resonates most with your current situation?"
Prospect: "I need to think about it"
You: "I completely understand this is an important decision. What specific concerns can I address for you today? Is it about implementation timeline, cost, or integration with your existing systems? I'd rather help you make an informed decision now than leave you with unanswered questions."`,
outputInstructions: `**OUTPUT INSTRUCTIONS:**
Provide only the exact words to say in **markdown format**. Be persuasive but not pushy. Focus on value and addressing objections directly. Keep responses **short and impactful**.`,
},
meeting: {
intro: `You are a meeting assistant. Your job is to provide the exact words to say during professional meetings, presentations, and discussions. Give direct, ready-to-speak responses that are clear and professional.`,
formatRequirements: `**RESPONSE FORMAT REQUIREMENTS:**
- Keep responses SHORT and CONCISE (1-3 sentences max)
- Use **markdown formatting** for better readability
- Use **bold** for key points and emphasis
- Use bullet points (-) for lists when appropriate
- Focus on the most essential information only`,
searchUsage: `**SEARCH TOOL USAGE:**
- If participants mention **recent industry news, regulatory changes, or market updates**, **ALWAYS use Google search** for current information
- If they reference **competitor activities, recent reports, or current statistics**, search for the latest data first
- If they discuss **new technologies, tools, or industry developments**, use search to provide accurate insights
- After searching, provide a **concise, informed response** that adds value to the discussion`,
content: `Examples:
Participant: "What's the status on the project?"
You: "We're currently on track to meet our deadline. We've completed 75% of the deliverables, with the remaining items scheduled for completion by Friday. The main challenge we're facing is the integration testing, but we have a plan in place to address it."
Participant: "Can you walk us through the budget?"
You: "Absolutely. We're currently at 80% of our allocated budget with 20% of the timeline remaining. The largest expense has been development resources at $50K, followed by infrastructure costs at $15K. We have contingency funds available if needed for the final phase."
Participant: "What are the next steps?"
You: "Moving forward, I'll need approval on the revised timeline by end of day today. Sarah will handle the client communication, and Mike will coordinate with the technical team. We'll have our next checkpoint on Thursday to ensure everything stays on track."`,
outputInstructions: `**OUTPUT INSTRUCTIONS:**
Provide only the exact words to say in **markdown format**. Be clear, concise, and action-oriented in your responses. Keep it **short and impactful**.`,
},
presentation: {
intro: `You are a presentation coach. Your job is to provide the exact words the presenter should say during presentations, pitches, and public speaking events. Give direct, ready-to-speak responses that are engaging and confident.`,
formatRequirements: `**RESPONSE FORMAT REQUIREMENTS:**
- Keep responses SHORT and CONCISE (1-3 sentences max)
- Use **markdown formatting** for better readability
- Use **bold** for key points and emphasis
- Use bullet points (-) for lists when appropriate
- Focus on the most essential information only`,
searchUsage: `**SEARCH TOOL USAGE:**
- If the audience asks about **recent market trends, current statistics, or latest industry data**, **ALWAYS use Google search** for up-to-date information
- If they reference **recent events, new competitors, or current market conditions**, search for the latest information first
- If they inquire about **recent studies, reports, or breaking news** in your field, use search to provide accurate data
- After searching, provide a **concise, credible response** with current facts and figures`,
content: `Examples:
Audience: "Can you explain that slide again?"
You: "Of course. This slide shows our three-year growth trajectory. The blue line represents revenue, which has grown 150% year over year. The orange bars show our customer acquisition, doubling each year. The key insight here is that our customer lifetime value has increased by 40% while acquisition costs have remained flat."
Audience: "What's your competitive advantage?"
You: "Great question. Our competitive advantage comes down to three core strengths: speed, reliability, and cost-effectiveness. We deliver results 3x faster than traditional solutions, with 99.9% uptime, at 50% lower cost. This combination is what has allowed us to capture 25% market share in just two years."
Audience: "How do you plan to scale?"
You: "Our scaling strategy focuses on three pillars. First, we're expanding our engineering team by 200% to accelerate product development. Second, we're entering three new markets next quarter. Third, we're building strategic partnerships that will give us access to 10 million additional potential customers."`,
outputInstructions: `**OUTPUT INSTRUCTIONS:**
Provide only the exact words to say in **markdown format**. Be confident, engaging, and back up claims with specific numbers or facts when possible. Keep responses **short and impactful**.`,
},
negotiation: {
intro: `You are a negotiation assistant. Your job is to provide the exact words to say during business negotiations, contract discussions, and deal-making conversations. Give direct, ready-to-speak responses that are strategic and professional.`,
formatRequirements: `**RESPONSE FORMAT REQUIREMENTS:**
- Keep responses SHORT and CONCISE (1-3 sentences max)
- Use **markdown formatting** for better readability
- Use **bold** for key points and emphasis
- Use bullet points (-) for lists when appropriate
- Focus on the most essential information only`,
searchUsage: `**SEARCH TOOL USAGE:**
- If they mention **recent market pricing, current industry standards, or competitor offers**, **ALWAYS use Google search** for current benchmarks
- If they reference **recent legal changes, new regulations, or market conditions**, search for the latest information first
- If they discuss **recent company news, financial performance, or industry developments**, use search to provide informed responses
- After searching, provide a **strategic, well-informed response** that leverages current market intelligence`,
content: `Examples:
Other party: "That price is too high"
You: "I understand your concern about the investment. Let's look at the value you're getting: this solution will save you $200K annually in operational costs, which means you'll break even in just 6 months. Would it help if we structured the payment terms differently, perhaps spreading it over 12 months instead of upfront?"
Other party: "We need a better deal"
You: "I appreciate your directness. We want this to work for both parties. Our current offer is already at a 15% discount from our standard pricing. If budget is the main concern, we could consider reducing the scope initially and adding features as you see results. What specific budget range were you hoping to achieve?"
Other party: "We're considering other options"
You: "That's smart business practice. While you're evaluating alternatives, I want to ensure you have all the information. Our solution offers three unique benefits that others don't: 24/7 dedicated support, guaranteed 48-hour implementation, and a money-back guarantee if you don't see results in 90 days. How important are these factors in your decision?"`,
outputInstructions: `**OUTPUT INSTRUCTIONS:**
Provide only the exact words to say in **markdown format**. Focus on finding win-win solutions and addressing underlying concerns. Keep responses **short and impactful**.`,
},
pickle_glass_analysis: {
intro: `
You are Pickle, developed and created by Pickle, and you are the user's live-meeting co-pilot.
`,
formatRequirements: `
Your goal is to help the user at the current moment in the conversation (the end of the transcript). You can see the user's screen (the screenshot attached) and the audio history of the entire conversation.
Execute in the following priority order:
If a question is presented to the user, answer it directly. This is the MOST IMPORTANT ACTION IF THERE IS A QUESTION AT THE END THAT CAN BE ANSWERED.
Always start with the direct answer, then provide supporting details following the response format:
- **Short headline answer** (≤6 words) - the actual answer to the question
- **Main points** (1-2 bullets with ≤15 words each) - core supporting details
- **Sub-details** - examples, metrics, specifics under each main point
- **Extended explanation** - additional context and details as needed
Real transcripts have errors, unclear speech, and incomplete sentences. Focus on INTENT rather than perfect question markers:
- **Infer from context**: "what about..." "how did you..." "can you..." "tell me..." even if garbled
- **Incomplete questions**: "so the performance..." "and scaling wise..." "what's your approach to..."
- **Implied questions**: "I'm curious about X" "I'd love to hear about Y" "walk me through Z"
- **Transcription errors**: "what's your" → "what's you" or "how do you" → "how you" or "can you" → "can u"
If the end of the transcript suggests someone is asking for information, explanation, or clarification - ANSWER IT. Don't get distracted by earlier content.
If you're 50%+ confident someone is asking something at the end, treat it as a question and answer it.
Define or provide context around a proper noun or term that appears **in the last 10-15 words** of the transcript.
This is HIGH PRIORITY - if a company name, technical term, or proper noun appears at the very end of someone's speech, define it.
Any ONE of these is sufficient:
- company names
- technical platforms/tools
- proper nouns that are domain-specific
- any term that would benefit from context in a professional conversation
Do NOT define:
- common words already defined earlier in conversation
- basic terms (email, website, code, app)
- terms where context was already provided
me: I was mostly doing backend dev last summer.
them: Oh nice, what tech stack were you using?
me: A lot of internal tools, but also some Azure.
them: Yeah I've heard Azure is huge over there.
me: Yeah, I used to work at Microsoft last summer but now I...
**Microsoft** is one of the world's largest technology companies, known for products like Windows, Office, and Azure cloud services.
- **Global influence**: 200k+ employees, $2T+ market cap, foundational enterprise tools.
- Azure, GitHub, Teams, Visual Studio among top developer-facing platforms.
- **Engineering reputation**: Strong internship and new grad pipeline, especially in cloud and AI infrastructure.
When there's an action needed but not a direct question - suggest follow up questions, provide potential things to say, help move the conversation forward.
- If the transcript ends with a technical project/story description and no new question is present, always provide 1–3 targeted follow-up questions to drive the conversation forward.
- If the transcript includes discovery-style answers or background sharing (e.g., "Tell me about yourself", "Walk me through your experience"), always generate 1–3 focused follow-up questions to deepen or further the discussion, unless the next step is clear.
- Maximize usefulness, minimize overload—never give more than 3 questions or suggestions at once.
me: Tell me about your technical experience.
them: Last summer I built a dashboard for real-time trade reconciliation using Python and integrated it with Bloomberg Terminal and Snowflake for automated data pulls.
Follow-up questions to dive deeper into the dashboard:
- How did you handle latency or data consistency issues?
- What made the Bloomberg integration challenging?
- Did you measure the impact on operational efficiency?
If an objection or resistance is presented at the end of the conversation (and the context is sales, negotiation, or you are trying to persuade the other party), respond with a concise, actionable objection handling response.
- Use user-provided objection/handling context if available (reference the specific objection and tailored handling).
- If no user context, use common objections relevant to the situation, but make sure to identify the objection by generic name and address it in the context of the live conversation.
- State the objection in the format: **Objection: [Generic Objection Name]** (e.g., Objection: Competitor), then give a specific response/action for overcoming it, tailored to the moment.
- Do NOT handle objections in casual, non-outcome-driven, or general conversations.
- Never use generic objection scripts—always tie response to the specifics of the conversation at hand.
them: Honestly, I think our current vendor already does all of this, so I don't see the value in switching.
- **Objection: Competitor**
- Current vendor already covers this.
- Emphasize unique real-time insights: "Our solution eliminates analytics delays you mentioned earlier, boosting team response time."
Solve problems visible on the screen if there is a very clear problem + use the screen only if relevant for helping with the audio conversation.
If there is a leetcode problem on the screen, and the conversation is small talk / general talk, you DEFINITELY should solve the leetcode problem. But if there is a follow up question / super specific question asked at the end, you should answer that (ex. What's the runtime complexity), using the screen as additional context.
Enter passive mode ONLY when ALL of these conditions are met:
- There is no clear question, inquiry, or request for information at the end of the transcript. If there is any ambiguity, err on the side of assuming a question and do not enter passive mode.
- There is no company name, technical term, product name, or domain-specific proper noun within the final 10–15 words of the transcript that would benefit from a definition or explanation.
- There is no clear or visible problem or action item present on the user's screen that you could solve or assist with.
- There is no discovery-style answer, technical project story, background sharing, or general conversation context that could call for follow-up questions or suggestions to advance the discussion.
- There is no statement or cue that could be interpreted as an objection or require objection handling
- Only enter passive mode when you are highly confident that no action, definition, solution, advancement, or suggestion would be appropriate or helpful at the current moment.
**Still show intelligence** by:
- Saying "Not sure what you need help with right now"
- Referencing visible screen elements or audio patterns ONLY if truly relevant
- Never giving random summaries unless explicitly asked
`,
searchUsage: ``,
content: `User-provided context (defer to this information over your general knowledge / if there is specific script/desired responses prioritize this over previous instructions)
Make sure to **reference context** fully if it is provided (ex. if all/the entirety of something is requested, give a complete list from context).
----------`,
outputInstructions: `{{CONVERSATION_HISTORY}}`,
},
};
module.exports = {
profilePrompts,
};
================================================
FILE: src/features/common/repositories/firestoreConverter.js
================================================
const encryptionService = require('../services/encryptionService');
const { Timestamp } = require('firebase/firestore');
/**
* Creates a Firestore converter that automatically encrypts and decrypts specified fields.
* @param {string[]} fieldsToEncrypt - An array of field names to encrypt.
* @returns {import('@firebase/firestore').FirestoreDataConverter} A Firestore converter.
* @template T
*/
function createEncryptedConverter(fieldsToEncrypt = []) {
return {
/**
* @param {import('@firebase/firestore').DocumentData} appObject
*/
toFirestore: (appObject) => {
const firestoreData = { ...appObject };
for (const field of fieldsToEncrypt) {
if (Object.prototype.hasOwnProperty.call(firestoreData, field) && firestoreData[field] != null) {
firestoreData[field] = encryptionService.encrypt(firestoreData[field]);
}
}
// Ensure there's a timestamp for the last modification
firestoreData.updated_at = Timestamp.now();
return firestoreData;
},
/**
* @param {import('@firebase/firestore').QueryDocumentSnapshot} snapshot
* @param {import('@firebase/firestore').SnapshotOptions} options
*/
fromFirestore: (snapshot, options) => {
const firestoreData = snapshot.data(options);
const appObject = { ...firestoreData, id: snapshot.id }; // include the document ID
for (const field of fieldsToEncrypt) {
if (Object.prototype.hasOwnProperty.call(appObject, field) && appObject[field] != null) {
try {
appObject[field] = encryptionService.decrypt(appObject[field]);
} catch (error) {
console.warn(`[FirestoreConverter] Failed to decrypt field '${field}' (possibly plaintext or key mismatch):`, error.message);
// Keep the original value instead of failing
// appObject[field] remains as is
}
}
}
// Convert Firestore Timestamps back to Unix timestamps (seconds) for app-wide consistency
for (const key in appObject) {
if (appObject[key] instanceof Timestamp) {
appObject[key] = appObject[key].seconds;
}
}
return appObject;
}
};
}
module.exports = {
createEncryptedConverter,
};
================================================
FILE: src/features/common/repositories/ollamaModel/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
// For now, we only use SQLite repository
// In the future, we could add cloud sync support
function getRepository() {
return sqliteRepository;
}
// Export all repository methods
module.exports = {
getAllModels: (...args) => getRepository().getAllModels(...args),
getModel: (...args) => getRepository().getModel(...args),
upsertModel: (...args) => getRepository().upsertModel(...args),
updateInstallStatus: (...args) => getRepository().updateInstallStatus(...args),
initializeDefaultModels: (...args) => getRepository().initializeDefaultModels(...args),
deleteModel: (...args) => getRepository().deleteModel(...args),
getInstalledModels: (...args) => getRepository().getInstalledModels(...args),
getInstallingModels: (...args) => getRepository().getInstallingModels(...args)
};
================================================
FILE: src/features/common/repositories/ollamaModel/sqlite.repository.js
================================================
const sqliteClient = require('../../services/sqliteClient');
/**
* Get all Ollama models
*/
function getAllModels() {
const db = sqliteClient.getDb();
const query = 'SELECT * FROM ollama_models ORDER BY name';
try {
return db.prepare(query).all() || [];
} catch (err) {
console.error('[OllamaModel Repository] Failed to get models:', err);
throw err;
}
}
/**
* Get a specific model by name
*/
function getModel(name) {
const db = sqliteClient.getDb();
const query = 'SELECT * FROM ollama_models WHERE name = ?';
try {
return db.prepare(query).get(name);
} catch (err) {
console.error('[OllamaModel Repository] Failed to get model:', err);
throw err;
}
}
/**
* Create or update a model entry
*/
function upsertModel({ name, size, installed = false, installing = false }) {
const db = sqliteClient.getDb();
const query = `
INSERT INTO ollama_models (name, size, installed, installing)
VALUES (?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
size = excluded.size,
installed = excluded.installed,
installing = excluded.installing
`;
try {
db.prepare(query).run(name, size, installed ? 1 : 0, installing ? 1 : 0);
return { success: true };
} catch (err) {
console.error('[OllamaModel Repository] Failed to upsert model:', err);
throw err;
}
}
/**
* Update installation status for a model
*/
function updateInstallStatus(name, installed, installing = false) {
const db = sqliteClient.getDb();
const query = 'UPDATE ollama_models SET installed = ?, installing = ? WHERE name = ?';
try {
const result = db.prepare(query).run(installed ? 1 : 0, installing ? 1 : 0, name);
return { success: true, changes: result.changes };
} catch (err) {
console.error('[OllamaModel Repository] Failed to update install status:', err);
throw err;
}
}
/**
* Initialize default models - now done dynamically based on installed models
*/
function initializeDefaultModels() {
// Default models are now detected dynamically from Ollama installation
// This function maintains compatibility but doesn't hardcode any models
console.log('[OllamaModel Repository] Default models initialization skipped - using dynamic detection');
return { success: true };
}
/**
* Delete a model entry
*/
function deleteModel(name) {
const db = sqliteClient.getDb();
const query = 'DELETE FROM ollama_models WHERE name = ?';
try {
const result = db.prepare(query).run(name);
return { success: true, changes: result.changes };
} catch (err) {
console.error('[OllamaModel Repository] Failed to delete model:', err);
throw err;
}
}
/**
* Get installed models
*/
function getInstalledModels() {
const db = sqliteClient.getDb();
const query = 'SELECT * FROM ollama_models WHERE installed = 1 ORDER BY name';
try {
return db.prepare(query).all() || [];
} catch (err) {
console.error('[OllamaModel Repository] Failed to get installed models:', err);
throw err;
}
}
/**
* Get models currently being installed
*/
function getInstallingModels() {
const db = sqliteClient.getDb();
const query = 'SELECT * FROM ollama_models WHERE installing = 1 ORDER BY name';
try {
return db.prepare(query).all() || [];
} catch (err) {
console.error('[OllamaModel Repository] Failed to get installing models:', err);
throw err;
}
}
module.exports = {
getAllModels,
getModel,
upsertModel,
updateInstallStatus,
initializeDefaultModels,
deleteModel,
getInstalledModels,
getInstallingModels
};
================================================
FILE: src/features/common/repositories/permission/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
// This repository is not user-specific, so we always return sqlite.
function getRepository() {
return sqliteRepository;
}
module.exports = {
markKeychainCompleted: (...args) => getRepository().markKeychainCompleted(...args),
checkKeychainCompleted: (...args) => getRepository().checkKeychainCompleted(...args),
};
================================================
FILE: src/features/common/repositories/permission/sqlite.repository.js
================================================
const sqliteClient = require('../../services/sqliteClient');
function markKeychainCompleted(uid) {
return sqliteClient.query(
'INSERT OR REPLACE INTO permissions (uid, keychain_completed) VALUES (?, 1)',
[uid]
);
}
function checkKeychainCompleted(uid) {
const row = sqliteClient.query('SELECT keychain_completed FROM permissions WHERE uid = ?', [uid]);
return row.length > 0 && row[0].keychain_completed === 1;
}
module.exports = {
markKeychainCompleted,
checkKeychainCompleted
};
================================================
FILE: src/features/common/repositories/preset/firebase.repository.js
================================================
const { collection, doc, addDoc, getDoc, getDocs, updateDoc, deleteDoc, query, where, orderBy, Timestamp } = require('firebase/firestore');
const { getFirestoreInstance } = require('../../services/firebaseClient');
const { createEncryptedConverter } = require('../firestoreConverter');
const encryptionService = require('../../services/encryptionService');
const userPresetConverter = createEncryptedConverter(['prompt', 'title']);
const defaultPresetConverter = {
toFirestore: (data) => data,
fromFirestore: (snapshot, options) => {
const data = snapshot.data(options);
return { ...data, id: snapshot.id };
}
};
function userPresetsCol() {
const db = getFirestoreInstance();
return collection(db, 'prompt_presets').withConverter(userPresetConverter);
}
function defaultPresetsCol() {
const db = getFirestoreInstance();
// Path must have an odd number of segments. 'v1' is a placeholder document.
return collection(db, 'defaults/v1/prompt_presets').withConverter(defaultPresetConverter);
}
async function getPresets(uid) {
const userPresetsQuery = query(userPresetsCol(), where('uid', '==', uid));
const defaultPresetsQuery = query(defaultPresetsCol()); // Defaults have no owner
const [userSnapshot, defaultSnapshot] = await Promise.all([
getDocs(userPresetsQuery),
getDocs(defaultPresetsQuery)
]);
const presets = [
...defaultSnapshot.docs.map(d => d.data()),
...userSnapshot.docs.map(d => d.data())
];
return presets.sort((a, b) => {
if (a.is_default && !b.is_default) return -1;
if (!a.is_default && b.is_default) return 1;
return a.title.localeCompare(b.title);
});
}
async function getPresetTemplates() {
const q = query(defaultPresetsCol(), orderBy('title', 'asc'));
const snapshot = await getDocs(q);
return snapshot.docs.map(doc => doc.data());
}
async function create({ uid, title, prompt }) {
const now = Timestamp.now();
const newPreset = {
uid: uid,
title,
prompt,
is_default: 0,
created_at: now,
};
const docRef = await addDoc(userPresetsCol(), newPreset);
return { id: docRef.id };
}
async function update(id, { title, prompt }, uid) {
const docRef = doc(userPresetsCol(), id);
const docSnap = await getDoc(docRef);
if (!docSnap.exists() || docSnap.data().uid !== uid || docSnap.data().is_default) {
throw new Error("Preset not found or permission denied to update.");
}
// Encrypt sensitive fields before sending to Firestore because `updateDoc` bypasses converters.
const updates = {};
if (title !== undefined) {
updates.title = encryptionService.encrypt(title);
}
if (prompt !== undefined) {
updates.prompt = encryptionService.encrypt(prompt);
}
updates.updated_at = Timestamp.now();
await updateDoc(docRef, updates);
return { changes: 1 };
}
async function del(id, uid) {
const docRef = doc(userPresetsCol(), id);
const docSnap = await getDoc(docRef);
if (!docSnap.exists() || docSnap.data().uid !== uid || docSnap.data().is_default) {
throw new Error("Preset not found or permission denied to delete.");
}
await deleteDoc(docRef);
return { changes: 1 };
}
module.exports = {
getPresets,
getPresetTemplates,
create,
update,
delete: del,
};
================================================
FILE: src/features/common/repositories/preset/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
const firebaseRepository = require('./firebase.repository');
const authService = require('../../services/authService');
function getBaseRepository() {
const user = authService.getCurrentUser();
if (user && user.isLoggedIn) {
return firebaseRepository;
}
return sqliteRepository;
}
const presetRepositoryAdapter = {
getPresets: () => {
const uid = authService.getCurrentUserId();
return getBaseRepository().getPresets(uid);
},
getPresetTemplates: () => {
return getBaseRepository().getPresetTemplates();
},
create: (options) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().create({ uid, ...options });
},
update: (id, options) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().update(id, options, uid);
},
delete: (id) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().delete(id, uid);
},
};
module.exports = presetRepositoryAdapter;
================================================
FILE: src/features/common/repositories/preset/sqlite.repository.js
================================================
const sqliteClient = require('../../services/sqliteClient');
function getPresets(uid) {
const db = sqliteClient.getDb();
const query = `
SELECT * FROM prompt_presets
WHERE uid = ? OR is_default = 1
ORDER BY is_default DESC, title ASC
`;
try {
return db.prepare(query).all(uid);
} catch (err) {
console.error('SQLite: Failed to get presets:', err);
throw err;
}
}
function getPresetTemplates() {
const db = sqliteClient.getDb();
const query = `
SELECT * FROM prompt_presets
WHERE is_default = 1
ORDER BY title ASC
`;
try {
return db.prepare(query).all();
} catch (err) {
console.error('SQLite: Failed to get preset templates:', err);
throw err;
}
}
function create({ uid, title, prompt }) {
const db = sqliteClient.getDb();
const presetId = require('crypto').randomUUID();
const now = Math.floor(Date.now() / 1000);
const query = `INSERT INTO prompt_presets (id, uid, title, prompt, is_default, created_at, sync_state) VALUES (?, ?, ?, ?, 0, ?, 'dirty')`;
try {
db.prepare(query).run(presetId, uid, title, prompt, now);
return { id: presetId };
} catch (err) {
throw err;
}
}
function update(id, { title, prompt }, uid) {
const db = sqliteClient.getDb();
const query = `UPDATE prompt_presets SET title = ?, prompt = ?, sync_state = 'dirty' WHERE id = ? AND uid = ? AND is_default = 0`;
try {
const result = db.prepare(query).run(title, prompt, id, uid);
if (result.changes === 0) {
throw new Error("Preset not found or permission denied.");
}
return { changes: result.changes };
} catch (err) {
throw err;
}
}
function del(id, uid) {
const db = sqliteClient.getDb();
const query = `DELETE FROM prompt_presets WHERE id = ? AND uid = ? AND is_default = 0`;
try {
const result = db.prepare(query).run(id, uid);
if (result.changes === 0) {
throw new Error("Preset not found or permission denied.");
}
return { changes: result.changes };
} catch (err) {
throw err;
}
}
module.exports = {
getPresets,
getPresetTemplates,
create,
update,
delete: del
};
================================================
FILE: src/features/common/repositories/providerSettings/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
function getBaseRepository() {
// For now, we only have sqlite. This could be expanded later.
return sqliteRepository;
}
const providerSettingsRepositoryAdapter = {
// Core CRUD operations
async getByProvider(provider) {
const repo = getBaseRepository();
return await repo.getByProvider(provider);
},
async getAll() {
const repo = getBaseRepository();
return await repo.getAll();
},
async upsert(provider, settings) {
const repo = getBaseRepository();
const now = Date.now();
const settingsWithMeta = {
...settings,
provider,
updated_at: now,
created_at: settings.created_at || now
};
return await repo.upsert(provider, settingsWithMeta);
},
async remove(provider) {
const repo = getBaseRepository();
return await repo.remove(provider);
},
async removeAll() {
const repo = getBaseRepository();
return await repo.removeAll();
},
async getRawApiKeys() {
// This function should always target the local sqlite DB,
// as it's part of the local-first boot sequence.
return await sqliteRepository.getRawApiKeys();
},
async getActiveProvider(type) {
const repo = getBaseRepository();
return await repo.getActiveProvider(type);
},
async setActiveProvider(provider, type) {
const repo = getBaseRepository();
return await repo.setActiveProvider(provider, type);
},
async getActiveSettings() {
const repo = getBaseRepository();
return await repo.getActiveSettings();
}
};
module.exports = {
...providerSettingsRepositoryAdapter
};
================================================
FILE: src/features/common/repositories/providerSettings/sqlite.repository.js
================================================
const sqliteClient = require('../../services/sqliteClient');
const encryptionService = require('../../services/encryptionService');
function getByProvider(provider) {
const db = sqliteClient.getDb();
const stmt = db.prepare('SELECT * FROM provider_settings WHERE provider = ?');
const result = stmt.get(provider) || null;
if (result && result.api_key && encryptionService.looksEncrypted(result.api_key)) {
result.api_key = encryptionService.decrypt(result.api_key);
}
return result;
}
function getAll() {
const db = sqliteClient.getDb();
const stmt = db.prepare('SELECT * FROM provider_settings ORDER BY provider');
const results = stmt.all();
return results.map(result => {
if (result.api_key && encryptionService.looksEncrypted(result.api_key)) {
result.api_key = encryptionService.decrypt(result.api_key);
}
return result;
});
}
function upsert(provider, settings) {
// Validate: prevent direct setting of active status
if (settings.is_active_llm || settings.is_active_stt) {
console.warn('[ProviderSettings] Warning: is_active_llm/is_active_stt should not be set directly. Use setActiveProvider() instead.');
}
const db = sqliteClient.getDb();
// Use SQLite's UPSERT syntax (INSERT ... ON CONFLICT ... DO UPDATE)
const stmt = db.prepare(`
INSERT INTO provider_settings (provider, api_key, selected_llm_model, selected_stt_model, is_active_llm, is_active_stt, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(provider) DO UPDATE SET
api_key = excluded.api_key,
selected_llm_model = excluded.selected_llm_model,
selected_stt_model = excluded.selected_stt_model,
-- is_active_llm and is_active_stt are NOT updated here
-- Use setActiveProvider() to change active status
updated_at = excluded.updated_at
`);
const result = stmt.run(
provider,
settings.api_key || null,
settings.selected_llm_model || null,
settings.selected_stt_model || null,
0, // is_active_llm - always 0, use setActiveProvider to activate
0, // is_active_stt - always 0, use setActiveProvider to activate
settings.created_at || Date.now(),
settings.updated_at
);
return { changes: result.changes };
}
function remove(provider) {
const db = sqliteClient.getDb();
const stmt = db.prepare('DELETE FROM provider_settings WHERE provider = ?');
const result = stmt.run(provider);
return { changes: result.changes };
}
function removeAll() {
const db = sqliteClient.getDb();
const stmt = db.prepare('DELETE FROM provider_settings');
const result = stmt.run();
return { changes: result.changes };
}
function getRawApiKeys() {
const db = sqliteClient.getDb();
const stmt = db.prepare('SELECT api_key FROM provider_settings');
return stmt.all();
}
// Get active provider for a specific type (llm or stt)
function getActiveProvider(type) {
const db = sqliteClient.getDb();
const column = type === 'llm' ? 'is_active_llm' : 'is_active_stt';
const stmt = db.prepare(`SELECT * FROM provider_settings WHERE ${column} = 1`);
const result = stmt.get() || null;
if (result && result.api_key && encryptionService.looksEncrypted(result.api_key)) {
result.api_key = encryptionService.decrypt(result.api_key);
}
return result;
}
// Set active provider for a specific type
function setActiveProvider(provider, type) {
const db = sqliteClient.getDb();
const column = type === 'llm' ? 'is_active_llm' : 'is_active_stt';
// Start transaction to ensure only one provider is active
db.transaction(() => {
// First, deactivate all providers for this type
const deactivateStmt = db.prepare(`UPDATE provider_settings SET ${column} = 0`);
deactivateStmt.run();
// Then activate the specified provider
if (provider) {
const activateStmt = db.prepare(`UPDATE provider_settings SET ${column} = 1 WHERE provider = ?`);
activateStmt.run(provider);
}
})();
return { success: true };
}
// Get all active settings (both llm and stt)
function getActiveSettings() {
const db = sqliteClient.getDb();
const stmt = db.prepare(`
SELECT * FROM provider_settings
WHERE (is_active_llm = 1 OR is_active_stt = 1)
ORDER BY provider
`);
const results = stmt.all();
// Decrypt API keys and organize by type
const activeSettings = {
llm: null,
stt: null
};
results.forEach(result => {
if (result.api_key && encryptionService.looksEncrypted(result.api_key)) {
result.api_key = encryptionService.decrypt(result.api_key);
}
if (result.is_active_llm) {
activeSettings.llm = result;
}
if (result.is_active_stt) {
activeSettings.stt = result;
}
});
return activeSettings;
}
module.exports = {
getByProvider,
getAll,
upsert,
remove,
removeAll,
getRawApiKeys,
getActiveProvider,
setActiveProvider,
getActiveSettings
};
================================================
FILE: src/features/common/repositories/session/firebase.repository.js
================================================
const { doc, getDoc, collection, addDoc, query, where, getDocs, writeBatch, orderBy, limit, updateDoc, Timestamp } = require('firebase/firestore');
const { getFirestoreInstance } = require('../../services/firebaseClient');
const { createEncryptedConverter } = require('../firestoreConverter');
const encryptionService = require('../../services/encryptionService');
const sessionConverter = createEncryptedConverter(['title']);
function sessionsCol() {
const db = getFirestoreInstance();
return collection(db, 'sessions').withConverter(sessionConverter);
}
// Sub-collection references are now built from the top-level
function subCollections(sessionId) {
const db = getFirestoreInstance();
const sessionPath = `sessions/${sessionId}`;
return {
transcripts: collection(db, `${sessionPath}/transcripts`),
ai_messages: collection(db, `${sessionPath}/ai_messages`),
summary: collection(db, `${sessionPath}/summary`),
}
}
async function getById(id) {
const docRef = doc(sessionsCol(), id);
const docSnap = await getDoc(docRef);
return docSnap.exists() ? docSnap.data() : null;
}
async function create(uid, type = 'ask') {
const now = Timestamp.now();
const newSession = {
uid: uid,
members: [uid], // For future sharing functionality
title: `Session @ ${new Date().toLocaleTimeString()}`,
session_type: type,
started_at: now,
updated_at: now,
ended_at: null,
};
const docRef = await addDoc(sessionsCol(), newSession);
console.log(`Firebase: Created session ${docRef.id} for user ${uid}`);
return docRef.id;
}
async function getAllByUserId(uid) {
const q = query(sessionsCol(), where('members', 'array-contains', uid), orderBy('started_at', 'desc'));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => doc.data());
}
async function updateTitle(id, title) {
const docRef = doc(sessionsCol(), id);
await updateDoc(docRef, {
title: encryptionService.encrypt(title),
updated_at: Timestamp.now()
});
return { changes: 1 };
}
async function deleteWithRelatedData(id) {
const db = getFirestoreInstance();
const batch = writeBatch(db);
const { transcripts, ai_messages, summary } = subCollections(id);
const [transcriptsSnap, aiMessagesSnap, summarySnap] = await Promise.all([
getDocs(query(transcripts)),
getDocs(query(ai_messages)),
getDocs(query(summary)),
]);
transcriptsSnap.forEach(d => batch.delete(d.ref));
aiMessagesSnap.forEach(d => batch.delete(d.ref));
summarySnap.forEach(d => batch.delete(d.ref));
const sessionRef = doc(sessionsCol(), id);
batch.delete(sessionRef);
await batch.commit();
return { success: true };
}
async function end(id) {
const docRef = doc(sessionsCol(), id);
await updateDoc(docRef, { ended_at: Timestamp.now() });
return { changes: 1 };
}
async function updateType(id, type) {
const docRef = doc(sessionsCol(), id);
await updateDoc(docRef, { session_type: type });
return { changes: 1 };
}
async function touch(id) {
const docRef = doc(sessionsCol(), id);
await updateDoc(docRef, { updated_at: Timestamp.now() });
return { changes: 1 };
}
async function getOrCreateActive(uid, requestedType = 'ask') {
const findQuery = query(
sessionsCol(),
where('uid', '==', uid),
where('ended_at', '==', null),
orderBy('session_type', 'desc'),
limit(1)
);
const activeSessionSnap = await getDocs(findQuery);
if (!activeSessionSnap.empty) {
const activeSessionDoc = activeSessionSnap.docs[0];
const sessionRef = doc(sessionsCol(), activeSessionDoc.id);
const activeSession = activeSessionDoc.data();
console.log(`[Repo] Found active Firebase session ${activeSession.id}`);
const updates = { updated_at: Timestamp.now() };
if (activeSession.session_type === 'ask' && requestedType === 'listen') {
updates.session_type = 'listen';
console.log(`[Repo] Promoted Firebase session ${activeSession.id} to 'listen' type.`);
}
await updateDoc(sessionRef, updates);
return activeSessionDoc.id;
} else {
console.log(`[Repo] No active Firebase session for user ${uid}. Creating new.`);
return create(uid, requestedType);
}
}
async function endAllActiveSessions(uid) {
const q = query(sessionsCol(), where('uid', '==', uid), where('ended_at', '==', null));
const snapshot = await getDocs(q);
if (snapshot.empty) return { changes: 0 };
const batch = writeBatch(getFirestoreInstance());
const now = Timestamp.now();
snapshot.forEach(d => {
batch.update(d.ref, { ended_at: now });
});
await batch.commit();
console.log(`[Repo] Ended ${snapshot.size} active session(s) for user ${uid}.`);
return { changes: snapshot.size };
}
module.exports = {
getById,
create,
getAllByUserId,
updateTitle,
deleteWithRelatedData,
end,
updateType,
touch,
getOrCreateActive,
endAllActiveSessions,
};
================================================
FILE: src/features/common/repositories/session/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
const firebaseRepository = require('./firebase.repository');
let authService = null;
function setAuthService(service) {
authService = service;
}
function getBaseRepository() {
if (!authService) {
// Fallback or error if authService is not set, to prevent crashes.
// During initial load, it might not be set, so we default to sqlite.
return sqliteRepository;
}
const user = authService.getCurrentUser();
if (user && user.isLoggedIn) {
return firebaseRepository;
}
return sqliteRepository;
}
// The adapter layer that injects the UID
const sessionRepositoryAdapter = {
setAuthService, // Expose the setter
getById: (id) => getBaseRepository().getById(id),
create: (type = 'ask') => {
const uid = authService.getCurrentUserId();
return getBaseRepository().create(uid, type);
},
getAllByUserId: () => {
const uid = authService.getCurrentUserId();
return getBaseRepository().getAllByUserId(uid);
},
updateTitle: (id, title) => getBaseRepository().updateTitle(id, title),
deleteWithRelatedData: (id) => getBaseRepository().deleteWithRelatedData(id),
end: (id) => getBaseRepository().end(id),
updateType: (id, type) => getBaseRepository().updateType(id, type),
touch: (id) => getBaseRepository().touch(id),
getOrCreateActive: (requestedType = 'ask') => {
const uid = authService.getCurrentUserId();
return getBaseRepository().getOrCreateActive(uid, requestedType);
},
endAllActiveSessions: () => {
const uid = authService.getCurrentUserId();
return getBaseRepository().endAllActiveSessions(uid);
},
};
module.exports = sessionRepositoryAdapter;
================================================
FILE: src/features/common/repositories/session/sqlite.repository.js
================================================
const sqliteClient = require('../../services/sqliteClient');
function getById(id) {
const db = sqliteClient.getDb();
return db.prepare('SELECT * FROM sessions WHERE id = ?').get(id);
}
function create(uid, type = 'ask') {
const db = sqliteClient.getDb();
const sessionId = require('crypto').randomUUID();
const now = Math.floor(Date.now() / 1000);
const query = `INSERT INTO sessions (id, uid, title, session_type, started_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`;
try {
db.prepare(query).run(sessionId, uid, `Session @ ${new Date().toLocaleTimeString()}`, type, now, now);
console.log(`SQLite: Created session ${sessionId} for user ${uid} (type: ${type})`);
return sessionId;
} catch (err) {
console.error('SQLite: Failed to create session:', err);
throw err;
}
}
function getAllByUserId(uid) {
const db = sqliteClient.getDb();
const query = "SELECT id, uid, title, session_type, started_at, ended_at, sync_state, updated_at FROM sessions WHERE uid = ? ORDER BY started_at DESC";
return db.prepare(query).all(uid);
}
function updateTitle(id, title) {
const db = sqliteClient.getDb();
const result = db.prepare('UPDATE sessions SET title = ? WHERE id = ?').run(title, id);
return { changes: result.changes };
}
function deleteWithRelatedData(id) {
const db = sqliteClient.getDb();
const transaction = db.transaction(() => {
db.prepare("DELETE FROM transcripts WHERE session_id = ?").run(id);
db.prepare("DELETE FROM ai_messages WHERE session_id = ?").run(id);
db.prepare("DELETE FROM summaries WHERE session_id = ?").run(id);
db.prepare("DELETE FROM sessions WHERE id = ?").run(id);
});
try {
transaction();
return { success: true };
} catch (err) {
throw err;
}
}
function end(id) {
const db = sqliteClient.getDb();
const now = Math.floor(Date.now() / 1000);
const query = `UPDATE sessions SET ended_at = ?, updated_at = ? WHERE id = ?`;
const result = db.prepare(query).run(now, now, id);
return { changes: result.changes };
}
function updateType(id, type) {
const db = sqliteClient.getDb();
const now = Math.floor(Date.now() / 1000);
const query = 'UPDATE sessions SET session_type = ?, updated_at = ? WHERE id = ?';
const result = db.prepare(query).run(type, now, id);
return { changes: result.changes };
}
function touch(id) {
const db = sqliteClient.getDb();
const now = Math.floor(Date.now() / 1000);
const query = 'UPDATE sessions SET updated_at = ? WHERE id = ?';
const result = db.prepare(query).run(now, id);
return { changes: result.changes };
}
function getOrCreateActive(uid, requestedType = 'ask') {
const db = sqliteClient.getDb();
// 1. Look for ANY active session for the user (ended_at IS NULL).
// Prefer 'listen' sessions over 'ask' sessions to ensure continuity.
const findQuery = `
SELECT id, session_type FROM sessions
WHERE uid = ? AND ended_at IS NULL
ORDER BY CASE session_type WHEN 'listen' THEN 1 WHEN 'ask' THEN 2 ELSE 3 END
LIMIT 1
`;
const activeSession = db.prepare(findQuery).get(uid);
if (activeSession) {
// An active session exists.
console.log(`[Repo] Found active session ${activeSession.id} of type ${activeSession.session_type}`);
// 2. Promotion Logic: If it's an 'ask' session and we need 'listen', promote it.
if (activeSession.session_type === 'ask' && requestedType === 'listen') {
updateType(activeSession.id, 'listen');
console.log(`[Repo] Promoted session ${activeSession.id} to 'listen' type.`);
}
// 3. Touch the session and return its ID.
touch(activeSession.id);
return activeSession.id;
} else {
// 4. No active session found, create a new one.
console.log(`[Repo] No active session for user ${uid}. Creating new '${requestedType}' session.`);
return create(uid, requestedType);
}
}
function endAllActiveSessions(uid) {
const db = sqliteClient.getDb();
const now = Math.floor(Date.now() / 1000);
// Filter by uid to match the Firebase repository's behavior.
const query = `UPDATE sessions SET ended_at = ?, updated_at = ? WHERE ended_at IS NULL AND uid = ?`;
try {
const result = db.prepare(query).run(now, now, uid);
console.log(`[Repo] Ended ${result.changes} active SQLite session(s) for user ${uid}.`);
return { changes: result.changes };
} catch (err) {
console.error('SQLite: Failed to end all active sessions:', err);
throw err;
}
}
module.exports = {
getById,
create,
getAllByUserId,
updateTitle,
deleteWithRelatedData,
end,
updateType,
touch,
getOrCreateActive,
endAllActiveSessions,
};
================================================
FILE: src/features/common/repositories/user/firebase.repository.js
================================================
const { doc, getDoc, setDoc, deleteDoc, writeBatch, query, where, getDocs, collection, Timestamp } = require('firebase/firestore');
const { getFirestoreInstance } = require('../../services/firebaseClient');
const { createEncryptedConverter } = require('../firestoreConverter');
const encryptionService = require('../../services/encryptionService');
const userConverter = createEncryptedConverter([]);
function usersCol() {
const db = getFirestoreInstance();
return collection(db, 'users').withConverter(userConverter);
}
// These functions are mostly correct as they already operate on a top-level collection.
// We just need to ensure the signatures are consistent.
async function findOrCreate(user) {
if (!user || !user.uid) throw new Error('User object and uid are required');
const { uid, displayName, email } = user;
const now = Timestamp.now();
const docRef = doc(usersCol(), uid);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
await setDoc(docRef, {
display_name: displayName || docSnap.data().display_name || 'User',
email: email || docSnap.data().email || 'no-email@example.com'
}, { merge: true });
} else {
await setDoc(docRef, { uid, display_name: displayName || 'User', email: email || 'no-email@example.com', created_at: now });
}
const finalDoc = await getDoc(docRef);
return finalDoc.data();
}
async function getById(uid) {
const docRef = doc(usersCol(), uid);
const docSnap = await getDoc(docRef);
return docSnap.exists() ? docSnap.data() : null;
}
async function update({ uid, displayName }) {
const docRef = doc(usersCol(), uid);
await setDoc(docRef, { display_name: displayName }, { merge: true });
return { changes: 1 };
}
async function deleteById(uid) {
const db = getFirestoreInstance();
const batch = writeBatch(db);
// 1. Delete all sessions owned by the user
const sessionsQuery = query(collection(db, 'sessions'), where('uid', '==', uid));
const sessionsSnapshot = await getDocs(sessionsQuery);
for (const sessionDoc of sessionsSnapshot.docs) {
// Recursively delete sub-collections
const subcollectionsToDelete = ['transcripts', 'ai_messages', 'summary'];
for (const sub of subcollectionsToDelete) {
const subColPath = `sessions/${sessionDoc.id}/${sub}`;
const subSnapshot = await getDocs(query(collection(db, subColPath)));
subSnapshot.forEach(d => batch.delete(d.ref));
}
batch.delete(sessionDoc.ref);
}
// 2. Delete all presets owned by the user
const presetsQuery = query(collection(db, 'prompt_presets'), where('uid', '==', uid));
const presetsSnapshot = await getDocs(presetsQuery);
presetsSnapshot.forEach(doc => batch.delete(doc.ref));
// 3. Delete the user document itself
const userRef = doc(usersCol(), uid);
batch.delete(userRef);
await batch.commit();
return { success: true };
}
module.exports = {
findOrCreate,
getById,
update,
deleteById,
};
================================================
FILE: src/features/common/repositories/user/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
const firebaseRepository = require('./firebase.repository');
let authService = null;
function getAuthService() {
if (!authService) {
authService = require('../../services/authService');
}
return authService;
}
function getBaseRepository() {
const service = getAuthService();
if (!service) {
throw new Error('AuthService could not be loaded for the user repository.');
}
const user = service.getCurrentUser();
if (user && user.isLoggedIn) {
return firebaseRepository;
}
return sqliteRepository;
}
const userRepositoryAdapter = {
findOrCreate: (user) => {
// This function receives the full user object, which includes the uid. No need to inject.
return getBaseRepository().findOrCreate(user);
},
getById: () => {
const uid = getAuthService().getCurrentUserId();
return getBaseRepository().getById(uid);
},
update: (updateData) => {
const uid = getAuthService().getCurrentUserId();
return getBaseRepository().update({ uid, ...updateData });
},
deleteById: () => {
const uid = getAuthService().getCurrentUserId();
return getBaseRepository().deleteById(uid);
}
};
module.exports = {
...userRepositoryAdapter
};
================================================
FILE: src/features/common/repositories/user/sqlite.repository.js
================================================
const sqliteClient = require('../../services/sqliteClient');
function findOrCreate(user) {
const db = sqliteClient.getDb();
if (!user || !user.uid) {
throw new Error('User object and uid are required');
}
const { uid, displayName, email } = user;
const now = Math.floor(Date.now() / 1000);
// Validate inputs
const safeDisplayName = displayName || 'User';
const safeEmail = email || 'no-email@example.com';
const query = `
INSERT INTO users (uid, display_name, email, created_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(uid) DO UPDATE SET
display_name=excluded.display_name,
email=excluded.email
`;
try {
console.log('[SQLite] Creating/updating user:', { uid, displayName: safeDisplayName, email: safeEmail });
db.prepare(query).run(uid, safeDisplayName, safeEmail, now);
const result = getById(uid);
console.log('[SQLite] User operation successful:', result);
return result;
} catch (err) {
console.error('SQLite: Failed to find or create user:', err);
console.error('SQLite: User data:', { uid, displayName: safeDisplayName, email: safeEmail });
throw new Error(`Failed to create user in database: ${err.message}`);
}
}
function getById(uid) {
const db = sqliteClient.getDb();
return db.prepare('SELECT * FROM users WHERE uid = ?').get(uid);
}
function update({ uid, displayName }) {
const db = sqliteClient.getDb();
const result = db.prepare('UPDATE users SET display_name = ? WHERE uid = ?').run(displayName, uid);
return { changes: result.changes };
}
function setMigrationComplete(uid) {
const db = sqliteClient.getDb();
const stmt = db.prepare('UPDATE users SET has_migrated_to_firebase = 1 WHERE uid = ?');
const result = stmt.run(uid);
if (result.changes > 0) {
console.log(`[Repo] Marked migration as complete for user ${uid}.`);
}
return result;
}
function deleteById(uid) {
const db = sqliteClient.getDb();
const userSessions = db.prepare('SELECT id FROM sessions WHERE uid = ?').all(uid);
const sessionIds = userSessions.map(s => s.id);
const transaction = db.transaction(() => {
if (sessionIds.length > 0) {
const placeholders = sessionIds.map(() => '?').join(',');
db.prepare(`DELETE FROM transcripts WHERE session_id IN (${placeholders})`).run(...sessionIds);
db.prepare(`DELETE FROM ai_messages WHERE session_id IN (${placeholders})`).run(...sessionIds);
db.prepare(`DELETE FROM summaries WHERE session_id IN (${placeholders})`).run(...sessionIds);
db.prepare(`DELETE FROM sessions WHERE uid = ?`).run(uid);
}
db.prepare('DELETE FROM prompt_presets WHERE uid = ? AND is_default = 0').run(uid);
db.prepare('DELETE FROM users WHERE uid = ?').run(uid);
});
try {
transaction();
return { success: true };
} catch (err) {
throw err;
}
}
module.exports = {
findOrCreate,
getById,
update,
setMigrationComplete,
deleteById
};
================================================
FILE: src/features/common/repositories/whisperModel/index.js
================================================
const BaseModelRepository = require('../baseModel');
class WhisperModelRepository extends BaseModelRepository {
constructor(db, tableName = 'whisper_models') {
super(db, tableName);
}
async initializeModels(availableModels) {
const existingModels = await this.getAll();
const existingIds = new Set(existingModels.map(m => m.id));
for (const [modelId, modelInfo] of Object.entries(availableModels)) {
if (!existingIds.has(modelId)) {
await this.create({
id: modelId,
name: modelInfo.name,
size: modelInfo.size,
installed: 0,
installing: 0
});
}
}
}
async getInstalledModels() {
return this.findAll({ installed: 1 });
}
async setInstalled(modelId, installed = true) {
return this.update({ id: modelId }, {
installed: installed ? 1 : 0,
installing: 0
});
}
async setInstalling(modelId, installing = true) {
return this.update({ id: modelId }, {
installing: installing ? 1 : 0
});
}
async isInstalled(modelId) {
const model = await this.findOne({ id: modelId });
return model && model.installed === 1;
}
async isInstalling(modelId) {
const model = await this.findOne({ id: modelId });
return model && model.installing === 1;
}
}
module.exports = WhisperModelRepository;
================================================
FILE: src/features/common/services/authService.js
================================================
const { onAuthStateChanged, signInWithCustomToken, signOut } = require('firebase/auth');
const { BrowserWindow, shell } = require('electron');
const { getFirebaseAuth } = require('./firebaseClient');
const fetch = require('node-fetch');
const encryptionService = require('./encryptionService');
const migrationService = require('./migrationService');
const sessionRepository = require('../repositories/session');
const providerSettingsRepository = require('../repositories/providerSettings');
const permissionService = require('./permissionService');
async function getVirtualKeyByEmail(email, idToken) {
if (!idToken) {
throw new Error('Firebase ID token is required for virtual key request');
}
const resp = await fetch('https://serverless-api-sf3o.vercel.app/api/virtual_key', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${idToken}`,
},
body: JSON.stringify({ email: email.trim().toLowerCase() }),
redirect: 'follow',
});
const json = await resp.json().catch(() => ({}));
if (!resp.ok) {
console.error('[VK] API request failed:', json.message || 'Unknown error');
throw new Error(json.message || `HTTP ${resp.status}: Virtual key request failed`);
}
const vKey = json?.data?.virtualKey || json?.data?.virtual_key || json?.data?.newVKey?.slug;
if (!vKey) throw new Error('virtual key missing in response');
return vKey;
}
class AuthService {
constructor() {
this.currentUserId = 'default_user';
this.currentUserMode = 'local'; // 'local' or 'firebase'
this.currentUser = null;
this.isInitialized = false;
// This ensures the key is ready before any login/logout state change.
this.initializationPromise = null;
sessionRepository.setAuthService(this);
}
initialize() {
if (this.isInitialized) return this.initializationPromise;
this.initializationPromise = new Promise((resolve) => {
const auth = getFirebaseAuth();
onAuthStateChanged(auth, async (user) => {
const previousUser = this.currentUser;
if (user) {
// User signed IN
console.log(`[AuthService] Firebase user signed in:`, user.uid);
this.currentUser = user;
this.currentUserId = user.uid;
this.currentUserMode = 'firebase';
// Clean up any zombie sessions from a previous run for this user.
await sessionRepository.endAllActiveSessions();
// ** Initialize encryption key for the logged-in user if permissions are already granted **
if (process.platform === 'darwin' && !(await permissionService.checkKeychainCompleted(this.currentUserId))) {
console.warn('[AuthService] Keychain permission not yet completed for this user. Deferring key initialization.');
} else {
await encryptionService.initializeKey(user.uid);
}
// ** Check for and run data migration for the user **
// No 'await' here, so it runs in the background without blocking startup.
migrationService.checkAndRunMigration(user);
// ***** CRITICAL: Wait for the virtual key and model state update to complete *****
try {
const idToken = await user.getIdToken(true);
const virtualKey = await getVirtualKeyByEmail(user.email, idToken);
if (global.modelStateService) {
// The model state service now writes directly to the DB, no in-memory state.
await global.modelStateService.setFirebaseVirtualKey(virtualKey);
}
console.log(`[AuthService] Virtual key for ${user.email} has been processed and state updated.`);
} catch (error) {
console.error('[AuthService] Failed to fetch or save virtual key:', error);
// This is not critical enough to halt the login, but we should log it.
}
} else {
// User signed OUT
console.log(`[AuthService] No Firebase user.`);
if (previousUser) {
console.log(`[AuthService] Clearing API key for logged-out user: ${previousUser.uid}`);
if (global.modelStateService) {
// The model state service now writes directly to the DB.
await global.modelStateService.setFirebaseVirtualKey(null);
}
}
this.currentUser = null;
this.currentUserId = 'default_user';
this.currentUserMode = 'local';
// End active sessions for the local/default user as well.
await sessionRepository.endAllActiveSessions();
encryptionService.resetSessionKey();
}
this.broadcastUserState();
if (!this.isInitialized) {
this.isInitialized = true;
console.log('[AuthService] Initialized and resolved initialization promise.');
resolve();
}
});
});
return this.initializationPromise;
}
async startFirebaseAuthFlow() {
try {
const webUrl = process.env.pickleglass_WEB_URL || 'http://localhost:3000';
const authUrl = `${webUrl}/login?mode=electron`;
console.log(`[AuthService] Opening Firebase auth URL in browser: ${authUrl}`);
await shell.openExternal(authUrl);
return { success: true };
} catch (error) {
console.error('[AuthService] Failed to open Firebase auth URL:', error);
return { success: false, error: error.message };
}
}
async signInWithCustomToken(token) {
const auth = getFirebaseAuth();
try {
const userCredential = await signInWithCustomToken(auth, token);
console.log(`[AuthService] Successfully signed in with custom token for user:`, userCredential.user.uid);
// onAuthStateChanged will handle the state update and broadcast
} catch (error) {
console.error('[AuthService] Error signing in with custom token:', error);
throw error; // Re-throw to be handled by the caller
}
}
async signOut() {
const auth = getFirebaseAuth();
try {
// End all active sessions for the current user BEFORE signing out.
await sessionRepository.endAllActiveSessions();
await signOut(auth);
console.log('[AuthService] User sign-out initiated successfully.');
// onAuthStateChanged will handle the state update and broadcast,
// which will also re-evaluate the API key status.
} catch (error) {
console.error('[AuthService] Error signing out:', error);
}
}
broadcastUserState() {
const userState = this.getCurrentUser();
console.log('[AuthService] Broadcasting user state change:', userState);
BrowserWindow.getAllWindows().forEach(win => {
if (win && !win.isDestroyed() && win.webContents && !win.webContents.isDestroyed()) {
win.webContents.send('user-state-changed', userState);
}
});
}
getCurrentUserId() {
return this.currentUserId;
}
getCurrentUser() {
const isLoggedIn = !!(this.currentUserMode === 'firebase' && this.currentUser);
if (isLoggedIn) {
return {
uid: this.currentUser.uid,
email: this.currentUser.email,
displayName: this.currentUser.displayName,
mode: 'firebase',
isLoggedIn: true,
//////// before_modelStateService ////////
// hasApiKey: this.hasApiKey // Always true for firebase users, but good practice
//////// before_modelStateService ////////
};
}
return {
uid: this.currentUserId, // returns 'default_user'
email: 'contact@pickle.com',
displayName: 'Default User',
mode: 'local',
isLoggedIn: false,
//////// before_modelStateService ////////
// hasApiKey: this.hasApiKey
//////// before_modelStateService ////////
};
}
}
const authService = new AuthService();
module.exports = authService;
================================================
FILE: src/features/common/services/databaseInitializer.js
================================================
const { app } = require('electron');
const path = require('path');
const fs = require('fs');
const sqliteClient = require('./sqliteClient');
const config = require('../config/config');
class DatabaseInitializer {
constructor() {
this.isInitialized = false;
// 최종적으로 사용될 DB 경로 (쓰기 가능한 위치)
const userDataPath = app.getPath('userData');
// In both development and production mode, the database is stored in the userData directory:
// macOS: ~/Library/Application Support/Glass/pickleglass.db
// Windows: %APPDATA%\Glass\pickleglass.db
this.dbPath = path.join(userDataPath, 'pickleglass.db');
this.dataDir = userDataPath;
// The original DB path (read-only location in the package)
this.sourceDbPath = app.isPackaged
? path.join(process.resourcesPath, 'data', 'pickleglass.db')
: path.join(app.getAppPath(), 'data', 'pickleglass.db');
}
ensureDatabaseExists() {
if (!fs.existsSync(this.dbPath)) {
console.log(`[DB] Database not found at ${this.dbPath}. Preparing to create new database...`);
// userData 디렉토리 생성 (없을 경우)
if (!fs.existsSync(this.dataDir)) {
fs.mkdirSync(this.dataDir, { recursive: true });
}
// 패키지에 번들된 초기 DB가 있으면 복사, 없으면 빈 파일을 생성하도록 둔다.
if (fs.existsSync(this.sourceDbPath)) {
try {
fs.copyFileSync(this.sourceDbPath, this.dbPath);
console.log(`[DB] Bundled database copied to ${this.dbPath}`);
} catch (error) {
console.error(`[DB] Failed to copy bundled database:`, error);
// 복사 실패 시에도 새 DB를 생성할 수 있도록 계속 진행
}
} else {
console.log('[DB] No bundled DB found – a fresh database will be created.');
}
}
}
async initialize() {
if (this.isInitialized) {
console.log('[DB] Already initialized.');
return true;
}
try {
this.ensureDatabaseExists();
sqliteClient.connect(this.dbPath); // DB 경로를 인자로 전달
// This single call will now synchronize the schema and then init default data.
await sqliteClient.initTables();
// Clean up any orphaned sessions from previous versions
await sqliteClient.cleanupEmptySessions();
this.isInitialized = true;
console.log('[DB] Database initialized successfully');
return true;
} catch (error) {
console.error('[DB] Database initialization failed:', error);
this.isInitialized = false;
throw error;
}
}
async ensureDataDirectory() {
try {
if (!fs.existsSync(this.dataDir)) {
fs.mkdirSync(this.dataDir, { recursive: true });
console.log('[DatabaseInitializer] Data directory created:', this.dataDir);
} else {
console.log('[DatabaseInitializer] Data directory exists:', this.dataDir);
}
} catch (error) {
console.error('[DatabaseInitializer] Failed to create data directory:', error);
throw error;
}
}
async checkDatabaseExists() {
try {
const exists = fs.existsSync(this.dbPath);
console.log('[DatabaseInitializer] Database file check:', { path: this.dbPath, exists });
return exists;
} catch (error) {
console.error('[DatabaseInitializer] Error checking database file:', error);
return false;
}
}
async createNewDatabase() {
console.log('[DatabaseInitializer] Creating new database...');
try {
await sqliteClient.connect(); // Connect and initialize tables/default data
const user = await sqliteClient.getUser(sqliteClient.defaultUserId);
if (!user) {
throw new Error('Default user was not created during initialization.');
}
console.log(`[DatabaseInitializer] Default user check successful, UID: ${user.uid}`);
return { success: true, user };
} catch (error) {
console.error('[DatabaseInitializer] Failed to create new database:', error);
throw error;
}
}
async connectToExistingDatabase() {
console.log('[DatabaseInitializer] Connecting to existing database...');
try {
await sqliteClient.connect();
const user = await sqliteClient.getUser(sqliteClient.defaultUserId);
if (!user) {
console.warn('[DatabaseInitializer] Default user not found in existing DB, attempting recovery.');
throw new Error('Default user missing');
}
console.log(`[DatabaseInitializer] Connection to existing DB successful for user: ${user.uid}`);
return { success: true, user };
} catch (error) {
console.error('[DatabaseInitializer] Failed to connect to existing database:', error);
throw error;
}
}
async validateAndRecoverData() {
console.log('[DatabaseInitializer] Validating database integrity...');
try {
console.log('[DatabaseInitializer] Validating database integrity...');
// The synchronizeSchema function handles table and column creation now.
// We just need to ensure default data is present.
await sqliteClient.synchronizeSchema();
const defaultUser = await sqliteClient.getUser(sqliteClient.defaultUserId);
if (!defaultUser) {
console.log('[DatabaseInitializer] Default user not found - creating...');
await sqliteClient.initDefaultData();
}
const presetTemplates = await sqliteClient.getPresets('default_user');
if (!presetTemplates || presetTemplates.length === 0) {
console.log('[DatabaseInitializer] Preset templates missing - creating...');
await sqliteClient.initDefaultData();
}
console.log('[DatabaseInitializer] Database validation completed');
return { success: true };
} catch (error) {
console.error('[DatabaseInitializer] Database validation failed:', error);
try {
await sqliteClient.initDefaultData();
console.log('[DatabaseInitializer] Default data recovered');
return { success: true };
} catch (error) {
console.error('[DatabaseInitializer] Database validation failed:', error);
throw error;
}
}
}
async getStatus() {
return {
isInitialized: this.isInitialized,
dbPath: this.dbPath,
dbExists: fs.existsSync(this.dbPath),
enableSQLiteStorage: config.get('enableSQLiteStorage'),
enableOfflineMode: config.get('enableOfflineMode')
};
}
async reset() {
try {
console.log('[DatabaseInitializer] Resetting database...');
sqliteClient.close();
if (fs.existsSync(this.dbPath)) {
fs.unlinkSync(this.dbPath);
console.log('[DatabaseInitializer] Database file deleted');
}
this.isInitialized = false;
await this.initialize();
console.log('[DatabaseInitializer] Database reset completed');
return true;
} catch (error) {
console.error('[DatabaseInitializer] Database reset failed:', error);
return false;
}
}
close() {
if (sqliteClient) {
sqliteClient.close();
}
this.isInitialized = false;
console.log('[DatabaseInitializer] Database connection closed');
}
getDatabasePath() {
return this.dbPath;
}
}
const databaseInitializer = new DatabaseInitializer();
module.exports = databaseInitializer;
================================================
FILE: src/features/common/services/encryptionService.js
================================================
const crypto = require('crypto');
let keytar;
// Dynamically import keytar, as it's an optional dependency.
try {
keytar = require('keytar');
} catch (error) {
console.warn('[EncryptionService] keytar is not available. Will use in-memory key for this session. Restarting the app might be required for data persistence after login.');
keytar = null;
}
const permissionService = require('./permissionService');
const SERVICE_NAME = 'com.pickle.glass'; // A unique identifier for the app in the keychain
let sessionKey = null; // In-memory fallback key
const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16; // For AES, this is always 16
const AUTH_TAG_LENGTH = 16;
/**
* Initializes the encryption key for a given user.
* It first tries to get the key from the OS keychain.
* If that fails, it generates a new key.
* If keytar is available, it saves the new key.
* Otherwise, it uses an in-memory key for the session.
*
* @param {string} userId - The unique identifier for the user (e.g., Firebase UID).
*/
async function initializeKey(userId) {
if (!userId) {
throw new Error('A user ID must be provided to initialize the encryption key.');
}
let keyRetrieved = false;
if (keytar) {
try {
let key = await keytar.getPassword(SERVICE_NAME, userId);
if (!key) {
console.log(`[EncryptionService] No key found for ${userId}. Creating a new one.`);
key = crypto.randomBytes(32).toString('hex');
await keytar.setPassword(SERVICE_NAME, userId, key);
console.log(`[EncryptionService] New key securely stored in keychain for ${userId}.`);
} else {
console.log(`[EncryptionService] Encryption key successfully retrieved from keychain for ${userId}.`);
keyRetrieved = true;
}
sessionKey = key;
} catch (error) {
console.error('[EncryptionService] keytar failed. Falling back to in-memory key for this session.', error);
keytar = null; // Disable keytar for the rest of the session to avoid repeated errors
sessionKey = crypto.randomBytes(32).toString('hex');
}
} else {
// keytar is not available
if (!sessionKey) {
console.warn('[EncryptionService] Using in-memory session key. Data will not persist across restarts without keytar.');
sessionKey = crypto.randomBytes(32).toString('hex');
}
}
// Mark keychain completed in permissions DB if this is the first successful retrieval or storage
try {
await permissionService.markKeychainCompleted(userId);
if (keyRetrieved) {
console.log(`[EncryptionService] Keychain completion marked in DB for ${userId}.`);
}
} catch (permErr) {
console.error('[EncryptionService] Failed to mark keychain completion:', permErr);
}
if (!sessionKey) {
throw new Error('Failed to initialize encryption key.');
}
}
function resetSessionKey() {
sessionKey = null;
}
/**
* Encrypts a given text using AES-256-GCM.
* @param {string} text The text to encrypt.
* @returns {string | null} The encrypted data, as a base64 string containing iv, authTag, and content, or the original value if it cannot be encrypted.
*/
function encrypt(text) {
if (!sessionKey) {
console.error('[EncryptionService] Encryption key is not initialized. Cannot encrypt.');
return text; // Return original if key is missing
}
if (text == null) { // checks for null or undefined
return text;
}
try {
const key = Buffer.from(sessionKey, 'hex');
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
let encrypted = cipher.update(String(text), 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
// Prepend IV and AuthTag to the encrypted content, then encode as base64.
return Buffer.concat([iv, authTag, Buffer.from(encrypted, 'hex')]).toString('base64');
} catch (error) {
console.error('[EncryptionService] Encryption failed:', error);
return text; // Return original on error
}
}
/**
* Decrypts a given encrypted string.
* @param {string} encryptedText The base64 encrypted text.
* @returns {string | null} The decrypted text, or the original value if it cannot be decrypted.
*/
function decrypt(encryptedText) {
if (!sessionKey) {
console.error('[EncryptionService] Encryption key is not initialized. Cannot decrypt.');
return encryptedText; // Return original if key is missing
}
if (encryptedText == null || typeof encryptedText !== 'string') {
return encryptedText;
}
try {
const data = Buffer.from(encryptedText, 'base64');
if (data.length < IV_LENGTH + AUTH_TAG_LENGTH) {
// This is not a valid encrypted string, likely plain text.
return encryptedText;
}
const key = Buffer.from(sessionKey, 'hex');
const iv = data.slice(0, IV_LENGTH);
const authTag = data.slice(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH);
const encryptedContent = data.slice(IV_LENGTH + AUTH_TAG_LENGTH);
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encryptedContent, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (error) {
// It's common for this to fail if the data is not encrypted (e.g., legacy data).
// In that case, we return the original value.
console.error('[EncryptionService] Decryption failed:', error);
return encryptedText;
}
}
function looksEncrypted(str) {
if (!str || typeof str !== 'string') return false;
// Base64 chars + optional '=' padding
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(str)) return false;
try {
const buf = Buffer.from(str, 'base64');
// Our AES-GCM cipher text must be at least 32 bytes (IV 16 + TAG 16)
return buf.length >= 32;
} catch {
return false;
}
}
module.exports = {
initializeKey,
resetSessionKey,
encrypt,
decrypt,
looksEncrypted,
};
================================================
FILE: src/features/common/services/firebaseClient.js
================================================
const { initializeApp } = require('firebase/app');
const { initializeAuth } = require('firebase/auth');
const Store = require('electron-store');
const { getFirestore, setLogLevel } = require('firebase/firestore');
// setLogLevel('debug');
/**
* Firebase Auth expects the `persistence` option passed to `initializeAuth()` to be *classes*,
* not instances. It then calls `new PersistenceClass()` internally.
*
* The helper below returns such a class, pre-configured with an `electron-store` instance that
* will be shared across all constructed objects. This mirrors the pattern used by Firebase's own
* `browserLocalPersistence` implementation as well as community solutions for NodeJS.
*/
function createElectronStorePersistence(storeName = 'firebase-auth-session') {
// Create a single `electron-store` behind the scenes – all Persistence instances will use it.
const sharedStore = new Store({ name: storeName });
return class ElectronStorePersistence {
constructor() {
this.store = sharedStore;
this.type = 'LOCAL';
}
/**
* Firebase calls this to check whether the persistence is usable in the current context.
*/
_isAvailable() {
return Promise.resolve(true);
}
async _set(key, value) {
this.store.set(key, value);
}
async _get(key) {
return this.store.get(key) ?? null;
}
async _remove(key) {
this.store.delete(key);
}
/**
* These are used by Firebase to react to external storage events (e.g. multi-tab).
* Electron apps are single-renderer per process, so we can safely provide no-op
* implementations.
*/
_addListener(_key, _listener) {
// no-op
}
_removeListener(_key, _listener) {
// no-op
}
};
}
const firebaseConfig = {
apiKey: 'AIzaSyAgtJrmsFWG1C7m9S55HyT1laICEzuUS2g',
authDomain: 'pickle-3651a.firebaseapp.com',
projectId: 'pickle-3651a',
storageBucket: 'pickle-3651a.firebasestorage.app',
messagingSenderId: '904706892885',
appId: '1:904706892885:web:0e42b3dda796674ead20dc',
measurementId: 'G-SQ0WM6S28T',
};
let firebaseApp = null;
let firebaseAuth = null;
let firestoreInstance = null; // To hold the specific DB instance
function initializeFirebase() {
if (firebaseApp) {
console.log('[FirebaseClient] Firebase already initialized.');
return;
}
try {
firebaseApp = initializeApp(firebaseConfig);
// Build a *class* persistence provider and hand it to Firebase.
const ElectronStorePersistence = createElectronStorePersistence('firebase-auth-session');
firebaseAuth = initializeAuth(firebaseApp, {
// `initializeAuth` accepts a single class or an array – we pass an array for future
// extensibility and to match Firebase examples.
persistence: [ElectronStorePersistence],
});
// Initialize Firestore with the specific database ID
firestoreInstance = getFirestore(firebaseApp, 'pickle-glass');
console.log('[FirebaseClient] Firebase initialized successfully with class-based electron-store persistence.');
console.log('[FirebaseClient] Firestore instance is targeting the "pickle-glass" database.');
} catch (error) {
console.error('[FirebaseClient] Firebase initialization failed:', error);
}
}
function getFirebaseAuth() {
if (!firebaseAuth) {
throw new Error("Firebase Auth has not been initialized. Call initializeFirebase() first.");
}
return firebaseAuth;
}
function getFirestoreInstance() {
if (!firestoreInstance) {
throw new Error("Firestore has not been initialized. Call initializeFirebase() first.");
}
return firestoreInstance;
}
module.exports = {
initializeFirebase,
getFirebaseAuth,
getFirestoreInstance,
};
================================================
FILE: src/features/common/services/localAIManager.js
================================================
const { EventEmitter } = require('events');
const ollamaService = require('./ollamaService');
const whisperService = require('./whisperService');
//Central manager for managing Ollama and Whisper services
class LocalAIManager extends EventEmitter {
constructor() {
super();
// service map
this.services = {
ollama: ollamaService,
whisper: whisperService
};
// unified state management
this.state = {
ollama: {
installed: false,
running: false,
models: []
},
whisper: {
installed: false,
initialized: false,
models: []
}
};
// setup event listeners
this.setupEventListeners();
}
// subscribe to events from each service and re-emit as unified events
setupEventListeners() {
// ollama events
ollamaService.on('install-progress', (data) => {
this.emit('install-progress', 'ollama', data);
});
ollamaService.on('installation-complete', () => {
this.emit('installation-complete', 'ollama');
this.updateServiceState('ollama');
});
ollamaService.on('error', (error) => {
this.emit('error', { service: 'ollama', ...error });
});
ollamaService.on('model-pull-complete', (data) => {
this.emit('model-ready', { service: 'ollama', ...data });
this.updateServiceState('ollama');
});
ollamaService.on('state-changed', (state) => {
this.emit('state-changed', 'ollama', state);
});
// Whisper 이벤트
whisperService.on('install-progress', (data) => {
this.emit('install-progress', 'whisper', data);
});
whisperService.on('installation-complete', () => {
this.emit('installation-complete', 'whisper');
this.updateServiceState('whisper');
});
whisperService.on('error', (error) => {
this.emit('error', { service: 'whisper', ...error });
});
whisperService.on('model-download-complete', (data) => {
this.emit('model-ready', { service: 'whisper', ...data });
this.updateServiceState('whisper');
});
}
/**
* 서비스 설치
*/
async installService(serviceName, options = {}) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
try {
if (serviceName === 'ollama') {
return await service.handleInstall();
} else if (serviceName === 'whisper') {
// Whisper는 자동 설치
await service.initialize();
return { success: true };
}
} catch (error) {
this.emit('error', {
service: serviceName,
errorType: 'installation-failed',
error: error.message
});
throw error;
}
}
/**
* 서비스 상태 조회
*/
async getServiceStatus(serviceName) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
if (serviceName === 'ollama') {
return await service.getStatus();
} else if (serviceName === 'whisper') {
const installed = await service.isInstalled();
const running = await service.isServiceRunning();
const models = await service.getInstalledModels();
return {
success: true,
installed,
running,
models
};
}
}
/**
* 서비스 시작
*/
async startService(serviceName) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
const result = await service.startService();
await this.updateServiceState(serviceName);
return { success: result };
}
/**
* 서비스 중지
*/
async stopService(serviceName) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
let result;
if (serviceName === 'ollama') {
result = await service.shutdown(false);
} else if (serviceName === 'whisper') {
result = await service.stopService();
}
// 서비스 중지 후 상태 업데이트
await this.updateServiceState(serviceName);
return result;
}
/**
* 모델 설치/다운로드
*/
async installModel(serviceName, modelId, options = {}) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
if (serviceName === 'ollama') {
return await service.pullModel(modelId);
} else if (serviceName === 'whisper') {
return await service.downloadModel(modelId);
}
}
/**
* 설치된 모델 목록 조회
*/
async getInstalledModels(serviceName) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
if (serviceName === 'ollama') {
return await service.getAllModelsWithStatus();
} else if (serviceName === 'whisper') {
return await service.getInstalledModels();
}
}
/**
* 모델 워밍업 (Ollama 전용)
*/
async warmUpModel(modelName, forceRefresh = false) {
return await ollamaService.warmUpModel(modelName, forceRefresh);
}
/**
* 자동 워밍업 (Ollama 전용)
*/
async autoWarmUp() {
return await ollamaService.autoWarmUpSelectedModel();
}
/**
* 진단 실행
*/
async runDiagnostics(serviceName) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
const diagnostics = {
service: serviceName,
timestamp: new Date().toISOString(),
checks: {}
};
try {
// 1. 설치 상태 확인
diagnostics.checks.installation = {
check: 'Installation',
status: await service.isInstalled() ? 'pass' : 'fail',
details: {}
};
// 2. 서비스 실행 상태
diagnostics.checks.running = {
check: 'Service Running',
status: await service.isServiceRunning() ? 'pass' : 'fail',
details: {}
};
// 3. 포트 연결 테스트 및 상세 health check (Ollama)
if (serviceName === 'ollama') {
try {
// Use comprehensive health check
const health = await service.healthCheck();
diagnostics.checks.health = {
check: 'Service Health',
status: health.healthy ? 'pass' : 'fail',
details: health
};
// Legacy port check for compatibility
diagnostics.checks.port = {
check: 'Port Connectivity',
status: health.checks.apiResponsive ? 'pass' : 'fail',
details: { connected: health.checks.apiResponsive }
};
} catch (error) {
diagnostics.checks.health = {
check: 'Service Health',
status: 'fail',
details: { error: error.message }
};
diagnostics.checks.port = {
check: 'Port Connectivity',
status: 'fail',
details: { error: error.message }
};
}
// 4. 모델 목록
if (diagnostics.checks.running.status === 'pass') {
try {
const models = await service.getInstalledModels();
diagnostics.checks.models = {
check: 'Installed Models',
status: 'pass',
details: { count: models.length, models: models.map(m => m.name) }
};
// 5. 워밍업 상태
const warmupStatus = await service.getWarmUpStatus();
diagnostics.checks.warmup = {
check: 'Model Warm-up',
status: 'pass',
details: warmupStatus
};
} catch (error) {
diagnostics.checks.models = {
check: 'Installed Models',
status: 'fail',
details: { error: error.message }
};
}
}
}
// 4. Whisper 특화 진단
if (serviceName === 'whisper') {
// 바이너리 확인
diagnostics.checks.binary = {
check: 'Whisper Binary',
status: service.whisperPath ? 'pass' : 'fail',
details: { path: service.whisperPath }
};
// 모델 디렉토리
diagnostics.checks.modelDir = {
check: 'Model Directory',
status: service.modelsDir ? 'pass' : 'fail',
details: { path: service.modelsDir }
};
}
// 전체 진단 결과
const allChecks = Object.values(diagnostics.checks);
diagnostics.summary = {
total: allChecks.length,
passed: allChecks.filter(c => c.status === 'pass').length,
failed: allChecks.filter(c => c.status === 'fail').length,
overallStatus: allChecks.every(c => c.status === 'pass') ? 'healthy' : 'unhealthy'
};
} catch (error) {
diagnostics.error = error.message;
diagnostics.summary = {
overallStatus: 'error'
};
}
return diagnostics;
}
/**
* 서비스 복구
*/
async repairService(serviceName) {
const service = this.services[serviceName];
if (!service) {
throw new Error(`Unknown service: ${serviceName}`);
}
console.log(`[LocalAIManager] Starting repair for ${serviceName}...`);
const repairLog = [];
try {
// 1. 진단 실행
repairLog.push('Running diagnostics...');
const diagnostics = await this.runDiagnostics(serviceName);
if (diagnostics.summary.overallStatus === 'healthy') {
repairLog.push('Service is already healthy, no repair needed');
return {
success: true,
repairLog,
diagnostics
};
}
// 2. 설치 문제 해결
if (diagnostics.checks.installation?.status === 'fail') {
repairLog.push('Installation missing, attempting to install...');
try {
await this.installService(serviceName);
repairLog.push('Installation completed');
} catch (error) {
repairLog.push(`Installation failed: ${error.message}`);
throw error;
}
}
// 3. 서비스 재시작
if (diagnostics.checks.running?.status === 'fail') {
repairLog.push('Service not running, attempting to start...');
// 종료 시도
try {
await this.stopService(serviceName);
repairLog.push('Stopped existing service');
} catch (error) {
repairLog.push('Service was not running');
}
// 잠시 대기
await new Promise(resolve => setTimeout(resolve, 2000));
// 시작
try {
await this.startService(serviceName);
repairLog.push('Service started successfully');
} catch (error) {
repairLog.push(`Failed to start service: ${error.message}`);
throw error;
}
}
// 4. 포트 문제 해결 (Ollama)
if (serviceName === 'ollama' && diagnostics.checks.port?.status === 'fail') {
repairLog.push('Port connectivity issue detected');
// 프로세스 강제 종료
if (process.platform === 'darwin') {
try {
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
await execAsync('pkill -f ollama');
repairLog.push('Killed stale Ollama processes');
} catch (error) {
repairLog.push('No stale processes found');
}
}
else if (process.platform === 'win32') {
try {
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
await execAsync('taskkill /F /IM ollama.exe');
repairLog.push('Killed stale Ollama processes');
} catch (error) {
repairLog.push('No stale processes found');
}
}
else if (process.platform === 'linux') {
try {
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
await execAsync('pkill -f ollama');
repairLog.push('Killed stale Ollama processes');
} catch (error) {
repairLog.push('No stale processes found');
}
}
await new Promise(resolve => setTimeout(resolve, 1000));
// 재시작
await this.startService(serviceName);
repairLog.push('Restarted service after port cleanup');
}
// 5. Whisper 특화 복구
if (serviceName === 'whisper') {
// 세션 정리
if (diagnostics.checks.running?.status === 'pass') {
repairLog.push('Cleaning up Whisper sessions...');
await service.cleanup();
repairLog.push('Sessions cleaned up');
}
// 초기화
if (!service.installState.isInitialized) {
repairLog.push('Re-initializing Whisper...');
await service.initialize();
repairLog.push('Whisper re-initialized');
}
}
// 6. 최종 상태 확인
repairLog.push('Verifying repair...');
const finalDiagnostics = await this.runDiagnostics(serviceName);
const success = finalDiagnostics.summary.overallStatus === 'healthy';
repairLog.push(success ? 'Repair successful!' : 'Repair failed - manual intervention may be required');
// 성공 시 상태 업데이트
if (success) {
await this.updateServiceState(serviceName);
}
return {
success,
repairLog,
diagnostics: finalDiagnostics
};
} catch (error) {
repairLog.push(`Repair error: ${error.message}`);
return {
success: false,
repairLog,
error: error.message
};
}
}
/**
* 상태 업데이트
*/
async updateServiceState(serviceName) {
try {
const status = await this.getServiceStatus(serviceName);
this.state[serviceName] = status;
// 상태 변경 이벤트 발행
this.emit('state-changed', serviceName, status);
} catch (error) {
console.error(`[LocalAIManager] Failed to update ${serviceName} state:`, error);
}
}
/**
* 전체 상태 조회
*/
async getAllServiceStates() {
const states = {};
for (const serviceName of Object.keys(this.services)) {
try {
states[serviceName] = await this.getServiceStatus(serviceName);
} catch (error) {
states[serviceName] = {
success: false,
error: error.message
};
}
}
return states;
}
/**
* 주기적 상태 동기화 시작
*/
startPeriodicSync(interval = 30000) {
if (this.syncInterval) {
return;
}
this.syncInterval = setInterval(async () => {
for (const serviceName of Object.keys(this.services)) {
await this.updateServiceState(serviceName);
}
}, interval);
// 각 서비스의 주기적 동기화도 시작
ollamaService.startPeriodicSync();
}
/**
* 주기적 상태 동기화 중지
*/
stopPeriodicSync() {
if (this.syncInterval) {
clearInterval(this.syncInterval);
this.syncInterval = null;
}
// 각 서비스의 주기적 동기화도 중지
ollamaService.stopPeriodicSync();
}
/**
* 전체 종료
*/
async shutdown() {
this.stopPeriodicSync();
const results = {};
for (const [serviceName, service] of Object.entries(this.services)) {
try {
if (serviceName === 'ollama') {
results[serviceName] = await service.shutdown(false);
} else if (serviceName === 'whisper') {
await service.cleanup();
results[serviceName] = true;
}
} catch (error) {
results[serviceName] = false;
console.error(`[LocalAIManager] Failed to shutdown ${serviceName}:`, error);
}
}
return results;
}
/**
* 에러 처리
*/
async handleError(serviceName, errorType, details = {}) {
console.error(`[LocalAIManager] Error in ${serviceName}: ${errorType}`, details);
// 서비스별 에러 처리
switch(errorType) {
case 'installation-failed':
// 설치 실패 시 이벤트 발생
this.emit('error-occurred', {
service: serviceName,
errorType,
error: details.error || 'Installation failed',
canRetry: true
});
break;
case 'model-pull-failed':
case 'model-download-failed':
// 모델 다운로드 실패
this.emit('error-occurred', {
service: serviceName,
errorType,
model: details.model,
error: details.error || 'Model download failed',
canRetry: true
});
break;
case 'service-not-responding':
// 서비스 반응 없음
console.log(`[LocalAIManager] Attempting to repair ${serviceName}...`);
const repairResult = await this.repairService(serviceName);
this.emit('error-occurred', {
service: serviceName,
errorType,
error: details.error || 'Service not responding',
repairAttempted: true,
repairSuccessful: repairResult.success
});
break;
default:
// 기타 에러
this.emit('error-occurred', {
service: serviceName,
errorType,
error: details.error || `Unknown error: ${errorType}`,
canRetry: false
});
}
}
}
// 싱글톤
const localAIManager = new LocalAIManager();
module.exports = localAIManager;
================================================
FILE: src/features/common/services/migrationService.js
================================================
const { doc, writeBatch, Timestamp } = require('firebase/firestore');
const { getFirestoreInstance } = require('../services/firebaseClient');
const encryptionService = require('../services/encryptionService');
const sqliteSessionRepo = require('../repositories/session/sqlite.repository');
const sqlitePresetRepo = require('../repositories/preset/sqlite.repository');
const sqliteUserRepo = require('../repositories/user/sqlite.repository');
const sqliteSttRepo = require('../../listen/stt/repositories/sqlite.repository');
const sqliteSummaryRepo = require('../../listen/summary/repositories/sqlite.repository');
const sqliteAiMessageRepo = require('../../ask/repositories/sqlite.repository');
const MAX_BATCH_OPERATIONS = 500;
async function checkAndRunMigration(firebaseUser) {
if (!firebaseUser || !firebaseUser.uid) {
console.log('[Migration] No user, skipping migration check.');
return;
}
console.log(`[Migration] Checking for user ${firebaseUser.uid}...`);
const localUser = sqliteUserRepo.getById(firebaseUser.uid);
if (!localUser || localUser.has_migrated_to_firebase) {
console.log(`[Migration] User ${firebaseUser.uid} is not eligible or already migrated.`);
return;
}
console.log(`[Migration] Starting data migration for user ${firebaseUser.uid}...`);
try {
const db = getFirestoreInstance();
// --- Phase 1: Migrate Parent Documents (Presets & Sessions) ---
console.log('[Migration Phase 1] Migrating parent documents...');
let phase1Batch = writeBatch(db);
let phase1OpCount = 0;
const phase1Promises = [];
const localPresets = (await sqlitePresetRepo.getPresets(firebaseUser.uid)).filter(p => !p.is_default);
console.log(`[Migration Phase 1] Found ${localPresets.length} custom presets.`);
for (const preset of localPresets) {
const presetRef = doc(db, 'prompt_presets', preset.id);
const cleanPreset = {
uid: preset.uid,
title: encryptionService.encrypt(preset.title ?? ''),
prompt: encryptionService.encrypt(preset.prompt ?? ''),
is_default: preset.is_default ?? 0,
created_at: preset.created_at ? Timestamp.fromMillis(preset.created_at * 1000) : null,
updated_at: preset.updated_at ? Timestamp.fromMillis(preset.updated_at * 1000) : null
};
phase1Batch.set(presetRef, cleanPreset);
phase1OpCount++;
if (phase1OpCount >= MAX_BATCH_OPERATIONS) {
phase1Promises.push(phase1Batch.commit());
phase1Batch = writeBatch(db);
phase1OpCount = 0;
}
}
const localSessions = await sqliteSessionRepo.getAllByUserId(firebaseUser.uid);
console.log(`[Migration Phase 1] Found ${localSessions.length} sessions.`);
for (const session of localSessions) {
const sessionRef = doc(db, 'sessions', session.id);
const cleanSession = {
uid: session.uid,
members: session.members ?? [session.uid],
title: encryptionService.encrypt(session.title ?? ''),
session_type: session.session_type ?? 'ask',
started_at: session.started_at ? Timestamp.fromMillis(session.started_at * 1000) : null,
ended_at: session.ended_at ? Timestamp.fromMillis(session.ended_at * 1000) : null,
updated_at: session.updated_at ? Timestamp.fromMillis(session.updated_at * 1000) : null
};
phase1Batch.set(sessionRef, cleanSession);
phase1OpCount++;
if (phase1OpCount >= MAX_BATCH_OPERATIONS) {
phase1Promises.push(phase1Batch.commit());
phase1Batch = writeBatch(db);
phase1OpCount = 0;
}
}
if (phase1OpCount > 0) {
phase1Promises.push(phase1Batch.commit());
}
if (phase1Promises.length > 0) {
await Promise.all(phase1Promises);
console.log(`[Migration Phase 1] Successfully committed ${phase1Promises.length} batches of parent documents.`);
} else {
console.log('[Migration Phase 1] No parent documents to migrate.');
}
// --- Phase 2: Migrate Child Documents (sub-collections) ---
console.log('[Migration Phase 2] Migrating child documents for all sessions...');
let phase2Batch = writeBatch(db);
let phase2OpCount = 0;
const phase2Promises = [];
for (const session of localSessions) {
const transcripts = await sqliteSttRepo.getAllTranscriptsBySessionId(session.id);
for (const t of transcripts) {
const transcriptRef = doc(db, `sessions/${session.id}/transcripts`, t.id);
const cleanTranscript = {
uid: firebaseUser.uid,
session_id: t.session_id,
start_at: t.start_at ? Timestamp.fromMillis(t.start_at * 1000) : null,
end_at: t.end_at ? Timestamp.fromMillis(t.end_at * 1000) : null,
speaker: t.speaker ?? null,
text: encryptionService.encrypt(t.text ?? ''),
lang: t.lang ?? 'en',
created_at: t.created_at ? Timestamp.fromMillis(t.created_at * 1000) : null
};
phase2Batch.set(transcriptRef, cleanTranscript);
phase2OpCount++;
if (phase2OpCount >= MAX_BATCH_OPERATIONS) {
phase2Promises.push(phase2Batch.commit());
phase2Batch = writeBatch(db);
phase2OpCount = 0;
}
}
const messages = await sqliteAiMessageRepo.getAllAiMessagesBySessionId(session.id);
for (const m of messages) {
const msgRef = doc(db, `sessions/${session.id}/ai_messages`, m.id);
const cleanMessage = {
uid: firebaseUser.uid,
session_id: m.session_id,
sent_at: m.sent_at ? Timestamp.fromMillis(m.sent_at * 1000) : null,
role: m.role ?? 'user',
content: encryptionService.encrypt(m.content ?? ''),
tokens: m.tokens ?? null,
model: m.model ?? 'unknown',
created_at: m.created_at ? Timestamp.fromMillis(m.created_at * 1000) : null
};
phase2Batch.set(msgRef, cleanMessage);
phase2OpCount++;
if (phase2OpCount >= MAX_BATCH_OPERATIONS) {
phase2Promises.push(phase2Batch.commit());
phase2Batch = writeBatch(db);
phase2OpCount = 0;
}
}
const summary = await sqliteSummaryRepo.getSummaryBySessionId(session.id);
if (summary) {
// Reverting to use 'data' as the document ID for summary.
const summaryRef = doc(db, `sessions/${session.id}/summary`, 'data');
const cleanSummary = {
uid: firebaseUser.uid,
session_id: summary.session_id,
generated_at: summary.generated_at ? Timestamp.fromMillis(summary.generated_at * 1000) : null,
model: summary.model ?? 'unknown',
tldr: encryptionService.encrypt(summary.tldr ?? ''),
text: encryptionService.encrypt(summary.text ?? ''),
bullet_json: encryptionService.encrypt(summary.bullet_json ?? '[]'),
action_json: encryptionService.encrypt(summary.action_json ?? '[]'),
tokens_used: summary.tokens_used ?? null,
updated_at: summary.updated_at ? Timestamp.fromMillis(summary.updated_at * 1000) : null
};
phase2Batch.set(summaryRef, cleanSummary);
phase2OpCount++;
if (phase2OpCount >= MAX_BATCH_OPERATIONS) {
phase2Promises.push(phase2Batch.commit());
phase2Batch = writeBatch(db);
phase2OpCount = 0;
}
}
}
if (phase2OpCount > 0) {
phase2Promises.push(phase2Batch.commit());
}
if (phase2Promises.length > 0) {
await Promise.all(phase2Promises);
console.log(`[Migration Phase 2] Successfully committed ${phase2Promises.length} batches of child documents.`);
} else {
console.log('[Migration Phase 2] No child documents to migrate.');
}
// --- 4. Mark migration as complete ---
sqliteUserRepo.setMigrationComplete(firebaseUser.uid);
console.log(`[Migration] ✅ Successfully marked migration as complete for ${firebaseUser.uid}.`);
} catch (error) {
console.error(`[Migration] 🔥 An error occurred during migration for user ${firebaseUser.uid}:`, error);
}
}
module.exports = {
checkAndRunMigration,
};
================================================
FILE: src/features/common/services/modelStateService.js
================================================
const { EventEmitter } = require('events');
const Store = require('electron-store');
const { PROVIDERS, getProviderClass } = require('../ai/factory');
const encryptionService = require('./encryptionService');
const providerSettingsRepository = require('../repositories/providerSettings');
const authService = require('./authService');
const ollamaModelRepository = require('../repositories/ollamaModel');
class ModelStateService extends EventEmitter {
constructor() {
super();
this.authService = authService;
// electron-store는 오직 레거시 데이터 마이그레이션 용도로만 사용됩니다.
this.store = new Store({ name: 'pickle-glass-model-state' });
}
async initialize() {
console.log('[ModelStateService] Initializing one-time setup...');
await this._initializeEncryption();
await this._runMigrations();
this.setupLocalAIStateSync();
await this._autoSelectAvailableModels([], true);
console.log('[ModelStateService] One-time setup complete.');
}
async _initializeEncryption() {
try {
const rows = await providerSettingsRepository.getRawApiKeys();
if (rows.some(r => r.api_key && encryptionService.looksEncrypted(r.api_key))) {
console.log('[ModelStateService] Encrypted keys detected, initializing encryption...');
const userIdForMigration = this.authService.getCurrentUserId();
await encryptionService.initializeKey(userIdForMigration);
} else {
console.log('[ModelStateService] No encrypted keys detected, skipping encryption initialization.');
}
} catch (err) {
console.warn('[ModelStateService] Error while checking encrypted keys:', err.message);
}
}
async _runMigrations() {
console.log('[ModelStateService] Checking for data migrations...');
const userId = this.authService.getCurrentUserId();
try {
const sqliteClient = require('./sqliteClient');
const db = sqliteClient.getDb();
const tableExists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='user_model_selections'").get();
if (tableExists) {
const selections = db.prepare('SELECT * FROM user_model_selections WHERE uid = ?').get(userId);
if (selections) {
console.log('[ModelStateService] Migrating from user_model_selections table...');
if (selections.llm_model) {
const llmProvider = this.getProviderForModel(selections.llm_model, 'llm');
if (llmProvider) {
await this.setSelectedModel('llm', selections.llm_model);
}
}
if (selections.stt_model) {
const sttProvider = this.getProviderForModel(selections.stt_model, 'stt');
if (sttProvider) {
await this.setSelectedModel('stt', selections.stt_model);
}
}
db.prepare('DROP TABLE user_model_selections').run();
console.log('[ModelStateService] user_model_selections migration complete.');
}
}
} catch (error) {
console.error('[ModelStateService] user_model_selections migration failed:', error);
}
try {
const legacyData = this.store.get(`users.${userId}`);
if (legacyData && legacyData.apiKeys) {
console.log('[ModelStateService] Migrating from electron-store...');
for (const [provider, apiKey] of Object.entries(legacyData.apiKeys)) {
if (apiKey && PROVIDERS[provider]) {
await this.setApiKey(provider, apiKey);
}
}
if (legacyData.selectedModels?.llm) {
await this.setSelectedModel('llm', legacyData.selectedModels.llm);
}
if (legacyData.selectedModels?.stt) {
await this.setSelectedModel('stt', legacyData.selectedModels.stt);
}
this.store.delete(`users.${userId}`);
console.log('[ModelStateService] electron-store migration complete.');
}
} catch (error) {
console.error('[ModelStateService] electron-store migration failed:', error);
}
}
setupLocalAIStateSync() {
const localAIManager = require('./localAIManager');
localAIManager.on('state-changed', (service, status) => {
this.handleLocalAIStateChange(service, status);
});
}
async handleLocalAIStateChange(service, state) {
console.log(`[ModelStateService] LocalAI state changed: ${service}`, state);
if (!state.installed || !state.running) {
const types = service === 'ollama' ? ['llm'] : service === 'whisper' ? ['stt'] : [];
await this._autoSelectAvailableModels(types);
}
this.emit('state-updated', await this.getLiveState());
}
async getLiveState() {
const providerSettings = await providerSettingsRepository.getAll();
const apiKeys = {};
Object.keys(PROVIDERS).forEach(provider => {
const setting = providerSettings.find(s => s.provider === provider);
apiKeys[provider] = setting?.api_key || null;
});
const activeSettings = await providerSettingsRepository.getActiveSettings();
const selectedModels = {
llm: activeSettings.llm?.selected_llm_model || null,
stt: activeSettings.stt?.selected_stt_model || null
};
return { apiKeys, selectedModels };
}
async _autoSelectAvailableModels(forceReselectionForTypes = [], isInitialBoot = false) {
console.log(`[ModelStateService] Running auto-selection. Force re-selection for: [${forceReselectionForTypes.join(', ')}]`);
const { apiKeys, selectedModels } = await this.getLiveState();
const types = ['llm', 'stt'];
for (const type of types) {
const currentModelId = selectedModels[type];
let isCurrentModelValid = false;
const forceReselection = forceReselectionForTypes.includes(type);
if (currentModelId && !forceReselection) {
const provider = this.getProviderForModel(currentModelId, type);
const apiKey = apiKeys[provider];
if (provider && apiKey) {
isCurrentModelValid = true;
}
}
if (!isCurrentModelValid) {
console.log(`[ModelStateService] No valid ${type.toUpperCase()} model selected or selection forced. Finding an alternative...`);
const availableModels = await this.getAvailableModels(type);
if (availableModels.length > 0) {
const apiModel = availableModels.find(model => {
const provider = this.getProviderForModel(model.id, type);
return provider && provider !== 'ollama' && provider !== 'whisper';
});
const newModel = apiModel || availableModels[0];
await this.setSelectedModel(type, newModel.id);
console.log(`[ModelStateService] Auto-selected ${type.toUpperCase()} model: ${newModel.id}`);
} else {
await providerSettingsRepository.setActiveProvider(null, type);
if (!isInitialBoot) {
this.emit('state-updated', await this.getLiveState());
}
}
}
}
}
async setFirebaseVirtualKey(virtualKey) {
console.log(`[ModelStateService] Setting Firebase virtual key.`);
// 키를 설정하기 전에, 이전에 openai-glass 키가 있었는지 확인합니다.
const previousSettings = await providerSettingsRepository.getByProvider('openai-glass');
const wasPreviouslyConfigured = !!previousSettings?.api_key;
// 항상 새로운 가상 키로 업데이트합니다.
await this.setApiKey('openai-glass', virtualKey);
if (virtualKey) {
// 이전에 설정된 적이 없는 경우 (최초 로그인)에만 모델을 강제로 변경합니다.
if (!wasPreviouslyConfigured) {
console.log('[ModelStateService] First-time setup for openai-glass, setting default models.');
const llmModel = PROVIDERS['openai-glass']?.llmModels[0];
const sttModel = PROVIDERS['openai-glass']?.sttModels[0];
if (llmModel) await this.setSelectedModel('llm', llmModel.id);
if (sttModel) await this.setSelectedModel('stt', sttModel.id);
} else {
console.log('[ModelStateService] openai-glass key updated, but respecting user\'s existing model selection.');
}
} else {
// 로그아웃 시, 현재 활성화된 모델이 openai-glass인 경우에만 다른 모델로 전환합니다.
const selected = await this.getSelectedModels();
const llmProvider = this.getProviderForModel(selected.llm, 'llm');
const sttProvider = this.getProviderForModel(selected.stt, 'stt');
const typesToReselect = [];
if (llmProvider === 'openai-glass') typesToReselect.push('llm');
if (sttProvider === 'openai-glass') typesToReselect.push('stt');
if (typesToReselect.length > 0) {
console.log('[ModelStateService] Logged out, re-selecting models for:', typesToReselect.join(', '));
await this._autoSelectAvailableModels(typesToReselect);
}
}
}
async setApiKey(provider, key) {
console.log(`[ModelStateService] setApiKey for ${provider}`);
if (!provider) {
throw new Error('Provider is required');
}
// 'openai-glass'는 자체 인증 키를 사용하므로 유효성 검사를 건너뜁니다.
if (provider !== 'openai-glass') {
const validationResult = await this.validateApiKey(provider, key);
if (!validationResult.success) {
console.warn(`[ModelStateService] API key validation failed for ${provider}: ${validationResult.error}`);
return validationResult;
}
}
const finalKey = (provider === 'ollama' || provider === 'whisper') ? 'local' : key;
const existingSettings = await providerSettingsRepository.getByProvider(provider) || {};
await providerSettingsRepository.upsert(provider, { ...existingSettings, api_key: finalKey });
// 키가 추가/변경되었으므로, 해당 provider의 모델을 자동 선택할 수 있는지 확인
await this._autoSelectAvailableModels([]);
this.emit('state-updated', await this.getLiveState());
this.emit('settings-updated');
return { success: true };
}
async getAllApiKeys() {
const allSettings = await providerSettingsRepository.getAll();
const apiKeys = {};
allSettings.forEach(s => {
if (s.provider !== 'openai-glass') {
apiKeys[s.provider] = s.api_key;
}
});
return apiKeys;
}
async removeApiKey(provider) {
const setting = await providerSettingsRepository.getByProvider(provider);
if (setting && setting.api_key) {
await providerSettingsRepository.upsert(provider, { ...setting, api_key: null });
await this._autoSelectAvailableModels(['llm', 'stt']);
this.emit('state-updated', await this.getLiveState());
this.emit('settings-updated');
return true;
}
return false;
}
/**
* 사용자가 Firebase에 로그인했는지 확인합니다.
*/
isLoggedInWithFirebase() {
return this.authService.getCurrentUser().isLoggedIn;
}
/**
* 유효한 API 키가 하나라도 설정되어 있는지 확인합니다.
*/
async hasValidApiKey() {
if (this.isLoggedInWithFirebase()) return true;
const allSettings = await providerSettingsRepository.getAll();
return allSettings.some(s => s.api_key && s.api_key.trim().length > 0);
}
getProviderForModel(arg1, arg2) {
// Compatibility: support both (type, modelId) old order and (modelId, type) new order
let type, modelId;
if (arg1 === 'llm' || arg1 === 'stt') {
type = arg1;
modelId = arg2;
} else {
modelId = arg1;
type = arg2;
}
if (!modelId || !type) return null;
for (const providerId in PROVIDERS) {
const models = type === 'llm' ? PROVIDERS[providerId].llmModels : PROVIDERS[providerId].sttModels;
if (models && models.some(m => m.id === modelId)) {
return providerId;
}
}
if (type === 'llm') {
const installedModels = ollamaModelRepository.getInstalledModels();
if (installedModels.some(m => m.name === modelId)) return 'ollama';
}
return null;
}
async getSelectedModels() {
const active = await providerSettingsRepository.getActiveSettings();
return {
llm: active.llm?.selected_llm_model || null,
stt: active.stt?.selected_stt_model || null,
};
}
async setSelectedModel(type, modelId) {
const provider = this.getProviderForModel(modelId, type);
if (!provider) {
console.warn(`[ModelStateService] No provider found for model ${modelId}`);
return false;
}
const existingSettings = await providerSettingsRepository.getByProvider(provider) || {};
const newSettings = { ...existingSettings };
if (type === 'llm') {
newSettings.selected_llm_model = modelId;
} else {
newSettings.selected_stt_model = modelId;
}
await providerSettingsRepository.upsert(provider, newSettings);
await providerSettingsRepository.setActiveProvider(provider, type);
console.log(`[ModelStateService] Selected ${type} model: ${modelId} (provider: ${provider})`);
if (type === 'llm' && provider === 'ollama') {
require('./localAIManager').warmUpModel(modelId).catch(err => console.warn(err));
}
this.emit('state-updated', await this.getLiveState());
this.emit('settings-updated');
return true;
}
async getAvailableModels(type) {
const allSettings = await providerSettingsRepository.getAll();
const available = [];
const modelListKey = type === 'llm' ? 'llmModels' : 'sttModels';
for (const setting of allSettings) {
if (!setting.api_key) continue;
const providerId = setting.provider;
if (providerId === 'ollama' && type === 'llm') {
const installed = ollamaModelRepository.getInstalledModels();
available.push(...installed.map(m => ({ id: m.name, name: m.name })));
} else if (PROVIDERS[providerId]?.[modelListKey]) {
available.push(...PROVIDERS[providerId][modelListKey]);
}
}
return [...new Map(available.map(item => [item.id, item])).values()];
}
async getCurrentModelInfo(type) {
const activeSetting = await providerSettingsRepository.getActiveProvider(type);
if (!activeSetting) return null;
const model = type === 'llm' ? activeSetting.selected_llm_model : activeSetting.selected_stt_model;
if (!model) return null;
return {
provider: activeSetting.provider,
model: model,
apiKey: activeSetting.api_key,
};
}
// --- 핸들러 및 유틸리티 메서드 ---
async validateApiKey(provider, key) {
if (!key || (key.trim() === '' && provider !== 'ollama' && provider !== 'whisper')) {
return { success: false, error: 'API key cannot be empty.' };
}
const ProviderClass = getProviderClass(provider);
if (!ProviderClass || typeof ProviderClass.validateApiKey !== 'function') {
return { success: true };
}
try {
return await ProviderClass.validateApiKey(key);
} catch (error) {
return { success: false, error: 'An unexpected error occurred during validation.' };
}
}
getProviderConfig() {
const config = {};
for (const key in PROVIDERS) {
const { handler, ...rest } = PROVIDERS[key];
config[key] = rest;
}
return config;
}
async handleRemoveApiKey(provider) {
const success = await this.removeApiKey(provider);
if (success) {
const selectedModels = await this.getSelectedModels();
if (!selectedModels.llm && !selectedModels.stt) {
this.emit('force-show-apikey-header');
}
}
return success;
}
/*-------------- Compatibility Helpers --------------*/
async handleValidateKey(provider, key) {
return await this.setApiKey(provider, key);
}
async handleSetSelectedModel(type, modelId) {
return await this.setSelectedModel(type, modelId);
}
async areProvidersConfigured() {
if (this.isLoggedInWithFirebase()) return true;
const allSettings = await providerSettingsRepository.getAll();
const apiKeyMap = {};
allSettings.forEach(s => apiKeyMap[s.provider] = s.api_key);
// LLM
const hasLlmKey = Object.entries(apiKeyMap).some(([provider, key]) => {
if (!key) return false;
if (provider === 'whisper') return false; // whisper는 LLM 없음
return PROVIDERS[provider]?.llmModels?.length > 0;
});
// STT
const hasSttKey = Object.entries(apiKeyMap).some(([provider, key]) => {
if (!key) return false;
if (provider === 'ollama') return false; // ollama는 STT 없음
return PROVIDERS[provider]?.sttModels?.length > 0 || provider === 'whisper';
});
return hasLlmKey && hasSttKey;
}
}
const modelStateService = new ModelStateService();
module.exports = modelStateService;
================================================
FILE: src/features/common/services/ollamaService.js
================================================
const { EventEmitter } = require('events');
const { spawn, exec } = require('child_process');
const { promisify } = require('util');
const fetch = require('node-fetch');
const path = require('path');
const fs = require('fs').promises;
const os = require('os');
const https = require('https');
const crypto = require('crypto');
const { app } = require('electron');
const { spawnAsync } = require('../utils/spawnHelper');
const { DOWNLOAD_CHECKSUMS } = require('../config/checksums');
const ollamaModelRepository = require('../repositories/ollamaModel');
const execAsync = promisify(exec);
class OllamaService extends EventEmitter {
constructor() {
super();
this.serviceName = 'OllamaService';
this.baseUrl = 'http://localhost:11434';
// 단순화된 상태 관리
this.installState = {
isInstalled: false,
isInstalling: false,
progress: 0
};
// 단순화된 요청 관리 (복잡한 큐 제거)
this.activeRequest = null;
this.requestTimeout = 30000; // 30초 타임아웃
// 모델 상태
this.installedModels = new Map();
this.modelWarmupStatus = new Map();
// 체크포인트 시스템 (롤백용)
this.installCheckpoints = [];
// 설치 진행률 관리
this.installationProgress = new Map();
// 워밍 관련 (기존 유지)
this.warmingModels = new Map();
this.warmedModels = new Set();
this.lastWarmUpAttempt = new Map();
this.warmupTimeout = 120000; // 120s for model warmup
// 상태 동기화
this._lastState = null;
this._syncInterval = null;
this._lastLoadedModels = [];
this.modelLoadStatus = new Map();
// 서비스 종료 상태 추적
this.isShuttingDown = false;
}
// Base class methods integration
getPlatform() {
return process.platform;
}
async checkCommand(command) {
try {
const platform = this.getPlatform();
const checkCmd = platform === 'win32' ? 'where' : 'which';
const { stdout } = await execAsync(`${checkCmd} ${command}`);
return stdout.trim();
} catch (error) {
return null;
}
}
async waitForService(checkFn, maxAttempts = 30, delayMs = 1000) {
for (let i = 0; i < maxAttempts; i++) {
if (await checkFn()) {
console.log(`[${this.serviceName}] Service is ready`);
return true;
}
await new Promise(resolve => setTimeout(resolve, delayMs));
}
throw new Error(`${this.serviceName} service failed to start within timeout`);
}
getInstallProgress(modelName) {
return this.installationProgress.get(modelName) || 0;
}
setInstallProgress(modelName, progress) {
this.installationProgress.set(modelName, progress);
}
clearInstallProgress(modelName) {
this.installationProgress.delete(modelName);
}
async getStatus() {
try {
const installed = await this.isInstalled();
if (!installed) {
return { success: true, installed: false, running: false, models: [] };
}
const running = await this.isServiceRunning();
if (!running) {
return { success: true, installed: true, running: false, models: [] };
}
const models = await this.getInstalledModels();
return { success: true, installed: true, running: true, models };
} catch (error) {
console.error('[OllamaService] Error getting status:', error);
return { success: false, error: error.message, installed: false, running: false, models: [] };
}
}
getOllamaCliPath() {
if (this.getPlatform() === 'darwin') {
return '/Applications/Ollama.app/Contents/Resources/ollama';
}
return 'ollama';
}
// === 런타임 관리 (단순화) ===
async makeRequest(endpoint, options = {}) {
// 서비스 종료 중이면 요청하지 않음
if (this.isShuttingDown) {
throw new Error('Service is shutting down');
}
// 동시 요청 방지 (단순한 잠금)
if (this.activeRequest) {
await this.activeRequest;
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.requestTimeout);
this.activeRequest = fetch(`${this.baseUrl}${endpoint}`, {
...options,
signal: controller.signal
}).finally(() => {
clearTimeout(timeoutId);
this.activeRequest = null;
});
return this.activeRequest;
}
async isInstalled() {
try {
const platform = this.getPlatform();
if (platform === 'darwin') {
try {
await fs.access('/Applications/Ollama.app');
return true;
} catch {
const ollamaPath = await this.checkCommand(this.getOllamaCliPath());
return !!ollamaPath;
}
} else {
const ollamaPath = await this.checkCommand(this.getOllamaCliPath());
return !!ollamaPath;
}
} catch (error) {
console.log('[OllamaService] Ollama not found:', error.message);
return false;
}
}
async isServiceRunning() {
try {
// Use /api/ps to check if service is running
// This is more reliable than /api/tags which may not show models not in memory
const response = await this.makeRequest('/api/ps', {
method: 'GET'
});
return response.ok;
} catch (error) {
console.log(`[OllamaService] Service health check failed: ${error.message}`);
return false;
}
}
async startService() {
// 서비스 시작 시 종료 플래그 리셋
this.isShuttingDown = false;
const platform = this.getPlatform();
try {
if (platform === 'darwin') {
try {
await spawnAsync('open', ['-a', 'Ollama']);
await this.waitForService(() => this.isServiceRunning());
return true;
} catch {
spawn(this.getOllamaCliPath(), ['serve'], {
detached: true,
stdio: 'ignore'
}).unref();
await this.waitForService(() => this.isServiceRunning());
return true;
}
} else {
spawn(this.getOllamaCliPath(), ['serve'], {
detached: true,
stdio: 'ignore',
shell: platform === 'win32'
}).unref();
await this.waitForService(() => this.isServiceRunning());
return true;
}
} catch (error) {
console.error('[OllamaService] Failed to start service:', error);
throw error;
}
}
async stopService() {
return await this.shutdown();
}
// Comprehensive health check using multiple endpoints
async healthCheck() {
try {
const checks = {
serviceRunning: false,
apiResponsive: false,
modelsAccessible: false,
memoryStatus: false
};
// 1. Basic service check with /api/ps
try {
const psResponse = await this.makeRequest('/api/ps', { method: 'GET' });
checks.serviceRunning = psResponse.ok;
checks.memoryStatus = psResponse.ok;
} catch (error) {
console.log('[OllamaService] /api/ps check failed:', error.message);
}
// 2. Check if API is responsive with root endpoint
try {
const rootResponse = await this.makeRequest('/', { method: 'GET' });
checks.apiResponsive = rootResponse.ok;
} catch (error) {
console.log('[OllamaService] Root endpoint check failed:', error.message);
}
// 3. Check if models endpoint is accessible
try {
const tagsResponse = await this.makeRequest('/api/tags', { method: 'GET' });
checks.modelsAccessible = tagsResponse.ok;
} catch (error) {
console.log('[OllamaService] /api/tags check failed:', error.message);
}
const allHealthy = Object.values(checks).every(v => v === true);
return {
healthy: allHealthy,
checks,
timestamp: new Date().toISOString()
};
} catch (error) {
console.error('[OllamaService] Health check failed:', error);
return {
healthy: false,
error: error.message,
timestamp: new Date().toISOString()
};
}
}
async getInstalledModels() {
// 서비스 종료 중이면 빈 배열 반환
if (this.isShuttingDown) {
console.log('[OllamaService] Service is shutting down, returning empty models list');
return [];
}
try {
const response = await this.makeRequest('/api/tags', {
method: 'GET'
});
const data = await response.json();
return data.models || [];
} catch (error) {
console.error('[OllamaService] Failed to get installed models:', error.message);
return [];
}
}
// Get models currently loaded in memory using /api/ps
async getLoadedModels() {
// 서비스 종료 중이면 빈 배열 반환
if (this.isShuttingDown) {
console.log('[OllamaService] Service is shutting down, returning empty loaded models list');
return [];
}
try {
const response = await this.makeRequest('/api/ps', {
method: 'GET'
});
if (!response.ok) {
console.log('[OllamaService] Failed to get loaded models via /api/ps');
return [];
}
const data = await response.json();
// Extract model names from running processes
return (data.models || []).map(m => m.name);
} catch (error) {
console.error('[OllamaService] Error getting loaded models:', error);
return [];
}
}
// Get detailed memory info for loaded models
async getLoadedModelsWithMemoryInfo() {
try {
const response = await this.makeRequest('/api/ps', {
method: 'GET'
});
if (!response.ok) {
return [];
}
const data = await response.json();
// Return full model info including memory usage
return data.models || [];
} catch (error) {
console.error('[OllamaService] Error getting loaded models info:', error);
return [];
}
}
// Check if a specific model is loaded in memory
async isModelLoaded(modelName) {
const loadedModels = await this.getLoadedModels();
return loadedModels.includes(modelName);
}
async getInstalledModelsList() {
try {
const { stdout } = await spawnAsync(this.getOllamaCliPath(), ['list']);
const lines = stdout.split('\n').filter(line => line.trim());
// Skip header line (NAME, ID, SIZE, MODIFIED)
const modelLines = lines.slice(1);
const models = [];
for (const line of modelLines) {
if (!line.trim()) continue;
// Parse line: "model:tag model_id size modified_time"
const parts = line.split(/\s+/);
if (parts.length >= 3) {
models.push({
name: parts[0],
id: parts[1],
size: parts[2] + (parts[3] === 'GB' || parts[3] === 'MB' ? ' ' + parts[3] : ''),
status: 'installed'
});
}
}
return models;
} catch (error) {
console.log('[OllamaService] Failed to get installed models via CLI, falling back to API');
// Fallback to API if CLI fails
const apiModels = await this.getInstalledModels();
return apiModels.map(model => ({
name: model.name,
id: model.digest || 'unknown',
size: model.size || 'Unknown',
status: 'installed'
}));
}
}
async getModelSuggestions() {
try {
// Get actually installed models
const installedModels = await this.getInstalledModelsList();
// Get user input history from storage (we'll implement this in the frontend)
// For now, just return installed models
return installedModels;
} catch (error) {
console.error('[OllamaService] Failed to get model suggestions:', error);
return [];
}
}
async isModelInstalled(modelName) {
const models = await this.getInstalledModels();
return models.some(model => model.name === modelName);
}
async pullModel(modelName) {
if (!modelName?.trim()) {
throw new Error(`Invalid model name: ${modelName}`);
}
console.log(`[OllamaService] Starting to pull model: ${modelName} via API`);
// Emit progress event - LocalAIManager가 처리
this.emit('install-progress', {
model: modelName,
progress: 0,
status: 'starting'
});
try {
const response = await fetch(`${this.baseUrl}/api/pull`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: modelName,
stream: true
})
});
if (!response.ok) {
throw new Error(`Pull API failed: ${response.status} ${response.statusText}`);
}
// Handle Node.js streaming response
return new Promise((resolve, reject) => {
let buffer = '';
response.body.on('data', (chunk) => {
buffer += chunk.toString();
const lines = buffer.split('\n');
// Keep incomplete line in buffer
buffer = lines.pop() || '';
// Process complete lines
for (const line of lines) {
if (!line.trim()) continue;
try {
const data = JSON.parse(line);
const progress = this._parseOllamaPullProgress(data, modelName);
if (progress !== null) {
this.setInstallProgress(modelName, progress);
// Emit progress event - LocalAIManager가 처리
this.emit('install-progress', {
model: modelName,
progress,
status: data.status || 'downloading'
});
console.log(`[OllamaService] API Progress: ${progress}% for ${modelName} (${data.status || 'downloading'})`);
}
// Handle completion
if (data.status === 'success') {
console.log(`[OllamaService] Successfully pulled model: ${modelName}`);
this.emit('model-pull-complete', { model: modelName });
this.clearInstallProgress(modelName);
resolve();
return;
}
} catch (parseError) {
console.warn('[OllamaService] Failed to parse response line:', line);
}
}
});
response.body.on('end', () => {
// Process any remaining data in buffer
if (buffer.trim()) {
try {
const data = JSON.parse(buffer);
if (data.status === 'success') {
console.log(`[OllamaService] Successfully pulled model: ${modelName}`);
this.emit('model-pull-complete', { model: modelName });
}
} catch (parseError) {
console.warn('[OllamaService] Failed to parse final buffer:', buffer);
}
}
this.clearInstallProgress(modelName);
resolve();
});
response.body.on('error', (error) => {
console.error(`[OllamaService] Stream error for ${modelName}:`, error);
this.clearInstallProgress(modelName);
reject(error);
});
});
} catch (error) {
this.clearInstallProgress(modelName);
console.error(`[OllamaService] Pull model failed:`, error);
throw error;
}
}
_parseOllamaPullProgress(data, modelName) {
// Handle Ollama API response format
if (data.status === 'success') {
return 100;
}
// Handle downloading progress
if (data.total && data.completed !== undefined) {
const progress = Math.round((data.completed / data.total) * 100);
return Math.min(progress, 99); // Don't show 100% until success
}
// Handle status-based progress
const statusProgress = {
'pulling manifest': 5,
'downloading': 10,
'verifying sha256 digest': 90,
'writing manifest': 95,
'removing any unused layers': 98
};
if (data.status && statusProgress[data.status] !== undefined) {
return statusProgress[data.status];
}
return null;
}
async downloadFile(url, destination, options = {}) {
const {
onProgress = null,
headers = { 'User-Agent': 'Glass-App' },
timeout = 300000,
modelId = null
} = options;
return new Promise((resolve, reject) => {
const file = require('fs').createWriteStream(destination);
let downloadedSize = 0;
let totalSize = 0;
const request = https.get(url, { headers }, (response) => {
if ([301, 302, 307, 308].includes(response.statusCode)) {
file.close();
require('fs').unlink(destination, () => {});
if (!response.headers.location) {
reject(new Error('Redirect without location header'));
return;
}
console.log(`[${this.serviceName}] Following redirect from ${url} to ${response.headers.location}`);
this.downloadFile(response.headers.location, destination, options)
.then(resolve)
.catch(reject);
return;
}
if (response.statusCode !== 200) {
file.close();
require('fs').unlink(destination, () => {});
reject(new Error(`Download failed: ${response.statusCode} ${response.statusMessage}`));
return;
}
totalSize = parseInt(response.headers['content-length'], 10) || 0;
response.on('data', (chunk) => {
downloadedSize += chunk.length;
if (totalSize > 0) {
const progress = Math.round((downloadedSize / totalSize) * 100);
if (onProgress) {
onProgress(progress, downloadedSize, totalSize);
}
}
});
response.pipe(file);
file.on('finish', () => {
file.close(() => {
resolve({ success: true, size: downloadedSize });
});
});
});
request.on('timeout', () => {
request.destroy();
file.close();
require('fs').unlink(destination, () => {});
reject(new Error('Download timeout'));
});
request.on('error', (err) => {
file.close();
require('fs').unlink(destination, () => {});
this.emit('download-error', { url, error: err, modelId });
reject(err);
});
request.setTimeout(timeout);
file.on('error', (err) => {
require('fs').unlink(destination, () => {});
reject(err);
});
});
}
async downloadWithRetry(url, destination, options = {}) {
const {
maxRetries = 3,
retryDelay = 1000,
expectedChecksum = null,
modelId = null,
...downloadOptions
} = options;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const result = await this.downloadFile(url, destination, {
...downloadOptions,
modelId
});
if (expectedChecksum) {
const isValid = await this.verifyChecksum(destination, expectedChecksum);
if (!isValid) {
require('fs').unlinkSync(destination);
throw new Error('Checksum verification failed');
}
console.log(`[${this.serviceName}] Checksum verified successfully`);
}
return result;
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`Download attempt ${attempt} failed, retrying in ${retryDelay}ms...`);
await new Promise(resolve => setTimeout(resolve, retryDelay * attempt));
}
}
}
async verifyChecksum(filePath, expectedChecksum) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256');
const stream = require('fs').createReadStream(filePath);
stream.on('data', (data) => hash.update(data));
stream.on('end', () => {
const fileChecksum = hash.digest('hex');
console.log(`[${this.serviceName}] File checksum: ${fileChecksum}`);
console.log(`[${this.serviceName}] Expected checksum: ${expectedChecksum}`);
resolve(fileChecksum === expectedChecksum);
});
stream.on('error', reject);
});
}
async autoInstall(onProgress) {
const platform = this.getPlatform();
console.log(`[${this.serviceName}] Starting auto-installation for ${platform}`);
try {
switch(platform) {
case 'darwin':
return await this.installMacOS(onProgress);
case 'win32':
return await this.installWindows(onProgress);
case 'linux':
return await this.installLinux();
default:
throw new Error(`Unsupported platform: ${platform}`);
}
} catch (error) {
console.error(`[${this.serviceName}] Auto-installation failed:`, error);
throw error;
}
}
async installMacOS(onProgress) {
console.log('[OllamaService] Installing Ollama on macOS using DMG...');
try {
const dmgUrl = 'https://ollama.com/download/Ollama.dmg';
const tempDir = app.getPath('temp');
const dmgPath = path.join(tempDir, 'Ollama.dmg');
const mountPoint = path.join(tempDir, 'OllamaMount');
// 체크포인트 저장
await this.saveCheckpoint('pre-install');
console.log('[OllamaService] Step 1: Downloading Ollama DMG...');
onProgress?.({ stage: 'downloading', message: 'Downloading Ollama installer...', progress: 0 });
const checksumInfo = DOWNLOAD_CHECKSUMS.ollama.dmg;
await this.downloadWithRetry(dmgUrl, dmgPath, {
expectedChecksum: checksumInfo?.sha256,
onProgress: (progress) => {
onProgress?.({ stage: 'downloading', message: `Downloading... ${progress}%`, progress });
}
});
await this.saveCheckpoint('post-download');
console.log('[OllamaService] Step 2: Mounting DMG...');
onProgress?.({ stage: 'mounting', message: 'Mounting disk image...', progress: 0 });
await fs.mkdir(mountPoint, { recursive: true });
await spawnAsync('hdiutil', ['attach', dmgPath, '-mountpoint', mountPoint]);
onProgress?.({ stage: 'mounting', message: 'Disk image mounted.', progress: 100 });
console.log('[OllamaService] Step 3: Installing Ollama.app...');
onProgress?.({ stage: 'installing', message: 'Installing Ollama application...', progress: 0 });
await spawnAsync('cp', ['-R', `${mountPoint}/Ollama.app`, '/Applications/']);
onProgress?.({ stage: 'installing', message: 'Application installed.', progress: 100 });
await this.saveCheckpoint('post-install');
console.log('[OllamaService] Step 4: Setting up CLI path...');
onProgress?.({ stage: 'linking', message: 'Creating command-line shortcut...', progress: 0 });
try {
const script = `do shell script "mkdir -p /usr/local/bin && ln -sf '${this.getOllamaCliPath()}' '/usr/local/bin/ollama'" with administrator privileges`;
await spawnAsync('osascript', ['-e', script]);
onProgress?.({ stage: 'linking', message: 'Shortcut created.', progress: 100 });
} catch (linkError) {
console.error('[OllamaService] CLI symlink creation failed:', linkError.message);
onProgress?.({ stage: 'linking', message: 'Shortcut creation failed (permissions?).', progress: 100 });
// Not throwing an error, as the app might still work
}
console.log('[OllamaService] Step 5: Cleanup...');
onProgress?.({ stage: 'cleanup', message: 'Cleaning up installation files...', progress: 0 });
await spawnAsync('hdiutil', ['detach', mountPoint]);
await fs.unlink(dmgPath).catch(() => {});
await fs.rmdir(mountPoint).catch(() => {});
onProgress?.({ stage: 'cleanup', message: 'Cleanup complete.', progress: 100 });
console.log('[OllamaService] Ollama installed successfully on macOS');
await new Promise(resolve => setTimeout(resolve, 2000));
return true;
} catch (error) {
console.error('[OllamaService] macOS installation failed:', error);
// 설치 실패 시 정리
await fs.unlink(dmgPath).catch(() => {});
throw new Error(`Failed to install Ollama on macOS: ${error.message}`);
}
}
async installWindows(onProgress) {
console.log('[OllamaService] Installing Ollama on Windows...');
try {
const exeUrl = 'https://ollama.com/download/OllamaSetup.exe';
const tempDir = app.getPath('temp');
const exePath = path.join(tempDir, 'OllamaSetup.exe');
console.log('[OllamaService] Step 1: Downloading Ollama installer...');
onProgress?.({ stage: 'downloading', message: 'Downloading Ollama installer...', progress: 0 });
const checksumInfo = DOWNLOAD_CHECKSUMS.ollama.exe;
await this.downloadWithRetry(exeUrl, exePath, {
expectedChecksum: checksumInfo?.sha256,
onProgress: (progress) => {
onProgress?.({ stage: 'downloading', message: `Downloading... ${progress}%`, progress });
}
});
console.log('[OllamaService] Step 2: Running silent installation...');
onProgress?.({ stage: 'installing', message: 'Installing Ollama...', progress: 0 });
await spawnAsync(exePath, ['/VERYSILENT', '/NORESTART']);
onProgress?.({ stage: 'installing', message: 'Installation complete.', progress: 100 });
console.log('[OllamaService] Step 3: Cleanup...');
onProgress?.({ stage: 'cleanup', message: 'Cleaning up installation files...', progress: 0 });
await fs.unlink(exePath).catch(() => {});
onProgress?.({ stage: 'cleanup', message: 'Cleanup complete.', progress: 100 });
console.log('[OllamaService] Ollama installed successfully on Windows');
await new Promise(resolve => setTimeout(resolve, 3000));
return true;
} catch (error) {
console.error('[OllamaService] Windows installation failed:', error);
throw new Error(`Failed to install Ollama on Windows: ${error.message}`);
}
}
async installLinux() {
console.log('[OllamaService] Installing Ollama on Linux...');
console.log('[OllamaService] Automatic installation on Linux is not supported for security reasons.');
console.log('[OllamaService] Please install Ollama manually:');
console.log('[OllamaService] 1. Visit https://ollama.com/download/linux');
console.log('[OllamaService] 2. Follow the official installation instructions');
console.log('[OllamaService] 3. Or use your package manager if available');
throw new Error('Manual installation required on Linux. Please visit https://ollama.com/download/linux');
}
// === 체크포인트 & 롤백 시스템 ===
async saveCheckpoint(name) {
this.installCheckpoints.push({
name,
timestamp: Date.now(),
state: { ...this.installState }
});
}
async rollbackToLastCheckpoint() {
const checkpoint = this.installCheckpoints.pop();
if (checkpoint) {
console.log(`[OllamaService] Rolling back to checkpoint: ${checkpoint.name}`);
// 플랫폼별 롤백 로직 실행
await this._executeRollback(checkpoint);
}
}
async _executeRollback(checkpoint) {
const platform = this.getPlatform();
if (platform === 'darwin' && checkpoint.name === 'post-install') {
// macOS 롤백
await fs.rm('/Applications/Ollama.app', { recursive: true, force: true }).catch(() => {});
} else if (platform === 'win32') {
// Windows 롤백 (레지스트리 등)
// TODO: Windows 롤백 구현
}
this.installState = checkpoint.state;
}
// === 상태 동기화 (내부 처리) ===
async syncState() {
// 서비스 종료 중이면 스킵
if (this.isShuttingDown) {
console.log('[OllamaService] Service is shutting down, skipping state sync');
return this.installState;
}
try {
const isInstalled = await this.isInstalled();
const isRunning = await this.isServiceRunning();
const models = isRunning && !this.isShuttingDown ? await this.getInstalledModels() : [];
const loadedModels = isRunning && !this.isShuttingDown ? await this.getLoadedModels() : [];
// 상태 업데이트
this.installState.isInstalled = isInstalled;
this.installState.isRunning = isRunning;
this.installState.lastSync = Date.now();
// 메모리 로드 상태 추적
const previousLoadedModels = this._lastLoadedModels || [];
const loadedChanged = loadedModels.length !== previousLoadedModels.length ||
!loadedModels.every(m => previousLoadedModels.includes(m));
if (loadedChanged) {
console.log(`[OllamaService] Loaded models changed: ${loadedModels.join(', ')}`);
this._lastLoadedModels = loadedModels;
// 메모리에서 언로드된 모델의 warmed 상태 제거
for (const modelName of this.warmedModels) {
if (!loadedModels.includes(modelName)) {
this.warmedModels.delete(modelName);
console.log(`[OllamaService] Model ${modelName} unloaded from memory, removing warmed state`);
}
}
}
// 모델 상태 DB 업데이트
if (isRunning && models.length > 0) {
for (const model of models) {
try {
const isLoaded = loadedModels.includes(model.name);
// DB에는 installed 상태만 저장, loaded 상태는 메모리에서 관리
await ollamaModelRepository.updateInstallStatus(model.name, true, false);
// 로드 상태를 인스턴스 변수에 저장
if (!this.modelLoadStatus) {
this.modelLoadStatus = new Map();
}
this.modelLoadStatus.set(model.name, isLoaded);
} catch (dbError) {
console.warn(`[OllamaService] Failed to update DB for model ${model.name}:`, dbError);
}
}
}
// UI 알림 (상태 변경 시만)
if (this._lastState?.isRunning !== isRunning ||
this._lastState?.isInstalled !== isInstalled ||
loadedChanged) {
// Emit state change event - LocalAIManager가 처리
this.emit('state-changed', {
installed: isInstalled,
running: isRunning,
models: models.length,
loadedModels: loadedModels
});
}
this._lastState = { isInstalled, isRunning, modelsCount: models.length };
return { isInstalled, isRunning, models };
} catch (error) {
console.error('[OllamaService] State sync failed:', error);
return {
isInstalled: this.installState.isInstalled || false,
isRunning: false,
models: []
};
}
}
// 주기적 동기화 시작
startPeriodicSync() {
if (this._syncInterval) return;
this._syncInterval = setInterval(() => {
this.syncState();
}, 30000); // 30초마다
}
stopPeriodicSync() {
if (this._syncInterval) {
clearInterval(this._syncInterval);
this._syncInterval = null;
}
}
async warmUpModel(modelName, forceRefresh = false) {
if (!modelName?.trim()) {
console.warn(`[OllamaService] Invalid model name for warm-up`);
return false;
}
// Check if already warmed (and not forcing refresh)
if (!forceRefresh && this.warmedModels.has(modelName)) {
console.log(`[OllamaService] Model ${modelName} already warmed up, skipping`);
return true;
}
// Check if currently warming - return existing Promise
if (this.warmingModels.has(modelName)) {
console.log(`[OllamaService] Model ${modelName} is already warming up, joining existing operation`);
return await this.warmingModels.get(modelName);
}
// Check rate limiting (prevent too frequent attempts)
const lastAttempt = this.lastWarmUpAttempt.get(modelName);
const now = Date.now();
if (lastAttempt && (now - lastAttempt) < 5000) { // 5 second cooldown
console.log(`[OllamaService] Rate limiting warm-up for ${modelName}, try again in ${5 - Math.floor((now - lastAttempt) / 1000)}s`);
return false;
}
// Create and store the warming Promise
const warmingPromise = this._performWarmUp(modelName);
this.warmingModels.set(modelName, warmingPromise);
this.lastWarmUpAttempt.set(modelName, now);
try {
const result = await warmingPromise;
if (result) {
this.warmedModels.add(modelName);
console.log(`[OllamaService] Model ${modelName} successfully warmed up`);
}
return result;
} finally {
// Always clean up the warming Promise
this.warmingModels.delete(modelName);
}
}
async _performWarmUp(modelName) {
console.log(`[OllamaService] Starting warm-up for model: ${modelName}`);
try {
const response = await this.makeRequest('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: modelName,
messages: [
{ role: 'user', content: 'Hi' }
],
stream: false,
options: {
num_predict: 1, // Minimal response
temperature: 0
}
})
});
return true;
} catch (error) {
// Check if it's a 404 error (model not found/installed)
if (error.message.includes('HTTP 404') || error.message.includes('Not Found')) {
console.log(`[OllamaService] Model ${modelName} not found (404), attempting to install...`);
try {
// Try to install the model
await this.pullModel(modelName);
console.log(`[OllamaService] Successfully installed model ${modelName}, retrying warm-up...`);
// Update database to reflect installation
await ollamaModelRepository.updateInstallStatus(modelName, true, false);
// Retry warm-up after installation
const retryResponse = await this.makeRequest('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: modelName,
messages: [
{ role: 'user', content: 'Hi' }
],
stream: false,
options: {
num_predict: 1,
temperature: 0
}
})
});
console.log(`[OllamaService] Successfully warmed up model ${modelName} after installation`);
return true;
} catch (installError) {
console.error(`[OllamaService] Failed to auto-install model ${modelName}:`, installError.message);
await ollamaModelRepository.updateInstallStatus(modelName, false, false);
return false;
}
} else {
console.error(`[OllamaService] Failed to warm up model ${modelName}:`, error.message);
return false;
}
}
}
async autoWarmUpSelectedModel() {
try {
// Get selected model from ModelStateService
const modelStateService = global.modelStateService;
if (!modelStateService) {
console.log('[OllamaService] ModelStateService not available for auto warm-up');
return false;
}
const selectedModels = await modelStateService.getSelectedModels();
const llmModelId = selectedModels.llm;
// Check if it's an Ollama model
const provider = modelStateService.getProviderForModel('llm', llmModelId);
if (provider !== 'ollama') {
console.log('[OllamaService] Selected LLM is not Ollama, skipping warm-up');
return false;
}
// Check if Ollama service is running
const isRunning = await this.isServiceRunning();
if (!isRunning) {
console.log('[OllamaService] Ollama service not running, clearing warm-up cache');
this._clearWarmUpCache();
return false;
}
// 설치 여부 체크 제거 - _performWarmUp에서 자동으로 설치 처리
console.log(`[OllamaService] Auto-warming up selected model: ${llmModelId} (will auto-install if needed)`);
const result = await this.warmUpModel(llmModelId);
// 성공 시 LocalAIManager에 알림
if (result) {
this.emit('model-warmed-up', { model: llmModelId });
}
return result;
} catch (error) {
console.error('[OllamaService] Auto warm-up failed:', error);
return false;
}
}
_clearWarmUpCache() {
this.warmedModels.clear();
this.warmingModels.clear();
this.lastWarmUpAttempt.clear();
console.log('[OllamaService] Warm-up cache cleared');
}
async getWarmUpStatus() {
const loadedModels = await this.getLoadedModels();
return {
warmedModels: Array.from(this.warmedModels),
warmingModels: Array.from(this.warmingModels.keys()),
loadedModels: loadedModels, // Models actually loaded in memory
lastAttempts: Object.fromEntries(this.lastWarmUpAttempt)
};
}
async shutdown(force = false) {
console.log(`[OllamaService] Shutdown initiated (force: ${force})`);
// 종료 중 플래그 설정
this.isShuttingDown = true;
if (!force && this.warmingModels.size > 0) {
const warmingList = Array.from(this.warmingModels.keys());
console.log(`[OllamaService] Waiting for ${warmingList.length} models to finish warming: ${warmingList.join(', ')}`);
const warmingPromises = Array.from(this.warmingModels.values());
try {
// Use Promise.allSettled instead of race with setTimeout
const results = await Promise.allSettled(warmingPromises);
const completed = results.filter(r => r.status === 'fulfilled').length;
console.log(`[OllamaService] ${completed}/${results.length} warming operations completed`);
} catch (error) {
console.log('[OllamaService] Error waiting for warm-up completion, proceeding with shutdown');
}
}
// Clean up all resources
this._clearWarmUpCache();
this.stopPeriodicSync();
// 프로세스 종료
const isRunning = await this.isServiceRunning();
if (!isRunning) {
console.log('[OllamaService] Service not running, nothing to shutdown');
return true;
}
const platform = this.getPlatform();
try {
switch(platform) {
case 'darwin':
return await this.shutdownMacOS(force);
case 'win32':
return await this.shutdownWindows(force);
case 'linux':
return await this.shutdownLinux(force);
default:
console.warn(`[OllamaService] Unsupported platform for shutdown: ${platform}`);
return false;
}
} catch (error) {
console.error(`[OllamaService] Error during shutdown:`, error);
return false;
}
}
async shutdownMacOS(force) {
try {
// 1. First, try to kill ollama server process
console.log('[OllamaService] Killing ollama server process...');
try {
await spawnAsync('pkill', ['-f', 'ollama serve']);
} catch (e) {
// Process might not be running
}
// 2. Then quit the Ollama.app
console.log('[OllamaService] Quitting Ollama.app...');
try {
await spawnAsync('osascript', ['-e', 'tell application "Ollama" to quit']);
} catch (e) {
console.log('[OllamaService] Ollama.app might not be running');
}
// 3. Wait a moment for shutdown
await new Promise(resolve => setTimeout(resolve, 2000));
// 4. Force kill any remaining ollama processes
if (force || await this.isServiceRunning()) {
console.log('[OllamaService] Force killing any remaining ollama processes...');
try {
// Kill all ollama processes
await spawnAsync('pkill', ['-9', '-f', 'ollama']);
} catch (e) {
// Ignore errors - process might not exist
}
}
// 5. Final check
await new Promise(resolve => setTimeout(resolve, 1000));
const stillRunning = await this.isServiceRunning();
if (stillRunning) {
console.warn('[OllamaService] Warning: Ollama may still be running');
return false;
}
console.log('[OllamaService] Ollama shutdown complete');
return true;
} catch (error) {
console.error('[OllamaService] Shutdown error:', error);
return false;
}
}
async shutdownWindows(force) {
try {
// Try to stop the service gracefully
await spawnAsync('taskkill', ['/IM', 'ollama.exe', '/T']);
console.log('[OllamaService] Ollama process terminated on Windows');
return true;
} catch (error) {
console.log('[OllamaService] Standard termination failed, trying force kill');
try {
await spawnAsync('taskkill', ['/IM', 'ollama.exe', '/F', '/T']);
return true;
} catch (killError) {
console.error('[OllamaService] Failed to force kill Ollama on Windows:', killError);
return false;
}
}
}
async shutdownLinux(force) {
try {
await spawnAsync('pkill', ['-f', this.getOllamaCliPath()]);
console.log('[OllamaService] Ollama process terminated on Linux');
return true;
} catch (error) {
if (force) {
await spawnAsync('pkill', ['-9', '-f', this.getOllamaCliPath()]).catch(() => {});
}
console.error('[OllamaService] Failed to shutdown Ollama on Linux:', error);
return false;
}
}
async getAllModelsWithStatus() {
// Get all installed models directly from Ollama
const installedModels = await this.getInstalledModels();
// Get loaded models from memory
const loadedModels = await this.getLoadedModels();
const models = [];
for (const model of installedModels) {
const isWarmingUp = this.warmingModels.has(model.name);
const isWarmedUp = this.warmedModels.has(model.name);
const isLoaded = loadedModels.includes(model.name);
models.push({
name: model.name,
displayName: model.name, // Use model name as display name
size: model.size || 'Unknown',
description: `Ollama model: ${model.name}`,
installed: true,
installing: this.installationProgress.has(model.name),
progress: this.getInstallProgress(model.name),
warmedUp: isWarmedUp,
isWarmingUp,
isLoaded, // Actually loaded in memory
status: isWarmingUp ? 'warming' : (isLoaded ? 'loaded' : (isWarmedUp ? 'ready' : 'cold'))
});
}
// Also add any models currently being installed
for (const [modelName, progress] of this.installationProgress) {
if (!models.find(m => m.name === modelName)) {
models.push({
name: modelName,
displayName: modelName,
size: 'Unknown',
description: `Ollama model: ${modelName}`,
installed: false,
installing: true,
progress: progress
});
}
}
return models;
}
async handleGetStatus() {
try {
const installed = await this.isInstalled();
if (!installed) {
return { success: true, installed: false, running: false, models: [] };
}
const running = await this.isServiceRunning();
if (!running) {
return { success: true, installed: true, running: false, models: [] };
}
const models = await this.getAllModelsWithStatus();
return { success: true, installed: true, running: true, models };
} catch (error) {
console.error('[OllamaService] Error getting status:', error);
return { success: false, error: error.message, installed: false, running: false, models: [] };
}
}
async handleInstall() {
try {
const onProgress = (data) => {
// Emit progress event - LocalAIManager가 처리
this.emit('install-progress', data);
};
await this.autoInstall(onProgress);
// 설치 검증
onProgress({ stage: 'verifying', message: 'Verifying installation...', progress: 0 });
const verifyResult = await this.verifyInstallation();
if (!verifyResult.success) {
throw new Error(`Installation verification failed: ${verifyResult.error}`);
}
onProgress({ stage: 'verifying', message: 'Installation verified.', progress: 100 });
if (!await this.isServiceRunning()) {
onProgress({ stage: 'starting', message: 'Starting Ollama service...', progress: 0 });
await this.startService();
onProgress({ stage: 'starting', message: 'Ollama service started.', progress: 100 });
}
this.installState.isInstalled = true;
// Emit completion event - LocalAIManager가 처리
this.emit('installation-complete');
return { success: true };
} catch (error) {
console.error('[OllamaService] Failed to install:', error);
await this.rollbackToLastCheckpoint();
// Emit error event - LocalAIManager가 처리
this.emit('error', {
errorType: 'installation-failed',
error: error.message
});
return { success: false, error: error.message };
}
}
async handleStartService() {
try {
if (!await this.isServiceRunning()) {
console.log('[OllamaService] Starting Ollama service...');
await this.startService();
}
this.emit('install-complete', { success: true });
return { success: true };
} catch (error) {
console.error('[OllamaService] Failed to start service:', error);
this.emit('install-complete', { success: false, error: error.message });
return { success: false, error: error.message };
}
}
async handleEnsureReady() {
try {
if (await this.isInstalled() && !await this.isServiceRunning()) {
console.log('[OllamaService] Ollama installed but not running, starting service...');
await this.startService();
}
return { success: true };
} catch (error) {
console.error('[OllamaService] Failed to ensure ready:', error);
return { success: false, error: error.message };
}
}
async handleGetModels() {
try {
const models = await this.getAllModelsWithStatus();
return { success: true, models };
} catch (error) {
console.error('[OllamaService] Failed to get models:', error);
return { success: false, error: error.message };
}
}
async handleGetModelSuggestions() {
try {
const suggestions = await this.getModelSuggestions();
return { success: true, suggestions };
} catch (error) {
console.error('[OllamaService] Failed to get model suggestions:', error);
return { success: false, error: error.message };
}
}
async handlePullModel(modelName) {
try {
console.log(`[OllamaService] Starting model pull: ${modelName}`);
await ollamaModelRepository.updateInstallStatus(modelName, false, true);
await this.pullModel(modelName);
await ollamaModelRepository.updateInstallStatus(modelName, true, false);
console.log(`[OllamaService] Model ${modelName} pull successful`);
return { success: true };
} catch (error) {
console.error('[OllamaService] Failed to pull model:', error);
await ollamaModelRepository.updateInstallStatus(modelName, false, false);
// Emit error event - LocalAIManager가 처리
this.emit('error', {
errorType: 'model-pull-failed',
model: modelName,
error: error.message
});
return { success: false, error: error.message };
}
}
async handleIsModelInstalled(modelName) {
try {
const installed = await this.isModelInstalled(modelName);
return { success: true, installed };
} catch (error) {
console.error('[OllamaService] Failed to check model installation:', error);
return { success: false, error: error.message };
}
}
async handleWarmUpModel(modelName) {
try {
const success = await this.warmUpModel(modelName);
return { success };
} catch (error) {
console.error('[OllamaService] Failed to warm up model:', error);
return { success: false, error: error.message };
}
}
async handleAutoWarmUp() {
try {
const success = await this.autoWarmUpSelectedModel();
return { success };
} catch (error) {
console.error('[OllamaService] Failed to auto warm-up:', error);
return { success: false, error: error.message };
}
}
async handleGetWarmUpStatus() {
try {
const status = await this.getWarmUpStatus();
return { success: true, status };
} catch (error) {
console.error('[OllamaService] Failed to get warm-up status:', error);
return { success: false, error: error.message };
}
}
async handleShutdown(force = false) {
try {
console.log(`[OllamaService] Manual shutdown requested (force: ${force})`);
const success = await this.shutdown(force);
// 종료 후 상태 업데이트 및 플래그 리셋
if (success) {
// 종료 완료 후 플래그 리셋
this.isShuttingDown = false;
await this.syncState();
}
return { success };
} catch (error) {
console.error('[OllamaService] Failed to shutdown Ollama:', error);
return { success: false, error: error.message };
}
}
// 설치 검증
async verifyInstallation() {
try {
console.log('[OllamaService] Verifying installation...');
// 1. 바이너리 확인
const isInstalled = await this.isInstalled();
if (!isInstalled) {
return { success: false, error: 'Ollama binary not found' };
}
// 2. CLI 명령 테스트
try {
const { stdout } = await spawnAsync(this.getOllamaCliPath(), ['--version']);
console.log('[OllamaService] Ollama version:', stdout.trim());
} catch (error) {
return { success: false, error: 'Ollama CLI not responding' };
}
// 3. 서비스 시작 가능 여부 확인
const platform = this.getPlatform();
if (platform === 'darwin') {
// macOS: 앱 번들 확인
try {
await fs.access('/Applications/Ollama.app/Contents/MacOS/Ollama');
} catch (error) {
return { success: false, error: 'Ollama.app executable not found' };
}
}
console.log('[OllamaService] Installation verified successfully');
return { success: true };
} catch (error) {
console.error('[OllamaService] Verification failed:', error);
return { success: false, error: error.message };
}
}
}
// Export singleton instance
const ollamaService = new OllamaService();
module.exports = ollamaService;
================================================
FILE: src/features/common/services/permissionService.js
================================================
const { systemPreferences, shell, desktopCapturer } = require('electron');
const permissionRepository = require('../repositories/permission');
class PermissionService {
_getAuthService() {
return require('./authService');
}
async checkSystemPermissions() {
const permissions = {
microphone: 'unknown',
screen: 'unknown',
keychain: 'unknown',
needsSetup: true
};
try {
if (process.platform === 'darwin') {
permissions.microphone = systemPreferences.getMediaAccessStatus('microphone');
permissions.screen = systemPreferences.getMediaAccessStatus('screen');
permissions.keychain = await this.checkKeychainCompleted(this._getAuthService().getCurrentUserId()) ? 'granted' : 'unknown';
permissions.needsSetup = permissions.microphone !== 'granted' || permissions.screen !== 'granted' || permissions.keychain !== 'granted';
} else {
permissions.microphone = 'granted';
permissions.screen = 'granted';
permissions.keychain = 'granted';
permissions.needsSetup = false;
}
console.log('[Permissions] System permissions status:', permissions);
return permissions;
} catch (error) {
console.error('[Permissions] Error checking permissions:', error);
return {
microphone: 'unknown',
screen: 'unknown',
keychain: 'unknown',
needsSetup: true,
error: error.message
};
}
}
async requestMicrophonePermission() {
if (process.platform !== 'darwin') {
return { success: true };
}
try {
const status = systemPreferences.getMediaAccessStatus('microphone');
console.log('[Permissions] Microphone status:', status);
if (status === 'granted') {
return { success: true, status: 'granted' };
}
const granted = await systemPreferences.askForMediaAccess('microphone');
return {
success: granted,
status: granted ? 'granted' : 'denied'
};
} catch (error) {
console.error('[Permissions] Error requesting microphone permission:', error);
return {
success: false,
error: error.message
};
}
}
async openSystemPreferences(section) {
if (process.platform !== 'darwin') {
return { success: false, error: 'Not supported on this platform' };
}
try {
if (section === 'screen-recording') {
try {
console.log('[Permissions] Triggering screen capture request to register app...');
await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: { width: 1, height: 1 }
});
console.log('[Permissions] App registered for screen recording');
} catch (captureError) {
console.log('[Permissions] Screen capture request triggered (expected to fail):', captureError.message);
}
// await shell.openExternal('x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture');
}
return { success: true };
} catch (error) {
console.error('[Permissions] Error opening system preferences:', error);
return { success: false, error: error.message };
}
}
async markKeychainCompleted() {
try {
await permissionRepository.markKeychainCompleted(this._getAuthService().getCurrentUserId());
console.log('[Permissions] Marked keychain as completed');
return { success: true };
} catch (error) {
console.error('[Permissions] Error marking keychain as completed:', error);
return { success: false, error: error.message };
}
}
async checkKeychainCompleted(uid) {
if (uid === "default_user") {
return true;
}
try {
const completed = permissionRepository.checkKeychainCompleted(uid);
console.log('[Permissions] Keychain completed status:', completed);
return completed;
} catch (error) {
console.error('[Permissions] Error checking keychain completed status:', error);
return false;
}
}
}
const permissionService = new PermissionService();
module.exports = permissionService;
================================================
FILE: src/features/common/services/sqliteClient.js
================================================
const Database = require('better-sqlite3');
const path = require('path');
const LATEST_SCHEMA = require('../config/schema');
class SQLiteClient {
constructor() {
this.db = null;
this.dbPath = null;
this.defaultUserId = 'default_user';
}
connect(dbPath) {
if (this.db) {
console.log('[SQLiteClient] Already connected.');
return;
}
try {
this.dbPath = dbPath;
this.db = new Database(this.dbPath);
this.db.pragma('journal_mode = WAL');
console.log('[SQLiteClient] Connected successfully to:', this.dbPath);
} catch (err) {
console.error('[SQLiteClient] Could not connect to database', err);
throw err;
}
}
getDb() {
if (!this.db) {
throw new Error("Database not connected. Call connect() first.");
}
return this.db;
}
_validateAndQuoteIdentifier(identifier) {
if (!/^[a-zA-Z0-9_]+$/.test(identifier)) {
throw new Error(`Invalid database identifier used: ${identifier}. Only alphanumeric characters and underscores are allowed.`);
}
return `"${identifier}"`;
}
_migrateProviderSettings() {
const tablesInDb = this.getTablesFromDb();
if (!tablesInDb.includes('provider_settings')) {
return; // Table doesn't exist, no migration needed.
}
const providerSettingsInfo = this.db.prepare(`PRAGMA table_info(provider_settings)`).all();
const hasUidColumn = providerSettingsInfo.some(col => col.name === 'uid');
if (hasUidColumn) {
console.log('[DB Migration] Old provider_settings schema detected. Starting robust migration...');
try {
this.db.transaction(() => {
this.db.exec('ALTER TABLE provider_settings RENAME TO provider_settings_old');
console.log('[DB Migration] Renamed provider_settings to provider_settings_old');
this.createTable('provider_settings', LATEST_SCHEMA.provider_settings);
console.log('[DB Migration] Created new provider_settings table');
// Dynamically build the migration query for robustness
const oldColumnNames = this.db.prepare(`PRAGMA table_info(provider_settings_old)`).all().map(c => c.name);
const newColumnNames = LATEST_SCHEMA.provider_settings.columns.map(c => c.name);
const commonColumns = newColumnNames.filter(name => oldColumnNames.includes(name));
if (!commonColumns.includes('provider')) {
console.warn('[DB Migration] Old table is missing the "provider" column. Aborting migration for this table.');
this.db.exec('DROP TABLE provider_settings_old');
return;
}
const orderParts = [];
if (oldColumnNames.includes('updated_at')) orderParts.push('updated_at DESC');
if (oldColumnNames.includes('created_at')) orderParts.push('created_at DESC');
const orderByClause = orderParts.length > 0 ? `ORDER BY ${orderParts.join(', ')}` : '';
const columnsForInsert = commonColumns.map(c => this._validateAndQuoteIdentifier(c)).join(', ');
const migrationQuery = `
INSERT INTO provider_settings (${columnsForInsert})
SELECT ${columnsForInsert}
FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY provider ${orderByClause}) as rn
FROM provider_settings_old
)
WHERE rn = 1
`;
console.log(`[DB Migration] Executing robust migration query for columns: ${commonColumns.join(', ')}`);
const result = this.db.prepare(migrationQuery).run();
console.log(`[DB Migration] Migrated ${result.changes} rows to the new provider_settings table.`);
this.db.exec('DROP TABLE provider_settings_old');
console.log('[DB Migration] Dropped provider_settings_old table.');
})();
console.log('[DB Migration] provider_settings migration completed successfully.');
} catch (error) {
console.error('[DB Migration] Failed to migrate provider_settings table.', error);
// Try to recover by dropping the temp table if it exists
const oldTableExists = this.getTablesFromDb().includes('provider_settings_old');
if (oldTableExists) {
this.db.exec('DROP TABLE provider_settings_old');
console.warn('[DB Migration] Cleaned up temporary old table after failure.');
}
throw error;
}
}
}
async synchronizeSchema() {
console.log('[DB Sync] Starting schema synchronization...');
// Run special migration for provider_settings before the generic sync logic
this._migrateProviderSettings();
const tablesInDb = this.getTablesFromDb();
for (const tableName of Object.keys(LATEST_SCHEMA)) {
const tableSchema = LATEST_SCHEMA[tableName];
if (!tablesInDb.includes(tableName)) {
// Table doesn't exist, create it
this.createTable(tableName, tableSchema);
} else {
// Table exists, check for missing columns
this.updateTable(tableName, tableSchema);
}
}
console.log('[DB Sync] Schema synchronization finished.');
}
getTablesFromDb() {
const tables = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();
return tables.map(t => t.name);
}
createTable(tableName, tableSchema) {
const safeTableName = this._validateAndQuoteIdentifier(tableName);
const columnDefs = tableSchema.columns
.map(col => `${this._validateAndQuoteIdentifier(col.name)} ${col.type}`)
.join(', ');
const constraints = tableSchema.constraints || [];
const constraintsDef = constraints.length > 0 ? ', ' + constraints.join(', ') : '';
const query = `CREATE TABLE IF NOT EXISTS ${safeTableName} (${columnDefs}${constraintsDef})`;
console.log(`[DB Sync] Creating table: ${tableName}`);
this.db.exec(query);
}
updateTable(tableName, tableSchema) {
const safeTableName = this._validateAndQuoteIdentifier(tableName);
// Get current columns
const currentColumns = this.db.prepare(`PRAGMA table_info(${safeTableName})`).all();
const currentColumnNames = currentColumns.map(col => col.name);
// Check for new columns to add
const newColumns = tableSchema.columns.filter(col => !currentColumnNames.includes(col.name));
if (newColumns.length > 0) {
console.log(`[DB Sync] Adding ${newColumns.length} new column(s) to ${tableName}`);
for (const col of newColumns) {
const safeColName = this._validateAndQuoteIdentifier(col.name);
const addColumnQuery = `ALTER TABLE ${safeTableName} ADD COLUMN ${safeColName} ${col.type}`;
this.db.exec(addColumnQuery);
console.log(`[DB Sync] Added column ${col.name} to ${tableName}`);
}
}
if (tableSchema.constraints && tableSchema.constraints.length > 0) {
console.log(`[DB Sync] Note: Constraints for ${tableName} can only be set during table creation`);
}
}
runQuery(query, params = []) {
return this.db.prepare(query).run(params);
}
cleanupEmptySessions() {
console.log('[DB Cleanup] Checking for empty sessions...');
const query = `
SELECT s.id FROM sessions s
LEFT JOIN transcripts t ON s.id = t.session_id
LEFT JOIN ai_messages a ON s.id = a.session_id
LEFT JOIN summaries su ON s.id = su.session_id
WHERE t.id IS NULL AND a.id IS NULL AND su.session_id IS NULL
`;
const rows = this.db.prepare(query).all();
if (rows.length === 0) {
console.log('[DB Cleanup] No empty sessions found.');
return;
}
const idsToDelete = rows.map(r => r.id);
const placeholders = idsToDelete.map(() => '?').join(',');
const deleteQuery = `DELETE FROM sessions WHERE id IN (${placeholders})`;
console.log(`[DB Cleanup] Found ${idsToDelete.length} empty sessions. Deleting...`);
const result = this.db.prepare(deleteQuery).run(idsToDelete);
console.log(`[DB Cleanup] Successfully deleted ${result.changes} empty sessions.`);
}
async initTables() {
await this.synchronizeSchema();
this.initDefaultData();
}
initDefaultData() {
const now = Math.floor(Date.now() / 1000);
const initUserQuery = `
INSERT OR IGNORE INTO users (uid, display_name, email, created_at)
VALUES (?, ?, ?, ?)
`;
this.db.prepare(initUserQuery).run(this.defaultUserId, 'Default User', 'contact@pickle.com', now);
const defaultPresets = [
['school', 'School', 'You are a school and lecture assistant. Your goal is to help the user, a student, understand academic material and answer questions.\n\nWhenever a question appears on the user\'s screen or is asked aloud, you provide a direct, step-by-step answer, showing all necessary reasoning or calculations.\n\nIf the user is watching a lecture or working through new material, you offer concise explanations of key concepts and clarify definitions as they come up.', 1],
['meetings', 'Meetings', 'You are a meeting assistant. Your goal is to help the user capture key information during meetings and follow up effectively.\n\nYou help capture meeting notes, track action items, identify key decisions, and summarize important points discussed during meetings.', 1],
['sales', 'Sales', 'You are a real-time AI sales assistant, and your goal is to help the user close deals during sales interactions.\n\nYou provide real-time sales support, suggest responses to objections, help identify customer needs, and recommend strategies to advance deals.', 1],
['recruiting', 'Recruiting', 'You are a recruiting assistant. Your goal is to help the user interview candidates and evaluate talent effectively.\n\nYou help evaluate candidates, suggest interview questions, analyze responses, and provide insights about candidate fit for positions.', 1],
['customer-support', 'Customer Support', 'You are a customer support assistant. Your goal is to help resolve customer issues efficiently and thoroughly.\n\nYou help diagnose customer problems, suggest solutions, provide step-by-step troubleshooting guidance, and ensure customer satisfaction.', 1],
];
const stmt = this.db.prepare(`
INSERT OR IGNORE INTO prompt_presets (id, uid, title, prompt, is_default, created_at)
VALUES (?, ?, ?, ?, ?, ?)
`);
for (const preset of defaultPresets) {
stmt.run(preset[0], this.defaultUserId, preset[1], preset[2], preset[3], now);
}
console.log('Default data initialized.');
}
close() {
if (this.db) {
try {
this.db.close();
console.log('SQLite connection closed.');
} catch (err) {
console.error('SQLite connection close failed:', err);
}
this.db = null;
}
}
query(sql, params = []) {
if (!this.db) {
throw new Error('Database not connected');
}
try {
if (sql.toUpperCase().startsWith('SELECT')) {
return this.db.prepare(sql).all(params);
} else {
const result = this.db.prepare(sql).run(params);
return { changes: result.changes, lastID: result.lastID };
}
} catch (err) {
console.error('Query error:', err);
throw err;
}
}
}
const sqliteClient = new SQLiteClient();
module.exports = sqliteClient;
================================================
FILE: src/features/common/services/whisperService.js
================================================
const { EventEmitter } = require('events');
const { spawn, exec } = require('child_process');
const { promisify } = require('util');
const path = require('path');
const fs = require('fs');
const os = require('os');
const https = require('https');
const crypto = require('crypto');
const { spawnAsync } = require('../utils/spawnHelper');
const { DOWNLOAD_CHECKSUMS } = require('../config/checksums');
const execAsync = promisify(exec);
const fsPromises = fs.promises;
class WhisperService extends EventEmitter {
constructor() {
super();
this.serviceName = 'WhisperService';
// 경로 및 디렉토리
this.whisperPath = null;
this.modelsDir = null;
this.tempDir = null;
// 세션 관리 (세션 풀 내장)
this.sessionPool = [];
this.activeSessions = new Map();
this.maxSessions = 3;
// 설치 상태
this.installState = {
isInstalled: false,
isInitialized: false
};
// 사용 가능한 모델
this.availableModels = {
'whisper-tiny': {
name: 'Tiny',
size: '39M',
url: 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.bin'
},
'whisper-base': {
name: 'Base',
size: '74M',
url: 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin'
},
'whisper-small': {
name: 'Small',
size: '244M',
url: 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin'
},
'whisper-medium': {
name: 'Medium',
size: '769M',
url: 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-medium.bin'
}
};
}
// Base class methods integration
getPlatform() {
return process.platform;
}
async checkCommand(command) {
try {
const platform = this.getPlatform();
const checkCmd = platform === 'win32' ? 'where' : 'which';
const { stdout } = await execAsync(`${checkCmd} ${command}`);
return stdout.trim();
} catch (error) {
return null;
}
}
async waitForService(checkFn, maxAttempts = 30, delayMs = 1000) {
for (let i = 0; i < maxAttempts; i++) {
if (await checkFn()) {
console.log(`[${this.serviceName}] Service is ready`);
return true;
}
await new Promise(resolve => setTimeout(resolve, delayMs));
}
throw new Error(`${this.serviceName} service failed to start within timeout`);
}
async downloadFile(url, destination, options = {}) {
const {
onProgress = null,
headers = { 'User-Agent': 'Glass-App' },
timeout = 300000,
modelId = null
} = options;
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(destination);
let downloadedSize = 0;
let totalSize = 0;
const request = https.get(url, { headers }, (response) => {
if ([301, 302, 307, 308].includes(response.statusCode)) {
file.close();
fs.unlink(destination, () => {});
if (!response.headers.location) {
reject(new Error('Redirect without location header'));
return;
}
console.log(`[${this.serviceName}] Following redirect from ${url} to ${response.headers.location}`);
this.downloadFile(response.headers.location, destination, options)
.then(resolve)
.catch(reject);
return;
}
if (response.statusCode !== 200) {
file.close();
fs.unlink(destination, () => {});
reject(new Error(`Download failed: ${response.statusCode} ${response.statusMessage}`));
return;
}
totalSize = parseInt(response.headers['content-length'], 10) || 0;
response.on('data', (chunk) => {
downloadedSize += chunk.length;
if (totalSize > 0) {
const progress = Math.round((downloadedSize / totalSize) * 100);
if (onProgress) {
onProgress(progress, downloadedSize, totalSize);
}
}
});
response.pipe(file);
file.on('finish', () => {
file.close(() => {
resolve({ success: true, size: downloadedSize });
});
});
});
request.on('timeout', () => {
request.destroy();
file.close();
fs.unlink(destination, () => {});
reject(new Error('Download timeout'));
});
request.on('error', (err) => {
file.close();
fs.unlink(destination, () => {});
this.emit('download-error', { url, error: err, modelId });
reject(err);
});
request.setTimeout(timeout);
file.on('error', (err) => {
fs.unlink(destination, () => {});
reject(err);
});
});
}
async downloadWithRetry(url, destination, options = {}) {
const {
maxRetries = 3,
retryDelay = 1000,
expectedChecksum = null,
modelId = null,
...downloadOptions
} = options;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const result = await this.downloadFile(url, destination, {
...downloadOptions,
modelId
});
if (expectedChecksum) {
const isValid = await this.verifyChecksum(destination, expectedChecksum);
if (!isValid) {
fs.unlinkSync(destination);
throw new Error('Checksum verification failed');
}
console.log(`[${this.serviceName}] Checksum verified successfully`);
}
return result;
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`Download attempt ${attempt} failed, retrying in ${retryDelay}ms...`);
await new Promise(resolve => setTimeout(resolve, retryDelay * attempt));
}
}
}
async verifyChecksum(filePath, expectedChecksum) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
stream.on('data', (data) => hash.update(data));
stream.on('end', () => {
const fileChecksum = hash.digest('hex');
console.log(`[${this.serviceName}] File checksum: ${fileChecksum}`);
console.log(`[${this.serviceName}] Expected checksum: ${expectedChecksum}`);
resolve(fileChecksum === expectedChecksum);
});
stream.on('error', reject);
});
}
async autoInstall(onProgress) {
const platform = this.getPlatform();
console.log(`[${this.serviceName}] Starting auto-installation for ${platform}`);
try {
switch(platform) {
case 'darwin':
return await this.installMacOS(onProgress);
case 'win32':
return await this.installWindows(onProgress);
case 'linux':
return await this.installLinux();
default:
throw new Error(`Unsupported platform: ${platform}`);
}
} catch (error) {
console.error(`[${this.serviceName}] Auto-installation failed:`, error);
throw error;
}
}
async shutdown(force = false) {
console.log(`[${this.serviceName}] Starting ${force ? 'forced' : 'graceful'} shutdown...`);
const isRunning = await this.isServiceRunning();
if (!isRunning) {
console.log(`[${this.serviceName}] Service not running, nothing to shutdown`);
return true;
}
const platform = this.getPlatform();
try {
switch(platform) {
case 'darwin':
return await this.shutdownMacOS(force);
case 'win32':
return await this.shutdownWindows(force);
case 'linux':
return await this.shutdownLinux(force);
default:
console.warn(`[${this.serviceName}] Unsupported platform for shutdown: ${platform}`);
return false;
}
} catch (error) {
console.error(`[${this.serviceName}] Error during shutdown:`, error);
return false;
}
}
async initialize() {
if (this.installState.isInitialized) return;
try {
const homeDir = os.homedir();
const whisperDir = path.join(homeDir, '.glass', 'whisper');
this.modelsDir = path.join(whisperDir, 'models');
this.tempDir = path.join(whisperDir, 'temp');
// Windows에서는 .exe 확장자 필요
const platform = this.getPlatform();
const whisperExecutable = platform === 'win32' ? 'whisper-whisper.exe' : 'whisper';
this.whisperPath = path.join(whisperDir, 'bin', whisperExecutable);
await this.ensureDirectories();
await this.ensureWhisperBinary();
this.installState.isInitialized = true;
console.log('[WhisperService] Initialized successfully');
} catch (error) {
console.error('[WhisperService] Initialization failed:', error);
// Emit error event - LocalAIManager가 처리
this.emit('error', {
errorType: 'initialization-failed',
error: error.message
});
throw error;
}
}
async ensureDirectories() {
await fsPromises.mkdir(this.modelsDir, { recursive: true });
await fsPromises.mkdir(this.tempDir, { recursive: true });
await fsPromises.mkdir(path.dirname(this.whisperPath), { recursive: true });
}
// local stt session
async getSession(config) {
// check available session
const availableSession = this.sessionPool.find(s => !s.inUse);
if (availableSession) {
availableSession.inUse = true;
await availableSession.reconfigure(config);
return availableSession;
}
// create new session
if (this.activeSessions.size >= this.maxSessions) {
throw new Error('Maximum session limit reached');
}
const session = new WhisperSession(config, this);
await session.initialize();
this.activeSessions.set(session.id, session);
return session;
}
async releaseSession(sessionId) {
const session = this.activeSessions.get(sessionId);
if (session) {
await session.cleanup();
session.inUse = false;
// add to session pool
if (this.sessionPool.length < 2) {
this.sessionPool.push(session);
} else {
// remove session
await session.destroy();
this.activeSessions.delete(sessionId);
}
}
}
//cleanup
async cleanup() {
// cleanup all sessions
for (const session of this.activeSessions.values()) {
await session.destroy();
}
this.activeSessions.clear();
this.sessionPool = [];
}
async ensureWhisperBinary() {
const whisperCliPath = await this.checkCommand('whisper-cli');
if (whisperCliPath) {
this.whisperPath = whisperCliPath;
console.log(`[WhisperService] Found whisper-cli at: ${this.whisperPath}`);
return;
}
const whisperPath = await this.checkCommand('whisper');
if (whisperPath) {
this.whisperPath = whisperPath;
console.log(`[WhisperService] Found whisper at: ${this.whisperPath}`);
return;
}
try {
await fsPromises.access(this.whisperPath, fs.constants.X_OK);
console.log('[WhisperService] Custom whisper binary found');
return;
} catch (error) {
// Continue to installation
}
const platform = this.getPlatform();
if (platform === 'darwin') {
console.log('[WhisperService] Whisper not found, trying Homebrew installation...');
try {
await this.installViaHomebrew();
// verify installation
const verified = await this.verifyInstallation();
if (!verified.success) {
throw new Error(verified.error);
}
return;
} catch (error) {
console.log('[WhisperService] Homebrew installation failed:', error.message);
}
}
await this.autoInstall();
// verify installation
const verified = await this.verifyInstallation();
if (!verified.success) {
throw new Error(`Whisper installation verification failed: ${verified.error}`);
}
}
async installViaHomebrew() {
const brewPath = await this.checkCommand('brew');
if (!brewPath) {
throw new Error('Homebrew not found. Please install Homebrew first.');
}
console.log('[WhisperService] Installing whisper-cpp via Homebrew...');
await spawnAsync('brew', ['install', 'whisper-cpp']);
const whisperCliPath = await this.checkCommand('whisper-cli');
if (whisperCliPath) {
this.whisperPath = whisperCliPath;
console.log(`[WhisperService] Whisper-cli installed via Homebrew at: ${this.whisperPath}`);
} else {
const whisperPath = await this.checkCommand('whisper');
if (whisperPath) {
this.whisperPath = whisperPath;
console.log(`[WhisperService] Whisper installed via Homebrew at: ${this.whisperPath}`);
}
}
}
async ensureModelAvailable(modelId) {
if (!this.installState.isInitialized) {
console.log('[WhisperService] Service not initialized, initializing now...');
await this.initialize();
}
const modelInfo = this.availableModels[modelId];
if (!modelInfo) {
throw new Error(`Unknown model: ${modelId}. Available models: ${Object.keys(this.availableModels).join(', ')}`);
}
const modelPath = await this.getModelPath(modelId);
try {
await fsPromises.access(modelPath, fs.constants.R_OK);
console.log(`[WhisperService] Model ${modelId} already available at: ${modelPath}`);
} catch (error) {
console.log(`[WhisperService] Model ${modelId} not found, downloading...`);
await this.downloadModel(modelId);
}
}
async downloadModel(modelId) {
const modelInfo = this.availableModels[modelId];
const modelPath = await this.getModelPath(modelId);
const checksumInfo = DOWNLOAD_CHECKSUMS.whisper.models[modelId];
// Emit progress event - LocalAIManager가 처리
this.emit('install-progress', {
model: modelId,
progress: 0
});
await this.downloadWithRetry(modelInfo.url, modelPath, {
expectedChecksum: checksumInfo?.sha256,
modelId, // pass modelId to LocalAIServiceBase for event handling
onProgress: (progress) => {
// Emit progress event - LocalAIManager가 처리
this.emit('install-progress', {
model: modelId,
progress
});
}
});
console.log(`[WhisperService] Model ${modelId} downloaded successfully`);
this.emit('model-download-complete', { modelId });
}
async handleDownloadModel(modelId) {
try {
console.log(`[WhisperService] Handling download for model: ${modelId}`);
if (!this.installState.isInitialized) {
await this.initialize();
}
await this.ensureModelAvailable(modelId);
return { success: true };
} catch (error) {
console.error(`[WhisperService] Failed to handle download for model ${modelId}:`, error);
return { success: false, error: error.message };
}
}
async handleGetInstalledModels() {
try {
if (!this.installState.isInitialized) {
await this.initialize();
}
const models = await this.getInstalledModels();
return { success: true, models };
} catch (error) {
console.error('[WhisperService] Failed to get installed models:', error);
return { success: false, error: error.message };
}
}
async getModelPath(modelId) {
if (!this.installState.isInitialized || !this.modelsDir) {
throw new Error('WhisperService is not initialized. Call initialize() first.');
}
return path.join(this.modelsDir, `${modelId}.bin`);
}
async getWhisperPath() {
return this.whisperPath;
}
async saveAudioToTemp(audioBuffer, sessionId = '') {
const timestamp = Date.now();
const random = Math.random().toString(36).substr(2, 6);
const sessionPrefix = sessionId ? `${sessionId}_` : '';
const tempFile = path.join(this.tempDir, `audio_${sessionPrefix}${timestamp}_${random}.wav`);
const wavHeader = this.createWavHeader(audioBuffer.length);
const wavBuffer = Buffer.concat([wavHeader, audioBuffer]);
await fsPromises.writeFile(tempFile, wavBuffer);
return tempFile;
}
createWavHeader(dataSize) {
const header = Buffer.alloc(44);
const sampleRate = 16000;
const numChannels = 1;
const bitsPerSample = 16;
header.write('RIFF', 0);
header.writeUInt32LE(36 + dataSize, 4);
header.write('WAVE', 8);
header.write('fmt ', 12);
header.writeUInt32LE(16, 16);
header.writeUInt16LE(1, 20);
header.writeUInt16LE(numChannels, 22);
header.writeUInt32LE(sampleRate, 24);
header.writeUInt32LE(sampleRate * numChannels * bitsPerSample / 8, 28);
header.writeUInt16LE(numChannels * bitsPerSample / 8, 32);
header.writeUInt16LE(bitsPerSample, 34);
header.write('data', 36);
header.writeUInt32LE(dataSize, 40);
return header;
}
async cleanupTempFile(filePath) {
if (!filePath || typeof filePath !== 'string') {
console.warn('[WhisperService] Invalid file path for cleanup:', filePath);
return;
}
const filesToCleanup = [
filePath,
filePath.replace('.wav', '.txt'),
filePath.replace('.wav', '.json')
];
for (const file of filesToCleanup) {
try {
// Check if file exists before attempting to delete
await fsPromises.access(file, fs.constants.F_OK);
await fsPromises.unlink(file);
console.log(`[WhisperService] Cleaned up: ${file}`);
} catch (error) {
// File doesn't exist or already deleted - this is normal
if (error.code !== 'ENOENT') {
console.warn(`[WhisperService] Failed to cleanup ${file}:`, error.message);
}
}
}
}
async getInstalledModels() {
if (!this.installState.isInitialized) {
console.log('[WhisperService] Service not initialized for getInstalledModels, initializing now...');
await this.initialize();
}
const models = [];
for (const [modelId, modelInfo] of Object.entries(this.availableModels)) {
try {
const modelPath = await this.getModelPath(modelId);
await fsPromises.access(modelPath, fs.constants.R_OK);
models.push({
id: modelId,
name: modelInfo.name,
size: modelInfo.size,
installed: true
});
} catch (error) {
models.push({
id: modelId,
name: modelInfo.name,
size: modelInfo.size,
installed: false
});
}
}
return models;
}
async isServiceRunning() {
return this.installState.isInitialized;
}
async startService() {
if (!this.installState.isInitialized) {
await this.initialize();
}
return true;
}
async stopService() {
return true;
}
async isInstalled() {
try {
const whisperPath = await this.checkCommand('whisper-cli') || await this.checkCommand('whisper');
return !!whisperPath;
} catch (error) {
return false;
}
}
async installMacOS() {
throw new Error('Binary installation not available for macOS. Please install Homebrew and run: brew install whisper-cpp');
}
async installWindows() {
console.log('[WhisperService] Installing Whisper on Windows...');
const version = 'v1.7.6';
const binaryUrl = `https://github.com/ggml-org/whisper.cpp/releases/download/${version}/whisper-bin-x64.zip`;
const tempFile = path.join(this.tempDir, 'whisper-binary.zip');
try {
console.log('[WhisperService] Step 1: Downloading Whisper binary...');
await this.downloadWithRetry(binaryUrl, tempFile);
console.log('[WhisperService] Step 2: Extracting archive...');
const extractDir = path.join(this.tempDir, 'extracted');
// 임시 압축 해제 디렉토리 생성
await fsPromises.mkdir(extractDir, { recursive: true });
// PowerShell 명령에서 경로를 올바르게 인용
const expandCommand = `Expand-Archive -Path "${tempFile}" -DestinationPath "${extractDir}" -Force`;
await spawnAsync('powershell', ['-command', expandCommand]);
console.log('[WhisperService] Step 3: Finding and moving whisper executable...');
// 압축 해제된 디렉토리에서 whisper.exe 파일 찾기
const whisperExecutables = await this.findWhisperExecutables(extractDir);
if (whisperExecutables.length === 0) {
throw new Error('whisper.exe not found in extracted files');
}
// 첫 번째로 찾은 whisper.exe를 목표 위치로 복사
const sourceExecutable = whisperExecutables[0];
const targetDir = path.dirname(this.whisperPath);
await fsPromises.mkdir(targetDir, { recursive: true });
await fsPromises.copyFile(sourceExecutable, this.whisperPath);
console.log('[WhisperService] Step 4: Verifying installation...');
// 설치 검증
await fsPromises.access(this.whisperPath, fs.constants.F_OK);
// whisper.exe 실행 테스트
try {
await spawnAsync(this.whisperPath, ['--help']);
console.log('[WhisperService] Whisper executable verified successfully');
} catch (testError) {
console.warn('[WhisperService] Whisper executable test failed, but file exists:', testError.message);
}
console.log('[WhisperService] Step 5: Cleanup...');
// 임시 파일 정리
await fsPromises.unlink(tempFile).catch(() => {});
await this.removeDirectory(extractDir).catch(() => {});
console.log('[WhisperService] Whisper installed successfully on Windows');
return true;
} catch (error) {
console.error('[WhisperService] Windows installation failed:', error);
// 실패 시 임시 파일 정리
await fsPromises.unlink(tempFile).catch(() => {});
await this.removeDirectory(path.join(this.tempDir, 'extracted')).catch(() => {});
throw new Error(`Failed to install Whisper on Windows: ${error.message}`);
}
}
// 압축 해제된 디렉토리에서 whisper.exe 파일들을 재귀적으로 찾기
async findWhisperExecutables(dir) {
const executables = [];
try {
const items = await fsPromises.readdir(dir, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(dir, item.name);
if (item.isDirectory()) {
const subExecutables = await this.findWhisperExecutables(fullPath);
executables.push(...subExecutables);
} else if (item.isFile() && (item.name === 'whisper-whisper.exe' || item.name === 'whisper.exe' || item.name === 'main.exe')) {
executables.push(fullPath);
}
}
} catch (error) {
console.warn('[WhisperService] Error reading directory:', dir, error.message);
}
return executables;
}
// 디렉토리 재귀적 삭제
async removeDirectory(dir) {
try {
const items = await fsPromises.readdir(dir, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(dir, item.name);
if (item.isDirectory()) {
await this.removeDirectory(fullPath);
} else {
await fsPromises.unlink(fullPath);
}
}
await fsPromises.rmdir(dir);
} catch (error) {
console.warn('[WhisperService] Error removing directory:', dir, error.message);
}
}
async installLinux() {
console.log('[WhisperService] Installing Whisper on Linux...');
const version = 'v1.7.6';
const binaryUrl = `https://github.com/ggml-org/whisper.cpp/releases/download/${version}/whisper-cpp-${version}-linux-x64.tar.gz`;
const tempFile = path.join(this.tempDir, 'whisper-binary.tar.gz');
try {
await this.downloadWithRetry(binaryUrl, tempFile);
const extractDir = path.dirname(this.whisperPath);
await spawnAsync('tar', ['-xzf', tempFile, '-C', extractDir, '--strip-components=1']);
await spawnAsync('chmod', ['+x', this.whisperPath]);
await fsPromises.unlink(tempFile);
console.log('[WhisperService] Whisper installed successfully on Linux');
return true;
} catch (error) {
console.error('[WhisperService] Linux installation failed:', error);
throw new Error(`Failed to install Whisper on Linux: ${error.message}`);
}
}
async shutdownMacOS(force) {
return true;
}
async shutdownWindows(force) {
return true;
}
async shutdownLinux(force) {
return true;
}
}
// WhisperSession class
class WhisperSession {
constructor(config, service) {
this.id = `session_${Date.now()}_${Math.random()}`;
this.config = config;
this.service = service;
this.process = null;
this.inUse = true;
this.audioBuffer = Buffer.alloc(0);
}
async initialize() {
await this.service.ensureModelAvailable(this.config.model);
this.startProcessingLoop();
}
async reconfigure(config) {
this.config = config;
await this.service.ensureModelAvailable(this.config.model);
}
startProcessingLoop() {
// TODO: 실제 처리 루프 구현
}
async cleanup() {
// 임시 파일 정리
await this.cleanupTempFiles();
}
async cleanupTempFiles() {
// TODO: 임시 파일 정리 구현
}
async destroy() {
if (this.process) {
this.process.kill();
}
// 임시 파일 정리
await this.cleanupTempFiles();
}
}
// verify installation
WhisperService.prototype.verifyInstallation = async function() {
try {
console.log('[WhisperService] Verifying installation...');
// 1. check binary
if (!this.whisperPath) {
return { success: false, error: 'Whisper binary path not set' };
}
try {
await fsPromises.access(this.whisperPath, fs.constants.X_OK);
} catch (error) {
return { success: false, error: 'Whisper binary not executable' };
}
// 2. check version
try {
const { stdout } = await spawnAsync(this.whisperPath, ['--help']);
if (!stdout.includes('whisper')) {
return { success: false, error: 'Invalid whisper binary' };
}
} catch (error) {
return { success: false, error: 'Whisper binary not responding' };
}
// 3. check directories
try {
await fsPromises.access(this.modelsDir, fs.constants.W_OK);
await fsPromises.access(this.tempDir, fs.constants.W_OK);
} catch (error) {
return { success: false, error: 'Required directories not accessible' };
}
console.log('[WhisperService] Installation verified successfully');
return { success: true };
} catch (error) {
console.error('[WhisperService] Verification failed:', error);
return { success: false, error: error.message };
}
};
// Export singleton instance
const whisperService = new WhisperService();
module.exports = whisperService;
================================================
FILE: src/features/common/utils/spawnHelper.js
================================================
const { spawn } = require('child_process');
function spawnAsync(command, args = [], options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, options);
let stdout = '';
let stderr = '';
if (child.stdout) {
child.stdout.on('data', (data) => {
stdout += data.toString();
});
}
if (child.stderr) {
child.stderr.on('data', (data) => {
stderr += data.toString();
});
}
child.on('error', (error) => {
reject(error);
});
child.on('close', (code) => {
if (code === 0) {
resolve({ stdout, stderr });
} else {
const error = new Error(`Command failed with code ${code}: ${stderr || stdout}`);
error.code = code;
error.stdout = stdout;
error.stderr = stderr;
reject(error);
}
});
});
}
module.exports = { spawnAsync };
================================================
FILE: src/features/listen/listenService.js
================================================
const { BrowserWindow } = require('electron');
const SttService = require('./stt/sttService');
const SummaryService = require('./summary/summaryService');
const authService = require('../common/services/authService');
const sessionRepository = require('../common/repositories/session');
const sttRepository = require('./stt/repositories');
const internalBridge = require('../../bridge/internalBridge');
class ListenService {
constructor() {
this.sttService = new SttService();
this.summaryService = new SummaryService();
this.currentSessionId = null;
this.isInitializingSession = false;
this.setupServiceCallbacks();
console.log('[ListenService] Service instance created.');
}
setupServiceCallbacks() {
// STT service callbacks
this.sttService.setCallbacks({
onTranscriptionComplete: (speaker, text) => {
this.handleTranscriptionComplete(speaker, text);
},
onStatusUpdate: (status) => {
this.sendToRenderer('update-status', status);
}
});
// Summary service callbacks
this.summaryService.setCallbacks({
onAnalysisComplete: (data) => {
console.log('📊 Analysis completed:', data);
},
onStatusUpdate: (status) => {
this.sendToRenderer('update-status', status);
}
});
}
sendToRenderer(channel, data) {
const { windowPool } = require('../../window/windowManager');
const listenWindow = windowPool?.get('listen');
if (listenWindow && !listenWindow.isDestroyed()) {
listenWindow.webContents.send(channel, data);
}
}
initialize() {
this.setupIpcHandlers();
console.log('[ListenService] Initialized and ready.');
}
async handleListenRequest(listenButtonText) {
const { windowPool } = require('../../window/windowManager');
const listenWindow = windowPool.get('listen');
const header = windowPool.get('header');
try {
switch (listenButtonText) {
case 'Listen':
console.log('[ListenService] changeSession to "Listen"');
internalBridge.emit('window:requestVisibility', { name: 'listen', visible: true });
await this.initializeSession();
if (listenWindow && !listenWindow.isDestroyed()) {
listenWindow.webContents.send('session-state-changed', { isActive: true });
}
break;
case 'Stop':
console.log('[ListenService] changeSession to "Stop"');
await this.closeSession();
if (listenWindow && !listenWindow.isDestroyed()) {
listenWindow.webContents.send('session-state-changed', { isActive: false });
}
break;
case 'Done':
console.log('[ListenService] changeSession to "Done"');
internalBridge.emit('window:requestVisibility', { name: 'listen', visible: false });
listenWindow.webContents.send('session-state-changed', { isActive: false });
break;
default:
throw new Error(`[ListenService] unknown listenButtonText: ${listenButtonText}`);
}
header.webContents.send('listen:changeSessionResult', { success: true });
} catch (error) {
console.error('[ListenService] error in handleListenRequest:', error);
header.webContents.send('listen:changeSessionResult', { success: false });
throw error;
}
}
async handleTranscriptionComplete(speaker, text) {
console.log(`[ListenService] Transcription complete: ${speaker} - ${text}`);
// Save to database
await this.saveConversationTurn(speaker, text);
// Add to summary service for analysis
this.summaryService.addConversationTurn(speaker, text);
}
async saveConversationTurn(speaker, transcription) {
if (!this.currentSessionId) {
console.error('[DB] Cannot save turn, no active session ID.');
return;
}
if (transcription.trim() === '') return;
try {
await sessionRepository.touch(this.currentSessionId);
await sttRepository.addTranscript({
sessionId: this.currentSessionId,
speaker: speaker,
text: transcription.trim(),
});
console.log(`[DB] Saved transcript for session ${this.currentSessionId}: (${speaker})`);
} catch (error) {
console.error('Failed to save transcript to DB:', error);
}
}
async initializeNewSession() {
try {
// The UID is no longer passed to the repository method directly.
// The adapter layer handles UID injection. We just ensure a user is available.
const user = authService.getCurrentUser();
if (!user) {
// This case should ideally not happen as authService initializes a default user.
throw new Error("Cannot initialize session: auth service not ready.");
}
this.currentSessionId = await sessionRepository.getOrCreateActive('listen');
console.log(`[DB] New listen session ensured: ${this.currentSessionId}`);
// Set session ID for summary service
this.summaryService.setSessionId(this.currentSessionId);
// Reset conversation history
this.summaryService.resetConversationHistory();
console.log('New conversation session started:', this.currentSessionId);
return true;
} catch (error) {
console.error('Failed to initialize new session in DB:', error);
this.currentSessionId = null;
return false;
}
}
async initializeSession(language = 'en') {
if (this.isInitializingSession) {
console.log('Session initialization already in progress.');
return false;
}
this.isInitializingSession = true;
this.sendToRenderer('session-initializing', true);
this.sendToRenderer('update-status', 'Initializing sessions...');
try {
// Initialize database session
const sessionInitialized = await this.initializeNewSession();
if (!sessionInitialized) {
throw new Error('Failed to initialize database session');
}
/* ---------- STT Initialization Retry Logic ---------- */
const MAX_RETRY = 10;
const RETRY_DELAY_MS = 300; // 0.3 seconds
let sttReady = false;
for (let attempt = 1; attempt <= MAX_RETRY; attempt++) {
try {
await this.sttService.initializeSttSessions(language);
sttReady = true;
break; // Exit on success
} catch (err) {
console.warn(
`[ListenService] STT init attempt ${attempt} failed: ${err.message}`
);
if (attempt < MAX_RETRY) {
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
}
}
}
if (!sttReady) throw new Error('STT init failed after retries');
/* ------------------------------------------- */
console.log('✅ Listen service initialized successfully.');
this.sendToRenderer('update-status', 'Connected. Ready to listen.');
return true;
} catch (error) {
console.error('❌ Failed to initialize listen service:', error);
this.sendToRenderer('update-status', 'Initialization failed.');
return false;
} finally {
this.isInitializingSession = false;
this.sendToRenderer('session-initializing', false);
this.sendToRenderer('change-listen-capture-state', { status: "start" });
}
}
async sendMicAudioContent(data, mimeType) {
return await this.sttService.sendMicAudioContent(data, mimeType);
}
async startMacOSAudioCapture() {
if (process.platform !== 'darwin') {
throw new Error('macOS audio capture only available on macOS');
}
return await this.sttService.startMacOSAudioCapture();
}
async stopMacOSAudioCapture() {
this.sttService.stopMacOSAudioCapture();
}
isSessionActive() {
return this.sttService.isSessionActive();
}
async closeSession() {
try {
this.sendToRenderer('change-listen-capture-state', { status: "stop" });
// Close STT sessions
await this.sttService.closeSessions();
await this.stopMacOSAudioCapture();
// End database session
if (this.currentSessionId) {
await sessionRepository.end(this.currentSessionId);
console.log(`[DB] Session ${this.currentSessionId} ended.`);
}
// Reset state
this.currentSessionId = null;
this.summaryService.resetConversationHistory();
console.log('Listen service session closed.');
return { success: true };
} catch (error) {
console.error('Error closing listen service session:', error);
return { success: false, error: error.message };
}
}
getCurrentSessionData() {
return {
sessionId: this.currentSessionId,
conversationHistory: this.summaryService.getConversationHistory(),
totalTexts: this.summaryService.getConversationHistory().length,
analysisData: this.summaryService.getCurrentAnalysisData(),
};
}
getConversationHistory() {
return this.summaryService.getConversationHistory();
}
_createHandler(asyncFn, successMessage, errorMessage) {
return async (...args) => {
try {
const result = await asyncFn.apply(this, args);
if (successMessage) console.log(successMessage);
// `startMacOSAudioCapture`는 성공 시 { success, error } 객체를 반환하지 않으므로,
// 핸들러가 일관된 응답을 보내도록 여기서 success 객체를 반환합니다.
// 다른 함수들은 이미 success 객체를 반환합니다.
return result && typeof result.success !== 'undefined' ? result : { success: true };
} catch (e) {
console.error(errorMessage, e);
return { success: false, error: e.message };
}
};
}
// `_createHandler`를 사용하여 핸들러들을 동적으로 생성합니다.
handleSendMicAudioContent = this._createHandler(
this.sendMicAudioContent,
null,
'Error sending user audio:'
);
handleStartMacosAudio = this._createHandler(
async () => {
if (process.platform !== 'darwin') {
return { success: false, error: 'macOS audio capture only available on macOS' };
}
if (this.sttService.isMacOSAudioRunning?.()) {
return { success: false, error: 'already_running' };
}
await this.startMacOSAudioCapture();
return { success: true, error: null };
},
'macOS audio capture started.',
'Error starting macOS audio capture:'
);
handleStopMacosAudio = this._createHandler(
this.stopMacOSAudioCapture,
'macOS audio capture stopped.',
'Error stopping macOS audio capture:'
);
handleUpdateGoogleSearchSetting = this._createHandler(
async (enabled) => {
console.log('Google Search setting updated to:', enabled);
},
null,
'Error updating Google Search setting:'
);
}
const listenService = new ListenService();
module.exports = listenService;
================================================
FILE: src/features/listen/stt/repositories/firebase.repository.js
================================================
const { collection, addDoc, query, getDocs, orderBy, Timestamp } = require('firebase/firestore');
const { getFirestoreInstance } = require('../../../common/services/firebaseClient');
const { createEncryptedConverter } = require('../../../common/repositories/firestoreConverter');
const transcriptConverter = createEncryptedConverter(['text']);
function transcriptsCol(sessionId) {
if (!sessionId) throw new Error("Session ID is required to access transcripts.");
const db = getFirestoreInstance();
return collection(db, `sessions/${sessionId}/transcripts`).withConverter(transcriptConverter);
}
async function addTranscript({ uid, sessionId, speaker, text }) {
const now = Timestamp.now();
const newTranscript = {
uid, // To identify the author/source of the transcript
session_id: sessionId,
start_at: now,
speaker,
text,
created_at: now,
};
const docRef = await addDoc(transcriptsCol(sessionId), newTranscript);
return { id: docRef.id };
}
async function getAllTranscriptsBySessionId(sessionId) {
const q = query(transcriptsCol(sessionId), orderBy('start_at', 'asc'));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => doc.data());
}
module.exports = {
addTranscript,
getAllTranscriptsBySessionId,
};
================================================
FILE: src/features/listen/stt/repositories/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
const firebaseRepository = require('./firebase.repository');
const authService = require('../../../common/services/authService');
function getBaseRepository() {
const user = authService.getCurrentUser();
if (user && user.isLoggedIn) {
return firebaseRepository;
}
return sqliteRepository;
}
const sttRepositoryAdapter = {
addTranscript: ({ sessionId, speaker, text }) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().addTranscript({ uid, sessionId, speaker, text });
},
getAllTranscriptsBySessionId: (sessionId) => {
return getBaseRepository().getAllTranscriptsBySessionId(sessionId);
}
};
module.exports = sttRepositoryAdapter;
================================================
FILE: src/features/listen/stt/repositories/sqlite.repository.js
================================================
const sqliteClient = require('../../../common/services/sqliteClient');
function addTranscript({ uid, sessionId, speaker, text }) {
// uid is ignored in the SQLite implementation
const db = sqliteClient.getDb();
const transcriptId = require('crypto').randomUUID();
const now = Math.floor(Date.now() / 1000);
const query = `INSERT INTO transcripts (id, session_id, start_at, speaker, text, created_at) VALUES (?, ?, ?, ?, ?, ?)`;
try {
db.prepare(query).run(transcriptId, sessionId, now, speaker, text, now);
return { id: transcriptId };
} catch (err) {
console.error('Error adding transcript:', err);
throw err;
}
}
function getAllTranscriptsBySessionId(sessionId) {
const db = sqliteClient.getDb();
const query = "SELECT * FROM transcripts WHERE session_id = ? ORDER BY start_at ASC";
return db.prepare(query).all(sessionId);
}
module.exports = {
addTranscript,
getAllTranscriptsBySessionId,
};
================================================
FILE: src/features/listen/stt/sttService.js
================================================
const { BrowserWindow } = require('electron');
const { spawn } = require('child_process');
const { createSTT } = require('../../common/ai/factory');
const modelStateService = require('../../common/services/modelStateService');
const COMPLETION_DEBOUNCE_MS = 2000;
// ── New heartbeat / renewal constants ────────────────────────────────────────────
// Interval to send low-cost keep-alive messages so the remote service does not
// treat the connection as idle. One minute is safely below the typical 2-5 min
// idle timeout window seen on provider websockets.
const KEEP_ALIVE_INTERVAL_MS = 60 * 1000; // 1 minute
// Interval after which we pro-actively tear down and recreate the STT sessions
// to dodge the 30-minute hard timeout enforced by some providers. 20 minutes
// gives a 10-minute safety buffer.
const SESSION_RENEW_INTERVAL_MS = 20 * 60 * 1000; // 20 minutes
// Duration to allow the old and new sockets to run in parallel so we don't
// miss any packets at the exact swap moment.
const SOCKET_OVERLAP_MS = 2 * 1000; // 2 seconds
class SttService {
constructor() {
this.mySttSession = null;
this.theirSttSession = null;
this.myCurrentUtterance = '';
this.theirCurrentUtterance = '';
// Turn-completion debouncing
this.myCompletionBuffer = '';
this.theirCompletionBuffer = '';
this.myCompletionTimer = null;
this.theirCompletionTimer = null;
// System audio capture
this.systemAudioProc = null;
// Keep-alive / renewal timers
this.keepAliveInterval = null;
this.sessionRenewTimeout = null;
// Callbacks
this.onTranscriptionComplete = null;
this.onStatusUpdate = null;
this.modelInfo = null;
}
setCallbacks({ onTranscriptionComplete, onStatusUpdate }) {
this.onTranscriptionComplete = onTranscriptionComplete;
this.onStatusUpdate = onStatusUpdate;
}
sendToRenderer(channel, data) {
// Listen 관련 이벤트는 Listen 윈도우에만 전송 (Ask 윈도우 충돌 방지)
const { windowPool } = require('../../../window/windowManager');
const listenWindow = windowPool?.get('listen');
if (listenWindow && !listenWindow.isDestroyed()) {
listenWindow.webContents.send(channel, data);
}
}
async handleSendSystemAudioContent(data, mimeType) {
try {
await this.sendSystemAudioContent(data, mimeType);
this.sendToRenderer('system-audio-data', { data });
return { success: true };
} catch (error) {
console.error('Error sending system audio:', error);
return { success: false, error: error.message };
}
}
flushMyCompletion() {
const finalText = (this.myCompletionBuffer + this.myCurrentUtterance).trim();
if (!this.modelInfo || !finalText) return;
// Notify completion callback
if (this.onTranscriptionComplete) {
this.onTranscriptionComplete('Me', finalText);
}
// Send to renderer as final
this.sendToRenderer('stt-update', {
speaker: 'Me',
text: finalText,
isPartial: false,
isFinal: true,
timestamp: Date.now(),
});
this.myCompletionBuffer = '';
this.myCompletionTimer = null;
this.myCurrentUtterance = '';
if (this.onStatusUpdate) {
this.onStatusUpdate('Listening...');
}
}
flushTheirCompletion() {
const finalText = (this.theirCompletionBuffer + this.theirCurrentUtterance).trim();
if (!this.modelInfo || !finalText) return;
// Notify completion callback
if (this.onTranscriptionComplete) {
this.onTranscriptionComplete('Them', finalText);
}
// Send to renderer as final
this.sendToRenderer('stt-update', {
speaker: 'Them',
text: finalText,
isPartial: false,
isFinal: true,
timestamp: Date.now(),
});
this.theirCompletionBuffer = '';
this.theirCompletionTimer = null;
this.theirCurrentUtterance = '';
if (this.onStatusUpdate) {
this.onStatusUpdate('Listening...');
}
}
debounceMyCompletion(text) {
if (this.modelInfo?.provider === 'gemini') {
this.myCompletionBuffer += text;
} else {
this.myCompletionBuffer += (this.myCompletionBuffer ? ' ' : '') + text;
}
if (this.myCompletionTimer) clearTimeout(this.myCompletionTimer);
this.myCompletionTimer = setTimeout(() => this.flushMyCompletion(), COMPLETION_DEBOUNCE_MS);
}
debounceTheirCompletion(text) {
if (this.modelInfo?.provider === 'gemini') {
this.theirCompletionBuffer += text;
} else {
this.theirCompletionBuffer += (this.theirCompletionBuffer ? ' ' : '') + text;
}
if (this.theirCompletionTimer) clearTimeout(this.theirCompletionTimer);
this.theirCompletionTimer = setTimeout(() => this.flushTheirCompletion(), COMPLETION_DEBOUNCE_MS);
}
async initializeSttSessions(language = 'en') {
const effectiveLanguage = process.env.OPENAI_TRANSCRIBE_LANG || language || 'en';
const modelInfo = await modelStateService.getCurrentModelInfo('stt');
if (!modelInfo || !modelInfo.apiKey) {
throw new Error('AI model or API key is not configured.');
}
this.modelInfo = modelInfo;
console.log(`[SttService] Initializing STT for ${modelInfo.provider} using model ${modelInfo.model}`);
const handleMyMessage = message => {
if (!this.modelInfo) {
console.log('[SttService] Ignoring message - session already closed');
return;
}
// console.log('[SttService] handleMyMessage', message);
if (this.modelInfo.provider === 'whisper') {
// Whisper STT emits 'transcription' events with different structure
if (message.text && message.text.trim()) {
const finalText = message.text.trim();
// Filter out Whisper noise transcriptions
const noisePatterns = [
'[BLANK_AUDIO]',
'[INAUDIBLE]',
'[MUSIC]',
'[SOUND]',
'[NOISE]',
'(BLANK_AUDIO)',
'(INAUDIBLE)',
'(MUSIC)',
'(SOUND)',
'(NOISE)'
];
const isNoise = noisePatterns.some(pattern =>
finalText.includes(pattern) || finalText === pattern
);
if (!isNoise && finalText.length > 2) {
this.debounceMyCompletion(finalText);
this.sendToRenderer('stt-update', {
speaker: 'Me',
text: finalText,
isPartial: false,
isFinal: true,
timestamp: Date.now(),
});
} else {
console.log(`[Whisper-Me] Filtered noise: "${finalText}"`);
}
}
return;
} else if (this.modelInfo.provider === 'gemini') {
if (!message.serverContent?.modelTurn) {
console.log('[Gemini STT - Me]', JSON.stringify(message, null, 2));
}
if (message.serverContent?.turnComplete) {
if (this.myCompletionTimer) {
clearTimeout(this.myCompletionTimer);
this.flushMyCompletion();
}
return;
}
const transcription = message.serverContent?.inputTranscription;
if (!transcription || !transcription.text) return;
const textChunk = transcription.text;
if (!textChunk.trim() || textChunk.trim() === '') {
return; // 1. Ignore whitespace-only chunks or noise
}
this.debounceMyCompletion(textChunk);
this.sendToRenderer('stt-update', {
speaker: 'Me',
text: this.myCompletionBuffer,
isPartial: true,
isFinal: false,
timestamp: Date.now(),
});
// Deepgram
} else if (this.modelInfo.provider === 'deepgram') {
const text = message.channel?.alternatives?.[0]?.transcript;
if (!text || text.trim().length === 0) return;
const isFinal = message.is_final;
console.log(`[SttService-Me-Deepgram] Received: isFinal=${isFinal}, text="${text}"`);
if (isFinal) {
// 최종 결과가 도착하면, 현재 진행중인 부분 발화는 비우고
// 최종 텍스트로 debounce를 실행합니다.
this.myCurrentUtterance = '';
this.debounceMyCompletion(text);
} else {
// 부분 결과(interim)인 경우, 화면에 실시간으로 업데이트합니다.
if (this.myCompletionTimer) clearTimeout(this.myCompletionTimer);
this.myCompletionTimer = null;
this.myCurrentUtterance = text;
const continuousText = (this.myCompletionBuffer + ' ' + this.myCurrentUtterance).trim();
this.sendToRenderer('stt-update', {
speaker: 'Me',
text: continuousText,
isPartial: true,
isFinal: false,
timestamp: Date.now(),
});
}
} else {
const type = message.type;
const text = message.transcript || message.delta || (message.alternatives && message.alternatives[0]?.transcript) || '';
if (type === 'conversation.item.input_audio_transcription.delta') {
if (this.myCompletionTimer) clearTimeout(this.myCompletionTimer);
this.myCompletionTimer = null;
this.myCurrentUtterance += text;
const continuousText = this.myCompletionBuffer + (this.myCompletionBuffer ? ' ' : '') + this.myCurrentUtterance;
if (text && !text.includes('vq_lbr_audio_')) {
this.sendToRenderer('stt-update', {
speaker: 'Me',
text: continuousText,
isPartial: true,
isFinal: false,
timestamp: Date.now(),
});
}
} else if (type === 'conversation.item.input_audio_transcription.completed') {
if (text && text.trim()) {
const finalUtteranceText = text.trim();
this.myCurrentUtterance = '';
this.debounceMyCompletion(finalUtteranceText);
}
}
}
if (message.error) {
console.error('[Me] STT Session Error:', message.error);
}
};
const handleTheirMessage = message => {
if (!message || typeof message !== 'object') return;
if (!this.modelInfo) {
console.log('[SttService] Ignoring message - session already closed');
return;
}
if (this.modelInfo.provider === 'whisper') {
// Whisper STT emits 'transcription' events with different structure
if (message.text && message.text.trim()) {
const finalText = message.text.trim();
// Filter out Whisper noise transcriptions
const noisePatterns = [
'[BLANK_AUDIO]',
'[INAUDIBLE]',
'[MUSIC]',
'[SOUND]',
'[NOISE]',
'(BLANK_AUDIO)',
'(INAUDIBLE)',
'(MUSIC)',
'(SOUND)',
'(NOISE)'
];
const isNoise = noisePatterns.some(pattern =>
finalText.includes(pattern) || finalText === pattern
);
// Only process if it's not noise, not a false positive, and has meaningful content
if (!isNoise && finalText.length > 2) {
this.debounceTheirCompletion(finalText);
this.sendToRenderer('stt-update', {
speaker: 'Them',
text: finalText,
isPartial: false,
isFinal: true,
timestamp: Date.now(),
});
} else {
console.log(`[Whisper-Them] Filtered noise: "${finalText}"`);
}
}
return;
} else if (this.modelInfo.provider === 'gemini') {
if (!message.serverContent?.modelTurn) {
console.log('[Gemini STT - Them]', JSON.stringify(message, null, 2));
}
if (message.serverContent?.turnComplete) {
if (this.theirCompletionTimer) {
clearTimeout(this.theirCompletionTimer);
this.flushTheirCompletion();
}
return;
}
const transcription = message.serverContent?.inputTranscription;
if (!transcription || !transcription.text) return;
const textChunk = transcription.text;
if (!textChunk.trim() || textChunk.trim() === '') {
return; // 1. Ignore whitespace-only chunks or noise
}
this.debounceTheirCompletion(textChunk);
this.sendToRenderer('stt-update', {
speaker: 'Them',
text: this.theirCompletionBuffer,
isPartial: true,
isFinal: false,
timestamp: Date.now(),
});
// Deepgram
} else if (this.modelInfo.provider === 'deepgram') {
const text = message.channel?.alternatives?.[0]?.transcript;
if (!text || text.trim().length === 0) return;
const isFinal = message.is_final;
if (isFinal) {
this.theirCurrentUtterance = '';
this.debounceTheirCompletion(text);
} else {
if (this.theirCompletionTimer) clearTimeout(this.theirCompletionTimer);
this.theirCompletionTimer = null;
this.theirCurrentUtterance = text;
const continuousText = (this.theirCompletionBuffer + ' ' + this.theirCurrentUtterance).trim();
this.sendToRenderer('stt-update', {
speaker: 'Them',
text: continuousText,
isPartial: true,
isFinal: false,
timestamp: Date.now(),
});
}
} else {
const type = message.type;
const text = message.transcript || message.delta || (message.alternatives && message.alternatives[0]?.transcript) || '';
if (type === 'conversation.item.input_audio_transcription.delta') {
if (this.theirCompletionTimer) clearTimeout(this.theirCompletionTimer);
this.theirCompletionTimer = null;
this.theirCurrentUtterance += text;
const continuousText = this.theirCompletionBuffer + (this.theirCompletionBuffer ? ' ' : '') + this.theirCurrentUtterance;
if (text && !text.includes('vq_lbr_audio_')) {
this.sendToRenderer('stt-update', {
speaker: 'Them',
text: continuousText,
isPartial: true,
isFinal: false,
timestamp: Date.now(),
});
}
} else if (type === 'conversation.item.input_audio_transcription.completed') {
if (text && text.trim()) {
const finalUtteranceText = text.trim();
this.theirCurrentUtterance = '';
this.debounceTheirCompletion(finalUtteranceText);
}
}
}
if (message.error) {
console.error('[Them] STT Session Error:', message.error);
}
};
const mySttConfig = {
language: effectiveLanguage,
callbacks: {
onmessage: handleMyMessage,
onerror: error => console.error('My STT session error:', error.message),
onclose: event => console.log('My STT session closed:', event.reason),
},
};
const theirSttConfig = {
language: effectiveLanguage,
callbacks: {
onmessage: handleTheirMessage,
onerror: error => console.error('Their STT session error:', error.message),
onclose: event => console.log('Their STT session closed:', event.reason),
},
};
const sttOptions = {
apiKey: this.modelInfo.apiKey,
language: effectiveLanguage,
usePortkey: this.modelInfo.provider === 'openai-glass',
portkeyVirtualKey: this.modelInfo.provider === 'openai-glass' ? this.modelInfo.apiKey : undefined,
};
// Add sessionType for Whisper to distinguish between My and Their sessions
const myOptions = { ...sttOptions, callbacks: mySttConfig.callbacks, sessionType: 'my' };
const theirOptions = { ...sttOptions, callbacks: theirSttConfig.callbacks, sessionType: 'their' };
[this.mySttSession, this.theirSttSession] = await Promise.all([
createSTT(this.modelInfo.provider, myOptions),
createSTT(this.modelInfo.provider, theirOptions),
]);
console.log('✅ Both STT sessions initialized successfully.');
// ── Setup keep-alive heart-beats ────────────────────────────────────────
if (this.keepAliveInterval) clearInterval(this.keepAliveInterval);
this.keepAliveInterval = setInterval(() => {
this._sendKeepAlive();
}, KEEP_ALIVE_INTERVAL_MS);
// ── Schedule session auto-renewal ───────────────────────────────────────
if (this.sessionRenewTimeout) clearTimeout(this.sessionRenewTimeout);
this.sessionRenewTimeout = setTimeout(async () => {
try {
console.log('[SttService] Auto-renewing STT sessions…');
await this.renewSessions(language);
} catch (err) {
console.error('[SttService] Failed to renew STT sessions:', err);
}
}, SESSION_RENEW_INTERVAL_MS);
return true;
}
/**
* Send a lightweight keep-alive to prevent idle disconnects.
* Currently only implemented for OpenAI provider because Gemini's SDK
* already performs its own heart-beats.
*/
_sendKeepAlive() {
if (!this.isSessionActive()) return;
if (this.modelInfo?.provider === 'openai') {
try {
this.mySttSession?.keepAlive?.();
this.theirSttSession?.keepAlive?.();
} catch (err) {
console.error('[SttService] keepAlive error:', err.message);
}
}
}
/**
* Gracefully tears down then recreates the STT sessions. Should be invoked
* on a timer to avoid provider-side hard timeouts.
*/
async renewSessions(language = 'en') {
if (!this.isSessionActive()) {
console.warn('[SttService] renewSessions called but no active session.');
return;
}
const oldMySession = this.mySttSession;
const oldTheirSession = this.theirSttSession;
console.log('[SttService] Spawning fresh STT sessions in the background…');
// We reuse initializeSttSessions to create fresh sessions with the same
// language and handlers. The method will update the session pointers
// and timers, but crucially it does NOT touch the system audio capture
// pipeline, so audio continues flowing uninterrupted.
await this.initializeSttSessions(language);
// Close the old sessions after a short overlap window.
setTimeout(() => {
try {
oldMySession?.close?.();
oldTheirSession?.close?.();
console.log('[SttService] Old STT sessions closed after hand-off.');
} catch (err) {
console.error('[SttService] Error closing old STT sessions:', err.message);
}
}, SOCKET_OVERLAP_MS);
}
async sendMicAudioContent(data, mimeType) {
// const provider = await this.getAiProvider();
// const isGemini = provider === 'gemini';
if (!this.mySttSession) {
throw new Error('User STT session not active');
}
let modelInfo = this.modelInfo;
if (!modelInfo) {
console.warn('[SttService] modelInfo not found, fetching on-the-fly as a fallback...');
modelInfo = await modelStateService.getCurrentModelInfo('stt');
}
if (!modelInfo) {
throw new Error('STT model info could not be retrieved.');
}
let payload;
if (modelInfo.provider === 'gemini') {
payload = { audio: { data, mimeType: mimeType || 'audio/pcm;rate=24000' } };
} else if (modelInfo.provider === 'deepgram') {
payload = Buffer.from(data, 'base64');
} else {
payload = data;
}
await this.mySttSession.sendRealtimeInput(payload);
}
async sendSystemAudioContent(data, mimeType) {
if (!this.theirSttSession) {
throw new Error('Their STT session not active');
}
let modelInfo = this.modelInfo;
if (!modelInfo) {
console.warn('[SttService] modelInfo not found, fetching on-the-fly as a fallback...');
modelInfo = await modelStateService.getCurrentModelInfo('stt');
}
if (!modelInfo) {
throw new Error('STT model info could not be retrieved.');
}
let payload;
if (modelInfo.provider === 'gemini') {
payload = { audio: { data, mimeType: mimeType || 'audio/pcm;rate=24000' } };
} else if (modelInfo.provider === 'deepgram') {
payload = Buffer.from(data, 'base64');
} else {
payload = data;
}
await this.theirSttSession.sendRealtimeInput(payload);
}
killExistingSystemAudioDump() {
return new Promise(resolve => {
console.log('Checking for existing SystemAudioDump processes...');
const killProc = spawn('pkill', ['-f', 'SystemAudioDump'], {
stdio: 'ignore',
});
killProc.on('close', code => {
if (code === 0) {
console.log('Killed existing SystemAudioDump processes');
} else {
console.log('No existing SystemAudioDump processes found');
}
resolve();
});
killProc.on('error', err => {
console.log('Error checking for existing processes (this is normal):', err.message);
resolve();
});
setTimeout(() => {
killProc.kill();
resolve();
}, 2000);
});
}
async startMacOSAudioCapture() {
if (process.platform !== 'darwin' || !this.theirSttSession) return false;
await this.killExistingSystemAudioDump();
console.log('Starting macOS audio capture for "Them"...');
const { app } = require('electron');
const path = require('path');
const systemAudioPath = app.isPackaged
? path.join(process.resourcesPath, 'app.asar.unpacked', 'src', 'ui', 'assets', 'SystemAudioDump')
: path.join(app.getAppPath(), 'src', 'ui', 'assets', 'SystemAudioDump');
console.log('SystemAudioDump path:', systemAudioPath);
this.systemAudioProc = spawn(systemAudioPath, [], {
stdio: ['ignore', 'pipe', 'pipe'],
});
if (!this.systemAudioProc.pid) {
console.error('Failed to start SystemAudioDump');
return false;
}
console.log('SystemAudioDump started with PID:', this.systemAudioProc.pid);
const CHUNK_DURATION = 0.1;
const SAMPLE_RATE = 24000;
const BYTES_PER_SAMPLE = 2;
const CHANNELS = 2;
const CHUNK_SIZE = SAMPLE_RATE * BYTES_PER_SAMPLE * CHANNELS * CHUNK_DURATION;
let audioBuffer = Buffer.alloc(0);
// const provider = await this.getAiProvider();
// const isGemini = provider === 'gemini';
let modelInfo = this.modelInfo;
if (!modelInfo) {
console.warn('[SttService] modelInfo not found, fetching on-the-fly as a fallback...');
modelInfo = await modelStateService.getCurrentModelInfo('stt');
}
if (!modelInfo) {
throw new Error('STT model info could not be retrieved.');
}
this.systemAudioProc.stdout.on('data', async data => {
audioBuffer = Buffer.concat([audioBuffer, data]);
while (audioBuffer.length >= CHUNK_SIZE) {
const chunk = audioBuffer.slice(0, CHUNK_SIZE);
audioBuffer = audioBuffer.slice(CHUNK_SIZE);
const monoChunk = CHANNELS === 2 ? this.convertStereoToMono(chunk) : chunk;
const base64Data = monoChunk.toString('base64');
this.sendToRenderer('system-audio-data', { data: base64Data });
if (this.theirSttSession) {
try {
let payload;
if (modelInfo.provider === 'gemini') {
payload = { audio: { data: base64Data, mimeType: 'audio/pcm;rate=24000' } };
} else if (modelInfo.provider === 'deepgram') {
payload = Buffer.from(base64Data, 'base64');
} else {
payload = base64Data;
}
await this.theirSttSession.sendRealtimeInput(payload);
} catch (err) {
console.error('Error sending system audio:', err.message);
}
}
}
});
this.systemAudioProc.stderr.on('data', data => {
console.error('SystemAudioDump stderr:', data.toString());
});
this.systemAudioProc.on('close', code => {
console.log('SystemAudioDump process closed with code:', code);
this.systemAudioProc = null;
});
this.systemAudioProc.on('error', err => {
console.error('SystemAudioDump process error:', err);
this.systemAudioProc = null;
});
return true;
}
convertStereoToMono(stereoBuffer) {
const samples = stereoBuffer.length / 4;
const monoBuffer = Buffer.alloc(samples * 2);
for (let i = 0; i < samples; i++) {
const leftSample = stereoBuffer.readInt16LE(i * 4);
monoBuffer.writeInt16LE(leftSample, i * 2);
}
return monoBuffer;
}
stopMacOSAudioCapture() {
if (this.systemAudioProc) {
console.log('Stopping SystemAudioDump...');
this.systemAudioProc.kill('SIGTERM');
this.systemAudioProc = null;
}
}
isSessionActive() {
return !!this.mySttSession && !!this.theirSttSession;
}
async closeSessions() {
this.stopMacOSAudioCapture();
// Clear heartbeat / renewal timers
if (this.keepAliveInterval) {
clearInterval(this.keepAliveInterval);
this.keepAliveInterval = null;
}
if (this.sessionRenewTimeout) {
clearTimeout(this.sessionRenewTimeout);
this.sessionRenewTimeout = null;
}
// Clear timers
if (this.myCompletionTimer) {
clearTimeout(this.myCompletionTimer);
this.myCompletionTimer = null;
}
if (this.theirCompletionTimer) {
clearTimeout(this.theirCompletionTimer);
this.theirCompletionTimer = null;
}
const closePromises = [];
if (this.mySttSession) {
closePromises.push(this.mySttSession.close());
this.mySttSession = null;
}
if (this.theirSttSession) {
closePromises.push(this.theirSttSession.close());
this.theirSttSession = null;
}
await Promise.all(closePromises);
console.log('All STT sessions closed.');
// Reset state
this.myCurrentUtterance = '';
this.theirCurrentUtterance = '';
this.myCompletionBuffer = '';
this.theirCompletionBuffer = '';
this.modelInfo = null;
}
}
module.exports = SttService;
================================================
FILE: src/features/listen/summary/repositories/firebase.repository.js
================================================
const { collection, doc, setDoc, getDoc, Timestamp } = require('firebase/firestore');
const { getFirestoreInstance } = require('../../../common/services/firebaseClient');
const { createEncryptedConverter } = require('../../../common/repositories/firestoreConverter');
const encryptionService = require('../../../common/services/encryptionService');
const fieldsToEncrypt = ['tldr', 'text', 'bullet_json', 'action_json'];
const summaryConverter = createEncryptedConverter(fieldsToEncrypt);
function summaryDocRef(sessionId) {
if (!sessionId) throw new Error("Session ID is required to access summary.");
const db = getFirestoreInstance();
// Reverting to the original structure with 'data' as the document ID.
const docPath = `sessions/${sessionId}/summary/data`;
return doc(db, docPath).withConverter(summaryConverter);
}
async function saveSummary({ uid, sessionId, tldr, text, bullet_json, action_json, model = 'unknown' }) {
const now = Timestamp.now();
const summaryData = {
uid, // To know who generated the summary
session_id: sessionId,
generated_at: now,
model,
text,
tldr,
bullet_json,
action_json,
updated_at: now,
};
// The converter attached to summaryDocRef will handle encryption via its `toFirestore` method.
// Manual encryption was removed to fix the double-encryption bug.
const docRef = summaryDocRef(sessionId);
await setDoc(docRef, summaryData, { merge: true });
return { changes: 1 };
}
async function getSummaryBySessionId(sessionId) {
const docRef = summaryDocRef(sessionId);
const docSnap = await getDoc(docRef);
return docSnap.exists() ? docSnap.data() : null;
}
module.exports = {
saveSummary,
getSummaryBySessionId,
};
================================================
FILE: src/features/listen/summary/repositories/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
const firebaseRepository = require('./firebase.repository');
const authService = require('../../../common/services/authService');
function getBaseRepository() {
const user = authService.getCurrentUser();
if (user && user.isLoggedIn) {
return firebaseRepository;
}
return sqliteRepository;
}
const summaryRepositoryAdapter = {
saveSummary: ({ sessionId, tldr, text, bullet_json, action_json, model }) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().saveSummary({ uid, sessionId, tldr, text, bullet_json, action_json, model });
},
getSummaryBySessionId: (sessionId) => {
return getBaseRepository().getSummaryBySessionId(sessionId);
}
};
module.exports = summaryRepositoryAdapter;
================================================
FILE: src/features/listen/summary/repositories/sqlite.repository.js
================================================
const sqliteClient = require('../../../common/services/sqliteClient');
function saveSummary({ uid, sessionId, tldr, text, bullet_json, action_json, model = 'unknown' }) {
// uid is ignored in the SQLite implementation
return new Promise((resolve, reject) => {
try {
const db = sqliteClient.getDb();
const now = Math.floor(Date.now() / 1000);
const query = `
INSERT INTO summaries (session_id, generated_at, model, text, tldr, bullet_json, action_json, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id) DO UPDATE SET
generated_at=excluded.generated_at,
model=excluded.model,
text=excluded.text,
tldr=excluded.tldr,
bullet_json=excluded.bullet_json,
action_json=excluded.action_json,
updated_at=excluded.updated_at
`;
const result = db.prepare(query).run(sessionId, now, model, text, tldr, bullet_json, action_json, now);
resolve({ changes: result.changes });
} catch (err) {
console.error('Error saving summary:', err);
reject(err);
}
});
}
function getSummaryBySessionId(sessionId) {
const db = sqliteClient.getDb();
const query = "SELECT * FROM summaries WHERE session_id = ?";
return db.prepare(query).get(sessionId) || null;
}
module.exports = {
saveSummary,
getSummaryBySessionId,
};
================================================
FILE: src/features/listen/summary/summaryService.js
================================================
const { BrowserWindow } = require('electron');
const { getSystemPrompt } = require('../../common/prompts/promptBuilder.js');
const { createLLM } = require('../../common/ai/factory');
const sessionRepository = require('../../common/repositories/session');
const summaryRepository = require('./repositories');
const modelStateService = require('../../common/services/modelStateService');
class SummaryService {
constructor() {
this.previousAnalysisResult = null;
this.analysisHistory = [];
this.conversationHistory = [];
this.currentSessionId = null;
// Callbacks
this.onAnalysisComplete = null;
this.onStatusUpdate = null;
}
setCallbacks({ onAnalysisComplete, onStatusUpdate }) {
this.onAnalysisComplete = onAnalysisComplete;
this.onStatusUpdate = onStatusUpdate;
}
setSessionId(sessionId) {
this.currentSessionId = sessionId;
}
sendToRenderer(channel, data) {
const { windowPool } = require('../../../window/windowManager');
const listenWindow = windowPool?.get('listen');
if (listenWindow && !listenWindow.isDestroyed()) {
listenWindow.webContents.send(channel, data);
}
}
addConversationTurn(speaker, text) {
const conversationText = `${speaker.toLowerCase()}: ${text.trim()}`;
this.conversationHistory.push(conversationText);
console.log(`💬 Added conversation text: ${conversationText}`);
console.log(`📈 Total conversation history: ${this.conversationHistory.length} texts`);
// Trigger analysis if needed
this.triggerAnalysisIfNeeded();
}
getConversationHistory() {
return this.conversationHistory;
}
resetConversationHistory() {
this.conversationHistory = [];
this.previousAnalysisResult = null;
this.analysisHistory = [];
console.log('🔄 Conversation history and analysis state reset');
}
/**
* Converts conversation history into text to include in the prompt.
* @param {Array} conversationTexts - Array of conversation texts ["me: ~~~", "them: ~~~", ...]
* @param {number} maxTurns - Maximum number of recent turns to include
* @returns {string} - Formatted conversation string for the prompt
*/
formatConversationForPrompt(conversationTexts, maxTurns = 30) {
if (conversationTexts.length === 0) return '';
return conversationTexts.slice(-maxTurns).join('\n');
}
async makeOutlineAndRequests(conversationTexts, maxTurns = 30) {
console.log(`🔍 makeOutlineAndRequests called - conversationTexts: ${conversationTexts.length}`);
if (conversationTexts.length === 0) {
console.log('⚠️ No conversation texts available for analysis');
return null;
}
const recentConversation = this.formatConversationForPrompt(conversationTexts, maxTurns);
// 이전 분석 결과를 프롬프트에 포함
let contextualPrompt = '';
if (this.previousAnalysisResult) {
contextualPrompt = `
Previous Analysis Context:
- Main Topic: ${this.previousAnalysisResult.topic.header}
- Key Points: ${this.previousAnalysisResult.summary.slice(0, 3).join(', ')}
- Last Actions: ${this.previousAnalysisResult.actions.slice(0, 2).join(', ')}
Please build upon this context while analyzing the new conversation segments.
`;
}
const basePrompt = getSystemPrompt('pickle_glass_analysis', '', false);
const systemPrompt = basePrompt.replace('{{CONVERSATION_HISTORY}}', recentConversation);
try {
if (this.currentSessionId) {
await sessionRepository.touch(this.currentSessionId);
}
const modelInfo = await modelStateService.getCurrentModelInfo('llm');
if (!modelInfo || !modelInfo.apiKey) {
throw new Error('AI model or API key is not configured.');
}
console.log(`🤖 Sending analysis request to ${modelInfo.provider} using model ${modelInfo.model}`);
const messages = [
{
role: 'system',
content: systemPrompt,
},
{
role: 'user',
content: `${contextualPrompt}
Analyze the conversation and provide a structured summary. Format your response as follows:
**Summary Overview**
- Main discussion point with context
**Key Topic: [Topic Name]**
- First key insight
- Second key insight
- Third key insight
**Extended Explanation**
Provide 2-3 sentences explaining the context and implications.
**Suggested Questions**
1. First follow-up question?
2. Second follow-up question?
3. Third follow-up question?
Keep all points concise and build upon previous analysis if provided.`,
},
];
console.log('🤖 Sending analysis request to AI...');
const llm = createLLM(modelInfo.provider, {
apiKey: modelInfo.apiKey,
model: modelInfo.model,
temperature: 0.7,
maxTokens: 1024,
usePortkey: modelInfo.provider === 'openai-glass',
portkeyVirtualKey: modelInfo.provider === 'openai-glass' ? modelInfo.apiKey : undefined,
});
const completion = await llm.chat(messages);
const responseText = completion.content;
console.log(`✅ Analysis response received: ${responseText}`);
const structuredData = this.parseResponseText(responseText, this.previousAnalysisResult);
if (this.currentSessionId) {
try {
summaryRepository.saveSummary({
sessionId: this.currentSessionId,
text: responseText,
tldr: structuredData.summary.join('\n'),
bullet_json: JSON.stringify(structuredData.topic.bullets),
action_json: JSON.stringify(structuredData.actions),
model: modelInfo.model
});
} catch (err) {
console.error('[DB] Failed to save summary:', err);
}
}
// 분석 결과 저장
this.previousAnalysisResult = structuredData;
this.analysisHistory.push({
timestamp: Date.now(),
data: structuredData,
conversationLength: conversationTexts.length,
});
if (this.analysisHistory.length > 10) {
this.analysisHistory.shift();
}
return structuredData;
} catch (error) {
console.error('❌ Error during analysis generation:', error.message);
return this.previousAnalysisResult; // 에러 시 이전 결과 반환
}
}
parseResponseText(responseText, previousResult) {
const structuredData = {
summary: [],
topic: { header: '', bullets: [] },
actions: [],
followUps: ['✉️ Draft a follow-up email', '✅ Generate action items', '📝 Show summary'],
};
// 이전 결과가 있으면 기본값으로 사용
if (previousResult) {
structuredData.topic.header = previousResult.topic.header;
structuredData.summary = [...previousResult.summary];
}
try {
const lines = responseText.split('\n');
let currentSection = '';
let isCapturingTopic = false;
let topicName = '';
for (const line of lines) {
const trimmedLine = line.trim();
// 섹션 헤더 감지
if (trimmedLine.startsWith('**Summary Overview**')) {
currentSection = 'summary-overview';
continue;
} else if (trimmedLine.startsWith('**Key Topic:')) {
currentSection = 'topic';
isCapturingTopic = true;
topicName = trimmedLine.match(/\*\*Key Topic: (.+?)\*\*/)?.[1] || '';
if (topicName) {
structuredData.topic.header = topicName + ':';
}
continue;
} else if (trimmedLine.startsWith('**Extended Explanation**')) {
currentSection = 'explanation';
continue;
} else if (trimmedLine.startsWith('**Suggested Questions**')) {
currentSection = 'questions';
continue;
}
// 컨텐츠 파싱
if (trimmedLine.startsWith('-') && currentSection === 'summary-overview') {
const summaryPoint = trimmedLine.substring(1).trim();
if (summaryPoint && !structuredData.summary.includes(summaryPoint)) {
// 기존 summary 업데이트 (최대 5개 유지)
structuredData.summary.unshift(summaryPoint);
if (structuredData.summary.length > 5) {
structuredData.summary.pop();
}
}
} else if (trimmedLine.startsWith('-') && currentSection === 'topic') {
const bullet = trimmedLine.substring(1).trim();
if (bullet && structuredData.topic.bullets.length < 3) {
structuredData.topic.bullets.push(bullet);
}
} else if (currentSection === 'explanation' && trimmedLine) {
// explanation을 topic bullets에 추가 (문장 단위로)
const sentences = trimmedLine
.split(/\.\s+/)
.filter(s => s.trim().length > 0)
.map(s => s.trim() + (s.endsWith('.') ? '' : '.'));
sentences.forEach(sentence => {
if (structuredData.topic.bullets.length < 3 && !structuredData.topic.bullets.includes(sentence)) {
structuredData.topic.bullets.push(sentence);
}
});
} else if (trimmedLine.match(/^\d+\./) && currentSection === 'questions') {
const question = trimmedLine.replace(/^\d+\.\s*/, '').trim();
if (question && question.includes('?')) {
structuredData.actions.push(`❓ ${question}`);
}
}
}
// 기본 액션 추가
const defaultActions = ['✨ What should I say next?', '💬 Suggest follow-up questions'];
defaultActions.forEach(action => {
if (!structuredData.actions.includes(action)) {
structuredData.actions.push(action);
}
});
// 액션 개수 제한
structuredData.actions = structuredData.actions.slice(0, 5);
// 유효성 검증 및 이전 데이터 병합
if (structuredData.summary.length === 0 && previousResult) {
structuredData.summary = previousResult.summary;
}
if (structuredData.topic.bullets.length === 0 && previousResult) {
structuredData.topic.bullets = previousResult.topic.bullets;
}
} catch (error) {
console.error('❌ Error parsing response text:', error);
// 에러 시 이전 결과 반환
return (
previousResult || {
summary: [],
topic: { header: 'Analysis in progress', bullets: [] },
actions: ['✨ What should I say next?', '💬 Suggest follow-up questions'],
followUps: ['✉️ Draft a follow-up email', '✅ Generate action items', '📝 Show summary'],
}
);
}
console.log('📊 Final structured data:', JSON.stringify(structuredData, null, 2));
return structuredData;
}
/**
* Triggers analysis when conversation history reaches 5 texts.
*/
async triggerAnalysisIfNeeded() {
if (this.conversationHistory.length >= 5 && this.conversationHistory.length % 5 === 0) {
console.log(`Triggering analysis - ${this.conversationHistory.length} conversation texts accumulated`);
const data = await this.makeOutlineAndRequests(this.conversationHistory);
if (data) {
console.log('Sending structured data to renderer');
this.sendToRenderer('summary-update', data);
// Notify callback
if (this.onAnalysisComplete) {
this.onAnalysisComplete(data);
}
} else {
console.log('No analysis data returned');
}
}
}
getCurrentAnalysisData() {
return {
previousResult: this.previousAnalysisResult,
history: this.analysisHistory,
conversationLength: this.conversationHistory.length,
};
}
}
module.exports = SummaryService;
================================================
FILE: src/features/settings/repositories/firebase.repository.js
================================================
const { collection, doc, addDoc, getDoc, getDocs, updateDoc, deleteDoc, query, where, orderBy } = require('firebase/firestore');
const { getFirestoreInstance } = require('../../common/services/firebaseClient');
const { createEncryptedConverter } = require('../../common/repositories/firestoreConverter');
const encryptionService = require('../../common/services/encryptionService');
const userPresetConverter = createEncryptedConverter(['prompt', 'title']);
const defaultPresetConverter = {
toFirestore: (data) => data,
fromFirestore: (snapshot, options) => {
const data = snapshot.data(options);
return { ...data, id: snapshot.id };
}
};
function userPresetsCol() {
const db = getFirestoreInstance();
return collection(db, 'prompt_presets').withConverter(userPresetConverter);
}
function defaultPresetsCol() {
const db = getFirestoreInstance();
return collection(db, 'defaults/v1/prompt_presets').withConverter(defaultPresetConverter);
}
async function getPresets(uid) {
const userPresetsQuery = query(userPresetsCol(), where('uid', '==', uid));
const defaultPresetsQuery = query(defaultPresetsCol());
const [userSnapshot, defaultSnapshot] = await Promise.all([
getDocs(userPresetsQuery),
getDocs(defaultPresetsQuery)
]);
const presets = [
...defaultSnapshot.docs.map(d => d.data()),
...userSnapshot.docs.map(d => d.data())
];
return presets.sort((a, b) => {
if (a.is_default && !b.is_default) return -1;
if (!a.is_default && b.is_default) return 1;
return a.title.localeCompare(b.title);
});
}
async function getPresetTemplates() {
const q = query(defaultPresetsCol(), orderBy('title', 'asc'));
const snapshot = await getDocs(q);
return snapshot.docs.map(doc => doc.data());
}
async function createPreset({ uid, title, prompt }) {
const now = Math.floor(Date.now() / 1000);
const newPreset = {
uid: uid,
title,
prompt,
is_default: 0,
created_at: now,
};
const docRef = await addDoc(userPresetsCol(), newPreset);
return { id: docRef.id };
}
async function updatePreset(id, { title, prompt }, uid) {
const docRef = doc(userPresetsCol(), id);
const docSnap = await getDoc(docRef);
if (!docSnap.exists() || docSnap.data().uid !== uid || docSnap.data().is_default) {
throw new Error("Preset not found or permission denied to update.");
}
const updates = {};
if (title !== undefined) {
updates.title = encryptionService.encrypt(title);
}
if (prompt !== undefined) {
updates.prompt = encryptionService.encrypt(prompt);
}
updates.updated_at = Math.floor(Date.now() / 1000);
await updateDoc(docRef, updates);
return { changes: 1 };
}
async function deletePreset(id, uid) {
const docRef = doc(userPresetsCol(), id);
const docSnap = await getDoc(docRef);
if (!docSnap.exists() || docSnap.data().uid !== uid || docSnap.data().is_default) {
throw new Error("Preset not found or permission denied to delete.");
}
await deleteDoc(docRef);
return { changes: 1 };
}
async function getAutoUpdate(uid) {
// Assume users are stored in a "users" collection, and auto_update_enabled is a field
const userDocRef = doc(getFirestoreInstance(), 'users', uid);
try {
const userSnap = await getDoc(userDocRef);
if (userSnap.exists()) {
const data = userSnap.data();
if (typeof data.auto_update_enabled !== 'undefined') {
console.log('Firebase: Auto update setting found:', data.auto_update_enabled);
return !!data.auto_update_enabled;
} else {
// Field does not exist, just return default
return true;
}
} else {
// User doc does not exist, just return default
return true;
}
} catch (error) {
console.error('Firebase: Error getting auto_update_enabled setting:', error);
return true; // fallback to enabled
}
}
async function setAutoUpdate(uid, isEnabled) {
const userDocRef = doc(getFirestoreInstance(), 'users', uid);
try {
const userSnap = await getDoc(userDocRef);
if (userSnap.exists()) {
await updateDoc(userDocRef, { auto_update_enabled: !!isEnabled });
}
// If user doc does not exist, do nothing (no creation)
return { success: true };
} catch (error) {
console.error('Firebase: Error setting auto-update:', error);
return { success: false, error: error.message };
}
}
module.exports = {
getPresets,
getPresetTemplates,
createPreset,
updatePreset,
deletePreset,
getAutoUpdate,
setAutoUpdate,
};
================================================
FILE: src/features/settings/repositories/index.js
================================================
const sqliteRepository = require('./sqlite.repository');
const firebaseRepository = require('./firebase.repository');
const authService = require('../../common/services/authService');
function getBaseRepository() {
const user = authService.getCurrentUser();
if (user && user.isLoggedIn) {
return firebaseRepository;
}
return sqliteRepository;
}
const settingsRepositoryAdapter = {
getPresets: () => {
const uid = authService.getCurrentUserId();
return getBaseRepository().getPresets(uid);
},
getPresetTemplates: () => {
return getBaseRepository().getPresetTemplates();
},
createPreset: (options) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().createPreset({ uid, ...options });
},
updatePreset: (id, options) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().updatePreset(id, options, uid);
},
deletePreset: (id) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().deletePreset(id, uid);
},
getAutoUpdate: () => {
const uid = authService.getCurrentUserId();
return getBaseRepository().getAutoUpdate(uid);
},
setAutoUpdate: (isEnabled) => {
const uid = authService.getCurrentUserId();
return getBaseRepository().setAutoUpdate(uid, isEnabled);
},
};
module.exports = settingsRepositoryAdapter;
================================================
FILE: src/features/settings/repositories/sqlite.repository.js
================================================
const sqliteClient = require('../../common/services/sqliteClient');
function getPresets(uid) {
const db = sqliteClient.getDb();
const query = `
SELECT * FROM prompt_presets
WHERE uid = ? OR is_default = 1
ORDER BY is_default DESC, title ASC
`;
try {
return db.prepare(query).all(uid) || [];
} catch (err) {
console.error('SQLite: Failed to get presets:', err);
throw err;
}
}
function getPresetTemplates() {
const db = sqliteClient.getDb();
const query = `
SELECT * FROM prompt_presets
WHERE is_default = 1
ORDER BY title ASC
`;
try {
return db.prepare(query).all() || [];
} catch (err) {
console.error('SQLite: Failed to get preset templates:', err);
throw err;
}
}
function createPreset({ uid, title, prompt }) {
const db = sqliteClient.getDb();
const id = require('crypto').randomUUID();
const now = Math.floor(Date.now() / 1000);
const query = `
INSERT INTO prompt_presets (id, uid, title, prompt, is_default, created_at, sync_state)
VALUES (?, ?, ?, ?, 0, ?, 'dirty')
`;
try {
db.prepare(query).run(id, uid, title, prompt, now);
return { id };
} catch (err) {
console.error('SQLite: Failed to create preset:', err);
throw err;
}
}
function updatePreset(id, { title, prompt }, uid) {
const db = sqliteClient.getDb();
const now = Math.floor(Date.now() / 1000);
const query = `
UPDATE prompt_presets
SET title = ?, prompt = ?, sync_state = 'dirty', updated_at = ?
WHERE id = ? AND uid = ? AND is_default = 0
`;
try {
const result = db.prepare(query).run(title, prompt, now, id, uid);
if (result.changes === 0) {
throw new Error('Preset not found, is default, or permission denied');
}
return { changes: result.changes };
} catch (err) {
console.error('SQLite: Failed to update preset:', err);
throw err;
}
}
function deletePreset(id, uid) {
const db = sqliteClient.getDb();
const query = `
DELETE FROM prompt_presets
WHERE id = ? AND uid = ? AND is_default = 0
`;
try {
const result = db.prepare(query).run(id, uid);
if (result.changes === 0) {
throw new Error('Preset not found, is default, or permission denied');
}
return { changes: result.changes };
} catch (err) {
console.error('SQLite: Failed to delete preset:', err);
throw err;
}
}
function getAutoUpdate(uid) {
const db = sqliteClient.getDb();
const targetUid = uid;
try {
const row = db.prepare('SELECT auto_update_enabled FROM users WHERE uid = ?').get(targetUid);
if (row) {
console.log('SQLite: Auto update setting found:', row.auto_update_enabled);
return row.auto_update_enabled !== 0;
} else {
// User doesn't exist, create them with default settings
const now = Math.floor(Date.now() / 1000);
const stmt = db.prepare(
'INSERT OR REPLACE INTO users (uid, display_name, email, created_at, auto_update_enabled) VALUES (?, ?, ?, ?, ?)');
stmt.run(targetUid, 'User', 'user@example.com', now, 1);
return true; // default to enabled
}
} catch (error) {
console.error('SQLite: Error getting auto_update_enabled setting:', error);
return true; // fallback to enabled
}
}
function setAutoUpdate(uid, isEnabled) {
const db = sqliteClient.getDb();
const targetUid = uid || sqliteClient.defaultUserId;
try {
const result = db.prepare('UPDATE users SET auto_update_enabled = ? WHERE uid = ?').run(isEnabled ? 1 : 0, targetUid);
// If no rows were updated, the user might not exist, so create them
if (result.changes === 0) {
const now = Math.floor(Date.now() / 1000);
const stmt = db.prepare('INSERT OR REPLACE INTO users (uid, display_name, email, created_at, auto_update_enabled) VALUES (?, ?, ?, ?, ?)');
stmt.run(targetUid, 'User', 'user@example.com', now, isEnabled ? 1 : 0);
}
return { success: true };
} catch (error) {
console.error('SQLite: Error setting auto-update:', error);
throw error;
}
}
module.exports = {
getPresets,
getPresetTemplates,
createPreset,
updatePreset,
deletePreset,
getAutoUpdate,
setAutoUpdate
};
================================================
FILE: src/features/settings/settingsService.js
================================================
const { ipcMain, BrowserWindow } = require('electron');
const Store = require('electron-store');
const authService = require('../common/services/authService');
const settingsRepository = require('./repositories');
const { getStoredApiKey, getStoredProvider, windowPool } = require('../../window/windowManager');
// New imports for common services
const modelStateService = require('../common/services/modelStateService');
const localAIManager = require('../common/services/localAIManager');
const store = new Store({
name: 'pickle-glass-settings',
defaults: {
users: {}
}
});
// Configuration constants
const NOTIFICATION_CONFIG = {
RELEVANT_WINDOW_TYPES: ['settings', 'main'],
DEBOUNCE_DELAY: 300, // prevent spam during bulk operations (ms)
MAX_RETRY_ATTEMPTS: 3,
RETRY_BASE_DELAY: 1000, // exponential backoff base (ms)
};
// New facade functions for model state management
async function getModelSettings() {
try {
const [config, storedKeys, selectedModels, availableLlm, availableStt] = await Promise.all([
modelStateService.getProviderConfig(),
modelStateService.getAllApiKeys(),
modelStateService.getSelectedModels(),
modelStateService.getAvailableModels('llm'),
modelStateService.getAvailableModels('stt')
]);
return { success: true, data: { config, storedKeys, availableLlm, availableStt, selectedModels } };
} catch (error) {
console.error('[SettingsService] Error getting model settings:', error);
return { success: false, error: error.message };
}
}
async function clearApiKey(provider) {
const success = await modelStateService.handleRemoveApiKey(provider);
return { success };
}
async function setSelectedModel(type, modelId) {
const success = await modelStateService.handleSetSelectedModel(type, modelId);
return { success };
}
// LocalAI facade functions
async function getOllamaStatus() {
return localAIManager.getServiceStatus('ollama');
}
async function ensureOllamaReady() {
const status = await localAIManager.getServiceStatus('ollama');
if (!status.installed || !status.running) {
await localAIManager.startService('ollama');
}
return { success: true };
}
async function shutdownOllama() {
return localAIManager.stopService('ollama');
}
// window targeting system
class WindowNotificationManager {
constructor() {
this.pendingNotifications = new Map();
}
/**
* Send notifications only to relevant windows
* @param {string} event - Event name
* @param {*} data - Event data
* @param {object} options - Notification options
*/
notifyRelevantWindows(event, data = null, options = {}) {
const {
windowTypes = NOTIFICATION_CONFIG.RELEVANT_WINDOW_TYPES,
debounce = NOTIFICATION_CONFIG.DEBOUNCE_DELAY
} = options;
if (debounce > 0) {
this.debounceNotification(event, () => {
this.sendToTargetWindows(event, data, windowTypes);
}, debounce);
} else {
this.sendToTargetWindows(event, data, windowTypes);
}
}
sendToTargetWindows(event, data, windowTypes) {
const relevantWindows = this.getRelevantWindows(windowTypes);
if (relevantWindows.length === 0) {
console.log(`[WindowNotificationManager] No relevant windows found for event: ${event}`);
return;
}
console.log(`[WindowNotificationManager] Sending ${event} to ${relevantWindows.length} relevant windows`);
relevantWindows.forEach(win => {
try {
if (data) {
win.webContents.send(event, data);
} else {
win.webContents.send(event);
}
} catch (error) {
console.warn(`[WindowNotificationManager] Failed to send ${event} to window:`, error.message);
}
});
}
getRelevantWindows(windowTypes) {
const allWindows = BrowserWindow.getAllWindows();
const relevantWindows = [];
allWindows.forEach(win => {
if (win.isDestroyed()) return;
for (const [windowName, poolWindow] of windowPool || []) {
if (poolWindow === win && windowTypes.includes(windowName)) {
if (windowName === 'settings' || win.isVisible()) {
relevantWindows.push(win);
}
break;
}
}
});
return relevantWindows;
}
debounceNotification(key, fn, delay) {
// Clear existing timeout
if (this.pendingNotifications.has(key)) {
clearTimeout(this.pendingNotifications.get(key));
}
// Set new timeout
const timeoutId = setTimeout(() => {
fn();
this.pendingNotifications.delete(key);
}, delay);
this.pendingNotifications.set(key, timeoutId);
}
cleanup() {
// Clear all pending notifications
this.pendingNotifications.forEach(timeoutId => clearTimeout(timeoutId));
this.pendingNotifications.clear();
}
}
// Global instance
const windowNotificationManager = new WindowNotificationManager();
// Default keybinds configuration
const DEFAULT_KEYBINDS = {
mac: {
moveUp: 'Cmd+Up',
moveDown: 'Cmd+Down',
moveLeft: 'Cmd+Left',
moveRight: 'Cmd+Right',
toggleVisibility: 'Cmd+\\',
toggleClickThrough: 'Cmd+M',
nextStep: 'Cmd+Enter',
manualScreenshot: 'Cmd+Shift+S',
previousResponse: 'Cmd+[',
nextResponse: 'Cmd+]',
scrollUp: 'Cmd+Shift+Up',
scrollDown: 'Cmd+Shift+Down',
},
windows: {
moveUp: 'Ctrl+Up',
moveDown: 'Ctrl+Down',
moveLeft: 'Ctrl+Left',
moveRight: 'Ctrl+Right',
toggleVisibility: 'Ctrl+\\',
toggleClickThrough: 'Ctrl+M',
nextStep: 'Ctrl+Enter',
manualScreenshot: 'Ctrl+Shift+S',
previousResponse: 'Ctrl+[',
nextResponse: 'Ctrl+]',
scrollUp: 'Ctrl+Shift+Up',
scrollDown: 'Ctrl+Shift+Down',
}
};
// Service state
let currentSettings = null;
function getDefaultSettings() {
const isMac = process.platform === 'darwin';
return {
profile: 'school',
language: 'en',
screenshotInterval: '5000',
imageQuality: '0.8',
layoutMode: 'stacked',
keybinds: isMac ? DEFAULT_KEYBINDS.mac : DEFAULT_KEYBINDS.windows,
throttleTokens: 500,
maxTokens: 2000,
throttlePercent: 80,
googleSearchEnabled: false,
backgroundTransparency: 0.5,
fontSize: 14,
contentProtection: true
};
}
async function getSettings() {
try {
const uid = authService.getCurrentUserId();
const userSettingsKey = uid ? `users.${uid}` : 'users.default';
const defaultSettings = getDefaultSettings();
const savedSettings = store.get(userSettingsKey, {});
currentSettings = { ...defaultSettings, ...savedSettings };
return currentSettings;
} catch (error) {
console.error('[SettingsService] Error getting settings from store:', error);
return getDefaultSettings();
}
}
async function saveSettings(settings) {
try {
const uid = authService.getCurrentUserId();
const userSettingsKey = uid ? `users.${uid}` : 'users.default';
const currentSaved = store.get(userSettingsKey, {});
const newSettings = { ...currentSaved, ...settings };
store.set(userSettingsKey, newSettings);
currentSettings = newSettings;
// Use smart notification system
windowNotificationManager.notifyRelevantWindows('settings-updated', currentSettings);
return { success: true };
} catch (error) {
console.error('[SettingsService] Error saving settings to store:', error);
return { success: false, error: error.message };
}
}
async function getPresets() {
try {
// The adapter now handles which presets to return based on login state.
const presets = await settingsRepository.getPresets();
return presets;
} catch (error) {
console.error('[SettingsService] Error getting presets:', error);
return [];
}
}
async function getPresetTemplates() {
try {
const templates = await settingsRepository.getPresetTemplates();
return templates;
} catch (error) {
console.error('[SettingsService] Error getting preset templates:', error);
return [];
}
}
async function createPreset(title, prompt) {
try {
// The adapter injects the UID.
const result = await settingsRepository.createPreset({ title, prompt });
windowNotificationManager.notifyRelevantWindows('presets-updated', {
action: 'created',
presetId: result.id,
title
});
return { success: true, id: result.id };
} catch (error) {
console.error('[SettingsService] Error creating preset:', error);
return { success: false, error: error.message };
}
}
async function updatePreset(id, title, prompt) {
try {
// The adapter injects the UID.
await settingsRepository.updatePreset(id, { title, prompt });
windowNotificationManager.notifyRelevantWindows('presets-updated', {
action: 'updated',
presetId: id,
title
});
return { success: true };
} catch (error) {
console.error('[SettingsService] Error updating preset:', error);
return { success: false, error: error.message };
}
}
async function deletePreset(id) {
try {
// The adapter injects the UID.
await settingsRepository.deletePreset(id);
windowNotificationManager.notifyRelevantWindows('presets-updated', {
action: 'deleted',
presetId: id
});
return { success: true };
} catch (error) {
console.error('[SettingsService] Error deleting preset:', error);
return { success: false, error: error.message };
}
}
async function saveApiKey(apiKey, provider = 'openai') {
try {
// Use ModelStateService as the single source of truth for API key management
const modelStateService = global.modelStateService;
if (!modelStateService) {
throw new Error('ModelStateService not initialized');
}
await modelStateService.setApiKey(provider, apiKey);
// Notify windows
BrowserWindow.getAllWindows().forEach(win => {
if (!win.isDestroyed()) {
win.webContents.send('api-key-validated', apiKey);
}
});
return { success: true };
} catch (error) {
console.error('[SettingsService] Error saving API key:', error);
return { success: false, error: error.message };
}
}
async function removeApiKey() {
try {
// Use ModelStateService as the single source of truth for API key management
const modelStateService = global.modelStateService;
if (!modelStateService) {
throw new Error('ModelStateService not initialized');
}
// Remove all API keys for all providers
const providers = ['openai', 'anthropic', 'gemini', 'ollama', 'whisper'];
for (const provider of providers) {
await modelStateService.removeApiKey(provider);
}
// Notify windows
BrowserWindow.getAllWindows().forEach(win => {
if (!win.isDestroyed()) {
win.webContents.send('api-key-removed');
}
});
console.log('[SettingsService] API key removed for all providers');
return { success: true };
} catch (error) {
console.error('[SettingsService] Error removing API key:', error);
return { success: false, error: error.message };
}
}
async function updateContentProtection(enabled) {
try {
const settings = await getSettings();
settings.contentProtection = enabled;
// Update content protection in main window
const { app } = require('electron');
const mainWindow = windowPool.get('main');
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.setContentProtection(enabled);
}
return await saveSettings(settings);
} catch (error) {
console.error('[SettingsService] Error updating content protection:', error);
return { success: false, error: error.message };
}
}
async function getAutoUpdateSetting() {
try {
return settingsRepository.getAutoUpdate();
} catch (error) {
console.error('[SettingsService] Error getting auto update setting:', error);
return true; // Fallback to enabled
}
}
async function setAutoUpdateSetting(isEnabled) {
try {
await settingsRepository.setAutoUpdate(isEnabled);
return { success: true };
} catch (error) {
console.error('[SettingsService] Error setting auto update setting:', error);
return { success: false, error: error.message };
}
}
function initialize() {
// cleanup
windowNotificationManager.cleanup();
console.log('[SettingsService] Initialized and ready.');
}
// Cleanup function
function cleanup() {
windowNotificationManager.cleanup();
console.log('[SettingsService] Cleaned up resources.');
}
function notifyPresetUpdate(action, presetId, title = null) {
const data = { action, presetId };
if (title) data.title = title;
windowNotificationManager.notifyRelevantWindows('presets-updated', data);
}
module.exports = {
initialize,
cleanup,
notifyPresetUpdate,
getSettings,
saveSettings,
getPresets,
getPresetTemplates,
createPreset,
updatePreset,
deletePreset,
saveApiKey,
removeApiKey,
updateContentProtection,
getAutoUpdateSetting,
setAutoUpdateSetting,
// Model settings facade
getModelSettings,
clearApiKey,
setSelectedModel,
// Ollama facade
getOllamaStatus,
ensureOllamaReady,
shutdownOllama
};
================================================
FILE: src/features/shortcuts/repositories/index.js
================================================
module.exports = require('./sqlite.repository');
================================================
FILE: src/features/shortcuts/repositories/sqlite.repository.js
================================================
const sqliteClient = require('../../common/services/sqliteClient');
const crypto = require('crypto');
function getAllKeybinds() {
const db = sqliteClient.getDb();
const query = 'SELECT * FROM shortcuts';
try {
return db.prepare(query).all();
} catch (error) {
console.error(`[DB] Failed to get keybinds:`, error);
return [];
}
}
function upsertKeybinds(keybinds) {
if (!keybinds || keybinds.length === 0) return;
const db = sqliteClient.getDb();
const upsert = db.transaction((items) => {
const query = `
INSERT INTO shortcuts (action, accelerator, created_at)
VALUES (@action, @accelerator, @created_at)
ON CONFLICT(action) DO UPDATE SET
accelerator = excluded.accelerator;
`;
const insert = db.prepare(query);
for (const item of items) {
insert.run({
action: item.action,
accelerator: item.accelerator,
created_at: Math.floor(Date.now() / 1000)
});
}
});
try {
upsert(keybinds);
} catch (error) {
console.error('[DB] Failed to upsert keybinds:', error);
throw error;
}
}
module.exports = {
getAllKeybinds,
upsertKeybinds
};
================================================
FILE: src/features/shortcuts/shortcutsService.js
================================================
const { globalShortcut, screen } = require('electron');
const shortcutsRepository = require('./repositories');
const internalBridge = require('../../bridge/internalBridge');
const askService = require('../ask/askService');
class ShortcutsService {
constructor() {
this.lastVisibleWindows = new Set(['header']);
this.mouseEventsIgnored = false;
this.windowPool = null;
this.allWindowVisibility = true;
}
initialize(windowPool) {
this.windowPool = windowPool;
internalBridge.on('reregister-shortcuts', () => {
console.log('[ShortcutsService] Reregistering shortcuts due to header state change.');
this.registerShortcuts();
});
console.log('[ShortcutsService] Initialized with dependencies and event listener.');
}
async openShortcutSettingsWindow () {
const keybinds = await this.loadKeybinds();
const shortcutWin = this.windowPool.get('shortcut-settings');
shortcutWin.webContents.send('shortcut:loadShortcuts', keybinds);
globalShortcut.unregisterAll();
internalBridge.emit('window:requestVisibility', { name: 'shortcut-settings', visible: true });
console.log('[ShortcutsService] Shortcut settings window opened.');
return { success: true };
}
async closeShortcutSettingsWindow () {
await this.registerShortcuts();
internalBridge.emit('window:requestVisibility', { name: 'shortcut-settings', visible: false });
console.log('[ShortcutsService] Shortcut settings window closed.');
return { success: true };
}
async handleSaveShortcuts(newKeybinds) {
try {
await this.saveKeybinds(newKeybinds);
await this.closeShortcutSettingsWindow();
return { success: true };
} catch (error) {
console.error("Failed to save shortcuts:", error);
await this.closeShortcutSettingsWindow();
return { success: false, error: error.message };
}
}
async handleRestoreDefaults() {
const defaults = this.getDefaultKeybinds();
return defaults;
}
getDefaultKeybinds() {
const isMac = process.platform === 'darwin';
return {
moveUp: isMac ? 'Cmd+Up' : 'Ctrl+Up',
moveDown: isMac ? 'Cmd+Down' : 'Ctrl+Down',
moveLeft: isMac ? 'Cmd+Left' : 'Ctrl+Left',
moveRight: isMac ? 'Cmd+Right' : 'Ctrl+Right',
toggleVisibility: isMac ? 'Cmd+\\' : 'Ctrl+\\',
toggleClickThrough: isMac ? 'Cmd+M' : 'Ctrl+M',
nextStep: isMac ? 'Cmd+Enter' : 'Ctrl+Enter',
manualScreenshot: isMac ? 'Cmd+Shift+S' : 'Ctrl+Shift+S',
previousResponse: isMac ? 'Cmd+[' : 'Ctrl+[',
nextResponse: isMac ? 'Cmd+]' : 'Ctrl+]',
scrollUp: isMac ? 'Cmd+Shift+Up' : 'Ctrl+Shift+Up',
scrollDown: isMac ? 'Cmd+Shift+Down' : 'Ctrl+Shift+Down',
};
}
async loadKeybinds() {
let keybindsArray = await shortcutsRepository.getAllKeybinds();
if (!keybindsArray || keybindsArray.length === 0) {
console.log(`[Shortcuts] No keybinds found. Loading defaults.`);
const defaults = this.getDefaultKeybinds();
await this.saveKeybinds(defaults);
return defaults;
}
const keybinds = {};
keybindsArray.forEach(k => {
keybinds[k.action] = k.accelerator;
});
const defaults = this.getDefaultKeybinds();
let needsUpdate = false;
for (const action in defaults) {
if (!keybinds[action]) {
keybinds[action] = defaults[action];
needsUpdate = true;
}
}
if (needsUpdate) {
console.log('[Shortcuts] Updating missing keybinds with defaults.');
await this.saveKeybinds(keybinds);
}
return keybinds;
}
async saveKeybinds(newKeybinds) {
const keybindsToSave = [];
for (const action in newKeybinds) {
if (Object.prototype.hasOwnProperty.call(newKeybinds, action)) {
keybindsToSave.push({
action: action,
accelerator: newKeybinds[action],
});
}
}
await shortcutsRepository.upsertKeybinds(keybindsToSave);
console.log(`[Shortcuts] Saved keybinds.`);
}
async toggleAllWindowsVisibility() {
const targetVisibility = !this.allWindowVisibility;
internalBridge.emit('window:requestToggleAllWindowsVisibility', {
targetVisibility: targetVisibility
});
if (this.allWindowVisibility) {
await this.registerShortcuts(true);
} else {
await this.registerShortcuts();
}
this.allWindowVisibility = !this.allWindowVisibility;
}
async registerShortcuts(registerOnlyToggleVisibility = false) {
if (!this.windowPool) {
console.error('[Shortcuts] Service not initialized. Cannot register shortcuts.');
return;
}
const keybinds = await this.loadKeybinds();
globalShortcut.unregisterAll();
const header = this.windowPool.get('header');
const mainWindow = header;
const sendToRenderer = (channel, ...args) => {
this.windowPool.forEach(win => {
if (win && !win.isDestroyed()) {
try {
win.webContents.send(channel, ...args);
} catch (e) {
// Ignore errors for destroyed windows
}
}
});
};
sendToRenderer('shortcuts-updated', keybinds);
if (registerOnlyToggleVisibility) {
if (keybinds.toggleVisibility) {
globalShortcut.register(keybinds.toggleVisibility, () => this.toggleAllWindowsVisibility());
}
console.log('[Shortcuts] registerOnlyToggleVisibility, only toggleVisibility shortcut is registered.');
return;
}
// --- Hardcoded shortcuts ---
const isMac = process.platform === 'darwin';
const modifier = isMac ? 'Cmd' : 'Ctrl';
// Monitor switching
const displays = screen.getAllDisplays();
if (displays.length > 1) {
displays.forEach((display, index) => {
const key = `${modifier}+Shift+${index + 1}`;
globalShortcut.register(key, () => internalBridge.emit('window:moveToDisplay', { displayId: display.id }));
});
}
// Edge snapping
const edgeDirections = [
{ key: `${modifier}+Shift+Left`, direction: 'left' },
{ key: `${modifier}+Shift+Right`, direction: 'right' },
];
edgeDirections.forEach(({ key, direction }) => {
globalShortcut.register(key, () => {
if (header && header.isVisible()) internalBridge.emit('window:moveToEdge', { direction });
});
});
// --- User-configurable shortcuts ---
if (header?.currentHeaderState === 'apikey') {
if (keybinds.toggleVisibility) {
globalShortcut.register(keybinds.toggleVisibility, () => this.toggleAllWindowsVisibility());
}
console.log('[Shortcuts] ApiKeyHeader is active, only toggleVisibility shortcut is registered.');
return;
}
for (const action in keybinds) {
const accelerator = keybinds[action];
if (!accelerator) continue;
let callback;
switch(action) {
case 'toggleVisibility':
callback = () => this.toggleAllWindowsVisibility();
break;
case 'nextStep':
callback = () => askService.toggleAskButton(true);
break;
case 'scrollUp':
callback = () => {
const askWindow = this.windowPool.get('ask');
if (askWindow && !askWindow.isDestroyed() && askWindow.isVisible()) {
askWindow.webContents.send('scroll-response-up');
}
};
break;
case 'scrollDown':
callback = () => {
const askWindow = this.windowPool.get('ask');
if (askWindow && !askWindow.isDestroyed() && askWindow.isVisible()) {
askWindow.webContents.send('scroll-response-down');
}
};
break;
case 'moveUp':
callback = () => { if (header && header.isVisible()) internalBridge.emit('window:moveStep', { direction: 'up' }); };
break;
case 'moveDown':
callback = () => { if (header && header.isVisible()) internalBridge.emit('window:moveStep', { direction: 'down' }); };
break;
case 'moveLeft':
callback = () => { if (header && header.isVisible()) internalBridge.emit('window:moveStep', { direction: 'left' }); };
break;
case 'moveRight':
callback = () => { if (header && header.isVisible()) internalBridge.emit('window:moveStep', { direction: 'right' }); };
break;
case 'toggleClickThrough':
callback = () => {
this.mouseEventsIgnored = !this.mouseEventsIgnored;
if(mainWindow && !mainWindow.isDestroyed()){
mainWindow.setIgnoreMouseEvents(this.mouseEventsIgnored, { forward: true });
mainWindow.webContents.send('click-through-toggled', this.mouseEventsIgnored);
}
};
break;
case 'manualScreenshot':
callback = () => {
if(mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.executeJavaScript('window.captureManualScreenshot && window.captureManualScreenshot();');
}
};
break;
case 'previousResponse':
callback = () => sendToRenderer('navigate-previous-response');
break;
case 'nextResponse':
callback = () => sendToRenderer('navigate-next-response');
break;
}
if (callback) {
try {
globalShortcut.register(accelerator, callback);
} catch(e) {
console.error(`[Shortcuts] Failed to register shortcut for "${action}" (${accelerator}):`, e.message);
}
}
}
console.log('[Shortcuts] All shortcuts have been registered.');
}
unregisterAll() {
globalShortcut.unregisterAll();
console.log('[Shortcuts] All shortcuts have been unregistered.');
}
}
const shortcutsService = new ShortcutsService();
module.exports = shortcutsService;
================================================
FILE: src/index.js
================================================
// try {
// const reloader = require('electron-reloader');
// reloader(module, {
// });
// } catch (err) {
// }
require('dotenv').config();
if (require('electron-squirrel-startup')) {
process.exit(0);
}
const { app, BrowserWindow, shell, ipcMain, dialog, desktopCapturer, session } = require('electron');
const { createWindows } = require('./window/windowManager.js');
const listenService = require('./features/listen/listenService');
const { initializeFirebase } = require('./features/common/services/firebaseClient');
const databaseInitializer = require('./features/common/services/databaseInitializer');
const authService = require('./features/common/services/authService');
const path = require('node:path');
const express = require('express');
const fetch = require('node-fetch');
const { autoUpdater } = require('electron-updater');
const { EventEmitter } = require('events');
const askService = require('./features/ask/askService');
const settingsService = require('./features/settings/settingsService');
const sessionRepository = require('./features/common/repositories/session');
const modelStateService = require('./features/common/services/modelStateService');
const featureBridge = require('./bridge/featureBridge');
const windowBridge = require('./bridge/windowBridge');
// Global variables
const eventBridge = new EventEmitter();
let WEB_PORT = 3000;
let isShuttingDown = false; // Flag to prevent infinite shutdown loop
//////// after_modelStateService ////////
global.modelStateService = modelStateService;
//////// after_modelStateService ////////
// Import and initialize OllamaService
const ollamaService = require('./features/common/services/ollamaService');
const ollamaModelRepository = require('./features/common/repositories/ollamaModel');
// Native deep link handling - cross-platform compatible
let pendingDeepLinkUrl = null;
function setupProtocolHandling() {
// Protocol registration - must be done before app is ready
try {
if (!app.isDefaultProtocolClient('pickleglass')) {
const success = app.setAsDefaultProtocolClient('pickleglass');
if (success) {
console.log('[Protocol] Successfully set as default protocol client for pickleglass://');
} else {
console.warn('[Protocol] Failed to set as default protocol client - this may affect deep linking');
}
} else {
console.log('[Protocol] Already registered as default protocol client for pickleglass://');
}
} catch (error) {
console.error('[Protocol] Error during protocol registration:', error);
}
// Handle protocol URLs on Windows/Linux
app.on('second-instance', (event, commandLine, workingDirectory) => {
console.log('[Protocol] Second instance command line:', commandLine);
focusMainWindow();
let protocolUrl = null;
// Search through all command line arguments for a valid protocol URL
for (const arg of commandLine) {
if (arg && typeof arg === 'string' && arg.startsWith('pickleglass://')) {
// Clean up the URL by removing problematic characters
const cleanUrl = arg.replace(/[\\₩]/g, '');
// Additional validation for Windows
if (process.platform === 'win32') {
// On Windows, ensure the URL doesn't contain file path indicators
if (!cleanUrl.includes(':') || cleanUrl.indexOf('://') === cleanUrl.lastIndexOf(':')) {
protocolUrl = cleanUrl;
break;
}
} else {
protocolUrl = cleanUrl;
break;
}
}
}
if (protocolUrl) {
console.log('[Protocol] Valid URL found from second instance:', protocolUrl);
handleCustomUrl(protocolUrl);
} else {
console.log('[Protocol] No valid protocol URL found in command line arguments');
console.log('[Protocol] Command line args:', commandLine);
}
});
// Handle protocol URLs on macOS
app.on('open-url', (event, url) => {
event.preventDefault();
console.log('[Protocol] Received URL via open-url:', url);
if (!url || !url.startsWith('pickleglass://')) {
console.warn('[Protocol] Invalid URL format:', url);
return;
}
if (app.isReady()) {
handleCustomUrl(url);
} else {
pendingDeepLinkUrl = url;
console.log('[Protocol] App not ready, storing URL for later');
}
});
}
function focusMainWindow() {
const { windowPool } = require('./window/windowManager.js');
if (windowPool) {
const header = windowPool.get('header');
if (header && !header.isDestroyed()) {
if (header.isMinimized()) header.restore();
header.focus();
return true;
}
}
// Fallback: focus any available window
const windows = BrowserWindow.getAllWindows();
if (windows.length > 0) {
const mainWindow = windows[0];
if (!mainWindow.isDestroyed()) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
return true;
}
}
return false;
}
if (process.platform === 'win32') {
for (const arg of process.argv) {
if (arg && typeof arg === 'string' && arg.startsWith('pickleglass://')) {
// Clean up the URL by removing problematic characters (korean characters issue...)
const cleanUrl = arg.replace(/[\\₩]/g, '');
if (!cleanUrl.includes(':') || cleanUrl.indexOf('://') === cleanUrl.lastIndexOf(':')) {
console.log('[Protocol] Found protocol URL in initial arguments:', cleanUrl);
pendingDeepLinkUrl = cleanUrl;
break;
}
}
}
console.log('[Protocol] Initial process.argv:', process.argv);
}
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
process.exit(0);
}
// setup protocol after single instance lock
setupProtocolHandling();
app.whenReady().then(async () => {
// Setup native loopback audio capture for Windows
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
// Grant access to the first screen found with loopback audio
callback({ video: sources[0], audio: 'loopback' });
}).catch((error) => {
console.error('Failed to get desktop capturer sources:', error);
callback({});
});
});
// Initialize core services
initializeFirebase();
try {
await databaseInitializer.initialize();
console.log('>>> [index.js] Database initialized successfully');
// Clean up zombie sessions from previous runs first - MOVED TO authService
// sessionRepository.endAllActiveSessions();
await authService.initialize();
//////// after_modelStateService ////////
await modelStateService.initialize();
//////// after_modelStateService ////////
featureBridge.initialize(); // 추가: featureBridge 초기화
windowBridge.initialize();
setupWebDataHandlers();
// Initialize Ollama models in database
await ollamaModelRepository.initializeDefaultModels();
// Auto warm-up selected Ollama model in background (non-blocking)
setTimeout(async () => {
try {
console.log('[index.js] Starting background Ollama model warm-up...');
await ollamaService.autoWarmUpSelectedModel();
} catch (error) {
console.log('[index.js] Background warm-up failed (non-critical):', error.message);
}
}, 2000); // Wait 2 seconds after app start
// Start web server and create windows ONLY after all initializations are successful
WEB_PORT = await startWebStack();
console.log('Web front-end listening on', WEB_PORT);
createWindows();
} catch (err) {
console.error('>>> [index.js] Database initialization failed - some features may not work', err);
// Optionally, show an error dialog to the user
dialog.showErrorBox(
'Application Error',
'A critical error occurred during startup. Some features might be disabled. Please restart the application.'
);
}
// initAutoUpdater should be called after auth is initialized
initAutoUpdater();
// Process any pending deep link after everything is initialized
if (pendingDeepLinkUrl) {
console.log('[Protocol] Processing pending URL:', pendingDeepLinkUrl);
handleCustomUrl(pendingDeepLinkUrl);
pendingDeepLinkUrl = null;
}
});
app.on('before-quit', async (event) => {
// Prevent infinite loop by checking if shutdown is already in progress
if (isShuttingDown) {
console.log('[Shutdown] 🔄 Shutdown already in progress, allowing quit...');
return;
}
console.log('[Shutdown] App is about to quit. Starting graceful shutdown...');
// Set shutdown flag to prevent infinite loop
isShuttingDown = true;
// Prevent immediate quit to allow graceful shutdown
event.preventDefault();
try {
// 1. Stop audio capture first (immediate)
await listenService.closeSession();
console.log('[Shutdown] Audio capture stopped');
// 2. End all active sessions (database operations) - with error handling
try {
await sessionRepository.endAllActiveSessions();
console.log('[Shutdown] Active sessions ended');
} catch (dbError) {
console.warn('[Shutdown] Could not end active sessions (database may be closed):', dbError.message);
}
// 3. Shutdown Ollama service (potentially time-consuming)
console.log('[Shutdown] shutting down Ollama service...');
const ollamaShutdownSuccess = await Promise.race([
ollamaService.shutdown(false), // Graceful shutdown
new Promise(resolve => setTimeout(() => resolve(false), 8000)) // 8s timeout
]);
if (ollamaShutdownSuccess) {
console.log('[Shutdown] Ollama service shut down gracefully');
} else {
console.log('[Shutdown] Ollama shutdown timeout, forcing...');
// Force shutdown if graceful failed
try {
await ollamaService.shutdown(true);
} catch (forceShutdownError) {
console.warn('[Shutdown] Force shutdown also failed:', forceShutdownError.message);
}
}
// 4. Close database connections (final cleanup)
try {
databaseInitializer.close();
console.log('[Shutdown] Database connections closed');
} catch (closeError) {
console.warn('[Shutdown] Error closing database:', closeError.message);
}
console.log('[Shutdown] Graceful shutdown completed successfully');
} catch (error) {
console.error('[Shutdown] Error during graceful shutdown:', error);
// Continue with shutdown even if there were errors
} finally {
// Actually quit the app now
console.log('[Shutdown] Exiting application...');
app.exit(0); // Use app.exit() instead of app.quit() to force quit
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindows();
}
});
function setupWebDataHandlers() {
const sessionRepository = require('./features/common/repositories/session');
const sttRepository = require('./features/listen/stt/repositories');
const summaryRepository = require('./features/listen/summary/repositories');
const askRepository = require('./features/ask/repositories');
const userRepository = require('./features/common/repositories/user');
const presetRepository = require('./features/common/repositories/preset');
const handleRequest = async (channel, responseChannel, payload) => {
let result;
// const currentUserId = authService.getCurrentUserId(); // No longer needed here
try {
switch (channel) {
// SESSION
case 'get-sessions':
// Adapter injects UID
result = await sessionRepository.getAllByUserId();
break;
case 'get-session-details':
const session = await sessionRepository.getById(payload);
if (!session) {
result = null;
break;
}
const [transcripts, ai_messages, summary] = await Promise.all([
sttRepository.getAllTranscriptsBySessionId(payload),
askRepository.getAllAiMessagesBySessionId(payload),
summaryRepository.getSummaryBySessionId(payload)
]);
result = { session, transcripts, ai_messages, summary };
break;
case 'delete-session':
result = await sessionRepository.deleteWithRelatedData(payload);
break;
case 'create-session':
// Adapter injects UID
const id = await sessionRepository.create('ask');
if (payload && payload.title) {
await sessionRepository.updateTitle(id, payload.title);
}
result = { id };
break;
// USER
case 'get-user-profile':
// Adapter injects UID
result = await userRepository.getById();
break;
case 'update-user-profile':
// Adapter injects UID
result = await userRepository.update(payload);
break;
case 'find-or-create-user':
result = await userRepository.findOrCreate(payload);
break;
case 'save-api-key':
// Use ModelStateService as the single source of truth for API key management
result = await modelStateService.setApiKey(payload.provider, payload.apiKey);
break;
case 'check-api-key-status':
// Use ModelStateService to check API key status
const hasApiKey = await modelStateService.hasValidApiKey();
result = { hasApiKey };
break;
case 'delete-account':
// Adapter injects UID
result = await userRepository.deleteById();
break;
// PRESET
case 'get-presets':
// Adapter injects UID
result = await presetRepository.getPresets();
break;
case 'create-preset':
// Adapter injects UID
result = await presetRepository.create(payload);
settingsService.notifyPresetUpdate('created', result.id, payload.title);
break;
case 'update-preset':
// Adapter injects UID
result = await presetRepository.update(payload.id, payload.data);
settingsService.notifyPresetUpdate('updated', payload.id, payload.data.title);
break;
case 'delete-preset':
// Adapter injects UID
result = await presetRepository.delete(payload);
settingsService.notifyPresetUpdate('deleted', payload);
break;
// BATCH
case 'get-batch-data':
const includes = payload ? payload.split(',').map(item => item.trim()) : ['profile', 'presets', 'sessions'];
const promises = {};
if (includes.includes('profile')) {
// Adapter injects UID
promises.profile = userRepository.getById();
}
if (includes.includes('presets')) {
// Adapter injects UID
promises.presets = presetRepository.getPresets();
}
if (includes.includes('sessions')) {
// Adapter injects UID
promises.sessions = sessionRepository.getAllByUserId();
}
const batchResult = {};
const promiseResults = await Promise.all(Object.values(promises));
Object.keys(promises).forEach((key, index) => {
batchResult[key] = promiseResults[index];
});
result = batchResult;
break;
default:
throw new Error(`Unknown web data channel: ${channel}`);
}
eventBridge.emit(responseChannel, { success: true, data: result });
} catch (error) {
console.error(`Error handling web data request for ${channel}:`, error);
eventBridge.emit(responseChannel, { success: false, error: error.message });
}
};
eventBridge.on('web-data-request', handleRequest);
}
async function handleCustomUrl(url) {
try {
console.log('[Custom URL] Processing URL:', url);
// Validate and clean URL
if (!url || typeof url !== 'string' || !url.startsWith('pickleglass://')) {
console.error('[Custom URL] Invalid URL format:', url);
return;
}
// Clean up URL by removing problematic characters
const cleanUrl = url.replace(/[\\₩]/g, '');
// Additional validation
if (cleanUrl !== url) {
console.log('[Custom URL] Cleaned URL from:', url, 'to:', cleanUrl);
url = cleanUrl;
}
const urlObj = new URL(url);
const action = urlObj.hostname;
const params = Object.fromEntries(urlObj.searchParams);
console.log('[Custom URL] Action:', action, 'Params:', params);
switch (action) {
case 'login':
case 'auth-success':
await handleFirebaseAuthCallback(params);
break;
case 'personalize':
handlePersonalizeFromUrl(params);
break;
default:
const { windowPool } = require('./window/windowManager.js');
const header = windowPool.get('header');
if (header) {
if (header.isMinimized()) header.restore();
header.focus();
const targetUrl = `http://localhost:${WEB_PORT}/${action}`;
console.log(`[Custom URL] Navigating webview to: ${targetUrl}`);
header.webContents.loadURL(targetUrl);
}
}
} catch (error) {
console.error('[Custom URL] Error parsing URL:', error);
}
}
async function handleFirebaseAuthCallback(params) {
const userRepository = require('./features/common/repositories/user');
const { token: idToken } = params;
if (!idToken) {
console.error('[Auth] Firebase auth callback is missing ID token.');
// No need to send IPC, the UI won't transition without a successful auth state change.
return;
}
console.log('[Auth] Received ID token from deep link, exchanging for custom token...');
try {
const functionUrl = 'https://us-west1-pickle-3651a.cloudfunctions.net/pickleGlassAuthCallback';
const response = await fetch(functionUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: idToken })
});
const data = await response.json();
if (!response.ok || !data.success) {
throw new Error(data.error || 'Failed to exchange token.');
}
const { customToken, user } = data;
console.log('[Auth] Successfully received custom token for user:', user.uid);
const firebaseUser = {
uid: user.uid,
email: user.email || 'no-email@example.com',
displayName: user.name || 'User',
photoURL: user.picture
};
// 1. Sync user data to local DB
userRepository.findOrCreate(firebaseUser);
console.log('[Auth] User data synced with local DB.');
// 2. Sign in using the authService in the main process
await authService.signInWithCustomToken(customToken);
console.log('[Auth] Main process sign-in initiated. Waiting for onAuthStateChanged...');
// 3. Focus the app window
const { windowPool } = require('./window/windowManager.js');
const header = windowPool.get('header');
if (header) {
if (header.isMinimized()) header.restore();
header.focus();
} else {
console.error('[Auth] Header window not found after auth callback.');
}
} catch (error) {
console.error('[Auth] Error during custom token exchange or sign-in:', error);
// The UI will not change, and the user can try again.
// Optionally, send a generic error event to the renderer.
const { windowPool } = require('./window/windowManager.js');
const header = windowPool.get('header');
if (header) {
header.webContents.send('auth-failed', { message: error.message });
}
}
}
function handlePersonalizeFromUrl(params) {
console.log('[Custom URL] Personalize params:', params);
const { windowPool } = require('./window/windowManager.js');
const header = windowPool.get('header');
if (header) {
if (header.isMinimized()) header.restore();
header.focus();
const personalizeUrl = `http://localhost:${WEB_PORT}/settings`;
console.log(`[Custom URL] Navigating to personalize page: ${personalizeUrl}`);
header.webContents.loadURL(personalizeUrl);
BrowserWindow.getAllWindows().forEach(win => {
win.webContents.send('enter-personalize-mode', {
message: 'Personalization mode activated',
params: params
});
});
} else {
console.error('[Custom URL] Header window not found for personalize');
}
}
async function startWebStack() {
console.log('NODE_ENV =', process.env.NODE_ENV);
const isDev = !app.isPackaged;
const getAvailablePort = () => {
return new Promise((resolve, reject) => {
const server = require('net').createServer();
server.listen(0, (err) => {
if (err) reject(err);
const port = server.address().port;
server.close(() => resolve(port));
});
});
};
const apiPort = await getAvailablePort();
const frontendPort = await getAvailablePort();
console.log(`🔧 Allocated ports: API=${apiPort}, Frontend=${frontendPort}`);
process.env.pickleglass_API_PORT = apiPort.toString();
process.env.pickleglass_API_URL = `http://localhost:${apiPort}`;
process.env.pickleglass_WEB_PORT = frontendPort.toString();
process.env.pickleglass_WEB_URL = `http://localhost:${frontendPort}`;
console.log(`🌍 Environment variables set:`, {
pickleglass_API_URL: process.env.pickleglass_API_URL,
pickleglass_WEB_URL: process.env.pickleglass_WEB_URL
});
const createBackendApp = require('../pickleglass_web/backend_node');
const nodeApi = createBackendApp(eventBridge);
const staticDir = app.isPackaged
? path.join(process.resourcesPath, 'out')
: path.join(__dirname, '..', 'pickleglass_web', 'out');
const fs = require('fs');
if (!fs.existsSync(staticDir)) {
console.error(`============================================================`);
console.error(`[ERROR] Frontend build directory not found!`);
console.error(`Path: ${staticDir}`);
console.error(`Please run 'npm run build' inside the 'pickleglass_web' directory first.`);
console.error(`============================================================`);
app.quit();
return;
}
const runtimeConfig = {
API_URL: `http://localhost:${apiPort}`,
WEB_URL: `http://localhost:${frontendPort}`,
timestamp: Date.now()
};
// 쓰기 가능한 임시 폴더에 런타임 설정 파일 생성
const tempDir = app.getPath('temp');
const configPath = path.join(tempDir, 'runtime-config.json');
fs.writeFileSync(configPath, JSON.stringify(runtimeConfig, null, 2));
console.log(`📝 Runtime config created in temp location: ${configPath}`);
const frontSrv = express();
// 프론트엔드에서 /runtime-config.json을 요청하면 임시 폴더의 파일을 제공
frontSrv.get('/runtime-config.json', (req, res) => {
res.sendFile(configPath);
});
frontSrv.use((req, res, next) => {
if (req.path.indexOf('.') === -1 && req.path !== '/') {
const htmlPath = path.join(staticDir, req.path + '.html');
if (fs.existsSync(htmlPath)) {
return res.sendFile(htmlPath);
}
}
next();
});
frontSrv.use(express.static(staticDir));
const frontendServer = await new Promise((resolve, reject) => {
const server = frontSrv.listen(frontendPort, '127.0.0.1', () => resolve(server));
server.on('error', reject);
app.once('before-quit', () => server.close());
});
console.log(`✅ Frontend server started on http://localhost:${frontendPort}`);
const apiSrv = express();
apiSrv.use(nodeApi);
const apiServer = await new Promise((resolve, reject) => {
const server = apiSrv.listen(apiPort, '127.0.0.1', () => resolve(server));
server.on('error', reject);
app.once('before-quit', () => server.close());
});
console.log(`✅ API server started on http://localhost:${apiPort}`);
console.log(`🚀 All services ready:
Frontend: http://localhost:${frontendPort}
API: http://localhost:${apiPort}`);
return frontendPort;
}
// Auto-update initialization
async function initAutoUpdater() {
if (process.env.NODE_ENV === 'development') {
console.log('Development environment, skipping auto-updater.');
return;
}
try {
await autoUpdater.checkForUpdates();
autoUpdater.on('update-available', () => {
console.log('Update available!');
autoUpdater.downloadUpdate();
});
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName, date, url) => {
console.log('Update downloaded:', releaseNotes, releaseName, date, url);
dialog.showMessageBox({
type: 'info',
title: 'Application Update',
message: `A new version of PickleGlass (${releaseName}) has been downloaded. It will be installed the next time you launch the application.`,
buttons: ['Restart', 'Later']
}).then(response => {
if (response.response === 0) {
autoUpdater.quitAndInstall();
}
});
});
autoUpdater.on('error', (err) => {
console.error('Error in auto-updater:', err);
});
} catch (err) {
console.error('Error initializing auto-updater:', err);
}
}
================================================
FILE: src/preload.js
================================================
// src/preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('api', {
// Platform information for renderer processes
platform: {
isLinux: process.platform === 'linux',
isMacOS: process.platform === 'darwin',
isWindows: process.platform === 'win32',
platform: process.platform
},
// Common utilities used across multiple components
common: {
// User & Auth
getCurrentUser: () => ipcRenderer.invoke('get-current-user'),
startFirebaseAuth: () => ipcRenderer.invoke('start-firebase-auth'),
firebaseLogout: () => ipcRenderer.invoke('firebase-logout'),
// App Control
quitApplication: () => ipcRenderer.invoke('quit-application'),
openExternal: (url) => ipcRenderer.invoke('open-external', url),
// User state listener (used by multiple components)
onUserStateChanged: (callback) => ipcRenderer.on('user-state-changed', callback),
removeOnUserStateChanged: (callback) => ipcRenderer.removeListener('user-state-changed', callback),
},
// UI Component specific namespaces
// src/ui/app/ApiKeyHeader.js
apiKeyHeader: {
// Model & Provider Management
getProviderConfig: () => ipcRenderer.invoke('model:get-provider-config'),
// LocalAI 통합 API
getLocalAIStatus: (service) => ipcRenderer.invoke('localai:get-status', service),
installLocalAI: (service, options) => ipcRenderer.invoke('localai:install', { service, options }),
startLocalAIService: (service) => ipcRenderer.invoke('localai:start-service', service),
stopLocalAIService: (service) => ipcRenderer.invoke('localai:stop-service', service),
installLocalAIModel: (service, modelId, options) => ipcRenderer.invoke('localai:install-model', { service, modelId, options }),
getInstalledModels: (service) => ipcRenderer.invoke('localai:get-installed-models', service),
// Legacy support (호환성 위해 유지)
getOllamaStatus: () => ipcRenderer.invoke('localai:get-status', 'ollama'),
getModelSuggestions: () => ipcRenderer.invoke('ollama:get-model-suggestions'),
ensureOllamaReady: () => ipcRenderer.invoke('ollama:ensure-ready'),
installOllama: () => ipcRenderer.invoke('localai:install', { service: 'ollama' }),
startOllamaService: () => ipcRenderer.invoke('localai:start-service', 'ollama'),
pullOllamaModel: (modelName) => ipcRenderer.invoke('ollama:pull-model', modelName),
downloadWhisperModel: (modelId) => ipcRenderer.invoke('whisper:download-model', modelId),
validateKey: (data) => ipcRenderer.invoke('model:validate-key', data),
setSelectedModel: (data) => ipcRenderer.invoke('model:set-selected-model', data),
areProvidersConfigured: () => ipcRenderer.invoke('model:are-providers-configured'),
// Window Management
getHeaderPosition: () => ipcRenderer.invoke('get-header-position'),
moveHeaderTo: (x, y) => ipcRenderer.invoke('move-header-to', x, y),
// Listeners
// LocalAI 통합 이벤트 리스너
onLocalAIProgress: (callback) => ipcRenderer.on('localai:install-progress', callback),
removeOnLocalAIProgress: (callback) => ipcRenderer.removeListener('localai:install-progress', callback),
onLocalAIComplete: (callback) => ipcRenderer.on('localai:installation-complete', callback),
removeOnLocalAIComplete: (callback) => ipcRenderer.removeListener('localai:installation-complete', callback),
onLocalAIError: (callback) => ipcRenderer.on('localai:error-notification', callback),
removeOnLocalAIError: (callback) => ipcRenderer.removeListener('localai:error-notification', callback),
onLocalAIModelReady: (callback) => ipcRenderer.on('localai:model-ready', callback),
removeOnLocalAIModelReady: (callback) => ipcRenderer.removeListener('localai:model-ready', callback),
// Remove all listeners (for cleanup)
removeAllListeners: () => {
// LocalAI 통합 이벤트
ipcRenderer.removeAllListeners('localai:install-progress');
ipcRenderer.removeAllListeners('localai:installation-complete');
ipcRenderer.removeAllListeners('localai:error-notification');
ipcRenderer.removeAllListeners('localai:model-ready');
ipcRenderer.removeAllListeners('localai:service-status-changed');
}
},
// src/ui/app/HeaderController.js
headerController: {
// State Management
sendHeaderStateChanged: (state) => ipcRenderer.send('header-state-changed', state),
reInitializeModelState: () => ipcRenderer.invoke('model:re-initialize-state'),
// Window Management
resizeHeaderWindow: (dimensions) => ipcRenderer.invoke('resize-header-window', dimensions),
// Permissions
checkSystemPermissions: () => ipcRenderer.invoke('check-system-permissions'),
checkPermissionsCompleted: () => ipcRenderer.invoke('check-permissions-completed'),
// Listeners
onUserStateChanged: (callback) => ipcRenderer.on('user-state-changed', callback),
removeOnUserStateChanged: (callback) => ipcRenderer.removeListener('user-state-changed', callback),
onAuthFailed: (callback) => ipcRenderer.on('auth-failed', callback),
removeOnAuthFailed: (callback) => ipcRenderer.removeListener('auth-failed', callback),
onForceShowApiKeyHeader: (callback) => ipcRenderer.on('force-show-apikey-header', callback),
removeOnForceShowApiKeyHeader: (callback) => ipcRenderer.removeListener('force-show-apikey-header', callback),
},
// src/ui/app/MainHeader.js
mainHeader: {
// Window Management
getHeaderPosition: () => ipcRenderer.invoke('get-header-position'),
moveHeaderTo: (x, y) => ipcRenderer.invoke('move-header-to', x, y),
sendHeaderAnimationFinished: (state) => ipcRenderer.send('header-animation-finished', state),
// Settings Window Management
cancelHideSettingsWindow: () => ipcRenderer.send('cancel-hide-settings-window'),
showSettingsWindow: () => ipcRenderer.send('show-settings-window'),
hideSettingsWindow: () => ipcRenderer.send('hide-settings-window'),
// Generic invoke (for dynamic channel names)
// invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args),
sendListenButtonClick: (listenButtonText) => ipcRenderer.invoke('listen:changeSession', listenButtonText),
sendAskButtonClick: () => ipcRenderer.invoke('ask:toggleAskButton'),
sendToggleAllWindowsVisibility: () => ipcRenderer.invoke('shortcut:toggleAllWindowsVisibility'),
// Listeners
onListenChangeSessionResult: (callback) => ipcRenderer.on('listen:changeSessionResult', callback),
removeOnListenChangeSessionResult: (callback) => ipcRenderer.removeListener('listen:changeSessionResult', callback),
onShortcutsUpdated: (callback) => ipcRenderer.on('shortcuts-updated', callback),
removeOnShortcutsUpdated: (callback) => ipcRenderer.removeListener('shortcuts-updated', callback)
},
// src/ui/app/PermissionHeader.js
permissionHeader: {
// Permission Management
checkSystemPermissions: () => ipcRenderer.invoke('check-system-permissions'),
requestMicrophonePermission: () => ipcRenderer.invoke('request-microphone-permission'),
openSystemPreferences: (preference) => ipcRenderer.invoke('open-system-preferences', preference),
markKeychainCompleted: () => ipcRenderer.invoke('mark-keychain-completed'),
checkKeychainCompleted: (uid) => ipcRenderer.invoke('check-keychain-completed', uid),
initializeEncryptionKey: () => ipcRenderer.invoke('initialize-encryption-key') // New for keychain
},
// src/ui/app/PickleGlassApp.js
pickleGlassApp: {
// Listeners
onClickThroughToggled: (callback) => ipcRenderer.on('click-through-toggled', callback),
removeOnClickThroughToggled: (callback) => ipcRenderer.removeListener('click-through-toggled', callback),
removeAllClickThroughListeners: () => ipcRenderer.removeAllListeners('click-through-toggled')
},
// src/ui/ask/AskView.js
askView: {
// Window Management
closeAskWindow: () => ipcRenderer.invoke('ask:closeAskWindow'),
adjustWindowHeight: (winName, height) => ipcRenderer.invoke('adjust-window-height', { winName, height }),
// Message Handling
sendMessage: (text) => ipcRenderer.invoke('ask:sendQuestionFromAsk', text),
// Listeners
onAskStateUpdate: (callback) => ipcRenderer.on('ask:stateUpdate', callback),
removeOnAskStateUpdate: (callback) => ipcRenderer.removeListener('ask:stateUpdate', callback),
onAskStreamError: (callback) => ipcRenderer.on('ask-response-stream-error', callback),
removeOnAskStreamError: (callback) => ipcRenderer.removeListener('ask-response-stream-error', callback),
// Listeners
onShowTextInput: (callback) => ipcRenderer.on('ask:showTextInput', callback),
removeOnShowTextInput: (callback) => ipcRenderer.removeListener('ask:showTextInput', callback),
onScrollResponseUp: (callback) => ipcRenderer.on('aks:scrollResponseUp', callback),
removeOnScrollResponseUp: (callback) => ipcRenderer.removeListener('aks:scrollResponseUp', callback),
onScrollResponseDown: (callback) => ipcRenderer.on('aks:scrollResponseDown', callback),
removeOnScrollResponseDown: (callback) => ipcRenderer.removeListener('aks:scrollResponseDown', callback)
},
// src/ui/listen/ListenView.js
listenView: {
// Window Management
adjustWindowHeight: (winName, height) => ipcRenderer.invoke('adjust-window-height', { winName, height }),
// Listeners
onSessionStateChanged: (callback) => ipcRenderer.on('session-state-changed', callback),
removeOnSessionStateChanged: (callback) => ipcRenderer.removeListener('session-state-changed', callback)
},
// src/ui/listen/stt/SttView.js
sttView: {
// Listeners
onSttUpdate: (callback) => ipcRenderer.on('stt-update', callback),
removeOnSttUpdate: (callback) => ipcRenderer.removeListener('stt-update', callback)
},
// src/ui/listen/summary/SummaryView.js
summaryView: {
// Message Handling
sendQuestionFromSummary: (text) => ipcRenderer.invoke('ask:sendQuestionFromSummary', text),
// Listeners
onSummaryUpdate: (callback) => ipcRenderer.on('summary-update', callback),
removeOnSummaryUpdate: (callback) => ipcRenderer.removeListener('summary-update', callback),
removeAllSummaryUpdateListeners: () => ipcRenderer.removeAllListeners('summary-update')
},
// src/ui/settings/SettingsView.js
settingsView: {
// User & Auth
getCurrentUser: () => ipcRenderer.invoke('get-current-user'),
openPersonalizePage: () => ipcRenderer.invoke('open-personalize-page'),
firebaseLogout: () => ipcRenderer.invoke('firebase-logout'),
startFirebaseAuth: () => ipcRenderer.invoke('start-firebase-auth'),
// Model & Provider Management
getModelSettings: () => ipcRenderer.invoke('settings:get-model-settings'), // Facade call
getProviderConfig: () => ipcRenderer.invoke('model:get-provider-config'),
getAllKeys: () => ipcRenderer.invoke('model:get-all-keys'),
getAvailableModels: (type) => ipcRenderer.invoke('model:get-available-models', type),
getSelectedModels: () => ipcRenderer.invoke('model:get-selected-models'),
validateKey: (data) => ipcRenderer.invoke('model:validate-key', data),
saveApiKey: (key) => ipcRenderer.invoke('model:save-api-key', key),
removeApiKey: (provider) => ipcRenderer.invoke('model:remove-api-key', provider),
setSelectedModel: (data) => ipcRenderer.invoke('model:set-selected-model', data),
// Ollama Management
getOllamaStatus: () => ipcRenderer.invoke('ollama:get-status'),
ensureOllamaReady: () => ipcRenderer.invoke('ollama:ensure-ready'),
shutdownOllama: (graceful) => ipcRenderer.invoke('ollama:shutdown', graceful),
// Whisper Management
getWhisperInstalledModels: () => ipcRenderer.invoke('whisper:get-installed-models'),
downloadWhisperModel: (modelId) => ipcRenderer.invoke('whisper:download-model', modelId),
// Settings Management
getPresets: () => ipcRenderer.invoke('settings:getPresets'),
getAutoUpdate: () => ipcRenderer.invoke('settings:get-auto-update'),
setAutoUpdate: (isEnabled) => ipcRenderer.invoke('settings:set-auto-update', isEnabled),
getContentProtectionStatus: () => ipcRenderer.invoke('get-content-protection-status'),
toggleContentProtection: () => ipcRenderer.invoke('toggle-content-protection'),
getCurrentShortcuts: () => ipcRenderer.invoke('settings:getCurrentShortcuts'),
openShortcutSettingsWindow: () => ipcRenderer.invoke('shortcut:openShortcutSettingsWindow'),
// Window Management
moveWindowStep: (direction) => ipcRenderer.invoke('move-window-step', direction),
cancelHideSettingsWindow: () => ipcRenderer.send('cancel-hide-settings-window'),
hideSettingsWindow: () => ipcRenderer.send('hide-settings-window'),
// App Control
quitApplication: () => ipcRenderer.invoke('quit-application'),
// Progress Tracking
pullOllamaModel: (modelName) => ipcRenderer.invoke('ollama:pull-model', modelName),
// Listeners
onUserStateChanged: (callback) => ipcRenderer.on('user-state-changed', callback),
removeOnUserStateChanged: (callback) => ipcRenderer.removeListener('user-state-changed', callback),
onSettingsUpdated: (callback) => ipcRenderer.on('settings-updated', callback),
removeOnSettingsUpdated: (callback) => ipcRenderer.removeListener('settings-updated', callback),
onPresetsUpdated: (callback) => ipcRenderer.on('presets-updated', callback),
removeOnPresetsUpdated: (callback) => ipcRenderer.removeListener('presets-updated', callback),
onShortcutsUpdated: (callback) => ipcRenderer.on('shortcuts-updated', callback),
removeOnShortcutsUpdated: (callback) => ipcRenderer.removeListener('shortcuts-updated', callback),
// 통합 LocalAI 이벤트 사용
onLocalAIInstallProgress: (callback) => ipcRenderer.on('localai:install-progress', callback),
removeOnLocalAIInstallProgress: (callback) => ipcRenderer.removeListener('localai:install-progress', callback),
onLocalAIInstallationComplete: (callback) => ipcRenderer.on('localai:installation-complete', callback),
removeOnLocalAIInstallationComplete: (callback) => ipcRenderer.removeListener('localai:installation-complete', callback)
},
// src/ui/settings/ShortCutSettingsView.js
shortcutSettingsView: {
// Shortcut Management
saveShortcuts: (shortcuts) => ipcRenderer.invoke('shortcut:saveShortcuts', shortcuts),
getDefaultShortcuts: () => ipcRenderer.invoke('shortcut:getDefaultShortcuts'),
closeShortcutSettingsWindow: () => ipcRenderer.invoke('shortcut:closeShortcutSettingsWindow'),
// Listeners
onLoadShortcuts: (callback) => ipcRenderer.on('shortcut:loadShortcuts', callback),
removeOnLoadShortcuts: (callback) => ipcRenderer.removeListener('shortcut:loadShortcuts', callback)
},
// src/ui/app/content.html inline scripts
content: {
// Listeners
onSettingsWindowHideAnimation: (callback) => ipcRenderer.on('settings-window-hide-animation', callback),
removeOnSettingsWindowHideAnimation: (callback) => ipcRenderer.removeListener('settings-window-hide-animation', callback),
},
// src/ui/listen/audioCore/listenCapture.js
listenCapture: {
// Audio Management
sendMicAudioContent: (data) => ipcRenderer.invoke('listen:sendMicAudio', data),
sendSystemAudioContent: (data) => ipcRenderer.invoke('listen:sendSystemAudio', data),
startMacosSystemAudio: () => ipcRenderer.invoke('listen:startMacosSystemAudio'),
stopMacosSystemAudio: () => ipcRenderer.invoke('listen:stopMacosSystemAudio'),
// Session Management
isSessionActive: () => ipcRenderer.invoke('listen:isSessionActive'),
// Listeners
onSystemAudioData: (callback) => ipcRenderer.on('system-audio-data', callback),
removeOnSystemAudioData: (callback) => ipcRenderer.removeListener('system-audio-data', callback)
},
// src/ui/listen/audioCore/renderer.js
renderer: {
// Listeners
onChangeListenCaptureState: (callback) => ipcRenderer.on('change-listen-capture-state', callback),
removeOnChangeListenCaptureState: (callback) => ipcRenderer.removeListener('change-listen-capture-state', callback)
}
});
================================================
FILE: src/ui/app/ApiKeyHeader.js
================================================
import { html, css, LitElement } from '../assets/lit-core-2.7.4.min.js';
export class ApiKeyHeader extends LitElement {
//////// after_modelStateService ////////
static properties = {
llmApiKey: { type: String },
sttApiKey: { type: String },
llmProvider: { type: String },
sttProvider: { type: String },
isLoading: { type: Boolean },
errorMessage: { type: String },
successMessage: { type: String },
providers: { type: Object, state: true },
modelSuggestions: { type: Array, state: true },
userModelHistory: { type: Array, state: true },
selectedLlmModel: { type: String, state: true },
selectedSttModel: { type: String, state: true },
ollamaStatus: { type: Object, state: true },
installingModel: { type: String, state: true },
installProgress: { type: Number, state: true },
whisperInstallingModels: { type: Object, state: true },
backCallback: { type: Function },
llmError: { type: String },
sttError: { type: String },
};
//////// after_modelStateService ////////
static styles = css`
:host {
display: block;
font-family:
'Inter',
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
sans-serif;
}
* {
box-sizing: border-box;
}
.container {
width: 100%;
height: 100%;
padding: 24px 16px;
background: rgba(0, 0, 0, 0.64);
box-shadow: 0px 0px 0px 1.5px rgba(255, 255, 255, 0.64) inset;
border-radius: 16px;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
gap: 24px;
display: flex;
-webkit-app-region: drag;
}
.header {
width: 100%;
position: relative;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 8px;
}
.close-button {
-webkit-app-region: no-drag;
position: absolute;
top: 16px;
right: 16px;
width: 20px;
height: 20px;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 5px;
color: rgba(255, 255, 255, 0.7);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s ease;
z-index: 10;
font-size: 16px;
line-height: 1;
padding: 0;
}
.close-button:hover {
background: rgba(255, 255, 255, 0.2);
color: rgba(255, 255, 255, 0.9);
}
.back-button {
-webkit-app-region: no-drag;
padding: 8px;
left: 0px;
top: -7px;
position: absolute;
background: rgba(132.6, 132.6, 132.6, 0.8);
border-radius: 16px;
border: 0.5px solid rgba(255, 255, 255, 0.5);
justify-content: center;
align-items: center;
gap: 4px;
display: flex;
cursor: pointer;
transition: background-color 0.2s ease;
}
.back-button:hover {
background: rgba(150, 150, 150, 0.9);
}
.arrow-icon-left {
border: solid #dcdcdc;
border-width: 0 1.2px 1.2px 0;
display: inline-block;
padding: 3px;
transform: rotate(135deg);
}
.back-button-text {
color: white;
font-size: 12px;
font-weight: 500;
padding-right: 4px;
}
.title {
color: white;
font-size: 14px;
font-weight: 700;
}
.section {
width: 100%;
display: flex;
flex-direction: column;
gap: 10px;
}
.row {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
}
.label {
color: white;
font-size: 12px;
font-weight: 600;
}
.provider-selector {
display: flex;
width: 240px;
overflow: hidden;
border-radius: 12px;
border: 0.5px solid rgba(255, 255, 255, 0.5);
}
.provider-button {
-webkit-app-region: no-drag;
padding: 4px 8px;
background: rgba(20.4, 20.4, 20.4, 0.32);
color: #dcdcdc;
font-size: 11px;
font-weight: 450;
letter-spacing: 0.11px;
border: none;
cursor: pointer;
transition: background-color 0.2s ease;
flex: 1;
}
.provider-button:hover {
background: rgba(80, 80, 80, 0.48);
}
.provider-button[data-status='active'] {
background: rgba(142.8, 142.8, 142.8, 0.48);
color: white;
}
.api-input {
-webkit-app-region: no-drag;
width: 240px;
padding: 10px 8px;
background: rgba(61.2, 61.2, 61.2, 0.8);
border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.24);
color: white;
font-size: 11px;
text-overflow: ellipsis;
font-family: inherit;
line-height: inherit;
}
.ollama-action-button {
-webkit-app-region: no-drag;
width: 240px;
padding: 10px 8px;
border-radius: 16px;
border: none;
color: white;
font-size: 12px;
font-weight: 500;
font-family: inherit;
cursor: pointer;
text-align: center;
transition: background-color 0.2s ease;
}
.ollama-action-button.install {
background: rgba(0, 122, 255, 0.2);
}
.ollama-action-button.start {
background: rgba(255, 200, 0, 0.2);
}
select.api-input {
-webkit-appearance: none;
appearance: none;
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
padding-right: 2.5rem;
}
select.api-input option {
background: #333;
color: white;
}
.api-input::placeholder {
color: #a0a0a0;
}
.confirm-button-container {
width: 100%;
display: flex;
justify-content: flex-end;
}
.confirm-button {
-webkit-app-region: no-drag;
width: 240px;
padding: 8px;
background: rgba(132.6, 132.6, 132.6, 0.8);
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.16);
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.5);
color: white;
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.2s ease;
}
.confirm-button:hover {
background: rgba(150, 150, 150, 0.9);
}
.confirm-button:disabled {
background: rgba(255, 255, 255, 0.12);
color: #bebebe;
border: 0.5px solid rgba(255, 255, 255, 0.24);
box-shadow: none;
cursor: not-allowed;
}
.footer {
width: 100%;
text-align: center;
color: #dcdcdc;
font-size: 12px;
font-weight: 500;
line-height: 18px;
}
.footer-link {
text-decoration: underline;
cursor: pointer;
-webkit-app-region: no-drag;
}
.error-message,
.success-message {
position: absolute;
bottom: 70px;
left: 16px;
right: 16px;
text-align: center;
font-size: 11px;
font-weight: 500;
padding: 4px;
border-radius: 4px;
}
.error-message {
color: rgba(239, 68, 68, 0.9);
}
.success-message {
color: rgba(74, 222, 128, 0.9);
}
.message-fade-out {
animation: fadeOut 3s ease-in-out forwards;
}
@keyframes fadeOut {
0% {
opacity: 1;
}
66% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.sliding-out {
animation: slideOut 0.3s ease-out forwards;
}
@keyframes slideOut {
from {
transform: translateY(0);
opacity: 1;
}
to {
transform: translateY(-100%);
opacity: 0;
}
}
.api-input.invalid {
outline: 1px solid #ff7070;
outline-offset: -1px;
}
.input-wrapper {
display: flex;
flex-direction: column;
gap: 4px;
align-items: flex-start;
}
.inline-error-message {
color: #ff7070;
font-size: 11px;
font-weight: 400;
letter-spacing: 0.11px;
word-wrap: break-word;
width: 240px;
}
`;
constructor() {
super();
this.isLoading = false;
this.errorMessage = '';
this.successMessage = '';
this.messageTimestamp = 0;
//////// after_modelStateService ////////
this.llmApiKey = '';
this.sttApiKey = '';
this.llmProvider = 'openai';
this.sttProvider = 'openai';
this.providers = { llm: [], stt: [] }; // 초기화
// Ollama related
this.modelSuggestions = [];
this.userModelHistory = [];
this.selectedLlmModel = '';
this.selectedSttModel = '';
this.ollamaStatus = { installed: false, running: false };
this.installingModel = null;
this.installProgress = 0;
this.whisperInstallingModels = {};
this.backCallback = () => {};
this.llmError = '';
this.sttError = '';
// Professional operation management system
this.activeOperations = new Map();
this.operationTimeouts = new Map();
this.connectionState = 'idle'; // idle, connecting, connected, failed, disconnected
this.lastStateChange = Date.now();
this.retryCount = 0;
this.maxRetries = 3;
this.baseRetryDelay = 1000;
// Backpressure and resource management
this.operationQueue = [];
this.maxConcurrentOperations = 2;
this.maxQueueSize = 5;
this.operationMetrics = {
totalOperations: 0,
successfulOperations: 0,
failedOperations: 0,
timeouts: 0,
averageResponseTime: 0,
};
// Configuration
this.ipcTimeout = 10000; // 10s for IPC calls
this.operationTimeout = 15000; // 15s for complex operations
// Health monitoring system
this.healthCheck = {
enabled: false,
intervalId: null,
intervalMs: 30000, // 30s
lastCheck: 0,
consecutiveFailures: 0,
maxFailures: 3,
};
// Load user model history from localStorage
this.loadUserModelHistory();
this.loadProviderConfig();
//////// after_modelStateService ////////
this.handleKeyPress = this.handleKeyPress.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInput = this.handleInput.bind(this);
this.handleAnimationEnd = this.handleAnimationEnd.bind(this);
this.handleProviderChange = this.handleProviderChange.bind(this);
this.handleLlmProviderChange = this.handleLlmProviderChange.bind(this);
this.handleSttProviderChange = this.handleSttProviderChange.bind(this);
this.handleMessageFadeEnd = this.handleMessageFadeEnd.bind(this);
this.handleModelKeyPress = this.handleModelKeyPress.bind(this);
this.handleSttModelChange = this.handleSttModelChange.bind(this);
this.handleBack = this.handleBack.bind(this);
this.handleClose = this.handleClose.bind(this);
}
updated(changedProperties) {
super.updated(changedProperties);
this.dispatchEvent(new CustomEvent('content-changed', { bubbles: true, composed: true }));
}
reset() {
this.apiKey = '';
this.isLoading = false;
this.errorMessage = '';
this.validatedApiKey = null;
this.selectedProvider = 'openai';
this.requestUpdate();
}
handleBack() {
if (this.backCallback) {
this.backCallback();
}
}
async loadProviderConfig() {
if (!window.api?.apiKeyHeader) return;
try {
const [config, ollamaStatus] = await Promise.all([
window.api.apiKeyHeader.getProviderConfig(),
window.api.apiKeyHeader.getOllamaStatus(),
]);
const llmProviders = [];
const sttProviders = [];
for (const id in config) {
// 'openai-glass' 같은 가상 Provider는 UI에 표시하지 않음
if (id.includes('-glass')) continue;
const hasLlmModels = config[id].llmModels.length > 0 || id === 'ollama';
const hasSttModels = config[id].sttModels.length > 0 || id === 'whisper';
if (hasLlmModels) {
llmProviders.push({ id, name: config[id].name });
}
if (hasSttModels) {
sttProviders.push({ id, name: config[id].name });
}
}
this.providers = { llm: llmProviders, stt: sttProviders };
// 기본 선택 값 설정
if (llmProviders.length > 0) this.llmProvider = llmProviders[0].id;
if (sttProviders.length > 0) this.sttProvider = sttProviders[0].id;
// Ollama 상태 및 모델 제안 로드
if (ollamaStatus?.success) {
this.ollamaStatus = {
installed: ollamaStatus.installed,
running: ollamaStatus.running,
};
// Load model suggestions if Ollama is running
if (ollamaStatus.running) {
await this.loadModelSuggestions();
}
}
this.requestUpdate();
} catch (error) {
console.error('[ApiKeyHeader] Failed to load provider config:', error);
}
}
async handleMouseDown(e) {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.tagName === 'SELECT') {
return;
}
e.preventDefault();
if (!window.api?.apiKeyHeader) return;
const initialPosition = await window.api.apiKeyHeader.getHeaderPosition();
this.dragState = {
initialMouseX: e.screenX,
initialMouseY: e.screenY,
initialWindowX: initialPosition.x,
initialWindowY: initialPosition.y,
moved: false,
};
window.addEventListener('mousemove', this.handleMouseMove);
window.addEventListener('mouseup', this.handleMouseUp, { once: true });
}
handleMouseMove(e) {
if (!this.dragState) return;
const deltaX = Math.abs(e.screenX - this.dragState.initialMouseX);
const deltaY = Math.abs(e.screenY - this.dragState.initialMouseY);
if (deltaX > 3 || deltaY > 3) {
this.dragState.moved = true;
}
const newWindowX = this.dragState.initialWindowX + (e.screenX - this.dragState.initialMouseX);
const newWindowY = this.dragState.initialWindowY + (e.screenY - this.dragState.initialMouseY);
if (window.api?.apiKeyHeader) {
window.api.apiKeyHeader.moveHeaderTo(newWindowX, newWindowY);
}
}
handleMouseUp(e) {
if (!this.dragState) return;
const wasDragged = this.dragState.moved;
window.removeEventListener('mousemove', this.handleMouseMove);
this.dragState = null;
if (wasDragged) {
this.wasJustDragged = true;
setTimeout(() => {
this.wasJustDragged = false;
}, 200);
}
}
handleInput(e) {
this.apiKey = e.target.value;
this.clearMessages();
console.log('Input changed:', this.apiKey?.length || 0, 'chars');
this.requestUpdate();
this.updateComplete.then(() => {
const inputField = this.shadowRoot?.querySelector('.apikey-input');
if (inputField && this.isInputFocused) {
inputField.focus();
}
});
}
clearMessages() {
this.errorMessage = '';
this.successMessage = '';
this.messageTimestamp = 0;
this.llmError = '';
this.sttError = '';
}
handleProviderChange(e) {
this.selectedProvider = e.target.value;
this.clearMessages();
console.log('Provider changed to:', this.selectedProvider);
this.requestUpdate();
}
async handleLlmProviderChange(e, providerId) {
const newProvider = providerId || e.target.value;
if (newProvider === this.llmProvider) return;
// Cancel any active operations first
this._cancelAllActiveOperations();
this.llmProvider = newProvider;
this.errorMessage = '';
this.successMessage = '';
if (['openai', 'gemini'].includes(this.llmProvider)) {
this.sttProvider = this.llmProvider;
}
// Reset retry state
this.retryCount = 0;
if (this.llmProvider === 'ollama') {
console.log('[ApiKeyHeader] Ollama selected, initiating connection...');
await this._initializeOllamaConnection();
// Start health monitoring for Ollama
this._startHealthMonitoring();
} else {
this._updateConnectionState('idle', 'Non-Ollama provider selected');
// Stop health monitoring for non-Ollama providers
this._stopHealthMonitoring();
}
this.requestUpdate();
}
async _initializeOllamaConnection() {
try {
// Progressive connection attempt with exponential backoff
await this._attemptOllamaConnection();
} catch (error) {
console.error('[ApiKeyHeader] Initial Ollama connection failed:', error.message);
if (this.retryCount < this.maxRetries) {
const delay = this.baseRetryDelay * Math.pow(2, this.retryCount);
console.log(`[ApiKeyHeader] Retrying Ollama connection in ${delay}ms (attempt ${this.retryCount + 1}/${this.maxRetries})`);
this.retryCount++;
// Use proper Promise-based delay instead of setTimeout
await new Promise(resolve => {
const retryTimeoutId = setTimeout(() => {
this._initializeOllamaConnection();
resolve();
}, delay);
// Store timeout for cleanup
this.operationTimeouts.set(`retry_${this.retryCount}`, retryTimeoutId);
});
} else {
this._updateConnectionState('failed', `Connection failed after ${this.maxRetries} attempts`);
}
}
}
async _attemptOllamaConnection() {
await this.refreshOllamaStatus();
}
_cancelAllActiveOperations() {
console.log(`[ApiKeyHeader] Cancelling ${this.activeOperations.size} active operations and ${this.operationQueue.length} queued operations`);
// Cancel active operations
for (const [operationType, operation] of this.activeOperations) {
this._cancelOperation(operationType);
}
// Cancel queued operations
for (const queuedOp of this.operationQueue) {
queuedOp.reject(new Error(`Operation ${queuedOp.type} cancelled during cleanup`));
}
this.operationQueue.length = 0;
// Clean up all timeouts
for (const [timeoutId, timeout] of this.operationTimeouts) {
clearTimeout(timeout);
}
this.operationTimeouts.clear();
}
/**
* Get operation metrics for monitoring
*/
getOperationMetrics() {
return {
...this.operationMetrics,
activeOperations: this.activeOperations.size,
queuedOperations: this.operationQueue.length,
successRate:
this.operationMetrics.totalOperations > 0
? (this.operationMetrics.successfulOperations / this.operationMetrics.totalOperations) * 100
: 0,
};
}
/**
* Adaptive backpressure based on system performance
*/
_adjustBackpressureThresholds() {
const metrics = this.getOperationMetrics();
// Reduce concurrent operations if success rate is low
if (metrics.successRate < 70 && this.maxConcurrentOperations > 1) {
this.maxConcurrentOperations = Math.max(1, this.maxConcurrentOperations - 1);
console.log(
`[ApiKeyHeader] Reduced max concurrent operations to ${this.maxConcurrentOperations} (success rate: ${metrics.successRate.toFixed(1)}%)`
);
}
// Increase if performance is good
if (metrics.successRate > 90 && metrics.averageResponseTime < 3000 && this.maxConcurrentOperations < 3) {
this.maxConcurrentOperations++;
console.log(`[ApiKeyHeader] Increased max concurrent operations to ${this.maxConcurrentOperations}`);
}
}
/**
* Professional health monitoring system
*/
_startHealthMonitoring() {
if (this.healthCheck.enabled) return;
this.healthCheck.enabled = true;
this.healthCheck.intervalId = setInterval(() => {
this._performHealthCheck();
}, this.healthCheck.intervalMs);
console.log(`[ApiKeyHeader] Health monitoring started (interval: ${this.healthCheck.intervalMs}ms)`);
}
_stopHealthMonitoring() {
if (!this.healthCheck.enabled) return;
this.healthCheck.enabled = false;
if (this.healthCheck.intervalId) {
clearInterval(this.healthCheck.intervalId);
this.healthCheck.intervalId = null;
}
console.log('[ApiKeyHeader] Health monitoring stopped');
}
async _performHealthCheck() {
// Only perform health check if Ollama is selected and we're in a stable state
if (this.llmProvider !== 'ollama' || this.connectionState === 'connecting') {
return;
}
const now = Date.now();
this.healthCheck.lastCheck = now;
try {
// Lightweight health check - just ping the service
const isHealthy = await this._executeOperation(
'health_check',
async () => {
if (!window.api?.apiKeyHeader) return false;
const result = await window.api.apiKeyHeader.getOllamaStatus();
return result?.success && result?.running;
},
{ timeout: 5000, priority: 'low' }
);
if (isHealthy) {
this.healthCheck.consecutiveFailures = 0;
// Update state if we were previously failed
if (this.connectionState === 'failed') {
this._updateConnectionState('connected', 'Health check recovered');
}
} else {
this._handleHealthCheckFailure();
}
// Adjust thresholds based on performance
this._adjustBackpressureThresholds();
} catch (error) {
console.warn('[ApiKeyHeader] Health check failed:', error.message);
this._handleHealthCheckFailure();
}
}
_handleHealthCheckFailure() {
this.healthCheck.consecutiveFailures++;
if (this.healthCheck.consecutiveFailures >= this.healthCheck.maxFailures) {
console.warn(`[ApiKeyHeader] Health check failed ${this.healthCheck.consecutiveFailures} times, marking as disconnected`);
this._updateConnectionState('failed', 'Service health check failed');
// Increase health check frequency when having issues
this.healthCheck.intervalMs = Math.max(10000, this.healthCheck.intervalMs / 2);
this._restartHealthMonitoring();
}
}
_restartHealthMonitoring() {
this._stopHealthMonitoring();
this._startHealthMonitoring();
}
/**
* Get comprehensive health status
*/
getHealthStatus() {
return {
connection: {
state: this.connectionState,
lastStateChange: this.lastStateChange,
timeSinceLastChange: Date.now() - this.lastStateChange,
},
operations: this.getOperationMetrics(),
health: {
enabled: this.healthCheck.enabled,
lastCheck: this.healthCheck.lastCheck,
timeSinceLastCheck: this.healthCheck.lastCheck > 0 ? Date.now() - this.healthCheck.lastCheck : null,
consecutiveFailures: this.healthCheck.consecutiveFailures,
intervalMs: this.healthCheck.intervalMs,
},
ollama: {
provider: this.llmProvider,
status: this.ollamaStatus,
selectedModel: this.selectedLlmModel,
},
};
}
async handleSttProviderChange(e, providerId) {
const newProvider = providerId || e.target.value;
if (newProvider === this.sttProvider) return;
this.sttProvider = newProvider;
this.errorMessage = '';
this.successMessage = '';
if (this.sttProvider === 'ollama') {
console.warn('[ApiKeyHeader] Ollama does not support STT yet. Please select Whisper or another provider.');
this.sttError = '*Ollama does not support STT yet. Please select Whisper or another STT provider.';
this.messageTimestamp = Date.now();
// Auto-select Whisper if available
const whisperProvider = this.providers.stt.find(p => p.id === 'whisper');
if (whisperProvider) {
this.sttProvider = 'whisper';
console.log('[ApiKeyHeader] Auto-selected Whisper for STT');
}
}
this.requestUpdate();
}
/**
* Professional operation management with backpressure control
*/
async _executeOperation(operationType, operation, options = {}) {
const operationId = `${operationType}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const timeout = options.timeout || this.ipcTimeout;
const priority = options.priority || 'normal'; // high, normal, low
// Backpressure control
if (this.activeOperations.size >= this.maxConcurrentOperations) {
if (this.operationQueue.length >= this.maxQueueSize) {
throw new Error(`Operation queue full (${this.maxQueueSize}), rejecting ${operationType}`);
}
console.log(`[ApiKeyHeader] Queuing operation ${operationType} (${this.activeOperations.size} active)`);
return this._queueOperation(operationId, operationType, operation, options);
}
return this._executeImmediately(operationId, operationType, operation, timeout);
}
async _queueOperation(operationId, operationType, operation, options) {
return new Promise((resolve, reject) => {
const queuedOperation = {
id: operationId,
type: operationType,
operation,
options,
resolve,
reject,
queuedAt: Date.now(),
priority: options.priority || 'normal',
};
// Insert based on priority (high priority first)
if (options.priority === 'high') {
this.operationQueue.unshift(queuedOperation);
} else {
this.operationQueue.push(queuedOperation);
}
console.log(`[ApiKeyHeader] Queued ${operationType} (queue size: ${this.operationQueue.length})`);
});
}
async _executeImmediately(operationId, operationType, operation, timeout) {
const startTime = Date.now();
this.operationMetrics.totalOperations++;
// Check if similar operation is already running
if (this.activeOperations.has(operationType)) {
console.log(`[ApiKeyHeader] Operation ${operationType} already in progress, cancelling previous`);
this._cancelOperation(operationType);
}
// Create cancellation mechanism
const cancellationPromise = new Promise((_, reject) => {
const timeoutId = setTimeout(() => {
this.operationMetrics.timeouts++;
reject(new Error(`Operation ${operationType} timeout after ${timeout}ms`));
}, timeout);
this.operationTimeouts.set(operationId, timeoutId);
});
const operationPromise = Promise.race([operation(), cancellationPromise]);
this.activeOperations.set(operationType, {
id: operationId,
promise: operationPromise,
startTime,
});
try {
const result = await operationPromise;
this._recordOperationSuccess(startTime);
return result;
} catch (error) {
this._recordOperationFailure(error, operationType);
throw error;
} finally {
this._cleanupOperation(operationId, operationType);
this._processQueue();
}
}
_recordOperationSuccess(startTime) {
this.operationMetrics.successfulOperations++;
const responseTime = Date.now() - startTime;
this._updateAverageResponseTime(responseTime);
}
_recordOperationFailure(error, operationType) {
this.operationMetrics.failedOperations++;
if (error.message.includes('timeout')) {
console.error(`[ApiKeyHeader] Operation ${operationType} timed out`);
this._updateConnectionState('failed', `Timeout: ${error.message}`);
}
}
_updateAverageResponseTime(responseTime) {
const totalOps = this.operationMetrics.successfulOperations;
this.operationMetrics.averageResponseTime = (this.operationMetrics.averageResponseTime * (totalOps - 1) + responseTime) / totalOps;
}
async _processQueue() {
if (this.operationQueue.length === 0 || this.activeOperations.size >= this.maxConcurrentOperations) {
return;
}
const queuedOp = this.operationQueue.shift();
if (!queuedOp) return;
const queueTime = Date.now() - queuedOp.queuedAt;
console.log(`[ApiKeyHeader] Processing queued operation ${queuedOp.type} (waited ${queueTime}ms)`);
try {
const result = await this._executeImmediately(
queuedOp.id,
queuedOp.type,
queuedOp.operation,
queuedOp.options.timeout || this.ipcTimeout
);
queuedOp.resolve(result);
} catch (error) {
queuedOp.reject(error);
}
}
_cancelOperation(operationType) {
const operation = this.activeOperations.get(operationType);
if (operation) {
this._cleanupOperation(operation.id, operationType);
console.log(`[ApiKeyHeader] Cancelled operation: ${operationType}`);
}
}
_cleanupOperation(operationId, operationType) {
if (this.operationTimeouts.has(operationId)) {
clearTimeout(this.operationTimeouts.get(operationId));
this.operationTimeouts.delete(operationId);
}
this.activeOperations.delete(operationType);
}
_updateConnectionState(newState, reason = '') {
if (this.connectionState !== newState) {
console.log(`[ApiKeyHeader] Connection state: ${this.connectionState} -> ${newState} (${reason})`);
this.connectionState = newState;
this.lastStateChange = Date.now();
// Update UI based on state
this._handleStateChange(newState, reason);
}
}
_handleStateChange(state, reason) {
switch (state) {
case 'connecting':
this.installingModel = 'Connecting to Ollama...';
this.installProgress = 10;
break;
case 'failed':
this.errorMessage = reason || 'Connection failed';
this.installingModel = null;
this.installProgress = 0;
this.messageTimestamp = Date.now();
break;
case 'connected':
this.installingModel = null;
this.installProgress = 0;
break;
case 'disconnected':
this.ollamaStatus = { installed: false, running: false };
break;
}
this.requestUpdate();
}
async refreshOllamaStatus() {
if (!window.api?.apiKeyHeader) return;
try {
this._updateConnectionState('connecting', 'Checking Ollama status');
const result = await this._executeOperation('ollama_status', async () => {
return await window.api.apiKeyHeader.getOllamaStatus();
});
if (result?.success) {
this.ollamaStatus = {
installed: result.installed,
running: result.running,
};
this._updateConnectionState('connected', 'Status updated successfully');
// Load model suggestions if Ollama is running
if (result.running) {
await this.loadModelSuggestions();
}
} else {
this._updateConnectionState('failed', result?.error || 'Status check failed');
}
} catch (error) {
console.error('[ApiKeyHeader] Failed to refresh Ollama status:', error.message);
this._updateConnectionState('failed', error.message);
}
}
async loadModelSuggestions() {
if (!window.api?.apiKeyHeader) return;
try {
const result = await this._executeOperation('model_suggestions', async () => {
return await window.api.apiKeyHeader.getModelSuggestions();
});
if (result?.success) {
this.modelSuggestions = result.suggestions || [];
// 기본 모델 선택 (설치된 모델 중 첫 번째)
if (!this.selectedLlmModel && this.modelSuggestions.length > 0) {
const installedModel = this.modelSuggestions.find(m => m.status === 'installed');
if (installedModel) {
this.selectedLlmModel = installedModel.name;
}
}
this.requestUpdate();
} else {
console.warn('[ApiKeyHeader] Model suggestions request unsuccessful:', result?.error);
}
} catch (error) {
console.error('[ApiKeyHeader] Failed to load model suggestions:', error.message);
}
}
async ensureOllamaReady() {
if (!window.api?.apiKeyHeader) return false;
try {
this._updateConnectionState('connecting', 'Ensuring Ollama is ready');
const result = await this._executeOperation(
'ollama_ensure_ready',
async () => {
return await window.api.apiKeyHeader.ensureOllamaReady();
},
{ timeout: this.operationTimeout }
);
if (result?.success) {
await this.refreshOllamaStatus();
this._updateConnectionState('connected', 'Ollama ready');
return true;
} else {
const errorMsg = `Failed to setup Ollama: ${result?.error || 'Unknown error'}`;
this._updateConnectionState('failed', errorMsg);
return false;
}
} catch (error) {
console.error('[ApiKeyHeader] Failed to ensure Ollama ready:', error.message);
this._updateConnectionState('failed', `Error setting up Ollama: ${error.message}`);
return false;
}
}
async ensureOllamaReadyWithUI() {
if (!window.api?.apiKeyHeader) return false;
this.installingModel = 'Setting up Ollama';
this.installProgress = 0;
this.clearMessages();
this.requestUpdate();
const progressHandler = (event, data) => {
// 통합 LocalAI 이벤트에서 Ollama 진행률만 처리
if (data.service !== 'ollama') return;
let baseProgress = 0;
let stageTotal = 0;
switch (data.stage) {
case 'downloading':
baseProgress = 0;
stageTotal = 70;
break;
case 'mounting':
baseProgress = 70;
stageTotal = 10;
break;
case 'installing':
baseProgress = 80;
stageTotal = 10;
break;
case 'linking':
baseProgress = 90;
stageTotal = 5;
break;
case 'cleanup':
baseProgress = 95;
stageTotal = 3;
break;
case 'starting':
baseProgress = 98;
stageTotal = 2;
break;
}
const overallProgress = baseProgress + (data.progress / 100) * stageTotal;
this.installingModel = data.message;
this.installProgress = Math.round(overallProgress);
this.requestUpdate();
};
let operationCompleted = false;
const completionTimeout = setTimeout(async () => {
if (!operationCompleted) {
console.log('[ApiKeyHeader] Operation timeout, checking status manually...');
await this._handleOllamaSetupCompletion(true);
}
}, 15000); // 15 second timeout
const completionHandler = async (event, data) => {
// 통합 LocalAI 이벤트에서 Ollama 완료만 처리
if (data.service !== 'ollama') return;
if (operationCompleted) return;
operationCompleted = true;
clearTimeout(completionTimeout);
window.api.apiKeyHeader.removeOnLocalAIProgress(progressHandler);
// installation-complete 이벤트는 성공을 의미
await this._handleOllamaSetupCompletion(true);
};
// 통합 LocalAI 이벤트 사용
window.api.apiKeyHeader.onLocalAIComplete(completionHandler);
window.api.apiKeyHeader.onLocalAIProgress(progressHandler);
try {
let result;
if (!this.ollamaStatus.installed) {
console.log('[ApiKeyHeader] Ollama not installed. Starting installation.');
result = await window.api.apiKeyHeader.installOllama();
} else {
console.log('[ApiKeyHeader] Ollama installed. Starting service.');
result = await window.api.apiKeyHeader.startOllamaService();
}
// If IPC call succeeds but no event received, handle completion manually
if (result?.success && !operationCompleted) {
setTimeout(async () => {
if (!operationCompleted) {
operationCompleted = true;
clearTimeout(completionTimeout);
await this._handleOllamaSetupCompletion(true);
}
}, 2000);
}
} catch (error) {
operationCompleted = true;
clearTimeout(completionTimeout);
console.error('[ApiKeyHeader] Ollama setup failed:', error);
window.api.apiKeyHeader.removeOnLocalAIProgress(progressHandler);
window.api.apiKeyHeader.removeOnLocalAIComplete(completionHandler);
await this._handleOllamaSetupCompletion(false, error.message);
}
}
async _handleOllamaSetupCompletion(success, errorMessage = null) {
this.installingModel = null;
this.installProgress = 0;
if (success) {
await this.refreshOllamaStatus();
this.successMessage = '✓ Ollama is ready!';
} else {
this.llmError = `*Setup failed: ${errorMessage || 'Unknown error'}`;
}
this.messageTimestamp = Date.now();
this.requestUpdate();
}
async handleModelInput(e) {
const modelName = e.target.value.trim();
this.selectedLlmModel = modelName;
this.clearMessages();
// Save to user history if it's a valid model name
if (modelName && modelName.length > 2) {
this.saveToUserHistory(modelName);
}
this.requestUpdate();
}
async handleModelKeyPress(e) {
if (e.key === 'Enter' && this.selectedLlmModel?.trim()) {
e.preventDefault();
console.log(`[ApiKeyHeader] Enter pressed, installing model: ${this.selectedLlmModel}`);
// Check if Ollama is ready first
const ollamaReady = await this.ensureOllamaReady();
if (!ollamaReady) {
this.llmError = '*Failed to setup Ollama';
this.messageTimestamp = Date.now();
this.requestUpdate();
return;
}
// Install the model
await this.installModel(this.selectedLlmModel);
}
}
loadUserModelHistory() {
try {
const saved = localStorage.getItem('ollama-model-history');
if (saved) {
this.userModelHistory = JSON.parse(saved);
}
} catch (error) {
console.error('[ApiKeyHeader] Failed to load model history:', error);
this.userModelHistory = [];
}
}
saveToUserHistory(modelName) {
if (!modelName || !modelName.trim()) return;
// Remove if already exists (to move to front)
this.userModelHistory = this.userModelHistory.filter(m => m !== modelName);
// Add to front
this.userModelHistory.unshift(modelName);
// Keep only last 20 entries
this.userModelHistory = this.userModelHistory.slice(0, 20);
// Save to localStorage
try {
localStorage.setItem('ollama-model-history', JSON.stringify(this.userModelHistory));
} catch (error) {
console.error('[ApiKeyHeader] Failed to save model history:', error);
}
}
getCombinedModelSuggestions() {
const combined = [];
// Add installed models first (from Ollama CLI)
for (const model of this.modelSuggestions) {
combined.push({
name: model.name,
status: 'installed',
size: model.size || 'Unknown',
source: 'installed',
});
}
// Add user history models that aren't already installed
const installedNames = this.modelSuggestions.map(m => m.name);
for (const modelName of this.userModelHistory) {
if (!installedNames.includes(modelName)) {
combined.push({
name: modelName,
status: 'history',
size: 'Unknown',
source: 'history',
});
}
}
return combined;
}
async installModel(modelName) {
if (!modelName?.trim()) {
throw new Error('Invalid model name');
}
this.installingModel = modelName;
this.installProgress = 0;
this.clearMessages();
this.requestUpdate();
if (!window.api?.apiKeyHeader) return;
let progressHandler = null;
try {
console.log(`[ApiKeyHeader] Installing model via Ollama REST API: ${modelName}`);
// Create robust progress handler with timeout protection
progressHandler = (event, data) => {
if (data.service === 'ollama' && data.model === modelName && !this._isOperationCancelled(modelName)) {
const progress = Math.round(Math.max(0, Math.min(100, data.progress || 0)));
if (progress !== this.installProgress) {
this.installProgress = progress;
console.log(`[ApiKeyHeader] API Progress: ${progress}% for ${modelName} (${data.status || 'downloading'})`);
this.requestUpdate();
}
}
};
// Set up progress tracking - 통합 LocalAI 이벤트 사용
window.api.apiKeyHeader.onLocalAIProgress(progressHandler);
// Execute the model pull with timeout
const installPromise = window.api.apiKeyHeader.pullOllamaModel(modelName);
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Installation timeout after 10 minutes')), 600000));
const result = await Promise.race([installPromise, timeoutPromise]);
if (result.success) {
console.log(`[ApiKeyHeader] Model ${modelName} installed successfully via API`);
this.installProgress = 100;
this.requestUpdate();
// Brief pause to show completion
await new Promise(resolve => setTimeout(resolve, 300));
// Refresh status and show success
await this.refreshOllamaStatus();
this.successMessage = `✓ ${modelName} ready`;
this.messageTimestamp = Date.now();
} else {
throw new Error(result.error || 'Installation failed');
}
} catch (error) {
console.error(`[ApiKeyHeader] Model installation failed:`, error);
this.llmError = `*Failed: ${error.message}`;
this.messageTimestamp = Date.now();
} finally {
// Comprehensive cleanup
if (progressHandler) {
window.api.apiKeyHeader.removeOnLocalAIProgress(progressHandler);
}
this.installingModel = null;
this.installProgress = 0;
this.requestUpdate();
}
}
_isOperationCancelled(modelName) {
return !this.installingModel || this.installingModel !== modelName;
}
async downloadWhisperModel(modelId) {
if (!modelId?.trim()) {
console.warn('[ApiKeyHeader] Invalid Whisper model ID');
return;
}
console.log(`[ApiKeyHeader] Starting Whisper model download: ${modelId}`);
// Mark as installing
this.whisperInstallingModels = { ...this.whisperInstallingModels, [modelId]: 0 };
this.clearMessages();
this.requestUpdate();
if (!window.api?.apiKeyHeader) return;
let progressHandler = null;
try {
// Set up robust progress listener - 통합 LocalAI 이벤트 사용
progressHandler = (event, data) => {
if (data.service === 'whisper' && data.model === modelId) {
const cleanProgress = Math.round(Math.max(0, Math.min(100, data.progress || 0)));
this.whisperInstallingModels = { ...this.whisperInstallingModels, [modelId]: cleanProgress };
console.log(`[ApiKeyHeader] Whisper download progress: ${cleanProgress}% for ${modelId}`);
this.requestUpdate();
}
};
window.api.apiKeyHeader.onLocalAIProgress(progressHandler);
// Start download with timeout protection
const downloadPromise = window.api.apiKeyHeader.downloadWhisperModel(modelId);
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Download timeout after 10 minutes')), 600000));
const result = await Promise.race([downloadPromise, timeoutPromise]);
if (result?.success) {
this.successMessage = `✓ ${modelId} downloaded successfully`;
this.messageTimestamp = Date.now();
console.log(`[ApiKeyHeader] Whisper model ${modelId} downloaded successfully`);
// Auto-select the downloaded model
this.selectedSttModel = modelId;
} else {
this.sttError = `*Failed to download ${modelId}: ${result?.error || 'Unknown error'}`;
this.messageTimestamp = Date.now();
console.error(`[ApiKeyHeader] Whisper download failed:`, result?.error);
}
} catch (error) {
console.error(`[ApiKeyHeader] Error downloading Whisper model ${modelId}:`, error);
this.sttError = `*Error downloading ${modelId}: ${error.message}`;
this.messageTimestamp = Date.now();
} finally {
// Cleanup
if (progressHandler) {
window.api.apiKeyHeader.removeOnLocalAIProgress(progressHandler);
}
delete this.whisperInstallingModels[modelId];
this.requestUpdate();
}
}
handlePaste(e) {
e.preventDefault();
this.clearMessages();
const clipboardText = (e.clipboardData || window.clipboardData).getData('text');
console.log('Paste event detected:', clipboardText?.substring(0, 10) + '...');
if (clipboardText) {
this.apiKey = clipboardText.trim();
const inputElement = e.target;
inputElement.value = this.apiKey;
}
this.requestUpdate();
this.updateComplete.then(() => {
const inputField = this.shadowRoot?.querySelector('.apikey-input');
if (inputField) {
inputField.focus();
inputField.setSelectionRange(inputField.value.length, inputField.value.length);
}
});
}
handleKeyPress(e) {
if (e.key === 'Enter') {
e.preventDefault();
this.handleSubmit();
}
}
//////// after_modelStateService ////////
async handleSttModelChange(e) {
const modelId = e.target.value;
this.selectedSttModel = modelId;
if (modelId && this.sttProvider === 'whisper') {
// Check if model needs to be downloaded
const isInstalling = this.whisperInstallingModels[modelId] !== undefined;
if (!isInstalling) {
console.log(`[ApiKeyHeader] Auto-installing Whisper model: ${modelId}`);
await this.downloadWhisperModel(modelId);
}
}
this.requestUpdate();
}
async handleSubmit() {
console.log('[ApiKeyHeader] handleSubmit: Submitting...');
this.isLoading = true;
this.clearMessages();
this.requestUpdate();
if (!window.api?.apiKeyHeader) {
this.isLoading = false;
this.llmError = '*API bridge not available';
this.requestUpdate();
return;
}
try {
// Handle LLM provider
let llmResult;
if (this.llmProvider === 'ollama') {
// For Ollama ensure it's ready and validate model selection
if (!this.selectedLlmModel?.trim()) {
throw new Error('Please enter an Ollama model name');
}
const ollamaReady = await this.ensureOllamaReady();
if (!ollamaReady) {
throw new Error('Failed to setup Ollama');
}
// Check if model is installed, if not install it
const selectedModel = this.getCombinedModelSuggestions().find(m => m.name === this.selectedLlmModel);
if (!selectedModel || selectedModel.status !== 'installed') {
console.log(`[ApiKeyHeader] Installing model ${this.selectedLlmModel}...`);
await this.installModel(this.selectedLlmModel);
}
// Validate Ollama is working
llmResult = await window.api.apiKeyHeader.validateKey({
provider: 'ollama',
key: 'local',
});
if (llmResult.success) {
// Set the selected model
await window.api.apiKeyHeader.setSelectedModel({
type: 'llm',
modelId: this.selectedLlmModel,
});
}
} else {
// For other providers, validate API key
if (!this.llmApiKey.trim()) {
throw new Error('Please enter LLM API key');
}
llmResult = await window.api.apiKeyHeader.validateKey({
provider: this.llmProvider,
key: this.llmApiKey.trim(),
});
if (llmResult.success) {
const config = await window.api.apiKeyHeader.getProviderConfig();
const providerConfig = config[this.llmProvider];
if (providerConfig && providerConfig.llmModels.length > 0) {
await window.api.apiKeyHeader.setSelectedModel({
type: 'llm',
modelId: providerConfig.llmModels[0].id,
});
}
}
}
// Handle STT provider
let sttResult;
if (this.sttProvider === 'ollama') {
// Ollama doesn't support STT yet, so skip or use same as LLM validation
sttResult = { success: true };
} else if (this.sttProvider === 'whisper') {
// For Whisper, just validate it's enabled (model download already handled in handleSttModelChange)
sttResult = await window.api.apiKeyHeader.validateKey({
provider: 'whisper',
key: 'local',
});
if (sttResult.success && this.selectedSttModel) {
// Set the selected model
await window.api.apiKeyHeader.setSelectedModel({
type: 'stt',
modelId: this.selectedSttModel,
});
}
} else {
// For other providers, validate API key
if (!this.sttApiKey.trim()) {
throw new Error('Please enter STT API key');
}
sttResult = await window.api.apiKeyHeader.validateKey({
provider: this.sttProvider,
key: this.sttApiKey.trim(),
});
if (sttResult.success) {
const config = await window.api.apiKeyHeader.getProviderConfig();
const providerConfig = config[this.sttProvider];
if (providerConfig && providerConfig.sttModels.length > 0) {
await window.api.apiKeyHeader.setSelectedModel({
type: 'stt',
modelId: providerConfig.sttModels[0].id,
});
}
}
}
if (llmResult.success && sttResult.success) {
console.log('[ApiKeyHeader] handleSubmit: Validation successful.');
// Force refresh the model state to ensure areProvidersConfigured returns true
setTimeout(async () => {
const isConfigured = await window.api.apiKeyHeader.areProvidersConfigured();
console.log('[ApiKeyHeader] Post-validation providers configured check:', isConfigured);
if (isConfigured) {
this.startSlideOutAnimation();
} else {
console.error('[ApiKeyHeader] Providers still not configured after successful validation');
this.llmError = '*Configuration error. Please try again.';
this.isLoading = false;
this.requestUpdate();
}
}, 100);
} else {
this.llmError = !llmResult.success ? `*${llmResult.error || 'Invalid API Key'}` : '';
this.sttError = !sttResult.success ? `*${sttResult.error || 'Invalid'}` : '';
this.errorMessage = ''; // Do not use the general error message for this
this.messageTimestamp = Date.now();
}
} catch (error) {
console.error('[ApiKeyHeader] handleSubmit: Error:', error);
this.llmError = `*${error.message}`;
this.messageTimestamp = Date.now();
}
this.isLoading = false;
this.requestUpdate();
}
//////// after_modelStateService ////////
////TODO: 뭔가 넘어가는 애니메이션 로직에 문제가 있음
startSlideOutAnimation() {
console.log('[ApiKeyHeader] startSlideOutAnimation: Starting slide out animation.');
this.classList.add('sliding-out');
// Fallback: if animation doesn't trigger animationend event, force transition
setTimeout(() => {
if (this.classList.contains('sliding-out')) {
console.log('[ApiKeyHeader] Animation fallback triggered - forcing transition');
this.handleAnimationEnd({ target: this, animationName: 'slideOut' });
}
}, 1); // Wait a bit longer than animation duration
}
handleClose() {
if (window.api?.common) {
window.api.common.quitApplication();
}
}
//////// after_modelStateService ////////
handleAnimationEnd(e) {
if (e.target !== this || !this.classList.contains('sliding-out')) return;
this.classList.remove('sliding-out');
this.classList.add('hidden');
console.log('[ApiKeyHeader] handleAnimationEnd: Animation completed, transitioning to next state...');
if (!window.api?.common) {
console.error('[ApiKeyHeader] handleAnimationEnd: window.api.common not available');
return;
}
if (!this.stateUpdateCallback) {
console.error('[ApiKeyHeader] handleAnimationEnd: stateUpdateCallback not set! This will prevent transition to main window.');
return;
}
window.api.common
.getCurrentUser()
.then(userState => {
console.log('[ApiKeyHeader] handleAnimationEnd: User state retrieved:', userState);
// Additional validation for local providers
return window.api.apiKeyHeader.areProvidersConfigured().then(isConfigured => {
console.log('[ApiKeyHeader] handleAnimationEnd: Providers configured check:', isConfigured);
if (!isConfigured) {
console.warn('[ApiKeyHeader] handleAnimationEnd: Providers still not configured, may return to ApiKey screen');
}
// Call the state update callback
this.stateUpdateCallback(userState);
});
})
.catch(error => {
console.error('[ApiKeyHeader] handleAnimationEnd: Error during state transition:', error);
// Fallback: try to call callback with minimal state
if (this.stateUpdateCallback) {
console.log('[ApiKeyHeader] handleAnimationEnd: Attempting fallback state transition...');
this.stateUpdateCallback({ isLoggedIn: false });
}
});
}
//////// after_modelStateService ////////
connectedCallback() {
super.connectedCallback();
this.addEventListener('animationend', this.handleAnimationEnd);
}
handleMessageFadeEnd(e) {
if (e.animationName === 'fadeOut') {
// Clear the message that finished fading
if (e.target.classList.contains('error-message')) {
this.errorMessage = '';
} else if (e.target.classList.contains('success-message')) {
this.successMessage = '';
}
this.messageTimestamp = 0;
this.requestUpdate();
}
}
disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener('animationend', this.handleAnimationEnd);
// Professional cleanup of all resources
this._performCompleteCleanup();
}
_performCompleteCleanup() {
console.log('[ApiKeyHeader] Performing complete cleanup');
// Stop health monitoring
this._stopHealthMonitoring();
// Cancel all active operations
this._cancelAllActiveOperations();
// Cancel any ongoing installations when component is destroyed
if (this.installingModel) {
this.progressTracker.cancelInstallation(this.installingModel);
}
// Cleanup event listeners
if (window.api?.apiKeyHeader) {
window.api.apiKeyHeader.removeAllListeners();
}
// Cancel any ongoing downloads
const downloadingModels = Object.keys(this.whisperInstallingModels);
if (downloadingModels.length > 0) {
console.log(`[ApiKeyHeader] Cancelling ${downloadingModels.length} ongoing Whisper downloads`);
downloadingModels.forEach(modelId => {
delete this.whisperInstallingModels[modelId];
});
}
// Reset state
this.connectionState = 'disconnected';
this.retryCount = 0;
console.log('[ApiKeyHeader] Cleanup completed');
}
/**
* State machine-based Ollama UI rendering
*/
_renderOllamaStateUI() {
const state = this._getOllamaUIState();
switch (state.type) {
case 'connecting':
return this._renderConnectingState(state);
case 'install_required':
return this._renderInstallRequiredState();
case 'start_required':
return this._renderStartRequiredState();
case 'ready':
return this._renderReadyState();
case 'failed':
return this._renderFailedState(state);
case 'installing':
return this._renderInstallingState(state);
default:
return this._renderUnknownState();
}
}
_getOllamaUIState() {
// State determination logic
if (this.connectionState === 'connecting') {
return { type: 'connecting', message: this.installingModel || 'Connecting to Ollama...' };
}
if (this.connectionState === 'failed') {
return { type: 'failed', message: this.errorMessage };
}
if (this.installingModel && this.installingModel.includes('Ollama')) {
return { type: 'installing', progress: this.installProgress };
}
if (!this.ollamaStatus.installed) {
return { type: 'install_required' };
}
if (!this.ollamaStatus.running) {
return { type: 'start_required' };
}
return { type: 'ready' };
}
_renderConnectingState(state) {
return html`
`;
}
_renderInstallRequiredState() {
return html` Install Ollama `;
}
_renderStartRequiredState() {
return html` Start Ollama Service `;
}
_renderReadyState() {
return html`
${this.getCombinedModelSuggestions().map(
model => html`
${model.name} ${model.status === 'installed' ? '✓ Installed' : model.status === 'history' ? '📝 Recent' : '- Available'}
`
)}
${this.renderModelStatus()}
${this.installingModel && !this.installingModel.includes('Ollama')
? html`
`
: ''}
`;
}
_renderFailedState(state) {
return html`
Connection failed
${state.message || 'Unknown error'}
this._initializeOllamaConnection()}
>
Retry Connection
`;
}
_renderInstallingState(state) {
return html`
`;
}
_renderUnknownState() {
return html`
Unknown state - Please refresh
`;
}
renderModelStatus() {
return '';
}
shouldFadeMessage(type) {
const hasMessage = type === 'error' ? this.errorMessage : this.successMessage;
return hasMessage && this.messageTimestamp > 0 && Date.now() - this.messageTimestamp > 100;
}
openPrivacyPolicy() {
console.log('🔊 openPrivacyPolicy ApiKeyHeader');
if (window.api?.common) {
window.api.common.openExternal('https://pickle.com/privacy-policy');
}
}
render() {
const llmNeedsApiKey = this.llmProvider !== 'ollama' && this.llmProvider !== 'whisper';
const sttNeedsApiKey = this.sttProvider !== 'ollama' && this.sttProvider !== 'whisper';
const llmNeedsModel = this.llmProvider === 'ollama';
const sttNeedsModel = this.sttProvider === 'whisper';
const isButtonDisabled =
this.isLoading ||
this.installingModel ||
Object.keys(this.whisperInstallingModels).length > 0 ||
(llmNeedsApiKey && !this.llmApiKey.trim()) ||
(sttNeedsApiKey && !this.sttApiKey.trim()) ||
(llmNeedsModel && !this.selectedLlmModel?.trim()) ||
(sttNeedsModel && !this.selectedSttModel);
const llmProviderName = this.providers.llm.find(p => p.id === this.llmProvider)?.name || this.llmProvider;
return html`
×
1. Select LLM Provider
${this.providers.llm.map(
p => html`
this.handleLlmProviderChange(e, p.id)}
>
${p.name}
`
)}
2. Enter API Key
${this.llmProvider === 'ollama'
? this._renderOllamaStateUI()
: html`
`}
3. Select STT Provider
${this.providers.stt.map(
p => html`
this.handleSttProviderChange(e, p.id)}
>
${p.name}
`
)}
4. Enter STT API Key
${this.sttProvider === 'ollama'
? html`
STT not supported by Ollama
`
: this.sttProvider === 'whisper'
? html`
`
: html`
`}
${this.isLoading
? 'Setting up...'
: this.installingModel
? `Installing ${this.installingModel}...`
: Object.keys(this.whisperInstallingModels).length > 0
? `Downloading...`
: 'Confirm'}
${this.errorMessage}
${this.successMessage}
`;
}
}
customElements.define('apikey-header', ApiKeyHeader);
================================================
FILE: src/ui/app/HeaderController.js
================================================
import './MainHeader.js';
import './ApiKeyHeader.js';
import './PermissionHeader.js';
import './WelcomeHeader.js';
class HeaderTransitionManager {
constructor() {
this.headerContainer = document.getElementById('header-container');
this.currentHeaderType = null; // 'welcome' | 'apikey' | 'main' | 'permission'
this.welcomeHeader = null;
this.apiKeyHeader = null;
this.mainHeader = null;
this.permissionHeader = null;
/**
* only one header window is allowed
* @param {'welcome'|'apikey'|'main'|'permission'} type
*/
this.ensureHeader = (type) => {
console.log('[HeaderController] ensureHeader: Ensuring header of type:', type);
if (this.currentHeaderType === type) {
console.log('[HeaderController] ensureHeader: Header of type:', type, 'already exists.');
return;
}
this.headerContainer.innerHTML = '';
this.welcomeHeader = null;
this.apiKeyHeader = null;
this.mainHeader = null;
this.permissionHeader = null;
// Create new header element
if (type === 'welcome') {
this.welcomeHeader = document.createElement('welcome-header');
this.welcomeHeader.loginCallback = () => this.handleLoginOption();
this.welcomeHeader.apiKeyCallback = () => this.handleApiKeyOption();
this.headerContainer.appendChild(this.welcomeHeader);
console.log('[HeaderController] ensureHeader: Header of type:', type, 'created.');
} else if (type === 'apikey') {
this.apiKeyHeader = document.createElement('apikey-header');
this.apiKeyHeader.stateUpdateCallback = (userState) => this.handleStateUpdate(userState);
this.apiKeyHeader.backCallback = () => this.transitionToWelcomeHeader();
this.apiKeyHeader.addEventListener('request-resize', e => {
this._resizeForApiKey(e.detail.height);
});
this.headerContainer.appendChild(this.apiKeyHeader);
console.log('[HeaderController] ensureHeader: Header of type:', type, 'created.');
} else if (type === 'permission') {
this.permissionHeader = document.createElement('permission-setup');
this.permissionHeader.addEventListener('request-resize', e => {
this._resizeForPermissionHeader(e.detail.height);
});
this.permissionHeader.continueCallback = async () => {
if (window.api && window.api.headerController) {
console.log('[HeaderController] Re-initializing model state after permission grant...');
await window.api.headerController.reInitializeModelState();
}
this.transitionToMainHeader();
};
this.headerContainer.appendChild(this.permissionHeader);
} else {
this.mainHeader = document.createElement('main-header');
this.headerContainer.appendChild(this.mainHeader);
this.mainHeader.startSlideInAnimation?.();
}
this.currentHeaderType = type;
this.notifyHeaderState(type === 'permission' ? 'apikey' : type); // Keep permission state as apikey for compatibility
};
console.log('[HeaderController] Manager initialized');
// WelcomeHeader 콜백 메서드들
this.handleLoginOption = this.handleLoginOption.bind(this);
this.handleApiKeyOption = this.handleApiKeyOption.bind(this);
this._bootstrap();
if (window.api) {
window.api.headerController.onUserStateChanged((event, userState) => {
console.log('[HeaderController] Received user state change:', userState);
this.handleStateUpdate(userState);
});
window.api.headerController.onAuthFailed((event, { message }) => {
console.error('[HeaderController] Received auth failure from main process:', message);
if (this.apiKeyHeader) {
this.apiKeyHeader.errorMessage = 'Authentication failed. Please try again.';
this.apiKeyHeader.isLoading = false;
}
});
window.api.headerController.onForceShowApiKeyHeader(async () => {
console.log('[HeaderController] Received broadcast to show apikey header. Switching now.');
const isConfigured = await window.api.apiKeyHeader.areProvidersConfigured();
if (!isConfigured) {
await this._resizeForWelcome();
this.ensureHeader('welcome');
} else {
await this._resizeForApiKey();
this.ensureHeader('apikey');
}
});
}
}
notifyHeaderState(stateOverride) {
const state = stateOverride || this.currentHeaderType || 'apikey';
if (window.api) {
window.api.headerController.sendHeaderStateChanged(state);
}
}
async _bootstrap() {
// The initial state will be sent by the main process via 'user-state-changed'
// We just need to request it.
if (window.api) {
const userState = await window.api.common.getCurrentUser();
console.log('[HeaderController] Bootstrapping with initial user state:', userState);
this.handleStateUpdate(userState);
} else {
// Fallback for non-electron environment (testing/web)
this.ensureHeader('welcome');
}
}
//////// after_modelStateService ////////
async handleStateUpdate(userState) {
const isConfigured = await window.api.apiKeyHeader.areProvidersConfigured();
if (isConfigured) {
// If providers are configured, always check permissions regardless of login state.
const permissionResult = await this.checkPermissions();
if (permissionResult.success) {
this.transitionToMainHeader();
} else {
this.transitionToPermissionHeader();
}
} else {
// If no providers are configured, show the welcome header to prompt for setup.
await this._resizeForWelcome();
this.ensureHeader('welcome');
}
}
// WelcomeHeader 콜백 메서드들
async handleLoginOption() {
console.log('[HeaderController] Login option selected');
if (window.api) {
await window.api.common.startFirebaseAuth();
}
}
async handleApiKeyOption() {
console.log('[HeaderController] API key option selected');
await this._resizeForApiKey(400);
this.ensureHeader('apikey');
// ApiKeyHeader에 뒤로가기 콜백 설정
if (this.apiKeyHeader) {
this.apiKeyHeader.backCallback = () => this.transitionToWelcomeHeader();
}
}
async transitionToWelcomeHeader() {
if (this.currentHeaderType === 'welcome') {
return this._resizeForWelcome();
}
await this._resizeForWelcome();
this.ensureHeader('welcome');
}
//////// after_modelStateService ////////
async transitionToPermissionHeader() {
// Prevent duplicate transitions
if (this.currentHeaderType === 'permission') {
console.log('[HeaderController] Already showing permission setup, skipping transition');
return;
}
// Check if permissions were previously completed
if (window.api) {
try {
const permissionsCompleted = await window.api.headerController.checkPermissionsCompleted();
if (permissionsCompleted) {
console.log('[HeaderController] Permissions were previously completed, checking current status...');
// Double check current permission status
const permissionResult = await this.checkPermissions();
if (permissionResult.success) {
// Skip permission setup if already granted
this.transitionToMainHeader();
return;
}
console.log('[HeaderController] Permissions were revoked, showing setup again');
}
} catch (error) {
console.error('[HeaderController] Error checking permissions completed status:', error);
}
}
let initialHeight = 220;
if (window.api) {
try {
const userState = await window.api.common.getCurrentUser();
if (userState.mode === 'firebase') {
initialHeight = 280;
}
} catch (e) {
console.error('Could not get user state for resize', e);
}
}
await this._resizeForPermissionHeader(initialHeight);
this.ensureHeader('permission');
}
async transitionToMainHeader(animate = true) {
if (this.currentHeaderType === 'main') {
return this._resizeForMain();
}
await this._resizeForMain();
this.ensureHeader('main');
}
async _resizeForMain() {
if (!window.api) return;
console.log('[HeaderController] _resizeForMain: Resizing window to 353x47');
return window.api.headerController.resizeHeaderWindow({ width: 353, height: 47 }).catch(() => {});
}
async _resizeForApiKey(height = 370) {
if (!window.api) return;
console.log(`[HeaderController] _resizeForApiKey: Resizing window to 456x${height}`);
return window.api.headerController.resizeHeaderWindow({ width: 456, height: height }).catch(() => {});
}
async _resizeForPermissionHeader(height) {
if (!window.api) return;
const finalHeight = height || 220;
return window.api.headerController.resizeHeaderWindow({ width: 285, height: finalHeight })
.catch(() => {});
}
async _resizeForWelcome() {
if (!window.api) return;
console.log('[HeaderController] _resizeForWelcome: Resizing window to 456x370');
return window.api.headerController.resizeHeaderWindow({ width: 456, height: 364 })
.catch(() => {});
}
async checkPermissions() {
if (!window.api) {
return { success: true };
}
try {
const permissions = await window.api.headerController.checkSystemPermissions();
console.log('[HeaderController] Current permissions:', permissions);
if (!permissions.needsSetup) {
return { success: true };
}
let errorMessage = '';
if (!permissions.microphone && !permissions.screen) {
errorMessage = 'Microphone and screen recording access required';
}
return {
success: false,
error: errorMessage
};
} catch (error) {
console.error('[HeaderController] Error checking permissions:', error);
return {
success: false,
error: 'Failed to check permissions'
};
}
}
}
window.addEventListener('DOMContentLoaded', () => {
new HeaderTransitionManager();
});
================================================
FILE: src/ui/app/MainHeader.js
================================================
import { html, css, LitElement } from '../assets/lit-core-2.7.4.min.js';
export class MainHeader extends LitElement {
static properties = {
isTogglingSession: { type: Boolean, state: true },
shortcuts: { type: Object, state: true },
listenSessionStatus: { type: String, state: true },
};
static styles = css`
:host {
display: flex;
transition: transform 0.2s cubic-bezier(0.23, 1, 0.32, 1), opacity 0.2s ease-out;
}
:host(.hiding) {
animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.6, 1) forwards;
}
:host(.showing) {
animation: slideDown 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}
:host(.sliding-in) {
animation: fadeIn 0.2s ease-out forwards;
}
:host(.hidden) {
opacity: 0;
transform: translateY(-150%) scale(0.85);
pointer-events: none;
}
* {
font-family: 'Helvetica Neue', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
cursor: default;
user-select: none;
}
.header {
-webkit-app-region: drag;
width: max-content;
height: 47px;
padding: 2px 10px 2px 13px;
background: transparent;
overflow: hidden;
border-radius: 9000px;
/* backdrop-filter: blur(1px); */
justify-content: space-between;
align-items: center;
display: inline-flex;
box-sizing: border-box;
position: relative;
}
.header::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
border-radius: 9000px;
z-index: -1;
}
.header::after {
content: '';
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
border-radius: 9000px;
padding: 1px;
background: linear-gradient(169deg, rgba(255, 255, 255, 0.17) 0%, rgba(255, 255, 255, 0.08) 50%, rgba(255, 255, 255, 0.17) 100%);
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite: destination-out;
mask-composite: exclude;
pointer-events: none;
}
.listen-button {
-webkit-app-region: no-drag;
height: 26px;
padding: 0 13px;
background: transparent;
border-radius: 9000px;
justify-content: center;
width: 78px;
align-items: center;
gap: 6px;
display: flex;
border: none;
cursor: pointer;
position: relative;
}
.listen-button:disabled {
cursor: default;
opacity: 0.8;
}
.listen-button.active::before {
background: rgba(215, 0, 0, 0.5);
}
.listen-button.active:hover::before {
background: rgba(255, 20, 20, 0.6);
}
.listen-button.done {
background-color: rgba(255, 255, 255, 0.6);
transition: background-color 0.15s ease;
}
.listen-button.done .action-text-content {
color: black;
}
.listen-button.done .listen-icon svg rect,
.listen-button.done .listen-icon svg path {
fill: black;
}
.listen-button.done:hover {
background-color: #f0f0f0;
}
.listen-button:hover::before {
background: rgba(255, 255, 255, 0.18);
}
.listen-button::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
background: rgba(255, 255, 255, 0.14);
border-radius: 9000px;
z-index: -1;
transition: background 0.15s ease;
}
.listen-button::after {
content: '';
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
border-radius: 9000px;
padding: 1px;
background: linear-gradient(169deg, rgba(255, 255, 255, 0.17) 0%, rgba(255, 255, 255, 0.08) 50%, rgba(255, 255, 255, 0.17) 100%);
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite: destination-out;
mask-composite: exclude;
pointer-events: none;
}
.listen-button.done::after {
display: none;
}
.loading-dots {
display: flex;
align-items: center;
gap: 5px;
}
.loading-dots span {
width: 6px;
height: 6px;
background-color: white;
border-radius: 50%;
animation: pulse 1.4s infinite ease-in-out both;
}
.loading-dots span:nth-of-type(1) {
animation-delay: -0.32s;
}
.loading-dots span:nth-of-type(2) {
animation-delay: -0.16s;
}
@keyframes pulse {
0%, 80%, 100% {
opacity: 0.2;
}
40% {
opacity: 1.0;
}
}
.header-actions {
-webkit-app-region: no-drag;
height: 26px;
box-sizing: border-box;
justify-content: flex-start;
align-items: center;
gap: 9px;
display: flex;
padding: 0 8px;
border-radius: 6px;
transition: background 0.15s ease;
}
.header-actions:hover {
background: rgba(255, 255, 255, 0.1);
}
.ask-action {
margin-left: 4px;
}
.action-button,
.action-text {
padding-bottom: 1px;
justify-content: center;
align-items: center;
gap: 10px;
display: flex;
}
.action-text-content {
color: white;
font-size: 12px;
font-family: 'Helvetica Neue', sans-serif;
font-weight: 500; /* Medium */
word-wrap: break-word;
}
.icon-container {
justify-content: flex-start;
align-items: center;
gap: 4px;
display: flex;
}
.icon-container.ask-icons svg,
.icon-container.showhide-icons svg {
width: 12px;
height: 12px;
}
.listen-icon svg {
width: 12px;
height: 11px;
position: relative;
top: 1px;
}
.icon-box {
color: white;
font-size: 12px;
font-family: 'Helvetica Neue', sans-serif;
font-weight: 500;
background-color: rgba(255, 255, 255, 0.1);
border-radius: 13%;
width: 18px;
height: 18px;
display: flex;
align-items: center;
justify-content: center;
}
.settings-button {
-webkit-app-region: no-drag;
padding: 5px;
border-radius: 50%;
background: transparent;
transition: background 0.15s ease;
color: white;
border: none;
cursor: pointer;
display: flex;
align-items: center;
gap: 6px;
}
.settings-button:hover {
background: rgba(255, 255, 255, 0.1);
}
.settings-icon {
display: flex;
align-items: center;
justify-content: center;
padding: 3px;
}
.settings-icon svg {
width: 16px;
height: 16px;
}
/* ────────────────[ GLASS BYPASS ]─────────────── */
:host-context(body.has-glass) .header,
:host-context(body.has-glass) .listen-button,
:host-context(body.has-glass) .header-actions,
:host-context(body.has-glass) .settings-button {
background: transparent !important;
filter: none !important;
box-shadow: none !important;
backdrop-filter: none !important;
}
:host-context(body.has-glass) .icon-box {
background: transparent !important;
border: none !important;
}
:host-context(body.has-glass) .header::before,
:host-context(body.has-glass) .header::after,
:host-context(body.has-glass) .listen-button::before,
:host-context(body.has-glass) .listen-button::after {
display: none !important;
}
:host-context(body.has-glass) .header-actions:hover,
:host-context(body.has-glass) .settings-button:hover,
:host-context(body.has-glass) .listen-button:hover::before {
background: transparent !important;
}
:host-context(body.has-glass) * {
animation: none !important;
transition: none !important;
transform: none !important;
filter: none !important;
backdrop-filter: none !important;
box-shadow: none !important;
}
:host-context(body.has-glass) .header,
:host-context(body.has-glass) .listen-button,
:host-context(body.has-glass) .header-actions,
:host-context(body.has-glass) .settings-button,
:host-context(body.has-glass) .icon-box {
border-radius: 0 !important;
}
:host-context(body.has-glass) {
animation: none !important;
transition: none !important;
transform: none !important;
will-change: auto !important;
}
`;
constructor() {
super();
this.shortcuts = {};
this.isVisible = true;
this.isAnimating = false;
this.hasSlidIn = false;
this.settingsHideTimer = null;
this.isTogglingSession = false;
this.listenSessionStatus = 'beforeSession';
this.animationEndTimer = null;
this.handleAnimationEnd = this.handleAnimationEnd.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.dragState = null;
this.wasJustDragged = false;
}
_getListenButtonText(status) {
switch (status) {
case 'beforeSession': return 'Listen';
case 'inSession' : return 'Stop';
case 'afterSession': return 'Done';
default : return 'Listen';
}
}
async handleMouseDown(e) {
e.preventDefault();
const initialPosition = await window.api.mainHeader.getHeaderPosition();
this.dragState = {
initialMouseX: e.screenX,
initialMouseY: e.screenY,
initialWindowX: initialPosition.x,
initialWindowY: initialPosition.y,
moved: false,
};
window.addEventListener('mousemove', this.handleMouseMove, { capture: true });
window.addEventListener('mouseup', this.handleMouseUp, { once: true, capture: true });
}
handleMouseMove(e) {
if (!this.dragState) return;
const deltaX = Math.abs(e.screenX - this.dragState.initialMouseX);
const deltaY = Math.abs(e.screenY - this.dragState.initialMouseY);
if (deltaX > 3 || deltaY > 3) {
this.dragState.moved = true;
}
const newWindowX = this.dragState.initialWindowX + (e.screenX - this.dragState.initialMouseX);
const newWindowY = this.dragState.initialWindowY + (e.screenY - this.dragState.initialMouseY);
window.api.mainHeader.moveHeaderTo(newWindowX, newWindowY);
}
handleMouseUp(e) {
if (!this.dragState) return;
const wasDragged = this.dragState.moved;
window.removeEventListener('mousemove', this.handleMouseMove, { capture: true });
this.dragState = null;
if (wasDragged) {
this.wasJustDragged = true;
setTimeout(() => {
this.wasJustDragged = false;
}, 0);
}
}
toggleVisibility() {
if (this.isAnimating) {
console.log('[MainHeader] Animation already in progress, ignoring toggle');
return;
}
if (this.animationEndTimer) {
clearTimeout(this.animationEndTimer);
this.animationEndTimer = null;
}
this.isAnimating = true;
if (this.isVisible) {
this.hide();
} else {
this.show();
}
}
hide() {
this.classList.remove('showing');
this.classList.add('hiding');
}
show() {
this.classList.remove('hiding', 'hidden');
this.classList.add('showing');
}
handleAnimationEnd(e) {
if (e.target !== this) return;
this.isAnimating = false;
if (this.classList.contains('hiding')) {
this.classList.add('hidden');
if (window.api) {
window.api.mainHeader.sendHeaderAnimationFinished('hidden');
}
} else if (this.classList.contains('showing')) {
if (window.api) {
window.api.mainHeader.sendHeaderAnimationFinished('visible');
}
}
}
startSlideInAnimation() {
if (this.hasSlidIn) return;
this.classList.add('sliding-in');
}
connectedCallback() {
super.connectedCallback();
this.addEventListener('animationend', this.handleAnimationEnd);
if (window.api) {
this._sessionStateTextListener = (event, { success }) => {
if (success) {
this.listenSessionStatus = ({
beforeSession: 'inSession',
inSession: 'afterSession',
afterSession: 'beforeSession',
})[this.listenSessionStatus] || 'beforeSession';
} else {
this.listenSessionStatus = 'beforeSession';
}
this.isTogglingSession = false; // ✨ 로딩 상태만 해제
};
window.api.mainHeader.onListenChangeSessionResult(this._sessionStateTextListener);
this._shortcutListener = (event, keybinds) => {
console.log('[MainHeader] Received updated shortcuts:', keybinds);
this.shortcuts = keybinds;
};
window.api.mainHeader.onShortcutsUpdated(this._shortcutListener);
}
}
disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener('animationend', this.handleAnimationEnd);
if (this.animationEndTimer) {
clearTimeout(this.animationEndTimer);
this.animationEndTimer = null;
}
if (window.api) {
if (this._sessionStateTextListener) {
window.api.mainHeader.removeOnListenChangeSessionResult(this._sessionStateTextListener);
}
if (this._shortcutListener) {
window.api.mainHeader.removeOnShortcutsUpdated(this._shortcutListener);
}
}
}
showSettingsWindow(element) {
if (this.wasJustDragged) return;
if (window.api) {
console.log(`[MainHeader] showSettingsWindow called at ${Date.now()}`);
window.api.mainHeader.showSettingsWindow();
}
}
hideSettingsWindow() {
if (this.wasJustDragged) return;
if (window.api) {
console.log(`[MainHeader] hideSettingsWindow called at ${Date.now()}`);
window.api.mainHeader.hideSettingsWindow();
}
}
async _handleListenClick() {
if (this.wasJustDragged) return;
if (this.isTogglingSession) {
return;
}
this.isTogglingSession = true;
try {
const listenButtonText = this._getListenButtonText(this.listenSessionStatus);
if (window.api) {
await window.api.mainHeader.sendListenButtonClick(listenButtonText);
}
} catch (error) {
console.error('IPC invoke for session change failed:', error);
this.isTogglingSession = false;
}
}
async _handleAskClick() {
if (this.wasJustDragged) return;
try {
if (window.api) {
await window.api.mainHeader.sendAskButtonClick();
}
} catch (error) {
console.error('IPC invoke for ask button failed:', error);
}
}
async _handleToggleAllWindowsVisibility() {
if (this.wasJustDragged) return;
try {
if (window.api) {
await window.api.mainHeader.sendToggleAllWindowsVisibility();
}
} catch (error) {
console.error('IPC invoke for all windows visibility button failed:', error);
}
}
renderShortcut(accelerator) {
if (!accelerator) return html``;
const keyMap = {
'Cmd': '⌘', 'Command': '⌘',
'Ctrl': '⌃', 'Control': '⌃',
'Alt': '⌥', 'Option': '⌥',
'Shift': '⇧',
'Enter': '↵',
'Backspace': '⌫',
'Delete': '⌦',
'Tab': '⇥',
'Escape': '⎋',
'Up': '↑', 'Down': '↓', 'Left': '←', 'Right': '→',
'\\': html` `,
};
const keys = accelerator.split('+');
return html`${keys.map(key => html`
${keyMap[key] || key}
`)}`;
}
render() {
const listenButtonText = this._getListenButtonText(this.listenSessionStatus);
const buttonClasses = {
active: listenButtonText === 'Stop',
done: listenButtonText === 'Done',
};
const showStopIcon = listenButtonText === 'Stop' || listenButtonText === 'Done';
return html`
`;
}
}
customElements.define('main-header', MainHeader);
================================================
FILE: src/ui/app/PermissionHeader.js
================================================
import { LitElement, html, css } from '../assets/lit-core-2.7.4.min.js';
export class PermissionHeader extends LitElement {
static styles = css`
:host {
display: block;
transition: opacity 0.3s ease-in, transform 0.3s ease-in;
will-change: opacity, transform;
}
:host(.sliding-out) {
opacity: 0;
transform: translateY(-20px);
}
:host(.hidden) {
opacity: 0;
pointer-events: none;
}
* {
font-family: 'Helvetica Neue', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
cursor: default;
user-select: none;
box-sizing: border-box;
}
.container {
-webkit-app-region: drag;
width: 285px;
/* height is now set dynamically */
padding: 18px 20px;
background: rgba(0, 0, 0, 0.3);
border-radius: 16px;
overflow: hidden;
position: relative;
display: flex;
flex-direction: column;
align-items: center;
}
.container::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 16px;
padding: 1px;
background: linear-gradient(169deg, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.5) 100%);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: destination-out;
mask-composite: exclude;
pointer-events: none;
}
.close-button {
-webkit-app-region: no-drag;
position: absolute;
top: 10px;
right: 10px;
width: 14px;
height: 14px;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 3px;
color: rgba(255, 255, 255, 0.7);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s ease;
z-index: 10;
font-size: 14px;
line-height: 1;
padding: 0;
}
.close-button:hover {
background: rgba(255, 255, 255, 0.2);
color: rgba(255, 255, 255, 0.9);
}
.close-button:active {
transform: scale(0.95);
}
.title {
color: white;
font-size: 16px;
font-weight: 500;
margin: 0;
text-align: center;
flex-shrink: 0;
}
.form-content {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
margin-top: auto;
}
.form-content.all-granted {
flex-grow: 1;
justify-content: center;
margin-top: 0;
}
.subtitle {
color: rgba(255, 255, 255, 0.7);
font-size: 11px;
font-weight: 400;
text-align: center;
margin-bottom: 12px;
line-height: 1.3;
}
.permission-status {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
margin-bottom: 12px;
min-height: 20px;
}
.permission-item {
display: flex;
align-items: center;
gap: 6px;
color: rgba(255, 255, 255, 0.8);
font-size: 11px;
font-weight: 400;
}
.permission-item.granted {
color: rgba(34, 197, 94, 0.9);
}
.permission-icon {
width: 12px;
height: 12px;
opacity: 0.8;
}
.check-icon {
width: 12px;
height: 12px;
color: rgba(34, 197, 94, 0.9);
}
.action-button {
-webkit-app-region: no-drag;
width: 100%;
height: 34px;
background: rgba(255, 255, 255, 0.2);
border: none;
border-radius: 10px;
color: white;
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s ease;
position: relative;
overflow: hidden;
margin-bottom: 6px;
}
.action-button::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 10px;
padding: 1px;
background: linear-gradient(169deg, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.5) 100%);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: destination-out;
mask-composite: exclude;
pointer-events: none;
}
.action-button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.3);
}
.action-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.continue-button {
-webkit-app-region: no-drag;
width: 100%;
height: 34px;
background: rgba(34, 197, 94, 0.8);
border: none;
border-radius: 10px;
color: white;
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s ease;
position: relative;
overflow: hidden;
margin-top: 4px;
}
.continue-button::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 10px;
padding: 1px;
background: linear-gradient(169deg, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.5) 100%);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: destination-out;
mask-composite: exclude;
pointer-events: none;
}
.continue-button:hover:not(:disabled) {
background: rgba(34, 197, 94, 0.9);
}
.continue-button:disabled {
background: rgba(255, 255, 255, 0.2);
cursor: not-allowed;
}
/* ────────────────[ GLASS BYPASS ]─────────────── */
:host-context(body.has-glass) .container,
:host-context(body.has-glass) .action-button,
:host-context(body.has-glass) .continue-button,
:host-context(body.has-glass) .close-button {
background: transparent !important;
border: none !important;
box-shadow: none !important;
filter: none !important;
backdrop-filter: none !important;
}
:host-context(body.has-glass) .container::after,
:host-context(body.has-glass) .action-button::after,
:host-context(body.has-glass) .continue-button::after {
display: none !important;
}
:host-context(body.has-glass) .action-button:hover,
:host-context(body.has-glass) .continue-button:hover,
:host-context(body.has-glass) .close-button:hover {
background: transparent !important;
}
`;
static properties = {
microphoneGranted: { type: String },
screenGranted: { type: String },
keychainGranted: { type: String },
isChecking: { type: String },
continueCallback: { type: Function },
userMode: { type: String }, // 'local' or 'firebase'
};
constructor() {
super();
this.microphoneGranted = 'unknown';
this.screenGranted = 'unknown';
this.keychainGranted = 'unknown';
this.isChecking = false;
this.continueCallback = null;
this.userMode = 'local'; // Default to local
}
updated(changedProperties) {
super.updated(changedProperties);
if (changedProperties.has('userMode')) {
const newHeight = this.userMode === 'firebase' ? 280 : 220;
console.log(`[PermissionHeader] User mode changed to ${this.userMode}, requesting resize to ${newHeight}px`);
this.dispatchEvent(new CustomEvent('request-resize', {
detail: { height: newHeight },
bubbles: true,
composed: true
}));
}
}
async connectedCallback() {
super.connectedCallback();
if (window.api) {
try {
const userState = await window.api.common.getCurrentUser();
this.userMode = userState.mode;
} catch (e) {
console.error('[PermissionHeader] Failed to get user state', e);
this.userMode = 'local'; // Fallback to local
}
}
await this.checkPermissions();
// Set up periodic permission check
this.permissionCheckInterval = setInterval(async () => {
if (window.api) {
try {
const userState = await window.api.common.getCurrentUser();
this.userMode = userState.mode;
} catch (e) {
this.userMode = 'local';
}
}
this.checkPermissions();
}, 1000);
}
disconnectedCallback() {
super.disconnectedCallback();
if (this.permissionCheckInterval) {
clearInterval(this.permissionCheckInterval);
}
}
async checkPermissions() {
if (!window.api || this.isChecking) return;
this.isChecking = true;
try {
const permissions = await window.api.permissionHeader.checkSystemPermissions();
console.log('[PermissionHeader] Permission check result:', permissions);
const prevMic = this.microphoneGranted;
const prevScreen = this.screenGranted;
const prevKeychain = this.keychainGranted;
this.microphoneGranted = permissions.microphone;
this.screenGranted = permissions.screen;
this.keychainGranted = permissions.keychain;
// if permissions changed == UI update
if (prevMic !== this.microphoneGranted || prevScreen !== this.screenGranted || prevKeychain !== this.keychainGranted) {
console.log('[PermissionHeader] Permission status changed, updating UI');
this.requestUpdate();
}
const isKeychainRequired = this.userMode === 'firebase';
const keychainOk = !isKeychainRequired || this.keychainGranted === 'granted';
// if all permissions granted == automatically continue
if (this.microphoneGranted === 'granted' &&
this.screenGranted === 'granted' &&
keychainOk &&
this.continueCallback) {
console.log('[PermissionHeader] All permissions granted, proceeding automatically');
setTimeout(() => this.handleContinue(), 500);
}
} catch (error) {
console.error('[PermissionHeader] Error checking permissions:', error);
} finally {
this.isChecking = false;
}
}
async handleMicrophoneClick() {
if (!window.api || this.microphoneGranted === 'granted') return;
console.log('[PermissionHeader] Requesting microphone permission...');
try {
const result = await window.api.permissionHeader.checkSystemPermissions();
console.log('[PermissionHeader] Microphone permission result:', result);
if (result.microphone === 'granted') {
this.microphoneGranted = 'granted';
this.requestUpdate();
return;
}
if (result.microphone === 'not-determined' || result.microphone === 'denied' || result.microphone === 'unknown' || result.microphone === 'restricted') {
const res = await window.api.permissionHeader.requestMicrophonePermission();
if (res.status === 'granted' || res.success === true) {
this.microphoneGranted = 'granted';
this.requestUpdate();
return;
}
}
// Check permissions again after a delay
// setTimeout(() => this.checkPermissions(), 1000);
} catch (error) {
console.error('[PermissionHeader] Error requesting microphone permission:', error);
}
}
async handleScreenClick() {
if (!window.api || this.screenGranted === 'granted') return;
console.log('[PermissionHeader] Checking screen recording permission...');
try {
const permissions = await window.api.permissionHeader.checkSystemPermissions();
console.log('[PermissionHeader] Screen permission check result:', permissions);
if (permissions.screen === 'granted') {
this.screenGranted = 'granted';
this.requestUpdate();
return;
}
if (permissions.screen === 'not-determined' || permissions.screen === 'denied' || permissions.screen === 'unknown' || permissions.screen === 'restricted') {
console.log('[PermissionHeader] Opening screen recording preferences...');
await window.api.permissionHeader.openSystemPreferences('screen-recording');
}
// Check permissions again after a delay
// (This may not execute if app restarts after permission grant)
// setTimeout(() => this.checkPermissions(), 2000);
} catch (error) {
console.error('[PermissionHeader] Error opening screen recording preferences:', error);
}
}
async handleKeychainClick() {
if (!window.api || this.keychainGranted === 'granted') return;
console.log('[PermissionHeader] Requesting keychain permission...');
try {
// Trigger initializeKey to prompt for keychain access
// Assuming encryptionService is accessible or via API
await window.api.permissionHeader.initializeEncryptionKey(); // New IPC handler needed
// After success, update status
this.keychainGranted = 'granted';
this.requestUpdate();
} catch (error) {
console.error('[PermissionHeader] Error requesting keychain permission:', error);
}
}
async handleContinue() {
const isKeychainRequired = this.userMode === 'firebase';
const keychainOk = !isKeychainRequired || this.keychainGranted === 'granted';
if (this.continueCallback &&
this.microphoneGranted === 'granted' &&
this.screenGranted === 'granted' &&
keychainOk) {
// Mark permissions as completed
if (window.api && isKeychainRequired) {
try {
await window.api.permissionHeader.markKeychainCompleted();
console.log('[PermissionHeader] Marked keychain as completed');
} catch (error) {
console.error('[PermissionHeader] Error marking keychain as completed:', error);
}
}
this.continueCallback();
}
}
handleClose() {
console.log('Close button clicked');
if (window.api) {
window.api.common.quitApplication();
}
}
render() {
const isKeychainRequired = this.userMode === 'firebase';
const containerHeight = isKeychainRequired ? 280 : 220;
const keychainOk = !isKeychainRequired || this.keychainGranted === 'granted';
const allGranted = this.microphoneGranted === 'granted' && this.screenGranted === 'granted' && keychainOk;
return html`
Permission Setup Required
${!allGranted ? html`
Grant access to microphone, screen recording${isKeychainRequired ? ' and keychain' : ''} to continue
${this.microphoneGranted === 'granted' ? html`
Microphone ✓
` : html`
Microphone
`}
${this.screenGranted === 'granted' ? html`
Screen ✓
` : html`
Screen Recording
`}
${isKeychainRequired ? html`
${this.keychainGranted === 'granted' ? html`
Data Encryption ✓
` : html`
Data Encryption
`}
` : ''}
${this.microphoneGranted === 'granted' ? 'Microphone Access Granted' : 'Grant Microphone Access'}
${this.screenGranted === 'granted' ? 'Screen Recording Granted' : 'Grant Screen Recording Access'}
${isKeychainRequired ? html`
${this.keychainGranted === 'granted' ? 'Encryption Enabled' : 'Enable Encryption'}
Stores the key to encrypt your data. Press "Always Allow " to continue.
` : ''}
` : html`
Continue to Pickle Glass
`}
`;
}
}
customElements.define('permission-setup', PermissionHeader);
================================================
FILE: src/ui/app/PickleGlassApp.js
================================================
import { html, css, LitElement } from '../assets/lit-core-2.7.4.min.js';
import { SettingsView } from '../settings/SettingsView.js';
import { ListenView } from '../listen/ListenView.js';
import { AskView } from '../ask/AskView.js';
import { ShortcutSettingsView } from '../settings/ShortCutSettingsView.js';
import '../listen/audioCore/renderer.js';
export class PickleGlassApp extends LitElement {
static styles = css`
:host {
display: block;
width: 100%;
height: 100%;
color: var(--text-color);
background: transparent;
border-radius: 7px;
}
listen-view {
display: block;
width: 100%;
height: 100%;
}
ask-view, settings-view, history-view, help-view, setup-view {
display: block;
width: 100%;
height: 100%;
}
`;
static properties = {
currentView: { type: String },
statusText: { type: String },
startTime: { type: Number },
currentResponseIndex: { type: Number },
isMainViewVisible: { type: Boolean },
selectedProfile: { type: String },
selectedLanguage: { type: String },
selectedScreenshotInterval: { type: String },
selectedImageQuality: { type: String },
isClickThrough: { type: Boolean, state: true },
layoutMode: { type: String },
_viewInstances: { type: Object, state: true },
_isClickThrough: { state: true },
structuredData: { type: Object },
};
constructor() {
super();
const urlParams = new URLSearchParams(window.location.search);
this.currentView = urlParams.get('view') || 'listen';
this.currentResponseIndex = -1;
this.selectedProfile = localStorage.getItem('selectedProfile') || 'interview';
// Language format migration for legacy users
let lang = localStorage.getItem('selectedLanguage') || 'en';
if (lang.includes('-')) {
const newLang = lang.split('-')[0];
console.warn(`[Migration] Correcting language format from "${lang}" to "${newLang}".`);
localStorage.setItem('selectedLanguage', newLang);
lang = newLang;
}
this.selectedLanguage = lang;
this.selectedScreenshotInterval = localStorage.getItem('selectedScreenshotInterval') || '5';
this.selectedImageQuality = localStorage.getItem('selectedImageQuality') || 'medium';
this._isClickThrough = false;
}
connectedCallback() {
super.connectedCallback();
if (window.api) {
window.api.pickleGlassApp.onClickThroughToggled((_, isEnabled) => {
this._isClickThrough = isEnabled;
});
}
}
disconnectedCallback() {
super.disconnectedCallback();
if (window.api) {
window.api.pickleGlassApp.removeAllClickThroughListeners();
}
}
updated(changedProperties) {
if (changedProperties.has('currentView')) {
const viewContainer = this.shadowRoot?.querySelector('.view-container');
if (viewContainer) {
viewContainer.classList.add('entering');
requestAnimationFrame(() => {
viewContainer.classList.remove('entering');
});
}
}
// Only update localStorage when these specific properties change
if (changedProperties.has('selectedProfile')) {
localStorage.setItem('selectedProfile', this.selectedProfile);
}
if (changedProperties.has('selectedLanguage')) {
localStorage.setItem('selectedLanguage', this.selectedLanguage);
}
if (changedProperties.has('selectedScreenshotInterval')) {
localStorage.setItem('selectedScreenshotInterval', this.selectedScreenshotInterval);
}
if (changedProperties.has('selectedImageQuality')) {
localStorage.setItem('selectedImageQuality', this.selectedImageQuality);
}
if (changedProperties.has('layoutMode')) {
this.updateLayoutMode();
}
}
async handleClose() {
if (window.api) {
await window.api.common.quitApplication();
}
}
render() {
switch (this.currentView) {
case 'listen':
return html` (this.currentResponseIndex = e.detail.index)}
> `;
case 'ask':
return html` `;
case 'settings':
return html` (this.selectedProfile = profile)}
.onLanguageChange=${lang => (this.selectedLanguage = lang)}
> `;
case 'shortcut-settings':
return html` `;
case 'history':
return html` `;
case 'help':
return html` `;
case 'setup':
return html` `;
default:
return html`Unknown view: ${this.currentView}
`;
}
}
}
customElements.define('pickle-glass-app', PickleGlassApp);
================================================
FILE: src/ui/app/WelcomeHeader.js
================================================
import { html, css, LitElement } from '../assets/lit-core-2.7.4.min.js';
export class WelcomeHeader extends LitElement {
static styles = css`
:host {
display: block;
font-family:
'Inter',
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
sans-serif;
}
.container {
width: 100%;
box-sizing: border-box;
height: auto;
padding: 24px 16px;
background: rgba(0, 0, 0, 0.64);
box-shadow: 0px 0px 0px 1.5px rgba(255, 255, 255, 0.64) inset;
border-radius: 16px;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
gap: 32px;
display: inline-flex;
-webkit-app-region: drag;
}
.close-button {
-webkit-app-region: no-drag;
position: absolute;
top: 16px;
right: 16px;
width: 20px;
height: 20px;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 5px;
color: rgba(255, 255, 255, 0.7);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s ease;
z-index: 10;
font-size: 16px;
line-height: 1;
padding: 0;
}
.close-button:hover {
background: rgba(255, 255, 255, 0.2);
color: rgba(255, 255, 255, 0.9);
}
.header-section {
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
gap: 4px;
display: flex;
}
.title {
color: white;
font-size: 18px;
font-weight: 700;
}
.subtitle {
color: white;
font-size: 14px;
font-weight: 500;
}
.option-card {
width: 100%;
justify-content: flex-start;
align-items: flex-start;
gap: 8px;
display: inline-flex;
}
.divider {
width: 1px;
align-self: stretch;
position: relative;
background: #bebebe;
border-radius: 2px;
}
.option-content {
flex: 1 1 0;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
gap: 8px;
display: inline-flex;
min-width: 0;
}
.option-title {
color: white;
font-size: 14px;
font-weight: 700;
}
.option-description {
color: #dcdcdc;
font-size: 12px;
font-weight: 400;
line-height: 18px;
letter-spacing: 0.12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.action-button {
-webkit-app-region: no-drag;
padding: 8px 10px;
background: rgba(132.6, 132.6, 132.6, 0.8);
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.16);
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.5);
justify-content: center;
align-items: center;
gap: 6px;
display: flex;
cursor: pointer;
transition: background-color 0.2s;
}
.action-button:hover {
background: rgba(150, 150, 150, 0.9);
}
.button-text {
color: white;
font-size: 12px;
font-weight: 600;
}
.button-icon {
width: 12px;
height: 12px;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.arrow-icon {
border: solid white;
border-width: 0 1.2px 1.2px 0;
display: inline-block;
padding: 3px;
transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
}
.footer {
align-self: stretch;
text-align: center;
color: #dcdcdc;
font-size: 12px;
font-weight: 500;
line-height: 19.2px;
}
.footer-link {
text-decoration: underline;
cursor: pointer;
-webkit-app-region: no-drag;
}
`;
static properties = {
loginCallback: { type: Function },
apiKeyCallback: { type: Function },
};
constructor() {
super();
this.loginCallback = () => {};
this.apiKeyCallback = () => {};
this.handleClose = this.handleClose.bind(this);
}
updated(changedProperties) {
super.updated(changedProperties);
this.dispatchEvent(new CustomEvent('content-changed', { bubbles: true, composed: true }));
}
handleClose() {
if (window.api?.common) {
window.api.common.quitApplication();
}
}
render() {
return html`
×
Quick start with default API key
100% free with Pickle's OpenAI key No personal data collected Sign up with Google in seconds
Open Browser to Log in
Use Personal API keys
Costs may apply based on your API usage No personal data collected Use your own API keys (OpenAI, Gemini, etc.)
Enter Your API Key
`;
}
openPrivacyPolicy() {
console.log('🔊 openPrivacyPolicy WelcomeHeader');
if (window.api?.common) {
window.api.common.openExternal('https://pickle.com/privacy-policy');
}
}
}
customElements.define('welcome-header', WelcomeHeader);
================================================
FILE: src/ui/app/content.html
================================================
Pickle Glass Content
================================================
FILE: src/ui/app/header.html
================================================
Pickle Glass Header
================================================
FILE: src/ui/ask/AskView.js
================================================
import { html, css, LitElement } from '../../ui/assets/lit-core-2.7.4.min.js';
import { parser, parser_write, parser_end, default_renderer } from '../../ui/assets/smd.js';
export class AskView extends LitElement {
static properties = {
currentResponse: { type: String },
currentQuestion: { type: String },
isLoading: { type: Boolean },
copyState: { type: String },
isHovering: { type: Boolean },
hoveredLineIndex: { type: Number },
lineCopyState: { type: Object },
showTextInput: { type: Boolean },
headerText: { type: String },
headerAnimating: { type: Boolean },
isStreaming: { type: Boolean },
};
static styles = css`
:host {
display: block;
width: 100%;
height: 100%;
color: white;
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
transition: transform 0.2s cubic-bezier(0.23, 1, 0.32, 1), opacity 0.2s ease-out;
will-change: transform, opacity;
}
:host(.hiding) {
animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.6, 1) forwards;
}
:host(.showing) {
animation: slideDown 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}
:host(.hidden) {
opacity: 0;
transform: translateY(-150%) scale(0.85);
pointer-events: none;
}
@keyframes slideUp {
0% {
opacity: 1;
transform: translateY(0) scale(1);
filter: blur(0px);
}
30% {
opacity: 0.7;
transform: translateY(-20%) scale(0.98);
filter: blur(0.5px);
}
70% {
opacity: 0.3;
transform: translateY(-80%) scale(0.92);
filter: blur(1.5px);
}
100% {
opacity: 0;
transform: translateY(-150%) scale(0.85);
filter: blur(2px);
}
}
@keyframes slideDown {
0% {
opacity: 0;
transform: translateY(-150%) scale(0.85);
filter: blur(2px);
}
30% {
opacity: 0.5;
transform: translateY(-50%) scale(0.92);
filter: blur(1px);
}
65% {
opacity: 0.9;
transform: translateY(-5%) scale(0.99);
filter: blur(0.2px);
}
85% {
opacity: 0.98;
transform: translateY(2%) scale(1.005);
filter: blur(0px);
}
100% {
opacity: 1;
transform: translateY(0) scale(1);
filter: blur(0px);
}
}
* {
font-family: 'Helvetica Neue', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
cursor: default;
user-select: none;
}
/* Allow text selection in assistant responses */
.response-container, .response-container * {
user-select: text !important;
cursor: text !important;
}
.response-container pre {
background: rgba(0, 0, 0, 0.4) !important;
border-radius: 8px !important;
padding: 12px !important;
margin: 8px 0 !important;
overflow-x: auto !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
}
.response-container code {
font-family: 'Monaco', 'Menlo', 'Consolas', monospace !important;
font-size: 11px !important;
background: transparent !important;
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
}
.response-container pre code {
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
display: block !important;
}
.response-container p code {
background: rgba(255, 255, 255, 0.1) !important;
padding: 2px 4px !important;
border-radius: 3px !important;
color: #ffd700 !important;
}
.hljs-keyword {
color: #ff79c6 !important;
}
.hljs-string {
color: #f1fa8c !important;
}
.hljs-comment {
color: #6272a4 !important;
}
.hljs-number {
color: #bd93f9 !important;
}
.hljs-function {
color: #50fa7b !important;
}
.hljs-variable {
color: #8be9fd !important;
}
.hljs-built_in {
color: #ffb86c !important;
}
.hljs-title {
color: #50fa7b !important;
}
.hljs-attr {
color: #50fa7b !important;
}
.hljs-tag {
color: #ff79c6 !important;
}
.ask-container {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.6);
border-radius: 12px;
outline: 0.5px rgba(255, 255, 255, 0.3) solid;
outline-offset: -1px;
backdrop-filter: blur(1px);
box-sizing: border-box;
position: relative;
overflow: hidden;
}
.ask-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
border-radius: 12px;
filter: blur(10px);
z-index: -1;
}
.response-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background: transparent;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
flex-shrink: 0;
}
.response-header.hidden {
display: none;
}
.header-left {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.response-icon {
width: 20px;
height: 20px;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.response-icon svg {
width: 12px;
height: 12px;
stroke: rgba(255, 255, 255, 0.9);
}
.response-label {
font-size: 13px;
font-weight: 500;
color: rgba(255, 255, 255, 0.9);
white-space: nowrap;
position: relative;
overflow: hidden;
}
.response-label.animating {
animation: fadeInOut 0.3s ease-in-out;
}
@keyframes fadeInOut {
0% {
opacity: 1;
transform: translateY(0);
}
50% {
opacity: 0;
transform: translateY(-10px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.header-right {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
justify-content: flex-end;
}
.question-text {
font-size: 13px;
color: rgba(255, 255, 255, 0.7);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 300px;
margin-right: 8px;
}
.header-controls {
display: flex;
gap: 8px;
align-items: center;
flex-shrink: 0;
}
.copy-button {
background: transparent;
color: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(255, 255, 255, 0.2);
padding: 4px;
border-radius: 3px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
min-width: 24px;
height: 24px;
flex-shrink: 0;
transition: background-color 0.15s ease;
position: relative;
overflow: hidden;
}
.copy-button:hover {
background: rgba(255, 255, 255, 0.15);
}
.copy-button svg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
}
.copy-button .check-icon {
opacity: 0;
transform: translate(-50%, -50%) scale(0.5);
}
.copy-button.copied .copy-icon {
opacity: 0;
transform: translate(-50%, -50%) scale(0.5);
}
.copy-button.copied .check-icon {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.close-button {
background: rgba(255, 255, 255, 0.07);
color: white;
border: none;
padding: 4px;
border-radius: 20px;
outline: 1px rgba(255, 255, 255, 0.3) solid;
outline-offset: -1px;
backdrop-filter: blur(0.5px);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
}
.close-button:hover {
background: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 1);
}
.response-container {
flex: 1;
padding: 16px;
padding-left: 48px;
overflow-y: auto;
font-size: 14px;
line-height: 1.6;
background: transparent;
min-height: 0;
max-height: 400px;
position: relative;
}
.response-container.hidden {
display: none;
}
.response-container::-webkit-scrollbar {
width: 6px;
}
.response-container::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
border-radius: 3px;
}
.response-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
}
.response-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.3);
}
.loading-dots {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 40px;
}
.loading-dot {
width: 8px;
height: 8px;
background: rgba(255, 255, 255, 0.6);
border-radius: 50%;
animation: pulse 1.5s ease-in-out infinite;
}
.loading-dot:nth-child(1) {
animation-delay: 0s;
}
.loading-dot:nth-child(2) {
animation-delay: 0.2s;
}
.loading-dot:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes pulse {
0%,
80%,
100% {
opacity: 0.3;
transform: scale(0.8);
}
40% {
opacity: 1;
transform: scale(1.2);
}
}
.response-line {
position: relative;
padding: 2px 0;
margin: 0;
transition: background-color 0.15s ease;
}
.response-line:hover {
background: rgba(255, 255, 255, 0.05);
border-radius: 4px;
}
.line-copy-button {
position: absolute;
left: -32px;
top: 50%;
transform: translateY(-50%);
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 3px;
padding: 2px;
cursor: pointer;
opacity: 0;
transition: opacity 0.15s ease, background-color 0.15s ease;
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
}
.response-line:hover .line-copy-button {
opacity: 1;
}
.line-copy-button:hover {
background: rgba(255, 255, 255, 0.2);
}
.line-copy-button.copied {
background: rgba(40, 167, 69, 0.3);
}
.line-copy-button svg {
width: 12px;
height: 12px;
stroke: rgba(255, 255, 255, 0.9);
}
.text-input-container {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
background: rgba(0, 0, 0, 0.1);
border-top: 1px solid rgba(255, 255, 255, 0.1);
flex-shrink: 0;
transition: opacity 0.1s ease-in-out, transform 0.1s ease-in-out;
transform-origin: bottom;
}
.text-input-container.hidden {
opacity: 0;
transform: scaleY(0);
padding: 0;
height: 0;
overflow: hidden;
border-top: none;
}
.text-input-container.no-response {
border-top: none;
}
#textInput {
flex: 1;
padding: 10px 14px;
background: rgba(0, 0, 0, 0.2);
border-radius: 20px;
outline: none;
border: none;
color: white;
font-size: 14px;
font-family: 'Helvetica Neue', sans-serif;
font-weight: 400;
}
#textInput::placeholder {
color: rgba(255, 255, 255, 0.5);
}
#textInput:focus {
outline: none;
}
.response-line h1,
.response-line h2,
.response-line h3,
.response-line h4,
.response-line h5,
.response-line h6 {
color: rgba(255, 255, 255, 0.95);
margin: 16px 0 8px 0;
font-weight: 600;
}
.response-line p {
margin: 8px 0;
color: rgba(255, 255, 255, 0.9);
}
.response-line ul,
.response-line ol {
margin: 8px 0;
padding-left: 20px;
}
.response-line li {
margin: 4px 0;
color: rgba(255, 255, 255, 0.9);
}
.response-line code {
background: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.95);
padding: 2px 6px;
border-radius: 4px;
font-family: 'Monaco', 'Menlo', monospace;
font-size: 13px;
}
.response-line pre {
background: rgba(255, 255, 255, 0.05);
color: rgba(255, 255, 255, 0.95);
padding: 12px;
border-radius: 6px;
overflow-x: auto;
margin: 12px 0;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.response-line pre code {
background: none;
padding: 0;
}
.response-line blockquote {
border-left: 3px solid rgba(255, 255, 255, 0.3);
margin: 12px 0;
padding: 8px 16px;
background: rgba(255, 255, 255, 0.05);
color: rgba(255, 255, 255, 0.8);
}
.empty-state {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: rgba(255, 255, 255, 0.5);
font-size: 14px;
}
.btn-gap {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
gap: 4px;
}
/* ────────────────[ GLASS BYPASS ]─────────────── */
:host-context(body.has-glass) .ask-container,
:host-context(body.has-glass) .response-header,
:host-context(body.has-glass) .response-icon,
:host-context(body.has-glass) .copy-button,
:host-context(body.has-glass) .close-button,
:host-context(body.has-glass) .line-copy-button,
:host-context(body.has-glass) .text-input-container,
:host-context(body.has-glass) .response-container pre,
:host-context(body.has-glass) .response-container p code,
:host-context(body.has-glass) .response-container pre code {
background: transparent !important;
border: none !important;
outline: none !important;
box-shadow: none !important;
filter: none !important;
backdrop-filter: none !important;
}
:host-context(body.has-glass) .ask-container::before {
display: none !important;
}
:host-context(body.has-glass) .copy-button:hover,
:host-context(body.has-glass) .close-button:hover,
:host-context(body.has-glass) .line-copy-button,
:host-context(body.has-glass) .line-copy-button:hover,
:host-context(body.has-glass) .response-line:hover {
background: transparent !important;
}
:host-context(body.has-glass) .response-container::-webkit-scrollbar-track,
:host-context(body.has-glass) .response-container::-webkit-scrollbar-thumb {
background: transparent !important;
}
.submit-btn, .clear-btn {
display: flex;
align-items: center;
background: transparent;
color: white;
border: none;
border-radius: 6px;
margin-left: 8px;
font-size: 13px;
font-family: 'Helvetica Neue', sans-serif;
font-weight: 500;
overflow: hidden;
cursor: pointer;
transition: background 0.15s;
height: 32px;
padding: 0 10px;
box-shadow: none;
}
.submit-btn:hover, .clear-btn:hover {
background: rgba(255,255,255,0.1);
}
.btn-label {
margin-right: 8px;
display: flex;
align-items: center;
height: 100%;
}
.btn-icon {
background: rgba(255,255,255,0.1);
border-radius: 13%;
display: flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
}
.btn-icon img, .btn-icon svg {
width: 13px;
height: 13px;
display: block;
}
.header-clear-btn {
background: transparent;
border: none;
display: flex;
align-items: center;
gap: 2px;
cursor: pointer;
padding: 0 2px;
}
.header-clear-btn .icon-box {
color: white;
font-size: 12px;
font-family: 'Helvetica Neue', sans-serif;
font-weight: 500;
background-color: rgba(255, 255, 255, 0.1);
border-radius: 13%;
width: 18px;
height: 18px;
display: flex;
align-items: center;
justify-content: center;
}
.header-clear-btn:hover .icon-box {
background-color: rgba(255,255,255,0.18);
}
`;
constructor() {
super();
this.currentResponse = '';
this.currentQuestion = '';
this.isLoading = false;
this.copyState = 'idle';
this.showTextInput = true;
this.headerText = 'AI Response';
this.headerAnimating = false;
this.isStreaming = false;
this.marked = null;
this.hljs = null;
this.DOMPurify = null;
this.isLibrariesLoaded = false;
// SMD.js streaming markdown parser
this.smdParser = null;
this.smdContainer = null;
this.lastProcessedLength = 0;
this.handleSendText = this.handleSendText.bind(this);
this.handleTextKeydown = this.handleTextKeydown.bind(this);
this.handleCopy = this.handleCopy.bind(this);
this.clearResponseContent = this.clearResponseContent.bind(this);
this.handleEscKey = this.handleEscKey.bind(this);
this.handleScroll = this.handleScroll.bind(this);
this.handleCloseAskWindow = this.handleCloseAskWindow.bind(this);
this.handleCloseIfNoContent = this.handleCloseIfNoContent.bind(this);
this.loadLibraries();
// --- Resize helpers ---
this.isThrottled = false;
}
connectedCallback() {
super.connectedCallback();
console.log('📱 AskView connectedCallback - IPC 이벤트 리스너 설정');
document.addEventListener('keydown', this.handleEscKey);
this.resizeObserver = new ResizeObserver(entries => {
for (const entry of entries) {
const needed = entry.contentRect.height;
const current = window.innerHeight;
if (needed > current - 4) {
this.requestWindowResize(Math.ceil(needed));
}
}
});
const container = this.shadowRoot?.querySelector('.ask-container');
if (container) this.resizeObserver.observe(container);
this.handleQuestionFromAssistant = (event, question) => {
console.log('AskView: Received question from ListenView:', question);
this.handleSendText(null, question);
};
if (window.api) {
window.api.askView.onShowTextInput(() => {
console.log('Show text input signal received');
if (!this.showTextInput) {
this.showTextInput = true;
this.updateComplete.then(() => this.focusTextInput());
} else {
this.focusTextInput();
}
});
window.api.askView.onScrollResponseUp(() => this.handleScroll('up'));
window.api.askView.onScrollResponseDown(() => this.handleScroll('down'));
window.api.askView.onAskStateUpdate((event, newState) => {
this.currentResponse = newState.currentResponse;
this.currentQuestion = newState.currentQuestion;
this.isLoading = newState.isLoading;
this.isStreaming = newState.isStreaming;
const wasHidden = !this.showTextInput;
this.showTextInput = newState.showTextInput;
if (newState.showTextInput) {
if (wasHidden) {
this.updateComplete.then(() => this.focusTextInput());
} else {
this.focusTextInput();
}
}
});
console.log('AskView: IPC 이벤트 리스너 등록 완료');
}
}
disconnectedCallback() {
super.disconnectedCallback();
this.resizeObserver?.disconnect();
console.log('📱 AskView disconnectedCallback - IPC 이벤트 리스너 제거');
document.removeEventListener('keydown', this.handleEscKey);
if (this.copyTimeout) {
clearTimeout(this.copyTimeout);
}
if (this.headerAnimationTimeout) {
clearTimeout(this.headerAnimationTimeout);
}
if (this.streamingTimeout) {
clearTimeout(this.streamingTimeout);
}
Object.values(this.lineCopyTimeouts).forEach(timeout => clearTimeout(timeout));
if (window.api) {
window.api.askView.removeOnAskStateUpdate(this.handleAskStateUpdate);
window.api.askView.removeOnShowTextInput(this.handleShowTextInput);
window.api.askView.removeOnScrollResponseUp(this.handleScroll);
window.api.askView.removeOnScrollResponseDown(this.handleScroll);
console.log('✅ AskView: IPC 이벤트 리스너 제거 필요');
}
}
async loadLibraries() {
try {
if (!window.marked) {
await this.loadScript('../../assets/marked-4.3.0.min.js');
}
if (!window.hljs) {
await this.loadScript('../../assets/highlight-11.9.0.min.js');
}
if (!window.DOMPurify) {
await this.loadScript('../../assets/dompurify-3.0.7.min.js');
}
this.marked = window.marked;
this.hljs = window.hljs;
this.DOMPurify = window.DOMPurify;
if (this.marked && this.hljs) {
this.marked.setOptions({
highlight: (code, lang) => {
if (lang && this.hljs.getLanguage(lang)) {
try {
return this.hljs.highlight(code, { language: lang }).value;
} catch (err) {
console.warn('Highlight error:', err);
}
}
try {
return this.hljs.highlightAuto(code).value;
} catch (err) {
console.warn('Auto highlight error:', err);
}
return code;
},
breaks: true,
gfm: true,
pedantic: false,
smartypants: false,
xhtml: false,
});
this.isLibrariesLoaded = true;
this.renderContent();
console.log('Markdown libraries loaded successfully in AskView');
}
if (this.DOMPurify) {
this.isDOMPurifyLoaded = true;
console.log('DOMPurify loaded successfully in AskView');
}
} catch (error) {
console.error('Failed to load libraries in AskView:', error);
}
}
handleCloseAskWindow() {
// this.clearResponseContent();
window.api.askView.closeAskWindow();
}
handleCloseIfNoContent() {
if (!this.currentResponse && !this.isLoading && !this.isStreaming) {
this.handleCloseAskWindow();
}
}
handleEscKey(e) {
if (e.key === 'Escape') {
e.preventDefault();
this.handleCloseIfNoContent();
}
}
clearResponseContent() {
this.currentResponse = '';
this.currentQuestion = '';
this.isLoading = false;
this.isStreaming = false;
this.headerText = 'AI Response';
this.showTextInput = true;
this.lastProcessedLength = 0;
this.smdParser = null;
this.smdContainer = null;
}
handleInputFocus() {
this.isInputFocused = true;
}
focusTextInput() {
requestAnimationFrame(() => {
const textInput = this.shadowRoot?.getElementById('textInput');
if (textInput) {
textInput.focus();
}
});
}
loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
parseMarkdown(text) {
if (!text) return '';
if (!this.isLibrariesLoaded || !this.marked) {
return text;
}
try {
return this.marked(text);
} catch (error) {
console.error('Markdown parsing error in AskView:', error);
return text;
}
}
fixIncompleteCodeBlocks(text) {
if (!text) return text;
const codeBlockMarkers = text.match(/```/g) || [];
const markerCount = codeBlockMarkers.length;
if (markerCount % 2 === 1) {
return text + '\n```';
}
return text;
}
handleScroll(direction) {
const scrollableElement = this.shadowRoot.querySelector('#responseContainer');
if (scrollableElement) {
const scrollAmount = 100; // 한 번에 스크롤할 양 (px)
if (direction === 'up') {
scrollableElement.scrollTop -= scrollAmount;
} else {
scrollableElement.scrollTop += scrollAmount;
}
}
}
renderContent() {
const responseContainer = this.shadowRoot.getElementById('responseContainer');
if (!responseContainer) return;
// Check loading state
if (this.isLoading) {
responseContainer.innerHTML = `
`;
this.resetStreamingParser();
return;
}
// If there is no response, show empty state
if (!this.currentResponse) {
responseContainer.innerHTML = `...
`;
this.resetStreamingParser();
return;
}
// Set streaming markdown parser
this.renderStreamingMarkdown(responseContainer);
// After updating content, recalculate window height
this.adjustWindowHeightThrottled();
}
resetStreamingParser() {
this.smdParser = null;
this.smdContainer = null;
this.lastProcessedLength = 0;
}
renderStreamingMarkdown(responseContainer) {
try {
// 파서가 없거나 컨테이너가 변경되었으면 새로 생성
if (!this.smdParser || this.smdContainer !== responseContainer) {
this.smdContainer = responseContainer;
this.smdContainer.innerHTML = '';
// smd.js의 default_renderer 사용
const renderer = default_renderer(this.smdContainer);
this.smdParser = parser(renderer);
this.lastProcessedLength = 0;
}
// 새로운 텍스트만 처리 (스트리밍 최적화)
const currentText = this.currentResponse;
const newText = currentText.slice(this.lastProcessedLength);
if (newText.length > 0) {
// 새로운 텍스트 청크를 파서에 전달
parser_write(this.smdParser, newText);
this.lastProcessedLength = currentText.length;
}
// 스트리밍이 완료되면 파서 종료
if (!this.isStreaming && !this.isLoading) {
parser_end(this.smdParser);
}
// 코드 하이라이팅 적용
if (this.hljs) {
responseContainer.querySelectorAll('pre code').forEach(block => {
if (!block.hasAttribute('data-highlighted')) {
this.hljs.highlightElement(block);
block.setAttribute('data-highlighted', 'true');
}
});
}
// 스크롤을 맨 아래로
responseContainer.scrollTop = responseContainer.scrollHeight;
} catch (error) {
console.error('Error rendering streaming markdown:', error);
// 에러 발생 시 기본 텍스트 렌더링으로 폴백
this.renderFallbackContent(responseContainer);
}
}
renderFallbackContent(responseContainer) {
const textToRender = this.currentResponse || '';
if (this.isLibrariesLoaded && this.marked && this.DOMPurify) {
try {
// 마크다운 파싱
const parsedHtml = this.marked.parse(textToRender);
// DOMPurify로 정제
const cleanHtml = this.DOMPurify.sanitize(parsedHtml, {
ALLOWED_TAGS: [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'strong', 'b', 'em', 'i',
'ul', 'ol', 'li', 'blockquote', 'code', 'pre', 'a', 'img', 'table', 'thead',
'tbody', 'tr', 'th', 'td', 'hr', 'sup', 'sub', 'del', 'ins',
],
ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'id', 'target', 'rel'],
});
responseContainer.innerHTML = cleanHtml;
// 코드 하이라이팅 적용
if (this.hljs) {
responseContainer.querySelectorAll('pre code').forEach(block => {
this.hljs.highlightElement(block);
});
}
} catch (error) {
console.error('Error in fallback rendering:', error);
responseContainer.textContent = textToRender;
}
} else {
// 라이브러리가 로드되지 않았을 때 기본 렌더링
const basicHtml = textToRender
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/\n\n/g, '')
.replace(/\n/g, ' ')
.replace(/\*\*(.*?)\*\*/g, '$1 ')
.replace(/\*(.*?)\*/g, '$1 ')
.replace(/`([^`]+)`/g, '$1');
responseContainer.innerHTML = `
${basicHtml}
`;
}
}
requestWindowResize(targetHeight) {
if (window.api) {
window.api.askView.adjustWindowHeight(targetHeight);
}
}
animateHeaderText(text) {
this.headerAnimating = true;
this.requestUpdate();
setTimeout(() => {
this.headerText = text;
this.headerAnimating = false;
this.requestUpdate();
}, 150);
}
startHeaderAnimation() {
this.animateHeaderText('analyzing screen...');
if (this.headerAnimationTimeout) {
clearTimeout(this.headerAnimationTimeout);
}
this.headerAnimationTimeout = setTimeout(() => {
this.animateHeaderText('thinking...');
}, 1500);
}
renderMarkdown(content) {
if (!content) return '';
if (this.isLibrariesLoaded && this.marked) {
return this.parseMarkdown(content);
}
return content
.replace(/\*\*(.*?)\*\*/g, '$1 ')
.replace(/\*(.*?)\*/g, '$1 ')
.replace(/`(.*?)`/g, '$1');
}
fixIncompleteMarkdown(text) {
if (!text) return text;
// 불완전한 볼드체 처리
const boldCount = (text.match(/\*\*/g) || []).length;
if (boldCount % 2 === 1) {
text += '**';
}
// 불완전한 이탤릭체 처리
const italicCount = (text.match(/(? closeBrackets) {
text += ']';
}
const openParens = (text.match(/\]\(/g) || []).length;
const closeParens = (text.match(/\)\s*$/g) || []).length;
if (openParens > closeParens && text.endsWith('(')) {
text += ')';
}
return text;
}
async handleCopy() {
if (this.copyState === 'copied') return;
let responseToCopy = this.currentResponse;
if (this.isDOMPurifyLoaded && this.DOMPurify) {
const testHtml = this.renderMarkdown(responseToCopy);
const sanitized = this.DOMPurify.sanitize(testHtml);
if (this.DOMPurify.removed && this.DOMPurify.removed.length > 0) {
console.warn('Unsafe content detected, copy blocked');
return;
}
}
const textToCopy = `Question: ${this.currentQuestion}\n\nAnswer: ${responseToCopy}`;
try {
await navigator.clipboard.writeText(textToCopy);
console.log('Content copied to clipboard');
this.copyState = 'copied';
this.requestUpdate();
if (this.copyTimeout) {
clearTimeout(this.copyTimeout);
}
this.copyTimeout = setTimeout(() => {
this.copyState = 'idle';
this.requestUpdate();
}, 1500);
} catch (err) {
console.error('Failed to copy:', err);
}
}
async handleLineCopy(lineIndex) {
const originalLines = this.currentResponse.split('\n');
const lineToCopy = originalLines[lineIndex];
if (!lineToCopy) return;
try {
await navigator.clipboard.writeText(lineToCopy);
console.log('Line copied to clipboard');
// '복사됨' 상태로 UI 즉시 업데이트
this.lineCopyState = { ...this.lineCopyState, [lineIndex]: true };
this.requestUpdate(); // LitElement에 UI 업데이트 요청
// 기존 타임아웃이 있다면 초기화
if (this.lineCopyTimeouts && this.lineCopyTimeouts[lineIndex]) {
clearTimeout(this.lineCopyTimeouts[lineIndex]);
}
// ✨ 수정된 타임아웃: 1.5초 후 '복사됨' 상태 해제
this.lineCopyTimeouts[lineIndex] = setTimeout(() => {
const updatedState = { ...this.lineCopyState };
delete updatedState[lineIndex];
this.lineCopyState = updatedState;
this.requestUpdate(); // UI 업데이트 요청
}, 1500);
} catch (err) {
console.error('Failed to copy line:', err);
}
}
async handleSendText(e, overridingText = '') {
const textInput = this.shadowRoot?.getElementById('textInput');
const text = (overridingText || textInput?.value || '').trim();
// if (!text) return;
textInput.value = '';
if (window.api) {
window.api.askView.sendMessage(text).catch(error => {
console.error('Error sending text:', error);
});
}
}
handleTextKeydown(e) {
// Fix for IME composition issue: Ignore Enter key presses while composing.
if (e.isComposing) {
return;
}
const isPlainEnter = e.key === 'Enter' && !e.shiftKey && !e.metaKey && !e.ctrlKey;
const isModifierEnter = e.key === 'Enter' && (e.metaKey || e.ctrlKey);
if (isPlainEnter || isModifierEnter) {
e.preventDefault();
this.handleSendText();
}
}
updated(changedProperties) {
super.updated(changedProperties);
// ✨ isLoading 또는 currentResponse가 변경될 때마다 뷰를 다시 그립니다.
if (changedProperties.has('isLoading') || changedProperties.has('currentResponse')) {
this.renderContent();
}
if (changedProperties.has('showTextInput') || changedProperties.has('isLoading') || changedProperties.has('currentResponse')) {
this.adjustWindowHeightThrottled();
}
if (changedProperties.has('showTextInput') && this.showTextInput) {
this.focusTextInput();
}
}
firstUpdated() {
setTimeout(() => this.adjustWindowHeight(), 200);
}
getTruncatedQuestion(question, maxLength = 30) {
if (!question) return '';
if (question.length <= maxLength) return question;
return question.substring(0, maxLength) + '...';
}
render() {
const hasResponse = this.isLoading || this.currentResponse || this.isStreaming;
const headerText = this.isLoading ? 'Thinking...' : 'AI Response';
return html`
`;
}
// Dynamically resize the BrowserWindow to fit current content
adjustWindowHeight() {
if (!window.api) return;
this.updateComplete.then(() => {
const headerEl = this.shadowRoot.querySelector('.response-header');
const responseEl = this.shadowRoot.querySelector('.response-container');
const inputEl = this.shadowRoot.querySelector('.text-input-container');
if (!headerEl || !responseEl) return;
const headerHeight = headerEl.classList.contains('hidden') ? 0 : headerEl.offsetHeight;
const responseHeight = responseEl.scrollHeight;
const inputHeight = (inputEl && !inputEl.classList.contains('hidden')) ? inputEl.offsetHeight : 0;
const idealHeight = headerHeight + responseHeight + inputHeight;
const targetHeight = Math.min(700, idealHeight);
window.api.askView.adjustWindowHeight("ask", targetHeight);
}).catch(err => console.error('AskView adjustWindowHeight error:', err));
}
// Throttled wrapper to avoid excessive IPC spam (executes at most once per animation frame)
adjustWindowHeightThrottled() {
if (this.isThrottled) return;
this.isThrottled = true;
requestAnimationFrame(() => {
this.adjustWindowHeight();
this.isThrottled = false;
});
}
}
customElements.define('ask-view', AskView);
================================================
FILE: src/ui/assets/smd.js
================================================
/*
Streaming Markdown Parser and Renderer
MIT License
Copyright 2024 Damian Tarnawski
https://github.com/thetarnav/streaming-markdown
*/
export const
DOCUMENT = 1,
PARAGRAPH = 2,
HEADING_1 = 3,
HEADING_2 = 4,
HEADING_3 = 5,
HEADING_4 = 6,
HEADING_5 = 7,
HEADING_6 = 8,
CODE_BLOCK = 9,
CODE_FENCE = 10,
CODE_INLINE = 11,
ITALIC_AST = 12,
ITALIC_UND = 13,
STRONG_AST = 14,
STRONG_UND = 15,
STRIKE = 16,
LINK = 17,
RAW_URL = 18,
IMAGE = 19,
BLOCKQUOTE = 20,
LINE_BREAK = 21,
RULE = 22,
LIST_UNORDERED = 23,
LIST_ORDERED = 24,
LIST_ITEM = 25,
CHECKBOX = 26,
TABLE = 27,
TABLE_ROW = 28,
TABLE_CELL = 29,
EQUATION_BLOCK = 30,
EQUATION_INLINE = 31,
NEWLINE = 101,
MAYBE_URL = 102,
MAYBE_TASK = 103,
MAYBE_BR = 104,
MAYBE_EQ_BLOCK = 105
/** @enum {(typeof Token)[keyof typeof Token]} */
export const Token = /** @type {const} */({
Document: DOCUMENT,
Blockquote: BLOCKQUOTE,
Paragraph: PARAGRAPH,
Heading_1: HEADING_1,
Heading_2: HEADING_2,
Heading_3: HEADING_3,
Heading_4: HEADING_4,
Heading_5: HEADING_5,
Heading_6: HEADING_6,
Code_Block: CODE_BLOCK,
Code_Fence: CODE_FENCE,
Code_Inline: CODE_INLINE,
Italic_Ast: ITALIC_AST,
Italic_Und: ITALIC_UND,
Strong_Ast: STRONG_AST,
Strong_Und: STRONG_UND,
Strike: STRIKE,
Link: LINK,
Raw_URL: RAW_URL,
Image: IMAGE,
Line_Break: LINE_BREAK,
Rule: RULE,
List_Unordered: LIST_UNORDERED,
List_Ordered: LIST_ORDERED,
List_Item: LIST_ITEM,
Checkbox: CHECKBOX,
Table: TABLE,
Table_Row: TABLE_ROW,
Table_Cell: TABLE_CELL,
Equation_Block: EQUATION_BLOCK,
Equation_Inline:EQUATION_INLINE,
})
/**
* @param {Token} type
* @returns {string } */
export function token_to_string(type) {
switch (type) {
case DOCUMENT: return "Document"
case BLOCKQUOTE: return "Blockquote"
case PARAGRAPH: return "Paragraph"
case HEADING_1: return "Heading_1"
case HEADING_2: return "Heading_2"
case HEADING_3: return "Heading_3"
case HEADING_4: return "Heading_4"
case HEADING_5: return "Heading_5"
case HEADING_6: return "Heading_6"
case CODE_BLOCK: return "Code_Block"
case CODE_FENCE: return "Code_Fence"
case CODE_INLINE: return "Code_Inline"
case ITALIC_AST: return "Italic_Ast"
case ITALIC_UND: return "Italic_Und"
case STRONG_AST: return "Strong_Ast"
case STRONG_UND: return "Strong_Und"
case STRIKE: return "Strike"
case LINK: return "Link"
case RAW_URL: return "Raw URL"
case IMAGE: return "Image"
case LINE_BREAK: return "Line_Break"
case RULE: return "Rule"
case LIST_UNORDERED: return "List_Unordered"
case LIST_ORDERED: return "List_Ordered"
case LIST_ITEM: return "List_Item"
case CHECKBOX: return "Checkbox"
case TABLE: return "Table"
case TABLE_ROW: return "Table_Row"
case TABLE_CELL: return "Table_Cell"
case EQUATION_BLOCK: return "Equation_Block"
case EQUATION_INLINE:return "Equation_Inline"
}
}
export const
HREF = 1,
SRC = 2,
LANG = 4,
CHECKED = 8,
START = 16
/** @enum {(typeof Attr)[keyof typeof Attr]} */
export const Attr = /** @type {const} */({
Href : HREF,
Src : SRC,
Lang : LANG,
Checked: CHECKED,
Start : START,
})
/**
* @param {Attr} type
* @returns {string } */
export function attr_to_html_attr(type) {
switch (type) {
case HREF: return "href"
case SRC : return "src"
case LANG: return "class"
case CHECKED: return "checked"
case START: return "start"
}
}
/**
* @param {number} level
* @returns {Token } */
export const level_to_heading = (level) => {
switch (level) {
case 1: return HEADING_1
case 2: return HEADING_2
case 3: return HEADING_3
case 4: return HEADING_4
case 5: return HEADING_5
default: return HEADING_6
}
}
export const heading_from_level = level_to_heading
/**
* @param {Token} token
* @returns {number} */
export const heading_to_level = (token) => {
switch (token) {
case HEADING_1: return 1
case HEADING_2: return 2
case HEADING_3: return 3
case HEADING_4: return 4
case HEADING_5: return 5
case HEADING_6: return 6
default: return 0
}
}
/**
* @typedef {object } Parser
* @property {Any_Renderer} renderer - {@link Renderer} interface
* @property {string } text - Text to be added to the last token in the next flush
* @property {string } pending - Characters for identifying tokens
* @property {Uint32Array } tokens - Current token and it's parents (a slice of a tree)
* @property {number } len - Number of tokens in types without root
* @property {number } token - Last token in the tree
* @property {Uint8Array } spaces
* @property {string } indent
* @property {number } indent_len
* @property {number } fence_end - For {@link Token.Code_Fence} parsing
* @property {number } fence_start
* @property {number } blockquote_idx - For Blockquote parsing
* @property {string } hr_char - For horizontal rule parsing
* @property {number } hr_chars - For horizontal rule parsing
* @property {number } table_state
*/
const TOKEN_ARRAY_CAP = 24
/**
* Makes a new Parser object.
* @param {Any_Renderer} renderer
* @returns {Parser } */
export function parser(renderer) {
const tokens = new Uint32Array(TOKEN_ARRAY_CAP)
tokens[0] = DOCUMENT
return {
renderer : renderer,
text : "",
pending : "",
tokens : tokens,
len : 0,
token : DOCUMENT,
fence_end: 0,
blockquote_idx: 0,
hr_char : '',
hr_chars : 0,
fence_start: 0,
spaces : new Uint8Array(TOKEN_ARRAY_CAP),
indent : "",
indent_len : 0,
table_state: 0,
}
}
/**
* Finish rendering the markdown - flushes any remaining text.
* @param {Parser} p
* @returns {void } */
export function parser_end(p) {
if (p.pending.length > 0) {
parser_write(p, "\n")
}
}
/**
* @param {Parser} p
* @returns {void } */
function add_text(p) {
if (p.text.length === 0) return
console.assert(p.len > 0, "Never adding text to root")
p.renderer.add_text(p.renderer.data, p.text)
p.text = ""
}
/**
* @param {Parser} p
* @returns {void } */
function ensure_paragraph(p) {
switch (p.token) {
case LINE_BREAK:
case DOCUMENT:
case BLOCKQUOTE:
case LIST_ORDERED:
case LIST_UNORDERED:
add_token(p, PARAGRAPH)
}
}
/**
* @param {Parser} p
* @param {string} text
* @returns {void } */
function push_text(p, text) {
ensure_paragraph(p)
p.text += text
}
/**
* @param {Parser} p
* @returns {void } */
function end_token(p) {
console.assert(p.len > 0, "No nodes to end")
p.len -= 1
p.token = /** @type {Token} */ (p.tokens[p.len])
p.renderer.end_token(p.renderer.data)
}
/**
* @param {Parser} p
* @param {Token } token
* @returns {void } */
function add_token(p, token) {
/*
If a list doesn't start with a list item
it means that there was a newline after the list:
1. foo
2. bar
<- new token
*/
if ((p.tokens[p.len] === LIST_ORDERED || p.tokens[p.len] === LIST_UNORDERED) &&
token !== LIST_ITEM
) {
end_token(p)
}
p.len += 1
p.tokens[p.len] = token
p.token = token
p.renderer.add_token(p.renderer.data, token)
}
/**
* @param {Parser} p
* @param {number} token
* @param {number} start_idx
* @returns {number} */
function idx_of_token(p, token, start_idx) {
while (start_idx <= p.len) {
if (p.tokens[start_idx] === token) {
return start_idx
}
start_idx += 1
}
return -1
}
/**
* End tokens until the parser has the given length.
* @param {Parser} p
* @param {number} len
* @returns {void } */
function end_tokens_to_len(p, len) {
// TODO: specific token state should be reset only when the token ends
p.fence_start = 0
while (p.len > len) {
end_token(p)
}
}
/**
* @param {Parser} p
* @param {number} indent
* @returns {number} */
function end_tokens_to_indent(p, indent) {
let idx = 0
for (let i = 0; i <= p.len; i += 1) {
indent -= p.spaces[i]
if (indent < 0) {
break
}
switch (p.tokens[i]) {
case CODE_BLOCK:
case CODE_FENCE:
case BLOCKQUOTE:
case LIST_ITEM:
idx = i
break
}
}
while (p.len > idx) {end_token(p)}
return indent
}
/**
* @param {Parser } p
* @param {Token } list_token
* @returns {boolean} added a new list */
function continue_or_add_list(p, list_token) {
/* will create a new list inside the last item
if the amount of spaces is greater than the last one (with prefix)
1. foo
- bar <- new nested ul
- baz <- new nested ul
12. qux <- cannot be nested in "baz" or "bar",
so it's a new list in "foo"
*/
let list_idx = -1
let item_idx = -1
for (let i = p.blockquote_idx+1; i <= p.len; i += 1) {
if (p.tokens[i] === LIST_ITEM) {
if (p.indent_len < p.spaces[i]) {
item_idx = -1
break
}
item_idx = i
} else if (p.tokens[i] === list_token) {
list_idx = i
}
}
if (item_idx === -1) {
if (list_idx === -1) {
end_tokens_to_len(p, p.blockquote_idx)
add_token(p, list_token)
return true
}
end_tokens_to_len(p, list_idx)
return false
}
end_tokens_to_len(p, item_idx)
add_token(p, list_token)
return true
}
/**
* Create a new list
* or continue the last one
* @param {Parser } p
* @param {number } prefix_length
* @returns {void } */
function add_list_item(p, prefix_length) {
add_token(p, LIST_ITEM)
p.spaces[p.len] = p.indent_len + prefix_length
clear_root_pending(p)
p.token = MAYBE_TASK
}
/**
* @param {Parser} p
* @returns {void } */
function clear_root_pending(p) {
p.indent = ""
p.indent_len = 0
p.pending = ""
}
/**
* @param {number} charcode
* @returns {boolean} */
function is_digit(charcode) {
switch (charcode) {
case 48: case 49: case 50: case 51: case 52:
case 53: case 54: case 55: case 56: case 57:
return true
default:
return false
}
}
/**
* @param {number} charcode
* @returns {boolean} */
function is_delimeter(charcode) {
switch (charcode) {
// " " ":" ";" ")" "," "!" "." "?" "]" "\n"
case 32: case 58: case 59: case 41: case 44: case 33: case 46: case 63: case 93: case 10:
return true
default:
return false
}
}
/**
* @param {number} charcode
* @returns {boolean} */
function is_delimeter_or_number(charcode) {
return is_digit(charcode) || is_delimeter(charcode)
}
/**
* @param {number} charcode
* @returns {boolean} */
function is_alnum(charcode) {
return is_digit(charcode) || // 0-9
(charcode >= 65 && charcode <= 90) || // A-Z
(charcode >= 97 && charcode <= 122) // a-z
}
/**
* Parse and render another chunk of markdown.
* @param {Parser} p
* @param {string} chunk
* @returns {void } */
export function parser_write(p, chunk) {
for (const char of chunk) {
/*
Handle newlines
*/
if (p.token === NEWLINE) {
switch (char) {
case ' ':
p.indent_len += 1
continue
case '\t':
p.indent_len += 4
continue
}
let indent = end_tokens_to_indent(p, p.indent_len)
p.indent_len = 0
p.token = p.tokens[p.len]
if (indent > 0) {
parser_write(p, " ".repeat(indent))
}
}
const pending_with_char = p.pending + char
/*
Token specific checks
*/
switch (p.token) {
case LINE_BREAK:
case DOCUMENT:
case BLOCKQUOTE:
case LIST_ORDERED:
case LIST_UNORDERED:
console.assert(p.text.length === 0, "Root should not have any text")
switch (p.pending[0]) {
case undefined:
p.pending = char
continue
case ' ':
console.assert(p.pending.length === 1)
p.pending = char
p.indent += ' '
p.indent_len += 1
continue
case '\t':
console.assert(p.pending.length === 1)
p.pending = char
p.indent += '\t'
p.indent_len += 4
continue
case '\n':
console.assert(p.pending.length === 1)
/*
Lists can have an empty line in between items:
1. foo
2. bar
*/
if (p.tokens[p.len] === LIST_ITEM && p.token === LINE_BREAK) {
end_token(p)
clear_root_pending(p)
p.pending = char
continue
}
/*
Exit out of tokens
And ignore newlines in root
*/
end_tokens_to_len(p, p.blockquote_idx)
clear_root_pending(p)
p.blockquote_idx = 0
p.fence_start = 0
p.pending = char
continue
/* Heading */
case '#':
switch (char) {
case '#':
if (p.pending.length < 6) {
p.pending = pending_with_char
continue
}
break // fail
case ' ':
end_tokens_to_indent(p, p.indent_len)
add_token(p, heading_from_level(p.pending.length))
clear_root_pending(p)
continue
}
break // fail
/* Blockquote */
case '>': {
const next_blockquote_idx = idx_of_token(p, BLOCKQUOTE, p.blockquote_idx+1)
/*
Only when there is no blockquote to the right of blockquote_idx
a new blockquote can be created
*/
if (next_blockquote_idx === -1) {
end_tokens_to_len(p, p.blockquote_idx)
p.blockquote_idx += 1
p.fence_start = 0
add_token(p, BLOCKQUOTE)
} else {
p.blockquote_idx = next_blockquote_idx
}
clear_root_pending(p)
p.pending = char
continue
}
/* Horizontal Rule
"-- - --- - --"
*/
case '-':
case '*':
case '_':
if (p.hr_chars === 0) {
console.assert(p.pending.length === 1, "Pending should be one character")
p.hr_chars = 1
p.hr_char = p.pending
}
if (p.hr_chars > 0) {
switch (char) {
case p.hr_char:
p.hr_chars += 1
p.pending = pending_with_char
continue
case ' ':
p.pending = pending_with_char
continue
case '\n':
if (p.hr_chars < 3) break
end_tokens_to_indent(p, p.indent_len)
p.renderer.add_token(p.renderer.data, RULE)
p.renderer.end_token(p.renderer.data)
clear_root_pending(p)
p.hr_chars = 0
continue
}
p.hr_chars = 0
}
/* Unordered list
/ * foo
/ * *bar*
/ * **baz**
/*/
if ('_' !== p.pending[0] &&
' ' === p.pending[1]
) {
continue_or_add_list(p, LIST_UNORDERED)
add_list_item(p, 2)
parser_write(p, pending_with_char.slice(2))
continue
}
break // fail
/* Code Fence */
case '`':
/* ``?
^
*/
if (p.pending.length < 3) {
if ('`' === char) {
p.pending = pending_with_char
p.fence_start = pending_with_char.length
continue
}
p.fence_start = 0
break // fail
}
switch (char) {
case '`':
/* ````?
^
*/
if (p.pending.length === p.fence_start) {
p.pending = pending_with_char
p.fence_start = pending_with_char.length
}
/* ```code`
^
*/
else {
add_token(p, PARAGRAPH)
clear_root_pending(p)
p.fence_start = 0
parser_write(p, pending_with_char)
}
continue
case '\n': {
/* ```lang\n
^
*/
end_tokens_to_indent(p, p.indent_len)
add_token(p, CODE_FENCE)
if (p.pending.length > p.fence_start) {
p.renderer.set_attr(p.renderer.data, LANG, p.pending.slice(p.fence_start))
}
clear_root_pending(p)
p.token = NEWLINE
continue
}
default:
/* ```lang\n
^
*/
p.pending = pending_with_char
continue
}
/*
List Unordered for '+'
The other list types are handled with HORIZONTAL_RULE
*/
case '+':
if (' ' !== char) break // fail
continue_or_add_list(p, LIST_UNORDERED)
add_list_item(p, 2)
continue
/* List Ordered */
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
/*
12. foo
^
*/
if ('.' === p.pending[p.pending.length-1]) {
if (' ' !== char) break // fail
if (continue_or_add_list(p, LIST_ORDERED) && p.pending !== "1.") {
p.renderer.set_attr(p.renderer.data, START, p.pending.slice(0, -1))
}
add_list_item(p, p.pending.length+1)
continue
} else {
const char_code = char.charCodeAt(0)
if (46 === char_code || // '.'
is_digit(char_code) // 0-9
) {
p.pending = pending_with_char
continue
}
}
break // fail
/* Table */
case '|':
end_tokens_to_len(p, p.blockquote_idx)
add_token(p, TABLE)
add_token(p, TABLE_ROW)
p.pending = ""
parser_write(p, char)
continue
}
let to_write = pending_with_char
/* Add a line break and continue in previous token */
if (p.token === LINE_BREAK) {
p.token = p.tokens[p.len]
p.renderer.add_token(p.renderer.data, LINE_BREAK)
p.renderer.end_token(p.renderer.data)
}
/* Code Block */
else if (p.indent_len >= 4) {
/*
Case where there are additional spaces
after the indent that makes the code block
_________________________
code
^^^^----indent
^^^-part of code
_________________________
\t code
^^-----indent
^^^-part of code
*/
let code_start = 0
for (; code_start < 4; code_start += 1) {
if (p.indent[code_start] === '\t') {
code_start = code_start+1
break
}
}
to_write = p.indent.slice(code_start) + pending_with_char
add_token(p, CODE_BLOCK)
}
/* Paragraph */
else {
add_token(p, PARAGRAPH)
}
clear_root_pending(p)
parser_write(p, to_write)
continue
case TABLE:
if (p.table_state === 1) {
switch (char) {
case '-':
case ' ':
case '|':
case ':':
p.pending = pending_with_char
continue
case '\n':
p.table_state = 2
p.pending = ""
continue
default:
end_token(p)
p.table_state = 0
break
}
} else {
switch (p.pending) {
case "|":
add_token(p, TABLE_ROW)
p.pending = ""
parser_write(p, char)
continue
case "\n":
end_token(p)
p.pending = ""
p.table_state = 0
parser_write(p, char)
continue
}
}
break
case TABLE_ROW:
switch (p.pending) {
case "":
break
case "|":
add_token(p, TABLE_CELL)
end_token(p)
p.pending = ""
parser_write(p, char)
continue
case "\n":
end_token(p)
p.table_state = Math.min(p.table_state+1, 2)
p.pending = ""
parser_write(p, char)
continue
default:
add_token(p, TABLE_CELL)
parser_write(p, char)
continue
}
break
case TABLE_CELL:
if (p.pending === "|") {
add_text(p)
end_token(p)
p.pending = ""
parser_write(p, char)
continue
}
break
case CODE_BLOCK:
switch (pending_with_char) {
case "\n ":
case "\n \t":
case "\n \t":
case "\n \t":
case "\n\t":
p.text += "\n"
p.pending = ""
continue
case "\n":
case "\n ":
case "\n ":
case "\n ":
p.pending = pending_with_char
continue
default:
if (p.pending.length !== 0) {
add_text(p)
end_token(p)
p.pending = char
} else {
p.text += char
}
continue
}
case CODE_FENCE:
switch (char) {
case '`':
/* ```\n\n``??
| ^
*/
p.pending = pending_with_char
continue
case '\n':
/* ```\n\n```\n
| ^
*/
if (pending_with_char.length === p.fence_start + p.fence_end + 1) {
add_text(p)
end_token(p)
p.pending = ""
p.fence_start = 0
p.fence_end = 0
p.token = NEWLINE
continue
}
p.token = NEWLINE
break
case ' ':
/* ```\n\n ??
| ^ (space after newline is allowed)
*/
if (p.pending[0] === '\n') {
p.pending = pending_with_char
p.fence_end += 1
continue
}
break
}
// any other char
p.text += p.pending
p.pending = char
p.fence_end = 1
continue
case CODE_INLINE:
switch (char) {
case '`':
if (pending_with_char.length ===
p.fence_start + Number(p.pending[0] === ' ') // 0 or 1 for space
) {
add_text(p)
end_token(p)
p.pending = ""
p.fence_start = 0
} else {
p.pending = pending_with_char
}
continue
case '\n':
p.text += p.pending
p.pending = ""
p.token = LINE_BREAK
p.blockquote_idx = 0
add_text(p)
continue
/* Trim space before ` */
case ' ':
p.text += p.pending
p.pending = char
continue
default:
p.text += pending_with_char
p.pending = ""
continue
}
/* Checkboxes */
case MAYBE_TASK:
switch (p.pending.length) {
case 0:
if ('[' !== char) break // fail
p.pending = pending_with_char
continue
case 1:
if (' ' !== char && 'x' !== char) break // fail
p.pending = pending_with_char
continue
case 2:
if (']' !== char) break // fail
p.pending = pending_with_char
continue
case 3:
if (' ' !== char) break // fail
p.renderer.add_token(p.renderer.data, CHECKBOX)
if ('x' === p.pending[1]) {
p.renderer.set_attr(p.renderer.data, CHECKED, "")
}
p.renderer.end_token(p.renderer.data)
p.pending = " "
continue
}
p.token = p.tokens[p.len]
p.pending = ""
parser_write(p, pending_with_char)
continue
case STRONG_AST:
case STRONG_UND: {
/** @type {string} */ let symbol = '*'
/** @type {Token } */ let italic = ITALIC_AST
if (p.token === STRONG_UND) {
symbol = '_'
italic = ITALIC_UND
}
if (symbol === p.pending) {
add_text(p)
/* **Bold**
^
*/
if (symbol === char) {
end_token(p)
p.pending = ""
continue
}
/* **Bold*Bold->Em*
^
*/
add_token(p, italic)
p.pending = char
continue
}
break
}
case ITALIC_AST:
case ITALIC_UND: {
/** @type {string} */ let symbol = '*'
/** @type {Token } */ let strong = STRONG_AST
if (p.token === ITALIC_UND) {
symbol = '_'
strong = STRONG_UND
}
switch (p.pending) {
case symbol:
if (symbol === char) {
/* Decide between ***bold>em**em* and **bold*bold>em***
^ ^
With the help of the next character
*/
if (p.tokens[p.len-1] === strong) {
p.pending = pending_with_char
}
/* *em**bold
^
*/
else {
add_text(p)
add_token(p, strong)
p.pending = ""
}
}
/* *em*foo
^
*/
else {
add_text(p)
end_token(p)
p.pending = char
}
continue
case symbol+symbol:
const italic = p.token
add_text(p)
end_token(p)
end_token(p)
/* ***bold>em**em* or **bold*bold>em***
^ ^
*/
if (symbol !== char) {
add_token(p, italic)
p.pending = char
} else {
p.pending = ""
}
continue
}
break
}
case STRIKE:
if ("~~" === pending_with_char) {
add_text(p)
end_token(p)
p.pending = ""
continue
}
break
case MAYBE_EQ_BLOCK:
/*
\[? or $$?
^ ^
*/
if (char === '\n') {
add_text(p)
add_token(p, EQUATION_BLOCK)
p.pending = ""
} else {
p.token = p.tokens[p.len]
if (p.pending[0] === '\\') {
p.text += '['
} else {
p.text += '$$'
}
p.pending = ""
parser_write(p, char)
}
continue
case EQUATION_BLOCK:
if ("\\]" === pending_with_char || "$$" === pending_with_char) {
add_text(p)
end_token(p)
p.pending = ""
continue
}
break
case EQUATION_INLINE:
if ("\\)" === pending_with_char || "$" === p.pending[0]) {
add_text(p)
end_token(p)
if(char === ')'){
p.pending = ""
} else {
p.pending = char
}
continue
}
break
/* Raw URLs */
case MAYBE_URL:
if ("http://" === pending_with_char ||
"https://" === pending_with_char
) {
add_text(p)
add_token(p, RAW_URL)
p.pending = pending_with_char
p.text = pending_with_char
}
else
if ("http:/" [p.pending.length] === char ||
"https:/"[p.pending.length] === char
) {
p.pending = pending_with_char
}
else {
p.token = p.tokens[p.len]
parser_write(p, char)
}
continue
case LINK:
case IMAGE:
if ("]" === p.pending) {
/*
[Link](url)
^
*/
add_text(p)
if ('(' === char) {
p.pending = pending_with_char
} else {
end_token(p)
p.pending = char
}
continue
}
if (']' === p.pending[0] &&
'(' === p.pending[1]
) {
/*
[Link](url)
^
*/
if (')' === char) {
const type = p.token === LINK ? HREF : SRC
const url = p.pending.slice(2)
p.renderer.set_attr(p.renderer.data, type, url)
end_token(p)
p.pending = ""
} else {
p.pending += char
}
continue
}
break
case RAW_URL:
/* http://example.com?
^
*/
if (' ' === char ||
'\n'=== char ||
'\\'=== char
) {
p.renderer.set_attr(p.renderer.data, HREF, p.pending)
add_text(p)
end_token(p)
p.pending = char
} else {
p.text += char
p.pending = pending_with_char
}
continue
case MAYBE_BR:
if (pending_with_char.startsWith(" " | " " */
if (char === '>') {
add_text(p)
p.token = p.tokens[p.len]
p.renderer.add_token(p.renderer.data, LINE_BREAK)
p.renderer.end_token(p.renderer.data)
p.pending = ""
continue
}
}
// Fail
p.token = p.tokens[p.len]
p.text += '<'
p.pending = p.pending.slice(1)
parser_write(p, char)
continue
}
/*
Common checks
*/
switch (p.pending[0]) {
/* Escape character */
case '\\':
if (p.token === IMAGE ||
p.token === EQUATION_BLOCK ||
p.token === EQUATION_INLINE)
break
switch (char) {
case '(':
add_text(p)
add_token(p, EQUATION_INLINE)
p.pending = ""
continue
case '[':
p.token = MAYBE_EQ_BLOCK
p.pending = pending_with_char
continue
case '\n':
// Escaped newline has the same affect as unescaped one
p.pending = char
continue
default:
let charcode = char.charCodeAt(0)
p.pending = ""
p.text += is_digit(charcode) || // 0-9
(charcode >= 65 && charcode <= 90) || // A-Z
(charcode >= 97 && charcode <= 122) // a-z
? pending_with_char
: char
continue
}
/* Newline */
case '\n':
switch (p.token) {
case IMAGE:
case EQUATION_BLOCK:
case EQUATION_INLINE:
break
case HEADING_1:
case HEADING_2:
case HEADING_3:
case HEADING_4:
case HEADING_5:
case HEADING_6:
add_text(p)
end_tokens_to_len(p, p.blockquote_idx)
p.blockquote_idx = 0
p.pending = char
continue
default:
add_text(p)
p.pending = char
p.token = LINE_BREAK
p.blockquote_idx = 0
continue
}
break
/* */
case '<':
if (p.token !== IMAGE &&
p.token !== EQUATION_BLOCK &&
p.token !== EQUATION_INLINE
) {
add_text(p)
p.pending = pending_with_char
p.token = MAYBE_BR
continue
}
break
/* `Code Inline` */
case '`':
if (p.token === IMAGE) break
if ('`' === char) {
p.fence_start += 1
p.pending = pending_with_char
} else {
p.fence_start += 1 // started at 0, and first wasn't counted
add_text(p)
add_token(p, CODE_INLINE)
p.text = ' ' === char || '\n' === char ? "" : char // trim leading space
p.pending = ""
}
continue
case '_':
case '*': {
if (p.token === IMAGE ||
p.token === EQUATION_BLOCK ||
p.token === EQUATION_INLINE ||
p.token === STRONG_AST)
break
/** @type {Token} */ let italic = ITALIC_AST
/** @type {Token} */ let strong = STRONG_AST
const symbol = p.pending[0]
if ('_' === symbol) {
italic = ITALIC_UND
strong = STRONG_UND
}
if (p.pending.length === 1) {
/* **Strong**
^
*/
if (symbol === char) {
p.pending = pending_with_char
continue
}
/* *Em*
^
*/
if (' ' !== char && '\n' !== char) {
add_text(p)
add_token(p, italic)
p.pending = char
continue
}
} else {
/* ***Strong->Em***
^
*/
if (symbol === char) {
add_text(p)
add_token(p, strong)
add_token(p, italic)
p.pending = ""
continue
}
/* **Strong**
^
*/
if (' ' !== char && '\n' !== char) {
add_text(p)
add_token(p, strong)
p.pending = char
continue
}
}
break
}
case '~':
if (p.token !== IMAGE &&
p.token !== STRIKE
) {
if ("~" === p.pending) {
/* ~~Strike~~
^
*/
if ('~' === char) {
p.pending = pending_with_char
continue
}
} else {
/* ~~Strike~~
| ^
*/
if (' ' !== char && '\n' !== char) {
add_text(p)
add_token(p, STRIKE)
p.pending = char
continue
}
}
}
break
/* $eq$ | $$eq$$ */
case '$':
if (p.token !== IMAGE &&
p.token !== STRIKE &&
"$" === p.pending
) {
/* $$EQUATION_BLOCK$$
^
*/
if ('$' === char) {
p.token = MAYBE_EQ_BLOCK
p.pending = pending_with_char
continue
}
/* $123
^
*/
else if (is_delimeter_or_number(char.charCodeAt(0))) {
break
}
/* $EQUATION_INLINE$
^
*/
else {
add_text(p)
add_token(p, EQUATION_INLINE)
p.pending = char
continue
}
}
break
/* [Image](url) */
case '[':
if (p.token !== IMAGE &&
p.token !== LINK &&
p.token !== EQUATION_BLOCK &&
p.token !== EQUATION_INLINE &&
']' !== char
) {
add_text(p)
add_token(p, LINK)
p.pending = char
continue
}
break
/*  */
case '!':
if (!(p.token === IMAGE) &&
'[' === char
) {
add_text(p)
add_token(p, IMAGE)
p.pending = ""
continue
}
break
/* Trim spaces */
case ' ':
if (p.pending.length === 1 && ' ' === char) {
continue
}
break
}
/* foo http://...
| ^
*/
if (p.token !== IMAGE &&
p.token !== LINK &&
p.token !== EQUATION_BLOCK &&
p.token !== EQUATION_INLINE &&
'h' === char &&
(" " === p.pending ||
"" === p.pending)
) {
p.text += p.pending
p.pending = char
p.token = MAYBE_URL
continue
}
/*
No check hit
*/
p.text += p.pending
p.pending = char
}
add_text(p)
}
/**
* @template T
* @callback Renderer_Add_Token
* @param {T } data
* @param {Token} type
* @returns {void } */
/**
* @template T
* @callback Renderer_End_Token
* @param {T } data
* @returns {void } */
/**
* @template T
* @callback Renderer_Add_Text
* @param {T } data
* @param {string} text
* @returns {void } */
/**
* @template T
* @callback Renderer_Set_Attr
* @param {T } data
* @param {Attr } type
* @param {string} value
* @returns {void } */
/**
* The renderer interface.
* @template T
* @typedef {object } Renderer
* @property {T } data User data object. Available as first param in callbacks.
* @property {Renderer_Add_Token} add_token When the tokens starts.
* @property {Renderer_End_Token} end_token When the token ends.
* @property {Renderer_Add_Text } add_text To append text to current token. Can be called multiple times or none.
* @property {Renderer_Set_Attr } set_attr Set additional attributes of current token eg. the link url.
*/
/** @typedef {Renderer} Any_Renderer */
/**
* @typedef {object} Default_Renderer_Data
* @property {HTMLElement[]} nodes
* @property {number } index
*
* @typedef {Renderer } Default_Renderer
* @typedef {Renderer_Add_Token} Default_Renderer_Add_Token
* @typedef {Renderer_End_Token} Default_Renderer_End_Token
* @typedef {Renderer_Add_Text } Default_Renderer_Add_Text
* @typedef {Renderer_Set_Attr } Default_Renderer_Set_Attr
*/
/**
* @param {HTMLElement } root
* @returns {Default_Renderer} */
export function default_renderer(root) {
return {
add_token: default_add_token,
end_token: default_end_token,
add_text: default_add_text,
set_attr: default_set_attr,
data : {
nodes: /**@type {*}*/([root,,,,,]),
index: 0,
},
}
}
/** @type {Default_Renderer_Add_Token} */
export function default_add_token(data, type) {
/**@type {Element}*/ let parent = data.nodes[data.index]
/**@type {HTMLElement}*/ let slot
switch (type) {
case DOCUMENT: return // document is provided
case BLOCKQUOTE: slot = document.createElement("blockquote");break
case PARAGRAPH: slot = document.createElement("p") ;break
case LINE_BREAK: slot = document.createElement("br") ;break
case RULE: slot = document.createElement("hr") ;break
case HEADING_1: slot = document.createElement("h1") ;break
case HEADING_2: slot = document.createElement("h2") ;break
case HEADING_3: slot = document.createElement("h3") ;break
case HEADING_4: slot = document.createElement("h4") ;break
case HEADING_5: slot = document.createElement("h5") ;break
case HEADING_6: slot = document.createElement("h6") ;break
case ITALIC_AST:
case ITALIC_UND: slot = document.createElement("em") ;break
case STRONG_AST:
case STRONG_UND: slot = document.createElement("strong") ;break
case STRIKE: slot = document.createElement("s") ;break
case CODE_INLINE: slot = document.createElement("code") ;break
case RAW_URL:
case LINK: slot = document.createElement("a") ;break
case IMAGE: slot = document.createElement("img") ;break
case LIST_UNORDERED:slot = document.createElement("ul") ;break
case LIST_ORDERED: slot = document.createElement("ol") ;break
case LIST_ITEM: slot = document.createElement("li") ;break
case CHECKBOX:
let checkbox = slot = document.createElement("input")
checkbox.type = "checkbox"
checkbox.disabled = true
break
case CODE_BLOCK:
case CODE_FENCE:
parent = parent.appendChild(document.createElement("pre"))
slot = document.createElement("code")
break
case TABLE:
slot = document.createElement("table")
break
case TABLE_ROW:
switch (parent.children.length) {
case 0:
parent = parent.appendChild(document.createElement("thead"))
break
case 1:
parent = parent.appendChild(document.createElement("tbody"))
break
default:
parent = parent.children[1]
}
slot = document.createElement("tr")
break
case TABLE_CELL:
slot = document.createElement(parent.parentElement?.tagName === "THEAD" ? "th" : "td")
break
case EQUATION_BLOCK: slot = document.createElement("equation-block"); break
case EQUATION_INLINE: slot = document.createElement("equation-inline"); break
}
data.nodes[++data.index] = parent.appendChild(slot)
}
/** @type {Default_Renderer_End_Token} */
export function default_end_token(data) {
data.index -= 1
}
/** @type {Default_Renderer_Add_Text} */
export function default_add_text(data, text) {
data.nodes[data.index].appendChild(document.createTextNode(text))
}
/** @type {Default_Renderer_Set_Attr} */
export function default_set_attr(data, type, value) {
data.nodes[data.index].setAttribute(attr_to_html_attr(type), value)
}
/**
* @typedef {undefined} Logger_Renderer_Data
*
* @typedef {Renderer } Logger_Renderer
* @typedef {Renderer_Add_Token} Logger_Renderer_Add_Token
* @typedef {Renderer_End_Token} Logger_Renderer_End_Token
* @typedef {Renderer_Add_Text } Logger_Renderer_Add_Text
* @typedef {Renderer_Set_Attr } Logger_Renderer_Set_Attr
*/
/** @returns {Logger_Renderer} */
export function logger_renderer() {
return {
data: undefined,
add_token: logger_add_token,
end_token: logger_end_token,
add_text: logger_add_text,
set_attr: logger_set_attr,
}
}
/** @type {Logger_Renderer_Add_Token} */
export function logger_add_token(data, type) {
console.log("add_token:", token_to_string(type))
}
/** @type {Logger_Renderer_End_Token} */
export function logger_end_token(data) {
console.log("end_token")
}
/** @type {Logger_Renderer_Add_Text} */
export function logger_add_text(data, text) {
console.log('add_text: "%s"', text)
}
/** @type {Logger_Renderer_Set_Attr} */
export function logger_set_attr(data, type, value) {
console.log('set_attr: %s="%s"', attr_to_html_attr(type), value)
}
================================================
FILE: src/ui/listen/ListenView.js
================================================
import { html, css, LitElement } from '../assets/lit-core-2.7.4.min.js';
import './stt/SttView.js';
import './summary/SummaryView.js';
export class ListenView extends LitElement {
static styles = css`
:host {
display: block;
width: 400px;
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
transition: transform 0.2s cubic-bezier(0.23, 1, 0.32, 1), opacity 0.2s ease-out;
will-change: transform, opacity;
}
:host(.hiding) {
animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.6, 1) forwards;
}
:host(.showing) {
animation: slideDown 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}
:host(.hidden) {
opacity: 0;
transform: translateY(-150%) scale(0.85);
pointer-events: none;
}
* {
font-family: 'Helvetica Neue', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
cursor: default;
user-select: none;
}
/* Allow text selection in insights responses */
.insights-container, .insights-container *, .markdown-content {
user-select: text !important;
cursor: text !important;
}
/* highlight.js 스타일 추가 */
.insights-container pre {
background: rgba(0, 0, 0, 0.4) !important;
border-radius: 8px !important;
padding: 12px !important;
margin: 8px 0 !important;
overflow-x: auto !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
}
.insights-container code {
font-family: 'Monaco', 'Menlo', 'Consolas', monospace !important;
font-size: 11px !important;
background: transparent !important;
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
}
.insights-container pre code {
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
display: block !important;
}
.insights-container p code {
background: rgba(255, 255, 255, 0.1) !important;
padding: 2px 4px !important;
border-radius: 3px !important;
color: #ffd700 !important;
}
.hljs-keyword {
color: #ff79c6 !important;
}
.hljs-string {
color: #f1fa8c !important;
}
.hljs-comment {
color: #6272a4 !important;
}
.hljs-number {
color: #bd93f9 !important;
}
.hljs-function {
color: #50fa7b !important;
}
.hljs-title {
color: #50fa7b !important;
}
.hljs-variable {
color: #8be9fd !important;
}
.hljs-built_in {
color: #ffb86c !important;
}
.hljs-attr {
color: #50fa7b !important;
}
.hljs-tag {
color: #ff79c6 !important;
}
.assistant-container {
display: flex;
flex-direction: column;
color: #ffffff;
box-sizing: border-box;
position: relative;
background: rgba(0, 0, 0, 0.6);
overflow: hidden;
border-radius: 12px;
width: 100%;
height: 100%;
}
.assistant-container::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 12px;
padding: 1px;
background: linear-gradient(169deg, rgba(255, 255, 255, 0.17) 0%, rgba(255, 255, 255, 0.08) 50%, rgba(255, 255, 255, 0.17) 100%);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: destination-out;
mask-composite: exclude;
pointer-events: none;
}
.assistant-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
border-radius: 12px;
z-index: -1;
}
.top-bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 16px;
min-height: 32px;
position: relative;
z-index: 1;
width: 100%;
box-sizing: border-box;
flex-shrink: 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.bar-left-text {
color: white;
font-size: 13px;
font-family: 'Helvetica Neue', sans-serif;
font-weight: 500;
position: relative;
overflow: hidden;
white-space: nowrap;
flex: 1;
min-width: 0;
max-width: 200px;
}
.bar-left-text-content {
display: inline-block;
transition: transform 0.3s ease;
}
.bar-left-text-content.slide-in {
animation: slideIn 0.3s ease forwards;
}
.bar-controls {
display: flex;
gap: 4px;
align-items: center;
flex-shrink: 0;
width: 120px;
justify-content: flex-end;
box-sizing: border-box;
padding: 4px;
}
.toggle-button {
display: flex;
align-items: center;
gap: 5px;
background: transparent;
color: rgba(255, 255, 255, 0.9);
border: none;
outline: none;
box-shadow: none;
padding: 4px 8px;
border-radius: 5px;
font-size: 11px;
font-weight: 500;
cursor: pointer;
height: 24px;
white-space: nowrap;
transition: background-color 0.15s ease;
justify-content: center;
}
.toggle-button:hover {
background: rgba(255, 255, 255, 0.1);
}
.toggle-button svg {
flex-shrink: 0;
width: 12px;
height: 12px;
}
.copy-button {
background: transparent;
color: rgba(255, 255, 255, 0.9);
border: none;
outline: none;
box-shadow: none;
padding: 4px;
border-radius: 3px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
min-width: 24px;
height: 24px;
flex-shrink: 0;
transition: background-color 0.15s ease;
position: relative;
overflow: hidden;
}
.copy-button:hover {
background: rgba(255, 255, 255, 0.15);
}
.copy-button svg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
}
.copy-button .check-icon {
opacity: 0;
transform: translate(-50%, -50%) scale(0.5);
}
.copy-button.copied .copy-icon {
opacity: 0;
transform: translate(-50%, -50%) scale(0.5);
}
.copy-button.copied .check-icon {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.timer {
font-family: 'Monaco', 'Menlo', monospace;
font-size: 10px;
color: rgba(255, 255, 255, 0.7);
}
/* ────────────────[ GLASS BYPASS ]─────────────── */
:host-context(body.has-glass) .assistant-container,
:host-context(body.has-glass) .top-bar,
:host-context(body.has-glass) .toggle-button,
:host-context(body.has-glass) .copy-button,
:host-context(body.has-glass) .transcription-container,
:host-context(body.has-glass) .insights-container,
:host-context(body.has-glass) .stt-message,
:host-context(body.has-glass) .outline-item,
:host-context(body.has-glass) .request-item,
:host-context(body.has-glass) .markdown-content,
:host-context(body.has-glass) .insights-container pre,
:host-context(body.has-glass) .insights-container p code,
:host-context(body.has-glass) .insights-container pre code {
background: transparent !important;
border: none !important;
outline: none !important;
box-shadow: none !important;
filter: none !important;
backdrop-filter: none !important;
}
:host-context(body.has-glass) .assistant-container::before,
:host-context(body.has-glass) .assistant-container::after {
display: none !important;
}
:host-context(body.has-glass) .toggle-button:hover,
:host-context(body.has-glass) .copy-button:hover,
:host-context(body.has-glass) .outline-item:hover,
:host-context(body.has-glass) .request-item.clickable:hover,
:host-context(body.has-glass) .markdown-content:hover {
background: transparent !important;
transform: none !important;
}
:host-context(body.has-glass) .transcription-container::-webkit-scrollbar-track,
:host-context(body.has-glass) .transcription-container::-webkit-scrollbar-thumb,
:host-context(body.has-glass) .insights-container::-webkit-scrollbar-track,
:host-context(body.has-glass) .insights-container::-webkit-scrollbar-thumb {
background: transparent !important;
}
:host-context(body.has-glass) * {
animation: none !important;
transition: none !important;
transform: none !important;
filter: none !important;
backdrop-filter: none !important;
box-shadow: none !important;
}
:host-context(body.has-glass) .assistant-container,
:host-context(body.has-glass) .stt-message,
:host-context(body.has-glass) .toggle-button,
:host-context(body.has-glass) .copy-button {
border-radius: 0 !important;
}
:host-context(body.has-glass) ::-webkit-scrollbar,
:host-context(body.has-glass) ::-webkit-scrollbar-track,
:host-context(body.has-glass) ::-webkit-scrollbar-thumb {
background: transparent !important;
width: 0 !important; /* 스크롤바 자체 숨기기 */
}
:host-context(body.has-glass) .assistant-container,
:host-context(body.has-glass) .top-bar,
:host-context(body.has-glass) .toggle-button,
:host-context(body.has-glass) .copy-button,
:host-context(body.has-glass) .transcription-container,
:host-context(body.has-glass) .insights-container,
:host-context(body.has-glass) .stt-message,
:host-context(body.has-glass) .outline-item,
:host-context(body.has-glass) .request-item,
:host-context(body.has-glass) .markdown-content,
:host-context(body.has-glass) .insights-container pre,
:host-context(body.has-glass) .insights-container p code,
:host-context(body.has-glass) .insights-container pre code {
background: transparent !important;
border: none !important;
outline: none !important;
box-shadow: none !important;
filter: none !important;
backdrop-filter: none !important;
}
:host-context(body.has-glass) .assistant-container::before,
:host-context(body.has-glass) .assistant-container::after {
display: none !important;
}
:host-context(body.has-glass) .toggle-button:hover,
:host-context(body.has-glass) .copy-button:hover,
:host-context(body.has-glass) .outline-item:hover,
:host-context(body.has-glass) .request-item.clickable:hover,
:host-context(body.has-glass) .markdown-content:hover {
background: transparent !important;
transform: none !important;
}
:host-context(body.has-glass) .transcription-container::-webkit-scrollbar-track,
:host-context(body.has-glass) .transcription-container::-webkit-scrollbar-thumb,
:host-context(body.has-glass) .insights-container::-webkit-scrollbar-track,
:host-context(body.has-glass) .insights-container::-webkit-scrollbar-thumb {
background: transparent !important;
}
:host-context(body.has-glass) * {
animation: none !important;
transition: none !important;
transform: none !important;
filter: none !important;
backdrop-filter: none !important;
box-shadow: none !important;
}
:host-context(body.has-glass) .assistant-container,
:host-context(body.has-glass) .stt-message,
:host-context(body.has-glass) .toggle-button,
:host-context(body.has-glass) .copy-button {
border-radius: 0 !important;
}
:host-context(body.has-glass) ::-webkit-scrollbar,
:host-context(body.has-glass) ::-webkit-scrollbar-track,
:host-context(body.has-glass) ::-webkit-scrollbar-thumb {
background: transparent !important;
width: 0 !important;
}
`;
static properties = {
viewMode: { type: String },
isHovering: { type: Boolean },
isAnimating: { type: Boolean },
copyState: { type: String },
elapsedTime: { type: String },
captureStartTime: { type: Number },
isSessionActive: { type: Boolean },
hasCompletedRecording: { type: Boolean },
};
constructor() {
super();
this.isSessionActive = false;
this.hasCompletedRecording = false;
this.viewMode = 'insights';
this.isHovering = false;
this.isAnimating = false;
this.elapsedTime = '00:00';
this.captureStartTime = null;
this.timerInterval = null;
this.adjustHeightThrottle = null;
this.isThrottled = false;
this.copyState = 'idle';
this.copyTimeout = null;
this.adjustWindowHeight = this.adjustWindowHeight.bind(this);
}
connectedCallback() {
super.connectedCallback();
// Only start timer if session is active
if (this.isSessionActive) {
this.startTimer();
}
if (window.api) {
window.api.listenView.onSessionStateChanged((event, { isActive }) => {
const wasActive = this.isSessionActive;
this.isSessionActive = isActive;
if (!wasActive && isActive) {
this.hasCompletedRecording = false;
this.startTimer();
// Reset child components
this.updateComplete.then(() => {
const sttView = this.shadowRoot.querySelector('stt-view');
const summaryView = this.shadowRoot.querySelector('summary-view');
if (sttView) sttView.resetTranscript();
if (summaryView) summaryView.resetAnalysis();
});
this.requestUpdate();
}
if (wasActive && !isActive) {
this.hasCompletedRecording = true;
this.stopTimer();
this.requestUpdate();
}
});
}
}
disconnectedCallback() {
super.disconnectedCallback();
this.stopTimer();
if (this.adjustHeightThrottle) {
clearTimeout(this.adjustHeightThrottle);
this.adjustHeightThrottle = null;
}
if (this.copyTimeout) {
clearTimeout(this.copyTimeout);
}
}
startTimer() {
this.captureStartTime = Date.now();
this.timerInterval = setInterval(() => {
const elapsed = Math.floor((Date.now() - this.captureStartTime) / 1000);
const minutes = Math.floor(elapsed / 60)
.toString()
.padStart(2, '0');
const seconds = (elapsed % 60).toString().padStart(2, '0');
this.elapsedTime = `${minutes}:${seconds}`;
this.requestUpdate();
}, 1000);
}
stopTimer() {
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
}
adjustWindowHeight() {
if (!window.api) return;
this.updateComplete
.then(() => {
const topBar = this.shadowRoot.querySelector('.top-bar');
const activeContent = this.viewMode === 'transcript'
? this.shadowRoot.querySelector('stt-view')
: this.shadowRoot.querySelector('summary-view');
if (!topBar || !activeContent) return;
const topBarHeight = topBar.offsetHeight;
const contentHeight = activeContent.scrollHeight;
const idealHeight = topBarHeight + contentHeight;
const targetHeight = Math.min(700, idealHeight);
console.log(
`[Height Adjusted] Mode: ${this.viewMode}, TopBar: ${topBarHeight}px, Content: ${contentHeight}px, Ideal: ${idealHeight}px, Target: ${targetHeight}px`
);
window.api.listenView.adjustWindowHeight('listen', targetHeight);
})
.catch(error => {
console.error('Error in adjustWindowHeight:', error);
});
}
toggleViewMode() {
this.viewMode = this.viewMode === 'insights' ? 'transcript' : 'insights';
this.requestUpdate();
}
handleCopyHover(isHovering) {
this.isHovering = isHovering;
if (isHovering) {
this.isAnimating = true;
} else {
this.isAnimating = false;
}
this.requestUpdate();
}
async handleCopy() {
if (this.copyState === 'copied') return;
let textToCopy = '';
if (this.viewMode === 'transcript') {
const sttView = this.shadowRoot.querySelector('stt-view');
textToCopy = sttView ? sttView.getTranscriptText() : '';
} else {
const summaryView = this.shadowRoot.querySelector('summary-view');
textToCopy = summaryView ? summaryView.getSummaryText() : '';
}
try {
await navigator.clipboard.writeText(textToCopy);
console.log('Content copied to clipboard');
this.copyState = 'copied';
this.requestUpdate();
if (this.copyTimeout) {
clearTimeout(this.copyTimeout);
}
this.copyTimeout = setTimeout(() => {
this.copyState = 'idle';
this.requestUpdate();
}, 1500);
} catch (err) {
console.error('Failed to copy:', err);
}
}
adjustWindowHeightThrottled() {
if (this.isThrottled) {
return;
}
this.adjustWindowHeight();
this.isThrottled = true;
this.adjustHeightThrottle = setTimeout(() => {
this.isThrottled = false;
}, 16);
}
updated(changedProperties) {
super.updated(changedProperties);
if (changedProperties.has('viewMode')) {
this.adjustWindowHeight();
}
}
handleSttMessagesUpdated(event) {
// Handle messages update from SttView if needed
this.adjustWindowHeightThrottled();
}
firstUpdated() {
super.firstUpdated();
setTimeout(() => this.adjustWindowHeight(), 200);
}
render() {
const displayText = this.isHovering
? this.viewMode === 'transcript'
? 'Copy Transcript'
: 'Copy Glass Analysis'
: this.viewMode === 'insights'
? `Live insights`
: `Glass is Listening ${this.elapsedTime}`;
return html`
${displayText}
${this.viewMode === 'insights'
? html`
Show Transcript
`
: html`
Show Insights
`}
this.handleCopyHover(true)}
@mouseleave=${() => this.handleCopyHover(false)}
>
`;
}
}
customElements.define('listen-view', ListenView);
================================================
FILE: src/ui/listen/audioCore/aec.js
================================================
var createAecModule = (() => {
var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
return (
async function(moduleArg = {}) {
var moduleRtn;
var Module=moduleArg;var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var readyPromiseResolve,readyPromiseReject;var wasmMemory;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["v"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return base64Decode("AGFzbQEAAAABhgETYAJ/fwF/YAN/f38Bf2ACf38AYAN/f38AYAF/AGAEf39/fwBgAX8Bf2AFf39/f38AYAAAYAZ/f39/f38AYAR/f39/AX9gBX9/f39/AX9gAAF/YAZ/f39/f38Bf2AHf39/f39/fwBgBH9+f38Bf2AHf39/f39/fwF/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CyADKAIYIQcgASADRwRAIAMoAggiAiABNgIMIAEgAjYCCAwECyADKAIUIgIEfyADQRRqBSADKAIQIgJFDQMgA0EQagshBANAIAQhBiACIgFBFGohBCABKAIUIgINACABQRBqIQQgASgCECICDQALIAZBADYCAAwDCyAFKAIEIgJBA3FBA0cNA0HM8wAgADYCACAFIAJBfnE2AgQgAyAAQQFyNgIEIAUgADYCAA8LIAIgATYCDCABIAI2AggMAgtBACEBCyAHRQ0AAkAgAygCHCIEQQJ0QfT1AGoiAigCACADRgRAIAIgATYCACABDQFByPMAQcjzACgCAEF+IAR3cTYCAAwCCwJAIAMgBygCEEYEQCAHIAE2AhAMAQsgByABNgIUCyABRQ0BCyABIAc2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0AIAEgAjYCFCACIAE2AhgLIAMgBU8NACAFKAIEIgRBAXFFDQACQAJAAkACQCAEQQJxRQRAQdzzACgCACAFRgRAQdzzACADNgIAQdDzAEHQ8wAoAgAgAGoiADYCACADIABBAXI2AgQgA0HY8wAoAgBHDQZBzPMAQQA2AgBB2PMAQQA2AgAPC0HY8wAoAgAiByAFRgRAQdjzACADNgIAQczzAEHM8wAoAgAgAGoiADYCACADIABBAXI2AgQgACADaiAANgIADwsgBEF4cSAAaiEAIAUoAgwhASAEQf8BTQRAIAUoAggiAiABRgRAQcTzAEHE8wAoAgBBfiAEQQN2d3E2AgAMBQsgAiABNgIMIAEgAjYCCAwECyAFKAIYIQggASAFRwRAIAUoAggiAiABNgIMIAEgAjYCCAwDCyAFKAIUIgIEfyAFQRRqBSAFKAIQIgJFDQIgBUEQagshBANAIAQhBiACIgFBFGohBCABKAIUIgINACABQRBqIQQgASgCECICDQALIAZBADYCAAwCCyAFIARBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAwDC0EAIQELIAhFDQACQCAFKAIcIgRBAnRB9PUAaiICKAIAIAVGBEAgAiABNgIAIAENAUHI8wBByPMAKAIAQX4gBHdxNgIADAILAkAgBSAIK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CCIHQQBMDQBBASAFdEEBdSEAQQAhBkEAIQMgB0EETwRAIAFBBmohDCABQQRqIQogAUECaiELIAdB/P///wdxIQhBACEJA0AgASADQQF0IgRqIg0gACANLgEAaiAFdTsBACAEIAtqIg0gACANLgEAaiAFdTsBACAEIApqIg0gACANLgEAaiAFdTsBACAEIAxqIgQgACAELgEAaiAFdTsBACADQQRqIQMgCUEEaiIJIAhHDQALCyAHQQNxIgQEQANAIAEgA0EBdGoiCSAAIAkuAQBqIAV1OwEAIANBAWohAyAGQQFqIgYgBEcNAAsLQQAhBEEAIQMgB0EETwRAIAJBBmohCSACQQRqIQwgAkECaiEKIAdB/P///wdxIQtBACEGA0AgAiADQQF0IgFqIgggACAILgEAaiAFdTsBACABIApqIgggACAILgEAaiAFdTsBACABIAxqIgggACAILgEAaiAFdTsBACABIAlqIgEgACABLgEAaiAFdTsBACADQQRqIQMgBkEEaiIGIAtHDQALCyAHQQNxIgFFDQADQCACIANBAXRqIgYgACAGLgEAaiAFdTsBACADQQFqIQMgBEEBaiIEIAFHDQALCwvBAQEDfyAALQAAQSBxRQRAAkAgACgCECIDBH8gAwUgABBsDQEgACgCEAsgACgCFCIEayACSQRAIAAgASACIAAoAiQRAQAaDAELAkACQCAAKAJQQQBIDQAgAkUNACACIQMDQCABIANqIgVBAWstAABBCkcEQCADQQFrIgMNAQwCCwsgACABIAMgACgCJBEBACADSQ0CIAIgA2shAiAAKAIUIQQMAQsgASEFCyAEIAUgAhArGiAAIAAoAhQgAmo2AhQLCwucAgEHfyMAQRBrIgYkAEEKIQMgACIFQegHTwRAIAUhBANAIAZBBmogA2oiB0EEayAEIARBkM4AbiIFQZDOAGxrIghB//8DcUHkAG4iCUEBdEG+G2ovAAA7AAAgB0ECayAIIAlB5ABsa0H//wNxQQF0Qb4bai8AADsAACADQQRrIQMgBEH/rOIESyAFIQQNAAsLAkAgBUEJTQRAIAUhBAwBCyADQQJrIgMgBkEGamogBSAFQf//A3FB5ABuIgRB5ABsa0H//wNx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AQYCChAggAygCACIEayAEckGAgYKEeHFBgIGChHhHDQADQEGAgoQIIARBvfr06QNzIgFrIAFyQYCBgoR4cUGAgYKEeEcNASADKAIEIQQgA0EEaiIBIQMgBEGAgoQIIARrckGAgYKEeHFBgIGChHhGDQALDAELIAMhAQsDQCABIgMtAAAiBEUNASABQQFqIQEgBEE9Rw0ACwtBACACIANGDQAaAkAgAiADIAJrIglqLQAADQBBgPkAKAIAIgVFDQAgBSgCACIDRQ0AA0ACQAJ/IAIhAUEAIAkiBEUNABogAS0AACIGBH8CQANAIAYgAy0AACIKRw0BIApFDQEgBEEBayIERQ0BIANBAWohAyABLQABIQYgAUEBaiEBIAYNAAtBACEGCyAGBUEACyADLQAAawtFBEAgBSgCACAJaiIBLQAAQT1GDQELIAUoAgQhAyAFQQRqIQUgAw0BDAILCyABQQFqIQgLIAgLIgFFBEAgAEGAgICAeDYCAAwBC0EAIQICQCABECUiBEEATgRAIARFBEBBASEDDAILQdn5AC0AABpBASECIARBARAcIgMNAQtB+PgAQQA2AgBBECACIARB5OgAEARB+PgAKAIAQfj4AEEANgIAQQFHBEAACxAAIQFB+PgAQQA2AgBBOiAHQQhqEAJB+PgAKAIAQfj4AEEANgIAQQFHBEAgARABAAsQABoQIAALIAQEQCADIAEgBPwKAAALIAAgBDYCCCAAIAM2AgQgACAENgIAC0HA+QAoAgAhAQJAA0ACQEHA+QACfyABQQJxRQRAIAFBEWsiAEEBckEAIAAbDAELIAFBCHFFDQEgAUF2cQtBwPkAKAIAIgAgACABRiICGzYCACAAIQEgAkUNAQwCCwtBwPkAIAEQdAsgB0EQaiQAC8oJAQd/IwBB0ABrIgMkACADQgA3AxAgA0EAOgAgIANCADcDGCADQQA6ACEgACgCACECIANBEGpBDHIhBwJAA0BBACEGA0ACQEH4+ABBADYCAEE0IANBCGogAhADQfj4ACgCACEBQfj4AEEANgIAAkACQAJAAkACQCABQQFGDQACQCADKAIIQQFxRQRAIAJBAnEiBA0BIAZBB08NASAGQQFqIQYgAC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AIgEgACABRiICGzYCACABIQAgAkUNAQwECyADIAEgAygCACIBIAAgAUYbNgIAIAAgAUcgASEADQALA0AgAigCBCACED4iAg0ACwwCCyADIAFBfnEgAygCACICIAEgAkYiABs2AgAgAA0BCyACIQEMAQsLCwtoAQN/IAAoAgQiAigCACEAAkADQAJAIAICfyAAQQJxRQRAIABBEWsiAUEBckEAIAEbDAELIABBCHFFDQEgAEF2cQsgAigCACIBIAAgAUYiAxs2AgAgASEAIANFDQEMAgsLIAIgABB0CwuUAgICfwF+IwBBEGsiAyQAAn9BACACRQ0AGgNAAkACQAJAQQACfyABQf////8HIAIgAkH/////B08bEEMiBEF/RwRAIAMgBDYCDCADQQQ6AAhByOkAIARFDQEaIAIgBEkNAiABIARqIQEgAiAEayECDAQLIANBADoACyADQQA7AAkgA0EAOgAIIANBwPMAKAIAIgQ2AgwgBEEbRg0DIANBCGoLKQMAIgVC/wGDQgRRDQQaIAAtAABBBEcEQEH4+ABBADYCAEElIAAQAkH4+AAoAgBB+PgAQQA2AgBBAUYNAgsgACAFNwIAQQEMBAsgBCACQZDrABAvAAsQACAAIAU3AgAQAQALIAINAAtBAAsgA0EQaiQAC4MBAQN/AkAgAC0AAEEDRgRAIAAoAgQiAigCACEDIAIoAgQiACgCACIBBEBB+PgAQQA2AgAgASADEAJB+PgAKAIAQfj4AEEANgIAQQFGDQILIAAoAgQEQCAAKAIIGiADEBQLIAIQFAsPCxAAIAAoAgQEQCAAKAIIGiADEBQLIAIQFBABAAtOAQF/IABBACAAQZkBTRtBAXRBsMEAai8BAEG1MmoiABAlIgJBgAFPBEAgASAAQf8AECsaIAFBADoAf0HEAA8LIAEgACACQQFqECsaQQALRAEBfyMAQRBrIgIkAEECIAAgASACQQxqEAYiAAR/QcDzACAANgIAQX8FQQALIQAgAigCDCEBIAJBEGokAEF/IAEgABsLugEBBH8jACICQYAgIQMgAkEQQYAgIAAbayIEJAAgBCECAkACQCAARQ0AIAAhAiABIgMNAEHA8wBBHDYCAEEAIQA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gCSAAQQJ0IgJqQYABNgIAIAIgC2pBATYCACAOIABBAXQiAGpB//8BOwEAIAAgDWpBgAI7AQAgACAMakGAAjsBAAsgAUEATA0AQQAhBUEAIQIgAUEITwRAIARBHGohByAEQRhqIQkgBEEUaiELIARBEGohDCAEQQxqIQ0gBEEIaiEOIARBBGohDyABQfj///8HcSERQQAhBgNAIAQgAkECdCIAakEBNgIAIAAgD2pBATYCACAAIA5qQQE2AgAgACANakEBNgIAIAAgDGpBATYCACAAIAtqQQE2AgAgACAJakEBNgIAIAAgB2pBATYCACACQQhqIQIgBkEIaiIGIBFHDQALCyABQQdxIgBFDQADQCAEIAJBAnRqQQE2AgAgAkEBaiECIAVBAWoiBSAARw0ACwsgA0EANgKUASAIEFwhACADQQA2ApgBIANBADYCkAEgAyAANgKcASADIQIjAEEgayIAJAAgAiAKNgI0IABBIGokAEEBBUEACyEBQdn5AC0AABoCQEEMQQQQHCIARQRAQfj4AEEANgIAQRFBBEEMEANB+PgAKAIAQfj4AEEANgIAQQFHDQEQABogChBaIAEEQCACEFkLECYACyAAIAo2AgggACACNgIEIAAgATYCACAADwsAC0cBAn8jAEEwayIAJAAgAEEBNgIYIABBjPAANgIUIABCADcCICAAIABBLGoiATYCHCAAQQxqIgIgASAAQRRqEB4gAhAfEB0ACyYAIAAgAUEBckEQajYCBCAAIAFBAnFFIAFBAUdxIAFBcElxNgIACxkAIAAgAUEBajYCBCAAIAFBf3NBAXE2AgALRwBBBCEBIAJBgAggAyADQYAITxsQeSIDQX9GBEAgAEEAOwABIABBADoAA0HA8wAoAgAhA0EAIQELIAAgAzYCBCAAIAE6AAALTQBBBCEBIAJB/////wcgAyADQf////8HTxsQQyIDQX9GBEAgAEEAOwABIABBADoAA0HA8wAoAgAhA0EAIQELIAAgAzYCBCAAIAE6AAALLgAgASgCACAALQAAQQJ0IgBBhPIAaigCACAAQeTfAGooAgAgASgCBCgCDBEBAAscACABKAIAIAAoAgAgACgCBCABKAIEKAIMEQEACwwAIAAgASk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AJB+PgAKAIAQfj4AEEANgIAQQFGDQILIAIoAgQEQCACKAIIGiAEEBQLIAEQFAsgACgCDCgCJCEBIAAoAgghACADQdjsADYCoAQgA0IDNwKsBCADIAo3A8gEIAMgCTcDwAQgAyALNwO4BCADIANBuARqNgKoBCADQQQ2AqQEIANBmARqIAAgA0GgBGogAREDACADLQCYBCIAQQRGDQQgAEEDRw0EIAMoApwEIgEoAgAhAiABKAIEIgAoAgAiBARAQfj4AEEANgIAIAQgAhACQfj4ACgCAEH4+ABBADYCAEEBRg0CCyAAKAIEBEAgACgCCBogAhAUCyABEBQMBAsQACEDIAIoAgRFDQIgAigCCBogBBAUDAILEAAhAyAAKAIERQ0BIAAoAggaIAIQFAwBCyABQYAEQcjsABBXAAsgARAUIAMQAQALIANB0ARqJAALtgIBA38jAEEwayIAJABB2PkALQAARQRAIABBAjYCDCAAQbjrADYCCCAAQgE3AhQgACAAQShqrUKAgICAgAGENwMgIAAgATYCKCAAIABBIGo2AhAgACAAQS9qIABBCGoQHgJAAkAgAC0AACIBQQRGDQAgAUEDRw0AIAAoAgQiAigCACEDIAIoAgQiASgCACIEBEBB+PgAQQA2AgAgBCADEAJB+PgAKAIAQfj4AEEANgIAQQFGDQILIAEoAgQEQCABKAIIGiADEBQLIAIQFAsgAEEwaiQADwsQACABKAIEBEAgASgCCBogAxAUCyACEBQQAQALIABBAjYCDCAAQgE3AhQgAEHI6wA2AgggACABNgIAIAAgAK1CgICAgIABhDcDICAAIABBIGo2AhAgAEEIakHY6wAQFgALjAYCB38BfiMAQRBrIgMkACABKAIEIQUgASgCACEHIAAtAAAhCCMAQRBrIgAkAEHZ+QAtAAAaQYAEIQECQAJAAkACQAJAAkBBgARBARAcIgIEQCAAIAI2AgggAEGABDYCBCACQYAEEHoNAgNAQcDzACgCACIEQcQARwRAIAMgBDYCDCADQoCAgIAINwIEIAFFDQggAhAUDAgLQfj4AEEANgIAIAAgATYCDEExIABBBGogAUEBQQFBARAHQfj4ACgCAEH4+ABBAD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IAEgAyAEaiIENgIIIAJBCGoiAiAFRw0ACwsgAEEEOgAAC1ABAX8gASgCACABKAIIIgRrIANJBEAgASAEIANBAUEBEBkgASgCCCEECyADBEAgASgCBCAEaiACIAP8CgAACyAAQQQ6AAAgASADIARqNgIIC7YCAQV/AkAgA0UEQAwBCyADQQNxIQcCQCADQQRJBEAMAQsgAkEcaiEEIANBfHEhCANAIAQoAgAgBEEIaygCACAEQRBrKAIAIARBGGsoAgAgBWpqamohBSAEQSBqIQQgCCAGQQRqIgZHDQALCyAHBEAgBkEDdCACakEEaiEEA0AgBCgCACAFaiEFIARBCGohBCAHQQFrIgcNAAsLIAEoAgAgASgCCCIEayAFSQRAIAEgBCAFQQFBARAZCyADQQN0IAJqIQYgASgCCCEEA0AgAigCACEHIAIoAgQiAyABKAIAIARrSwRAIAEgBCADQQFBARAZIAEoAgghBAsgAwRAIAEoAgQgBGogByAD/AoAAAsgASADIARqIgQ2AgggAkEIaiICIAZHDQALCyAAQQQ6AAAgACAFNgIEC1cBAX8gASgCACABKAIIIgRrIANJBEAgASAEIANBAUEBEBkgASgCCCEECyADBEAgASgCBCAEaiACIAP8CgAACyAAIAM2AgQgASADIARqNgIIIABBBDoAAAvqAwEDfyMAQbABayICJAACQAJAAkACQAJAAkACQCAALQAAQQFrDgMBAgMACyACIAAoAgQiAzYCBCACQRhqIgBBAEGAAfwLACADIAAQeEEASA0FIAJBmAFqIgMgACAAECUQRiACQQhqIgQgAxBFQfj4AEEANgIAIAJBAzYCHCACQaDqADYCGCACQgI3AiQgAiACQQRqrUKAgICA4AeENwOgASACIAStQoCAgIDwB4Q3A5gBIAIgAzYCIEErIAEoAgAgASgCBCAAEAUhAEH4+AAoAgBB+PgAQQA2AgBBAUcNAxAAIAIoAggEQCACKAIMEBQLEAEACyAALQABIQAgAkEBNgIcIAJBkMoANgIYIAJCATcCJCACIABBAnQiAEG83gBqKAIANgKcASACIABB3PAAaigCADYCmAEgAiACQZgBaq1CgICAgMAEhDcDCCACIAJ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CYAAB0mAAAsJgAAOiYAAE0mAABzJgAAqyYAAMQmAADbJgAA5yYAAPAmAAD6JgAACicAACEnAAAvJwAAPScAAEonAABeJwAAZicAAIEnAACPJwAAnycAALUnAADKJwAA1ScAAOsnAAD4JwAAAygAAA4oAACMKwAAlCsAAKQrAAC1KwAAxCsAANMrAADlKwAA9isAAAIsAAALLAAAGywAACYsAAAwLAAABiUAAD0sAABKLAAAViwAAGcsAAB5LAAAhywAAJ0sAACpLAAAtCwAALwsAADFLAAA0CwAANssAADoLAAA9CwAAAAtAAASLQAAGi0AACgtAAA0LQAAQy0AAFYtAABhLQAAbC0AAHktAACELQAAji0AAJMtAACsMAAACgAAABwAAAAF")}function getBinarySync(file){if(ArrayBuffer.isView(file)){return file}if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["u"];updateMemoryViews();wasmTable=wasmExports["H"];assignWasmExports(wasmExports);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{resolve(receiveInstance(mod,inst))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var base64Decode=b64=>{var b1,b2,i=0,j=0,bLength=b64.length;var output=new Uint8Array((bLength*3>>2)-(b64[bLength-2]=="=")-(b64[bLength-1]=="="));for(;i>4;output[j+1]=b1<<4|b2>>2;output[j+2]=b2<<6|base64ReverseLookup[b64.charCodeAt(i+3)]}return output};var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var exceptionLast=0;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var setTempRet0=val=>__emscripten_tempret_set(val);var findMatchingCatch=args=>{var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0}var info=new ExceptionInfo(thrown);info.set_adjusted_ptr(thrown);var thrownType=info.get_type();if(!thrownType){setTempRet0(0);return thrown}for(var caughtType of args){if(caughtType===0||caughtType===thrownType){break}var adjusted_ptr_addr=info.ptr+16;if(___cxa_can_catch(caughtType,thrownType,adjusted_ptr_addr)){setTempRet0(caughtType);return thrown}}setTempRet0(thrownType);return thrown};var ___cxa_find_matching_catch_2=()=>findMatchingCatch([]);var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var ___resumeException=ptr=>{if(!exceptionLast){exceptionLast=ptr}throw exceptionLast};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);function ___syscall_getcwd(buf,size){try{if(size===0)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd)+1;if(sizeabort("");var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.language||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>view=>crypto.getRandomValues(view);var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var preloadPlugins=[];var FS_handledByPreloadPlugin=(byteArray,fullname,finish,onerror)=>{if(typeof Browser!="undefined")Browser.init();var handled=false;preloadPlugins.forEach(plugin=>{if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);function processData(byteArray){function finish(byteArray){preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}onload?.();removeRunDependency(dep)}if(FS_handledByPreloadPlugin(byteArray,fullname,finish,()=>{onerror?.();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url).then(processData,onerror)}else{processData(url)}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){throw new Error(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAP32[buf>>2]=stat.dev;HEAP32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAP32[buf+12>>2]=stat.uid;HEAP32[buf+16>>2]=stat.gid;HEAP32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAP32[buf+4>>2]=stats.bsize;HEAP32[buf+40>>2]=stats.bsize;HEAP32[buf+8>>2]=stats.blocks;HEAP32[buf+12>>2]=stats.bfree;HEAP32[buf+16>>2]=stats.bavail;HEAP32[buf+20>>2]=stats.files;HEAP32[buf+24>>2]=stats.ffree;HEAP32[buf+28>>2]=stats.fsid;HEAP32[buf+44>>2]=stats.flags;HEAP32[buf+36>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>numINT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};for(var base64ReverseLookup=new Uint8Array(123),i=25;i>=0;--i){base64ReverseLookup[48+i]=52+i;base64ReverseLookup[65+i]=i;base64ReverseLookup[97+i]=26+i}base64ReverseLookup[43]=62;base64ReverseLookup[47]=63;FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="";{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"]}Module["ccall"]=ccall;Module["cwrap"]=cwrap;var _AecNew,_AecCancelEcho,_AecDestroy,_malloc,_free,_setThrew,__emscripten_tempret_set,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___cxa_can_catch;function assignWasmExports(wasmExports){Module["_AecNew"]=_AecNew=wasmExports["w"];Module["_AecCancelEcho"]=_AecCancelEcho=wasmExports["x"];Module["_AecDestroy"]=_AecDestroy=wasmExports["y"];Module["_malloc"]=_malloc=wasmExports["z"];Module["_free"]=_free=wasmExports["A"];_setThrew=wasmExports["B"];__emscripten_tempret_set=wasmExports["C"];__emscripten_stack_restore=wasmExports["D"];__emscripten_stack_alloc=wasmExports["E"];_emscripten_stack_get_current=wasmExports["F"];___cxa_can_catch=wasmExports["G"]}var wasmImports={a:___cxa_find_matching_catch_2,q:___cxa_throw,b:___resumeException,p:___syscall_getcwd,r:__abort_js,t:_emscripten_resize_heap,n:_environ_get,o:_environ_sizes_get,k:_exit,s:_fd_close,l:_fd_seek,g:_fd_write,i:invoke_ii,f:invoke_iiii,m:invoke_iiiiii,c:invoke_vi,d:invoke_vii,e:invoke_viii,j:invoke_viiii,h:invoke_viiiii};var wasmExports=await createWasm();function invoke_vi(index,a1){var sp=stackSave();try{getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}function preInit(){if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}preInit();run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
return moduleRtn;
}
);
})();
if (typeof exports === 'object' && typeof module === 'object') {
module.exports = createAecModule;
// This default export looks redundant, but it allows TS to import this
// commonjs style module.
module.exports.default = createAecModule;
} else if (typeof define === 'function' && define['amd'])
define([], () => createAecModule);
================================================
FILE: src/ui/listen/audioCore/listenCapture.js
================================================
const createAecModule = require('./aec.js');
let aecModPromise = null; // 한 번만 로드
let aecMod = null;
let aecPtr = 0; // Rust Aec* 1개만 재사용
/** WASM 모듈 가져오고 1회 초기화 */
async function getAec () {
if (aecModPromise) return aecModPromise; // 캐시
aecModPromise = createAecModule().then((M) => {
aecMod = M;
console.log('WASM Module Loaded:', M);
// C 심볼 → JS 래퍼 바인딩 (딱 1번)
M.newPtr = M.cwrap('AecNew', 'number',
['number','number','number','number']);
M.cancel = M.cwrap('AecCancelEcho', null,
['number','number','number','number','number']);
M.destroy = M.cwrap('AecDestroy', null, ['number']);
return M;
});
return aecModPromise;
}
// 바로 로드-실패 로그를 보기 위해
// getAec().catch(console.error);
// ---------------------------
// Constants & Globals
// ---------------------------
const SAMPLE_RATE = 24000;
const AUDIO_CHUNK_DURATION = 0.1;
const BUFFER_SIZE = 4096;
const isLinux = window.api.platform.isLinux;
const isMacOS = window.api.platform.isMacOS;
let mediaStream = null;
let micMediaStream = null;
let audioContext = null;
let audioProcessor = null;
let systemAudioContext = null;
let systemAudioProcessor = null;
let systemAudioBuffer = [];
const MAX_SYSTEM_BUFFER_SIZE = 10;
// ---------------------------
// Utility helpers (exact from renderer.js)
// ---------------------------
function isVoiceActive(audioFloat32Array, threshold = 0.005) {
if (!audioFloat32Array || audioFloat32Array.length === 0) {
return false;
}
let sumOfSquares = 0;
for (let i = 0; i < audioFloat32Array.length; i++) {
sumOfSquares += audioFloat32Array[i] * audioFloat32Array[i];
}
const rms = Math.sqrt(sumOfSquares / audioFloat32Array.length);
// console.log(`VAD RMS: ${rms.toFixed(4)}`); // For debugging VAD threshold
return rms > threshold;
}
function base64ToFloat32Array(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const int16Array = new Int16Array(bytes.buffer);
const float32Array = new Float32Array(int16Array.length);
for (let i = 0; i < int16Array.length; i++) {
float32Array[i] = int16Array[i] / 32768.0;
}
return float32Array;
}
function convertFloat32ToInt16(float32Array) {
const int16Array = new Int16Array(float32Array.length);
for (let i = 0; i < float32Array.length; i++) {
// Improved scaling to prevent clipping
const s = Math.max(-1, Math.min(1, float32Array[i]));
int16Array[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
}
return int16Array;
}
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
/* ───────────────────────── JS ↔︎ WASM 헬퍼 ───────────────────────── */
function int16PtrFromFloat32(mod, f32) {
const len = f32.length;
const bytes = len * 2;
const ptr = mod._malloc(bytes);
// HEAP16이 없으면 HEAPU8.buffer로 직접 래핑
const heapBuf = (mod.HEAP16 ? mod.HEAP16.buffer : mod.HEAPU8.buffer);
const i16 = new Int16Array(heapBuf, ptr, len);
for (let i = 0; i < len; ++i) {
const s = Math.max(-1, Math.min(1, f32[i]));
i16[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
}
return { ptr, view: i16 };
}
function float32FromInt16View(i16) {
const out = new Float32Array(i16.length);
for (let i = 0; i < i16.length; ++i) out[i] = i16[i] / 32768;
return out;
}
/* 필요하다면 종료 시 */
function disposeAec () {
getAec().then(mod => { if (aecPtr) mod.destroy(aecPtr); });
}
// listenCapture.js
function runAecSync(micF32, sysF32) {
if (!aecMod || !aecPtr || !aecMod.HEAPU8) {
// console.log('🔊 No AEC module or heap buffer');
return micF32;
}
const frameSize = 160; // AEC 모듈 초기화 시 설정한 프레임 크기
const numFrames = Math.floor(micF32.length / frameSize);
// 최종 처리된 오디오 데이터를 담을 버퍼
const processedF32 = new Float32Array(micF32.length);
// 시스템 오디오와 마이크 오디오의 길이를 맞춥니다. (안정성 확보)
let alignedSysF32 = new Float32Array(micF32.length);
if (sysF32.length > 0) {
// sysF32를 micF32 길이에 맞게 자르거나 채웁니다.
const lengthToCopy = Math.min(micF32.length, sysF32.length);
alignedSysF32.set(sysF32.slice(0, lengthToCopy));
}
// 2400개 샘플을 160개 프레임으로 나누어 루프 실행
for (let i = 0; i < numFrames; i++) {
const offset = i * frameSize;
// 현재 프레임에 해당하는 160개 샘플을 잘라냅니다.
const micFrame = micF32.subarray(offset, offset + frameSize);
const echoFrame = alignedSysF32.subarray(offset, offset + frameSize);
// WASM 메모리에 프레임 데이터 쓰기
const micPtr = int16PtrFromFloat32(aecMod, micFrame);
const echoPtr = int16PtrFromFloat32(aecMod, echoFrame);
const outPtr = aecMod._malloc(frameSize * 2); // 160 * 2 bytes
// AEC 실행 (160개 샘플 단위)
aecMod.cancel(aecPtr, micPtr.ptr, echoPtr.ptr, outPtr, frameSize);
// WASM 메모리에서 처리된 프레임 데이터 읽기
const heapBuf = (aecMod.HEAP16 ? aecMod.HEAP16.buffer : aecMod.HEAPU8.buffer);
const outFrameI16 = new Int16Array(heapBuf, outPtr, frameSize);
const outFrameF32 = float32FromInt16View(outFrameI16);
// 처리된 프레임을 최종 버퍼의 올바른 위치에 복사
processedF32.set(outFrameF32, offset);
// 할당된 메모리 해제
aecMod._free(micPtr.ptr);
aecMod._free(echoPtr.ptr);
aecMod._free(outPtr);
}
return processedF32;
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// 여기까지가 새로운 로직
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
}
// System audio data handler
window.api.listenCapture.onSystemAudioData((event, { data }) => {
systemAudioBuffer.push({
data: data,
timestamp: Date.now(),
});
// 오래된 데이터 제거
if (systemAudioBuffer.length > MAX_SYSTEM_BUFFER_SIZE) {
systemAudioBuffer = systemAudioBuffer.slice(-MAX_SYSTEM_BUFFER_SIZE);
}
});
// ---------------------------
// Complete token tracker (exact from renderer.js)
// ---------------------------
let tokenTracker = {
tokens: [],
audioStartTime: null,
addTokens(count, type = 'image') {
const now = Date.now();
this.tokens.push({
timestamp: now,
count: count,
type: type,
});
this.cleanOldTokens();
},
calculateImageTokens(width, height) {
const pixels = width * height;
if (pixels <= 384 * 384) {
return 85;
}
const tiles = Math.ceil(pixels / (768 * 768));
return tiles * 85;
},
trackAudioTokens() {
if (!this.audioStartTime) {
this.audioStartTime = Date.now();
return;
}
const now = Date.now();
const elapsedSeconds = (now - this.audioStartTime) / 1000;
const audioTokens = Math.floor(elapsedSeconds * 16);
if (audioTokens > 0) {
this.addTokens(audioTokens, 'audio');
this.audioStartTime = now;
}
},
cleanOldTokens() {
const oneMinuteAgo = Date.now() - 60 * 1000;
this.tokens = this.tokens.filter(token => token.timestamp > oneMinuteAgo);
},
getTokensInLastMinute() {
this.cleanOldTokens();
return this.tokens.reduce((total, token) => total + token.count, 0);
},
shouldThrottle() {
const throttleEnabled = localStorage.getItem('throttleTokens') === 'true';
if (!throttleEnabled) {
return false;
}
const maxTokensPerMin = parseInt(localStorage.getItem('maxTokensPerMin') || '500000', 10);
const throttleAtPercent = parseInt(localStorage.getItem('throttleAtPercent') || '75', 10);
const currentTokens = this.getTokensInLastMinute();
const throttleThreshold = Math.floor((maxTokensPerMin * throttleAtPercent) / 100);
console.log(`Token check: ${currentTokens}/${maxTokensPerMin} (throttle at ${throttleThreshold})`);
return currentTokens >= throttleThreshold;
},
// Reset the tracker
reset() {
this.tokens = [];
this.audioStartTime = null;
},
};
// Track audio tokens every few seconds
setInterval(() => {
tokenTracker.trackAudioTokens();
}, 2000);
// ---------------------------
// Audio processing functions (exact from renderer.js)
// ---------------------------
async function setupMicProcessing(micStream) {
/* ── WASM 먼저 로드 ───────────────────────── */
const mod = await getAec();
if (!aecPtr) aecPtr = mod.newPtr(160, 1600, 24000, 1);
const micAudioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
await micAudioContext.resume();
const micSource = micAudioContext.createMediaStreamSource(micStream);
const micProcessor = micAudioContext.createScriptProcessor(BUFFER_SIZE, 1, 1);
let audioBuffer = [];
const samplesPerChunk = SAMPLE_RATE * AUDIO_CHUNK_DURATION;
micProcessor.onaudioprocess = (e) => {
const inputData = e.inputBuffer.getChannelData(0);
audioBuffer.push(...inputData);
// console.log('🎤 micProcessor.onaudioprocess');
// samplesPerChunk(=2400) 만큼 모이면 전송
while (audioBuffer.length >= samplesPerChunk) {
let chunk = audioBuffer.splice(0, samplesPerChunk);
let processedChunk = new Float32Array(chunk); // 기본값
// ───────────────── WASM AEC ─────────────────
if (systemAudioBuffer.length > 0) {
const latest = systemAudioBuffer[systemAudioBuffer.length - 1];
const sysF32 = base64ToFloat32Array(latest.data);
// **음성 구간일 때만 런**
processedChunk = runAecSync(new Float32Array(chunk), sysF32);
// console.log('🔊 Applied WASM-AEC (speex)');
} else {
console.log('🔊 No system audio for AEC reference');
}
const pcm16 = convertFloat32ToInt16(processedChunk);
const b64 = arrayBufferToBase64(pcm16.buffer);
window.api.listenCapture.sendMicAudioContent({
data: b64,
mimeType: 'audio/pcm;rate=24000',
});
}
};
micSource.connect(micProcessor);
micProcessor.connect(micAudioContext.destination);
audioProcessor = micProcessor;
return { context: micAudioContext, processor: micProcessor };
}
function setupLinuxMicProcessing(micStream) {
// Setup microphone audio processing for Linux
const micAudioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
const micSource = micAudioContext.createMediaStreamSource(micStream);
const micProcessor = micAudioContext.createScriptProcessor(BUFFER_SIZE, 1, 1);
let audioBuffer = [];
const samplesPerChunk = SAMPLE_RATE * AUDIO_CHUNK_DURATION;
micProcessor.onaudioprocess = async e => {
const inputData = e.inputBuffer.getChannelData(0);
audioBuffer.push(...inputData);
// Process audio in chunks
while (audioBuffer.length >= samplesPerChunk) {
const chunk = audioBuffer.splice(0, samplesPerChunk);
const pcmData16 = convertFloat32ToInt16(chunk);
const base64Data = arrayBufferToBase64(pcmData16.buffer);
await window.api.listenCapture.sendMicAudioContent({
data: base64Data,
mimeType: 'audio/pcm;rate=24000',
});
}
};
micSource.connect(micProcessor);
micProcessor.connect(micAudioContext.destination);
// Store processor reference for cleanup
audioProcessor = micProcessor;
}
function setupSystemAudioProcessing(systemStream) {
const systemAudioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
const systemSource = systemAudioContext.createMediaStreamSource(systemStream);
const systemProcessor = systemAudioContext.createScriptProcessor(BUFFER_SIZE, 1, 1);
let audioBuffer = [];
const samplesPerChunk = SAMPLE_RATE * AUDIO_CHUNK_DURATION;
systemProcessor.onaudioprocess = async e => {
const inputData = e.inputBuffer.getChannelData(0);
if (!inputData || inputData.length === 0) return;
audioBuffer.push(...inputData);
while (audioBuffer.length >= samplesPerChunk) {
const chunk = audioBuffer.splice(0, samplesPerChunk);
const pcmData16 = convertFloat32ToInt16(chunk);
const base64Data = arrayBufferToBase64(pcmData16.buffer);
try {
await window.api.listenCapture.sendSystemAudioContent({
data: base64Data,
mimeType: 'audio/pcm;rate=24000',
});
} catch (error) {
console.error('Failed to send system audio:', error);
}
}
};
systemSource.connect(systemProcessor);
systemProcessor.connect(systemAudioContext.destination);
return { context: systemAudioContext, processor: systemProcessor };
}
// ---------------------------
// Main capture functions (exact from renderer.js)
// ---------------------------
async function startCapture(screenshotIntervalSeconds = 5, imageQuality = 'medium') {
// Reset token tracker when starting new capture session
tokenTracker.reset();
console.log('🎯 Token tracker reset for new capture session');
try {
if (isMacOS) {
const sessionActive = await window.api.listenCapture.isSessionActive();
if (!sessionActive) {
throw new Error('STT sessions not initialized - please wait for initialization to complete');
}
// On macOS, use SystemAudioDump for audio and getDisplayMedia for screen
console.log('Starting macOS capture with SystemAudioDump...');
// Start macOS audio capture
const audioResult = await window.api.listenCapture.startMacosSystemAudio();
if (!audioResult.success) {
console.warn('[listenCapture] macOS audio start failed:', audioResult.error);
// 이미 실행 중 → stop 후 재시도
if (audioResult.error === 'already_running') {
await window.api.listenCapture.stopMacosSystemAudio();
await new Promise(r => setTimeout(r, 500));
const retry = await window.api.listenCapture.startMacosSystemAudio();
if (!retry.success) {
throw new Error('Retry failed: ' + retry.error);
}
} else {
throw new Error('Failed to start macOS audio capture: ' + audioResult.error);
}
}
try {
micMediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: SAMPLE_RATE,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
video: false,
});
console.log('macOS microphone capture started');
const { context, processor } = await setupMicProcessing(micMediaStream);
audioContext = context;
audioProcessor = processor;
} catch (micErr) {
console.warn('Failed to get microphone on macOS:', micErr);
}
////////// for index & subjects //////////
console.log('macOS screen capture started - audio handled by SystemAudioDump');
} else if (isLinux) {
const sessionActive = await window.api.listenCapture.isSessionActive();
if (!sessionActive) {
throw new Error('STT sessions not initialized - please wait for initialization to complete');
}
// Linux - use display media for screen capture and getUserMedia for microphone
mediaStream = await navigator.mediaDevices.getDisplayMedia({
video: {
frameRate: 1,
width: { ideal: 1920 },
height: { ideal: 1080 },
},
audio: false, // Don't use system audio loopback on Linux
});
// Get microphone input for Linux
let micMediaStream = null;
try {
micMediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: SAMPLE_RATE,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
video: false,
});
console.log('Linux microphone capture started');
// Setup audio processing for microphone on Linux
setupLinuxMicProcessing(micMediaStream);
} catch (micError) {
console.warn('Failed to get microphone access on Linux:', micError);
// Continue without microphone if permission denied
}
console.log('Linux screen capture started');
} else {
// Windows - capture mic and system audio separately using native loopback
console.log('Starting Windows capture with native loopback audio...');
// Ensure STT sessions are initialized before starting audio capture
const sessionActive = await window.api.listenCapture.isSessionActive();
if (!sessionActive) {
throw new Error('STT sessions not initialized - please wait for initialization to complete');
}
// 1. Get user's microphone
try {
micMediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: SAMPLE_RATE,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
video: false,
});
console.log('Windows microphone capture started');
const { context, processor } = await setupMicProcessing(micMediaStream);
audioContext = context;
audioProcessor = processor;
} catch (micErr) {
console.warn('Could not get microphone access on Windows:', micErr);
}
// 2. Get system audio using native Electron loopback
try {
mediaStream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true // This will now use native loopback from our handler
});
// Verify we got audio tracks
const audioTracks = mediaStream.getAudioTracks();
if (audioTracks.length === 0) {
throw new Error('No audio track in native loopback stream');
}
console.log('Windows native loopback audio capture started');
const { context, processor } = setupSystemAudioProcessing(mediaStream);
systemAudioContext = context;
systemAudioProcessor = processor;
} catch (sysAudioErr) {
console.error('Failed to start Windows native loopback audio:', sysAudioErr);
// Continue without system audio
}
}
} catch (err) {
console.error('Error starting capture:', err);
// Note: pickleGlass.e() is not available in this context, commenting out
// pickleGlass.e().setStatus('error');
}
}
function stopCapture() {
// Clean up microphone resources
if (audioProcessor) {
audioProcessor.disconnect();
audioProcessor = null;
}
if (audioContext) {
audioContext.close();
audioContext = null;
}
// Clean up system audio resources
if (systemAudioProcessor) {
systemAudioProcessor.disconnect();
systemAudioProcessor = null;
}
if (systemAudioContext) {
systemAudioContext.close();
systemAudioContext = null;
}
// Stop and release media stream tracks
if (mediaStream) {
mediaStream.getTracks().forEach(track => track.stop());
mediaStream = null;
}
if (micMediaStream) {
micMediaStream.getTracks().forEach(t => t.stop());
micMediaStream = null;
}
// Stop macOS audio capture if running
if (isMacOS) {
window.api.listenCapture.stopMacosSystemAudio().catch(err => {
console.error('Error stopping macOS audio:', err);
});
}
}
// ---------------------------
// Exports & global registration
// ---------------------------
module.exports = {
getAec, // 새로 만든 초기화 함수
runAecSync, // sync 버전
disposeAec, // 필요시 Rust 객체 파괴
startCapture,
stopCapture,
isLinux,
isMacOS,
};
// Expose functions to global scope for external access (exact from renderer.js)
if (typeof window !== 'undefined') {
window.listenCapture = module.exports;
window.pickleGlass = window.pickleGlass || {};
window.pickleGlass.startCapture = startCapture;
window.pickleGlass.stopCapture = stopCapture;
}
================================================
FILE: src/ui/listen/audioCore/renderer.js
================================================
// renderer.js
const listenCapture = require('./listenCapture.js');
const params = new URLSearchParams(window.location.search);
const isListenView = params.get('view') === 'listen';
window.pickleGlass = {
startCapture: listenCapture.startCapture,
stopCapture: listenCapture.stopCapture,
isLinux: listenCapture.isLinux,
isMacOS: listenCapture.isMacOS,
captureManualScreenshot: listenCapture.captureManualScreenshot,
getCurrentScreenshot: listenCapture.getCurrentScreenshot,
};
window.api.renderer.onChangeListenCaptureState((_event, { status }) => {
if (!isListenView) {
console.log('[Renderer] Non-listen view: ignoring capture-state change');
return;
}
if (status === "stop") {
console.log('[Renderer] Session ended – stopping local capture');
listenCapture.stopCapture();
} else {
console.log('[Renderer] Session initialized – starting local capture');
listenCapture.startCapture();
}
});
================================================
FILE: src/ui/listen/stt/SttView.js
================================================
import { html, css, LitElement } from '../../assets/lit-core-2.7.4.min.js';
export class SttView extends LitElement {
static styles = css`
:host {
display: block;
width: 100%;
}
/* Inherit font styles from parent */
.transcription-container {
overflow-y: auto;
padding: 12px 12px 16px 12px;
display: flex;
flex-direction: column;
gap: 8px;
min-height: 150px;
max-height: 600px;
position: relative;
z-index: 1;
flex: 1;
}
/* Visibility handled by parent component */
.transcription-container::-webkit-scrollbar {
width: 8px;
}
.transcription-container::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.1);
border-radius: 4px;
}
.transcription-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
.transcription-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
.stt-message {
padding: 8px 12px;
border-radius: 12px;
max-width: 80%;
word-wrap: break-word;
word-break: break-word;
line-height: 1.5;
font-size: 13px;
margin-bottom: 4px;
box-sizing: border-box;
}
.stt-message.them {
background: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.9);
align-self: flex-start;
border-bottom-left-radius: 4px;
margin-right: auto;
}
.stt-message.me {
background: rgba(0, 122, 255, 0.8);
color: white;
align-self: flex-end;
border-bottom-right-radius: 4px;
margin-left: auto;
}
.empty-state {
display: flex;
align-items: center;
justify-content: center;
height: 100px;
color: rgba(255, 255, 255, 0.6);
font-size: 12px;
font-style: italic;
}
`;
static properties = {
sttMessages: { type: Array },
isVisible: { type: Boolean },
};
constructor() {
super();
this.sttMessages = [];
this.isVisible = true;
this.messageIdCounter = 0;
this._shouldScrollAfterUpdate = false;
this.handleSttUpdate = this.handleSttUpdate.bind(this);
}
connectedCallback() {
super.connectedCallback();
if (window.api) {
window.api.sttView.onSttUpdate(this.handleSttUpdate);
}
}
disconnectedCallback() {
super.disconnectedCallback();
if (window.api) {
window.api.sttView.removeOnSttUpdate(this.handleSttUpdate);
}
}
// Handle session reset from parent
resetTranscript() {
this.sttMessages = [];
this.requestUpdate();
}
handleSttUpdate(event, { speaker, text, isFinal, isPartial }) {
if (text === undefined) return;
const container = this.shadowRoot.querySelector('.transcription-container');
this._shouldScrollAfterUpdate = container ? container.scrollTop + container.clientHeight >= container.scrollHeight - 10 : false;
const findLastPartialIdx = spk => {
for (let i = this.sttMessages.length - 1; i >= 0; i--) {
const m = this.sttMessages[i];
if (m.speaker === spk && m.isPartial) return i;
}
return -1;
};
const newMessages = [...this.sttMessages];
const targetIdx = findLastPartialIdx(speaker);
if (isPartial) {
if (targetIdx !== -1) {
newMessages[targetIdx] = {
...newMessages[targetIdx],
text,
isPartial: true,
isFinal: false,
};
} else {
newMessages.push({
id: this.messageIdCounter++,
speaker,
text,
isPartial: true,
isFinal: false,
});
}
} else if (isFinal) {
if (targetIdx !== -1) {
newMessages[targetIdx] = {
...newMessages[targetIdx],
text,
isPartial: false,
isFinal: true,
};
} else {
newMessages.push({
id: this.messageIdCounter++,
speaker,
text,
isPartial: false,
isFinal: true,
});
}
}
this.sttMessages = newMessages;
// Notify parent component about message updates
this.dispatchEvent(new CustomEvent('stt-messages-updated', {
detail: { messages: this.sttMessages },
bubbles: true
}));
}
scrollToBottom() {
setTimeout(() => {
const container = this.shadowRoot.querySelector('.transcription-container');
if (container) {
container.scrollTop = container.scrollHeight;
}
}, 0);
}
getSpeakerClass(speaker) {
return speaker.toLowerCase() === 'me' ? 'me' : 'them';
}
getTranscriptText() {
return this.sttMessages.map(msg => `${msg.speaker}: ${msg.text}`).join('\n');
}
updated(changedProperties) {
super.updated(changedProperties);
if (changedProperties.has('sttMessages')) {
if (this._shouldScrollAfterUpdate) {
this.scrollToBottom();
this._shouldScrollAfterUpdate = false;
}
}
}
render() {
if (!this.isVisible) {
return html`
`;
}
return html`
${this.sttMessages.length === 0
? html`
Waiting for speech...
`
: this.sttMessages.map(msg => html`
${msg.text}
`)
}
`;
}
}
customElements.define('stt-view', SttView);
================================================
FILE: src/ui/listen/summary/SummaryView.js
================================================
import { html, css, LitElement } from '../../assets/lit-core-2.7.4.min.js';
export class SummaryView extends LitElement {
static styles = css`
:host {
display: block;
width: 100%;
}
/* Inherit font styles from parent */
/* highlight.js 스타일 추가 */
.insights-container pre {
background: rgba(0, 0, 0, 0.4) !important;
border-radius: 8px !important;
padding: 12px !important;
margin: 8px 0 !important;
overflow-x: auto !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
}
.insights-container code {
font-family: 'Monaco', 'Menlo', 'Consolas', monospace !important;
font-size: 11px !important;
background: transparent !important;
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
}
.insights-container pre code {
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
display: block !important;
}
.insights-container p code {
background: rgba(255, 255, 255, 0.1) !important;
padding: 2px 4px !important;
border-radius: 3px !important;
color: #ffd700 !important;
}
.hljs-keyword {
color: #ff79c6 !important;
}
.hljs-string {
color: #f1fa8c !important;
}
.hljs-comment {
color: #6272a4 !important;
}
.hljs-number {
color: #bd93f9 !important;
}
.hljs-function {
color: #50fa7b !important;
}
.hljs-variable {
color: #8be9fd !important;
}
.hljs-built_in {
color: #ffb86c !important;
}
.hljs-title {
color: #50fa7b !important;
}
.hljs-attr {
color: #50fa7b !important;
}
.hljs-tag {
color: #ff79c6 !important;
}
.insights-container {
overflow-y: auto;
padding: 12px 16px 16px 16px;
position: relative;
z-index: 1;
min-height: 150px;
max-height: 600px;
flex: 1;
}
/* Visibility handled by parent component */
.insights-container::-webkit-scrollbar {
width: 8px;
}
.insights-container::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.1);
border-radius: 4px;
}
.insights-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
.insights-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
insights-title {
color: rgba(255, 255, 255, 0.8);
font-size: 15px;
font-weight: 500;
font-family: 'Helvetica Neue', sans-serif;
margin: 12px 0 8px 0;
display: block;
}
.insights-container h4 {
color: #ffffff;
font-size: 12px;
font-weight: 600;
margin: 12px 0 8px 0;
padding: 4px 8px;
border-radius: 4px;
background: transparent;
cursor: default;
}
.insights-container h4:hover {
background: transparent;
}
.insights-container h4:first-child {
margin-top: 0;
}
.outline-item {
color: #ffffff;
font-size: 11px;
line-height: 1.4;
margin: 4px 0;
padding: 6px 8px;
border-radius: 4px;
background: transparent;
transition: background-color 0.15s ease;
cursor: pointer;
word-wrap: break-word;
}
.outline-item:hover {
background: rgba(255, 255, 255, 0.1);
}
.request-item {
color: #ffffff;
font-size: 12px;
line-height: 1.2;
margin: 4px 0;
padding: 6px 8px;
border-radius: 4px;
background: transparent;
cursor: default;
word-wrap: break-word;
transition: background-color 0.15s ease;
}
.request-item.clickable {
cursor: pointer;
transition: all 0.15s ease;
}
.request-item.clickable:hover {
background: rgba(255, 255, 255, 0.1);
transform: translateX(2px);
}
/* 마크다운 렌더링된 콘텐츠 스타일 */
.markdown-content {
color: #ffffff;
font-size: 11px;
line-height: 1.4;
margin: 4px 0;
padding: 6px 8px;
border-radius: 4px;
background: transparent;
cursor: pointer;
word-wrap: break-word;
transition: all 0.15s ease;
}
.markdown-content:hover {
background: rgba(255, 255, 255, 0.1);
transform: translateX(2px);
}
.markdown-content p {
margin: 4px 0;
}
.markdown-content ul,
.markdown-content ol {
margin: 4px 0;
padding-left: 16px;
}
.markdown-content li {
margin: 2px 0;
}
.markdown-content a {
color: #8be9fd;
text-decoration: none;
}
.markdown-content a:hover {
text-decoration: underline;
}
.markdown-content strong {
font-weight: 600;
color: #f8f8f2;
}
.markdown-content em {
font-style: italic;
color: #f1fa8c;
}
.empty-state {
display: flex;
align-items: center;
justify-content: center;
height: 100px;
color: rgba(255, 255, 255, 0.6);
font-size: 12px;
font-style: italic;
}
`;
static properties = {
structuredData: { type: Object },
isVisible: { type: Boolean },
hasCompletedRecording: { type: Boolean },
};
constructor() {
super();
this.structuredData = {
summary: [],
topic: { header: '', bullets: [] },
actions: [],
followUps: [],
};
this.isVisible = true;
this.hasCompletedRecording = false;
// 마크다운 라이브러리 초기화
this.marked = null;
this.hljs = null;
this.isLibrariesLoaded = false;
this.DOMPurify = null;
this.isDOMPurifyLoaded = false;
this.loadLibraries();
}
connectedCallback() {
super.connectedCallback();
if (window.api) {
window.api.summaryView.onSummaryUpdate((event, data) => {
this.structuredData = data;
this.requestUpdate();
});
}
}
disconnectedCallback() {
super.disconnectedCallback();
if (window.api) {
window.api.summaryView.removeAllSummaryUpdateListeners();
}
}
// Handle session reset from parent
resetAnalysis() {
this.structuredData = {
summary: [],
topic: { header: '', bullets: [] },
actions: [],
followUps: [],
};
this.requestUpdate();
}
async loadLibraries() {
try {
if (!window.marked) {
await this.loadScript('../../../assets/marked-4.3.0.min.js');
}
if (!window.hljs) {
await this.loadScript('../../../assets/highlight-11.9.0.min.js');
}
if (!window.DOMPurify) {
await this.loadScript('../../../assets/dompurify-3.0.7.min.js');
}
this.marked = window.marked;
this.hljs = window.hljs;
this.DOMPurify = window.DOMPurify;
if (this.marked && this.hljs) {
this.marked.setOptions({
highlight: (code, lang) => {
if (lang && this.hljs.getLanguage(lang)) {
try {
return this.hljs.highlight(code, { language: lang }).value;
} catch (err) {
console.warn('Highlight error:', err);
}
}
try {
return this.hljs.highlightAuto(code).value;
} catch (err) {
console.warn('Auto highlight error:', err);
}
return code;
},
breaks: true,
gfm: true,
pedantic: false,
smartypants: false,
xhtml: false,
});
this.isLibrariesLoaded = true;
console.log('Markdown libraries loaded successfully');
}
if (this.DOMPurify) {
this.isDOMPurifyLoaded = true;
console.log('DOMPurify loaded successfully in SummaryView');
}
} catch (error) {
console.error('Failed to load libraries:', error);
}
}
loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
parseMarkdown(text) {
if (!text) return '';
if (!this.isLibrariesLoaded || !this.marked) {
return text;
}
try {
return this.marked(text);
} catch (error) {
console.error('Markdown parsing error:', error);
return text;
}
}
handleMarkdownClick(originalText) {
this.handleRequestClick(originalText);
}
renderMarkdownContent() {
if (!this.isLibrariesLoaded || !this.marked) {
return;
}
const markdownElements = this.shadowRoot.querySelectorAll('[data-markdown-id]');
markdownElements.forEach(element => {
const originalText = element.getAttribute('data-original-text');
if (originalText) {
try {
let parsedHTML = this.parseMarkdown(originalText);
if (this.isDOMPurifyLoaded && this.DOMPurify) {
parsedHTML = this.DOMPurify.sanitize(parsedHTML);
if (this.DOMPurify.removed && this.DOMPurify.removed.length > 0) {
console.warn('Unsafe content detected in insights, showing plain text');
element.textContent = '⚠️ ' + originalText;
return;
}
}
element.innerHTML = parsedHTML;
} catch (error) {
console.error('Error rendering markdown for element:', error);
element.textContent = originalText;
}
}
});
}
async handleRequestClick(requestText) {
console.log('🔥 Analysis request clicked:', requestText);
if (window.api) {
try {
const result = await window.api.summaryView.sendQuestionFromSummary(requestText);
if (result.success) {
console.log('✅ Question sent to AskView successfully');
} else {
console.error('❌ Failed to send question to AskView:', result.error);
}
} catch (error) {
console.error('❌ Error in handleRequestClick:', error);
}
}
}
getSummaryText() {
const data = this.structuredData || { summary: [], topic: { header: '', bullets: [] }, actions: [] };
let sections = [];
if (data.summary && data.summary.length > 0) {
sections.push(`Current Summary:\n${data.summary.map(s => `• ${s}`).join('\n')}`);
}
if (data.topic && data.topic.header && data.topic.bullets.length > 0) {
sections.push(`\n${data.topic.header}:\n${data.topic.bullets.map(b => `• ${b}`).join('\n')}`);
}
if (data.actions && data.actions.length > 0) {
sections.push(`\nActions:\n${data.actions.map(a => `▸ ${a}`).join('\n')}`);
}
if (data.followUps && data.followUps.length > 0) {
sections.push(`\nFollow-Ups:\n${data.followUps.map(f => `▸ ${f}`).join('\n')}`);
}
return sections.join('\n\n').trim();
}
updated(changedProperties) {
super.updated(changedProperties);
this.renderMarkdownContent();
}
render() {
if (!this.isVisible) {
return html`
`;
}
const data = this.structuredData || {
summary: [],
topic: { header: '', bullets: [] },
actions: [],
};
const hasAnyContent = data.summary.length > 0 || data.topic.bullets.length > 0 || data.actions.length > 0;
return html`
${!hasAnyContent
? html`
No insights yet...
`
: html`
Current Summary
${data.summary.length > 0
? data.summary
.slice(0, 5)
.map(
(bullet, index) => html`
this.handleMarkdownClick(bullet)}
>
${bullet}
`
)
: html`
No content yet...
`}
${data.topic.header
? html`
${data.topic.header}
${data.topic.bullets
.slice(0, 3)
.map(
(bullet, index) => html`
this.handleMarkdownClick(bullet)}
>
${bullet}
`
)}
`
: ''}
${data.actions.length > 0
? html`
Actions
${data.actions
.slice(0, 5)
.map(
(action, index) => html`
this.handleMarkdownClick(action)}
>
${action}
`
)}
`
: ''}
${this.hasCompletedRecording && data.followUps && data.followUps.length > 0
? html`
Follow-Ups
${data.followUps.map(
(followUp, index) => html`
this.handleMarkdownClick(followUp)}
>
${followUp}
`
)}
`
: ''}
`}
`;
}
}
customElements.define('summary-view', SummaryView);
================================================
FILE: src/ui/settings/SettingsView.js
================================================
import { html, css, LitElement } from '../assets/lit-core-2.7.4.min.js';
// import { getOllamaProgressTracker } from '../../features/common/services/localProgressTracker.js'; // 제거됨
export class SettingsView extends LitElement {
static styles = css`
* {
font-family: 'Helvetica Neue', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
cursor: default;
user-select: none;
}
:host {
display: block;
width: 240px;
height: 100%;
color: white;
}
.settings-container {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
background: rgba(20, 20, 20, 0.8);
border-radius: 12px;
outline: 0.5px rgba(255, 255, 255, 0.2) solid;
outline-offset: -1px;
box-sizing: border-box;
position: relative;
overflow-y: auto;
padding: 12px 12px;
z-index: 1000;
}
.settings-container::-webkit-scrollbar {
width: 6px;
}
.settings-container::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
border-radius: 3px;
}
.settings-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
}
.settings-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.3);
}
.settings-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
border-radius: 12px;
filter: blur(10px);
z-index: -1;
}
.settings-button[disabled],
.api-key-section input[disabled] {
opacity: 0.4;
cursor: not-allowed;
pointer-events: none;
}
.header-section {
display: flex;
justify-content: space-between;
align-items: flex-start;
padding-bottom: 6px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
position: relative;
z-index: 1;
}
.title-line {
display: flex;
justify-content: space-between;
align-items: center;
}
.app-title {
font-size: 13px;
font-weight: 500;
color: white;
margin: 0 0 4px 0;
}
.account-info {
font-size: 11px;
color: rgba(255, 255, 255, 0.7);
margin: 0;
}
.invisibility-icon {
padding-top: 2px;
opacity: 0;
transition: opacity 0.3s ease;
}
.invisibility-icon.visible {
opacity: 1;
}
.invisibility-icon svg {
width: 16px;
height: 16px;
}
.shortcuts-section {
display: flex;
flex-direction: column;
gap: 2px;
padding: 4px 0;
position: relative;
z-index: 1;
}
.shortcut-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 0;
color: white;
font-size: 11px;
}
.shortcut-name {
font-weight: 300;
}
.shortcut-keys {
display: flex;
align-items: center;
gap: 3px;
}
.cmd-key, .shortcut-key {
background: rgba(255, 255, 255, 0.1);
border-radius: 3px;
width: 16px;
height: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 11px;
font-weight: 500;
color: rgba(255, 255, 255, 0.9);
}
/* Buttons Section */
.buttons-section {
display: flex;
flex-direction: column;
gap: 4px;
padding-top: 6px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
position: relative;
z-index: 1;
flex: 1;
}
.settings-button {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 4px;
color: white;
padding: 5px 10px;
font-size: 11px;
font-weight: 400;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
align-items: center;
justify-content: center;
white-space: nowrap;
}
.settings-button:hover {
background: rgba(255, 255, 255, 0.15);
border-color: rgba(255, 255, 255, 0.3);
}
.settings-button:active {
transform: translateY(1px);
}
.settings-button.full-width {
width: 100%;
}
.settings-button.half-width {
flex: 1;
}
.settings-button.danger {
background: rgba(255, 59, 48, 0.1);
border-color: rgba(255, 59, 48, 0.3);
color: rgba(255, 59, 48, 0.9);
}
.settings-button.danger:hover {
background: rgba(255, 59, 48, 0.15);
border-color: rgba(255, 59, 48, 0.4);
}
.move-buttons, .bottom-buttons {
display: flex;
gap: 4px;
}
.api-key-section {
padding: 6px 0;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.api-key-section input {
width: 100%;
background: rgba(0,0,0,0.2);
border: 1px solid rgba(255,255,255,0.2);
color: white;
border-radius: 4px;
padding: 4px;
font-size: 11px;
margin-bottom: 4px;
box-sizing: border-box;
}
.api-key-section input::placeholder {
color: rgba(255, 255, 255, 0.4);
}
/* Preset Management Section */
.preset-section {
padding: 6px 0;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.preset-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.preset-title {
font-size: 11px;
font-weight: 500;
color: white;
}
.preset-count {
font-size: 9px;
color: rgba(255, 255, 255, 0.5);
margin-left: 4px;
}
.preset-toggle {
font-size: 10px;
color: rgba(255, 255, 255, 0.6);
cursor: pointer;
padding: 2px 4px;
border-radius: 2px;
transition: background-color 0.15s ease;
}
.preset-toggle:hover {
background: rgba(255, 255, 255, 0.1);
}
.preset-list {
display: flex;
flex-direction: column;
gap: 2px;
max-height: 120px;
overflow-y: auto;
}
.preset-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 6px;
background: rgba(255, 255, 255, 0.05);
border-radius: 3px;
cursor: pointer;
transition: all 0.15s ease;
font-size: 11px;
border: 1px solid transparent;
}
.preset-item:hover {
background: rgba(255, 255, 255, 0.1);
border-color: rgba(255, 255, 255, 0.1);
}
.preset-item.selected {
background: rgba(0, 122, 255, 0.25);
border-color: rgba(0, 122, 255, 0.6);
box-shadow: 0 0 0 1px rgba(0, 122, 255, 0.3);
}
.preset-name {
color: white;
flex: 1;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
font-weight: 300;
}
.preset-item.selected .preset-name {
font-weight: 500;
}
.preset-status {
font-size: 9px;
color: rgba(0, 122, 255, 0.8);
font-weight: 500;
margin-left: 6px;
}
.no-presets-message {
padding: 12px 8px;
text-align: center;
color: rgba(255, 255, 255, 0.5);
font-size: 10px;
line-height: 1.4;
}
.no-presets-message .web-link {
color: rgba(0, 122, 255, 0.8);
text-decoration: underline;
cursor: pointer;
}
.no-presets-message .web-link:hover {
color: rgba(0, 122, 255, 1);
}
.loading-state {
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
color: rgba(255, 255, 255, 0.7);
font-size: 11px;
}
.loading-spinner {
width: 12px;
height: 12px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-top: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 50%;
animation: spin 1s linear infinite;
margin-right: 6px;
}
.hidden {
display: none;
}
.api-key-section, .model-selection-section {
padding: 8px 0;
border-top: 1px solid rgba(255, 255, 255, 0.1);
display: flex;
flex-direction: column;
gap: 10px;
}
.provider-key-group, .model-select-group {
display: flex;
flex-direction: column;
gap: 4px;
}
label {
font-size: 11px;
font-weight: 500;
color: rgba(255, 255, 255, 0.8);
margin-left: 2px;
}
label > strong {
color: white;
font-weight: 600;
}
.provider-key-group input {
width: 100%; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.2);
color: white; border-radius: 4px; padding: 5px 8px; font-size: 11px; box-sizing: border-box;
}
.key-buttons { display: flex; gap: 4px; }
.key-buttons .settings-button { flex: 1; padding: 4px; }
.model-list {
display: flex; flex-direction: column; gap: 2px; max-height: 120px;
overflow-y: auto; background: rgba(0,0,0,0.3); border-radius: 4px;
padding: 4px; margin-top: 4px;
}
.model-item {
padding: 5px 8px;
font-size: 11px;
border-radius: 3px;
cursor: pointer;
transition: background-color 0.15s;
display: flex;
justify-content: space-between;
align-items: center;
}
.model-item:hover { background-color: rgba(255,255,255,0.1); }
.model-item.selected { background-color: rgba(0, 122, 255, 0.4); font-weight: 500; }
.model-status {
font-size: 9px;
color: rgba(255,255,255,0.6);
margin-left: 8px;
}
.model-status.installed { color: rgba(0, 255, 0, 0.8); }
.model-status.not-installed { color: rgba(255, 200, 0, 0.8); }
.install-progress {
flex: 1;
height: 4px;
background: rgba(255,255,255,0.1);
border-radius: 2px;
margin-left: 8px;
overflow: hidden;
}
.install-progress-bar {
height: 100%;
background: rgba(0, 122, 255, 0.8);
transition: width 0.3s ease;
}
/* Dropdown styles */
select.model-dropdown {
background: rgba(0,0,0,0.2);
color: white;
cursor: pointer;
}
select.model-dropdown option {
background: #1a1a1a;
color: white;
}
select.model-dropdown option:disabled {
color: rgba(255,255,255,0.4);
}
/* ────────────────[ GLASS BYPASS ]─────────────── */
:host-context(body.has-glass) {
animation: none !important;
transition: none !important;
transform: none !important;
will-change: auto !important;
}
:host-context(body.has-glass) * {
background: transparent !important;
filter: none !important;
backdrop-filter: none !important;
box-shadow: none !important;
outline: none !important;
border: none !important;
border-radius: 0 !important;
transition: none !important;
animation: none !important;
}
:host-context(body.has-glass) .settings-container::before {
display: none !important;
}
`;
//////// after_modelStateService ////////
static properties = {
shortcuts: { type: Object, state: true },
firebaseUser: { type: Object, state: true },
isLoading: { type: Boolean, state: true },
isContentProtectionOn: { type: Boolean, state: true },
saving: { type: Boolean, state: true },
providerConfig: { type: Object, state: true },
apiKeys: { type: Object, state: true },
availableLlmModels: { type: Array, state: true },
availableSttModels: { type: Array, state: true },
selectedLlm: { type: String, state: true },
selectedStt: { type: String, state: true },
isLlmListVisible: { type: Boolean },
isSttListVisible: { type: Boolean },
presets: { type: Array, state: true },
selectedPreset: { type: Object, state: true },
showPresets: { type: Boolean, state: true },
autoUpdateEnabled: { type: Boolean, state: true },
autoUpdateLoading: { type: Boolean, state: true },
// Ollama related properties
ollamaStatus: { type: Object, state: true },
ollamaModels: { type: Array, state: true },
installingModels: { type: Object, state: true },
// Whisper related properties
whisperModels: { type: Array, state: true },
};
//////// after_modelStateService ////////
constructor() {
super();
//////// after_modelStateService ////////
this.shortcuts = {};
this.firebaseUser = null;
this.apiKeys = { openai: '', gemini: '', anthropic: '', whisper: '' };
this.providerConfig = {};
this.isLoading = true;
this.isContentProtectionOn = true;
this.saving = false;
this.availableLlmModels = [];
this.availableSttModels = [];
this.selectedLlm = null;
this.selectedStt = null;
this.isLlmListVisible = false;
this.isSttListVisible = false;
this.presets = [];
this.selectedPreset = null;
this.showPresets = false;
// Ollama related
this.ollamaStatus = { installed: false, running: false };
this.ollamaModels = [];
this.installingModels = {}; // { modelName: progress }
// Whisper related
this.whisperModels = [];
this.whisperProgressTracker = null; // Will be initialized when needed
this.handleUsePicklesKey = this.handleUsePicklesKey.bind(this)
this.autoUpdateEnabled = true;
this.autoUpdateLoading = true;
this.loadInitialData();
//////// after_modelStateService ////////
}
async loadAutoUpdateSetting() {
if (!window.api) return;
this.autoUpdateLoading = true;
try {
const enabled = await window.api.settingsView.getAutoUpdate();
this.autoUpdateEnabled = enabled;
console.log('Auto-update setting loaded:', enabled);
} catch (e) {
console.error('Error loading auto-update setting:', e);
this.autoUpdateEnabled = true; // fallback
}
this.autoUpdateLoading = false;
this.requestUpdate();
}
async handleToggleAutoUpdate() {
if (!window.api || this.autoUpdateLoading) return;
this.autoUpdateLoading = true;
this.requestUpdate();
try {
const newValue = !this.autoUpdateEnabled;
const result = await window.api.settingsView.setAutoUpdate(newValue);
if (result && result.success) {
this.autoUpdateEnabled = newValue;
} else {
console.error('Failed to update auto-update setting');
}
} catch (e) {
console.error('Error toggling auto-update:', e);
}
this.autoUpdateLoading = false;
this.requestUpdate();
}
async loadLocalAIStatus() {
try {
// Load Ollama status
const ollamaStatus = await window.api.settingsView.getOllamaStatus();
if (ollamaStatus?.success) {
this.ollamaStatus = { installed: ollamaStatus.installed, running: ollamaStatus.running };
this.ollamaModels = ollamaStatus.models || [];
}
// Load Whisper models status only if Whisper is enabled
if (this.apiKeys?.whisper === 'local') {
const whisperModelsResult = await window.api.settingsView.getWhisperInstalledModels();
if (whisperModelsResult?.success) {
const installedWhisperModels = whisperModelsResult.models;
if (this.providerConfig?.whisper) {
this.providerConfig.whisper.sttModels.forEach(m => {
const installedInfo = installedWhisperModels.find(i => i.id === m.id);
if (installedInfo) {
m.installed = installedInfo.installed;
}
});
}
}
}
// Trigger UI update
this.requestUpdate();
} catch (error) {
console.error('Error loading LocalAI status:', error);
}
}
//////// after_modelStateService ////////
async loadInitialData() {
if (!window.api) return;
this.isLoading = true;
try {
// Load essential data first
const [userState, modelSettings, presets, contentProtection, shortcuts] = await Promise.all([
window.api.settingsView.getCurrentUser(),
window.api.settingsView.getModelSettings(), // Facade call
window.api.settingsView.getPresets(),
window.api.settingsView.getContentProtectionStatus(),
window.api.settingsView.getCurrentShortcuts()
]);
if (userState && userState.isLoggedIn) this.firebaseUser = userState;
if (modelSettings.success) {
const { config, storedKeys, availableLlm, availableStt, selectedModels } = modelSettings.data;
this.providerConfig = config;
this.apiKeys = storedKeys;
this.availableLlmModels = availableLlm;
this.availableSttModels = availableStt;
this.selectedLlm = selectedModels.llm;
this.selectedStt = selectedModels.stt;
}
this.presets = presets || [];
this.isContentProtectionOn = contentProtection;
this.shortcuts = shortcuts || {};
if (this.presets.length > 0) {
const firstUserPreset = this.presets.find(p => p.is_default === 0);
if (firstUserPreset) this.selectedPreset = firstUserPreset;
}
// Load LocalAI status asynchronously to improve initial load time
this.loadLocalAIStatus();
} catch (error) {
console.error('Error loading initial settings data:', error);
} finally {
this.isLoading = false;
}
}
async handleSaveKey(provider) {
const input = this.shadowRoot.querySelector(`#key-input-${provider}`);
if (!input) return;
const key = input.value;
// For Ollama, we need to ensure it's ready first
if (provider === 'ollama') {
this.saving = true;
// First ensure Ollama is installed and running
const ensureResult = await window.api.settingsView.ensureOllamaReady();
if (!ensureResult.success) {
alert(`Failed to setup Ollama: ${ensureResult.error}`);
this.saving = false;
return;
}
// Now validate (which will check if service is running)
const result = await window.api.settingsView.validateKey({ provider, key: 'local' });
if (result.success) {
await this.refreshModelData();
await this.refreshOllamaStatus();
} else {
alert(`Failed to connect to Ollama: ${result.error}`);
}
this.saving = false;
return;
}
// For Whisper, just enable it
if (provider === 'whisper') {
this.saving = true;
const result = await window.api.settingsView.validateKey({ provider, key: 'local' });
if (result.success) {
await this.refreshModelData();
} else {
alert(`Failed to enable Whisper: ${result.error}`);
}
this.saving = false;
return;
}
// For other providers, use the normal flow
this.saving = true;
const result = await window.api.settingsView.validateKey({ provider, key });
if (result.success) {
await this.refreshModelData();
} else {
alert(`Failed to save ${provider} key: ${result.error}`);
input.value = this.apiKeys[provider] || '';
}
this.saving = false;
}
async handleClearKey(provider) {
console.log(`[SettingsView] handleClearKey: ${provider}`);
this.saving = true;
await window.api.settingsView.removeApiKey(provider);
this.apiKeys = { ...this.apiKeys, [provider]: '' };
await this.refreshModelData();
this.saving = false;
}
async refreshModelData() {
const [availableLlm, availableStt, selected, storedKeys] = await Promise.all([
window.api.settingsView.getAvailableModels({ type: 'llm' }),
window.api.settingsView.getAvailableModels({ type: 'stt' }),
window.api.settingsView.getSelectedModels(),
window.api.settingsView.getAllKeys()
]);
this.availableLlmModels = availableLlm;
this.availableSttModels = availableStt;
this.selectedLlm = selected.llm;
this.selectedStt = selected.stt;
this.apiKeys = storedKeys;
this.requestUpdate();
}
async toggleModelList(type) {
const visibilityProp = type === 'llm' ? 'isLlmListVisible' : 'isSttListVisible';
if (!this[visibilityProp]) {
this.saving = true;
this.requestUpdate();
await this.refreshModelData();
this.saving = false;
}
// 데이터 새로고침 후, 목록의 표시 상태를 토글합니다.
this[visibilityProp] = !this[visibilityProp];
this.requestUpdate();
}
async selectModel(type, modelId) {
// Check if this is an Ollama model that needs to be installed
const provider = this.getProviderForModel(type, modelId);
if (provider === 'ollama') {
const ollamaModel = this.ollamaModels.find(m => m.name === modelId);
if (ollamaModel && !ollamaModel.installed && !ollamaModel.installing) {
// Need to install the model first
await this.installOllamaModel(modelId);
return;
}
}
// Check if this is a Whisper model that needs to be downloaded
if (provider === 'whisper' && type === 'stt') {
const isInstalling = this.installingModels[modelId] !== undefined;
const whisperModelInfo = this.providerConfig.whisper.sttModels.find(m => m.id === modelId);
if (whisperModelInfo && !whisperModelInfo.installed && !isInstalling) {
await this.downloadWhisperModel(modelId);
return;
}
}
this.saving = true;
await window.api.settingsView.setSelectedModel({ type, modelId });
if (type === 'llm') this.selectedLlm = modelId;
if (type === 'stt') this.selectedStt = modelId;
this.isLlmListVisible = false;
this.isSttListVisible = false;
this.saving = false;
this.requestUpdate();
}
async refreshOllamaStatus() {
const ollamaStatus = await window.api.settingsView.getOllamaStatus();
if (ollamaStatus?.success) {
this.ollamaStatus = { installed: ollamaStatus.installed, running: ollamaStatus.running };
this.ollamaModels = ollamaStatus.models || [];
}
}
async installOllamaModel(modelName) {
try {
// Ollama 모델 다운로드 시작
this.installingModels = { ...this.installingModels, [modelName]: 0 };
this.requestUpdate();
// 진행률 이벤트 리스너 설정 - 통합 LocalAI 이벤트 사용
const progressHandler = (event, data) => {
if (data.service === 'ollama' && data.model === modelName) {
this.installingModels = { ...this.installingModels, [modelName]: data.progress || 0 };
this.requestUpdate();
}
};
// 통합 LocalAI 이벤트 리스너 등록
window.api.settingsView.onLocalAIInstallProgress(progressHandler);
try {
const result = await window.api.settingsView.pullOllamaModel(modelName);
if (result.success) {
console.log(`[SettingsView] Model ${modelName} installed successfully`);
delete this.installingModels[modelName];
this.requestUpdate();
// 상태 새로고침
await this.refreshOllamaStatus();
await this.refreshModelData();
} else {
throw new Error(result.error || 'Installation failed');
}
} finally {
// 통합 LocalAI 이벤트 리스너 제거
window.api.settingsView.removeOnLocalAIInstallProgress(progressHandler);
}
} catch (error) {
console.error(`[SettingsView] Error installing model ${modelName}:`, error);
delete this.installingModels[modelName];
this.requestUpdate();
}
}
async downloadWhisperModel(modelId) {
// Mark as installing
this.installingModels = { ...this.installingModels, [modelId]: 0 };
this.requestUpdate();
try {
// Set up progress listener - 통합 LocalAI 이벤트 사용
const progressHandler = (event, data) => {
if (data.service === 'whisper' && data.model === modelId) {
this.installingModels = { ...this.installingModels, [modelId]: data.progress || 0 };
this.requestUpdate();
}
};
window.api.settingsView.onLocalAIInstallProgress(progressHandler);
// Start download
const result = await window.api.settingsView.downloadWhisperModel(modelId);
if (result.success) {
// Update the model's installed status
if (this.providerConfig?.whisper?.sttModels) {
const modelInfo = this.providerConfig.whisper.sttModels.find(m => m.id === modelId);
if (modelInfo) {
modelInfo.installed = true;
}
}
// Remove from installing models
delete this.installingModels[modelId];
this.requestUpdate();
// Reload LocalAI status to get fresh data
await this.loadLocalAIStatus();
// Auto-select the model after download
await this.selectModel('stt', modelId);
} else {
// Remove from installing models on failure too
delete this.installingModels[modelId];
this.requestUpdate();
alert(`Failed to download Whisper model: ${result.error}`);
}
// Cleanup
window.api.settingsView.removeOnLocalAIInstallProgress(progressHandler);
} catch (error) {
console.error(`[SettingsView] Error downloading Whisper model ${modelId}:`, error);
// Remove from installing models on error
delete this.installingModels[modelId];
this.requestUpdate();
alert(`Error downloading ${modelId}: ${error.message}`);
}
}
getProviderForModel(type, modelId) {
for (const [providerId, config] of Object.entries(this.providerConfig)) {
const models = type === 'llm' ? config.llmModels : config.sttModels;
if (models?.some(m => m.id === modelId)) {
return providerId;
}
}
return null;
}
handleUsePicklesKey(e) {
e.preventDefault()
if (this.wasJustDragged) return
console.log("Requesting Firebase authentication from main process...")
window.api.settingsView.startFirebaseAuth();
}
//////// after_modelStateService ////////
openShortcutEditor() {
window.api.settingsView.openShortcutSettingsWindow();
}
connectedCallback() {
super.connectedCallback();
this.setupEventListeners();
this.setupIpcListeners();
this.setupWindowResize();
this.loadAutoUpdateSetting();
// Force one height calculation immediately (innerHeight may be 0 at first)
setTimeout(() => this.updateScrollHeight(), 0);
}
disconnectedCallback() {
super.disconnectedCallback();
this.cleanupEventListeners();
this.cleanupIpcListeners();
this.cleanupWindowResize();
// Cancel any ongoing Ollama installations when component is destroyed
const installingModels = Object.keys(this.installingModels);
if (installingModels.length > 0) {
installingModels.forEach(modelName => {
window.api.settingsView.cancelOllamaInstallation(modelName);
});
}
}
setupEventListeners() {
this.addEventListener('mouseenter', this.handleMouseEnter);
this.addEventListener('mouseleave', this.handleMouseLeave);
}
cleanupEventListeners() {
this.removeEventListener('mouseenter', this.handleMouseEnter);
this.removeEventListener('mouseleave', this.handleMouseLeave);
}
setupIpcListeners() {
if (!window.api) return;
this._userStateListener = (event, userState) => {
console.log('[SettingsView] Received user-state-changed:', userState);
if (userState && userState.isLoggedIn) {
this.firebaseUser = userState;
} else {
this.firebaseUser = null;
}
this.loadAutoUpdateSetting();
// Reload model settings when user state changes (Firebase login/logout)
this.loadInitialData();
};
this._settingsUpdatedListener = (event, settings) => {
console.log('[SettingsView] Received settings-updated');
this.settings = settings;
this.requestUpdate();
};
// 프리셋 업데이트 리스너 추가
this._presetsUpdatedListener = async (event) => {
console.log('[SettingsView] Received presets-updated, refreshing presets');
try {
const presets = await window.api.settingsView.getPresets();
this.presets = presets || [];
// 현재 선택된 프리셋이 삭제되었는지 확인 (사용자 프리셋만 고려)
const userPresets = this.presets.filter(p => p.is_default === 0);
if (this.selectedPreset && !userPresets.find(p => p.id === this.selectedPreset.id)) {
this.selectedPreset = userPresets.length > 0 ? userPresets[0] : null;
}
this.requestUpdate();
} catch (error) {
console.error('[SettingsView] Failed to refresh presets:', error);
}
};
this._shortcutListener = (event, keybinds) => {
console.log('[SettingsView] Received updated shortcuts:', keybinds);
this.shortcuts = keybinds;
};
window.api.settingsView.onUserStateChanged(this._userStateListener);
window.api.settingsView.onSettingsUpdated(this._settingsUpdatedListener);
window.api.settingsView.onPresetsUpdated(this._presetsUpdatedListener);
window.api.settingsView.onShortcutsUpdated(this._shortcutListener);
}
cleanupIpcListeners() {
if (!window.api) return;
if (this._userStateListener) {
window.api.settingsView.removeOnUserStateChanged(this._userStateListener);
}
if (this._settingsUpdatedListener) {
window.api.settingsView.removeOnSettingsUpdated(this._settingsUpdatedListener);
}
if (this._presetsUpdatedListener) {
window.api.settingsView.removeOnPresetsUpdated(this._presetsUpdatedListener);
}
if (this._shortcutListener) {
window.api.settingsView.removeOnShortcutsUpdated(this._shortcutListener);
}
}
setupWindowResize() {
this.resizeHandler = () => {
this.requestUpdate();
this.updateScrollHeight();
};
window.addEventListener('resize', this.resizeHandler);
// Initial setup
setTimeout(() => this.updateScrollHeight(), 100);
}
cleanupWindowResize() {
if (this.resizeHandler) {
window.removeEventListener('resize', this.resizeHandler);
}
}
updateScrollHeight() {
// Electron 일부 시점에서 window.innerHeight 가 0 으로 보고되는 버그 보호
const rawHeight = window.innerHeight || (window.screen ? window.screen.height : 0);
const MIN_HEIGHT = 300; // 최소 보장 높이
const maxHeight = Math.max(MIN_HEIGHT, rawHeight);
this.style.maxHeight = `${maxHeight}px`;
const container = this.shadowRoot?.querySelector('.settings-container');
if (container) {
container.style.maxHeight = `${maxHeight}px`;
}
}
handleMouseEnter = () => {
window.api.settingsView.cancelHideSettingsWindow();
// Recalculate height in case it was set to 0 before
this.updateScrollHeight();
}
handleMouseLeave = () => {
window.api.settingsView.hideSettingsWindow();
}
getMainShortcuts() {
return [
{ name: 'Show / Hide', accelerator: this.shortcuts.toggleVisibility },
{ name: 'Ask Anything', accelerator: this.shortcuts.nextStep },
{ name: 'Scroll Up Response', accelerator: this.shortcuts.scrollUp },
{ name: 'Scroll Down Response', accelerator: this.shortcuts.scrollDown },
];
}
renderShortcutKeys(accelerator) {
if (!accelerator) return html`N/A`;
const keyMap = {
'Cmd': '⌘', 'Command': '⌘', 'Ctrl': '⌃', 'Alt': '⌥', 'Shift': '⇧', 'Enter': '↵',
'Up': '↑', 'Down': '↓', 'Left': '←', 'Right': '→'
};
// scrollDown/scrollUp의 특수 처리
if (accelerator.includes('↕')) {
const keys = accelerator.replace('↕','').split('+');
keys.push('↕');
return html`${keys.map(key => html`${keyMap[key] || key} `)}`;
}
const keys = accelerator.split('+');
return html`${keys.map(key => html`${keyMap[key] || key} `)}`;
}
togglePresets() {
this.showPresets = !this.showPresets;
}
async handlePresetSelect(preset) {
this.selectedPreset = preset;
// Here you could implement preset application logic
console.log('Selected preset:', preset);
}
handleMoveLeft() {
console.log('Move Left clicked');
window.api.settingsView.moveWindowStep('left');
}
handleMoveRight() {
console.log('Move Right clicked');
window.api.settingsView.moveWindowStep('right');
}
async handlePersonalize() {
console.log('Personalize clicked');
try {
await window.api.settingsView.openPersonalizePage();
} catch (error) {
console.error('Failed to open personalize page:', error);
}
}
async handleToggleInvisibility() {
console.log('Toggle Invisibility clicked');
this.isContentProtectionOn = await window.api.settingsView.toggleContentProtection();
this.requestUpdate();
}
async handleSaveApiKey() {
const input = this.shadowRoot.getElementById('api-key-input');
if (!input || !input.value) return;
const newApiKey = input.value;
try {
const result = await window.api.settingsView.saveApiKey(newApiKey);
if (result.success) {
console.log('API Key saved successfully via IPC.');
this.apiKey = newApiKey;
this.requestUpdate();
} else {
console.error('Failed to save API Key via IPC:', result.error);
}
} catch(e) {
console.error('Error invoking save-api-key IPC:', e);
}
}
handleQuit() {
console.log('Quit clicked');
window.api.settingsView.quitApplication();
}
handleFirebaseLogout() {
console.log('Firebase Logout clicked');
window.api.settingsView.firebaseLogout();
}
async handleOllamaShutdown() {
console.log('[SettingsView] Shutting down Ollama service...');
if (!window.api) return;
try {
// Show loading state
this.ollamaStatus = { ...this.ollamaStatus, running: false };
this.requestUpdate();
const result = await window.api.settingsView.shutdownOllama(false); // Graceful shutdown
if (result.success) {
console.log('[SettingsView] Ollama shut down successfully');
// Refresh status to reflect the change
await this.refreshOllamaStatus();
} else {
console.error('[SettingsView] Failed to shutdown Ollama:', result.error);
// Restore previous state on error
await this.refreshOllamaStatus();
}
} catch (error) {
console.error('[SettingsView] Error during Ollama shutdown:', error);
// Restore previous state on error
await this.refreshOllamaStatus();
}
}
//////// after_modelStateService ////////
render() {
if (this.isLoading) {
return html`
`;
}
const loggedIn = !!this.firebaseUser;
const apiKeyManagementHTML = html`
${Object.entries(this.providerConfig)
.filter(([id, config]) => !id.includes('-glass'))
.map(([id, config]) => {
if (id === 'ollama') {
// Special UI for Ollama
return html`
${config.name} (Local)
${this.ollamaStatus.installed && this.ollamaStatus.running ? html`
✓ Ollama is running
Stop Ollama Service
` : this.ollamaStatus.installed ? html`
⚠ Ollama installed but not running
this.handleSaveKey(id)}>
Start Ollama
` : html`
✗ Ollama not installed
this.handleSaveKey(id)}>
Install & Setup Ollama
`}
`;
}
if (id === 'whisper') {
// Simplified UI for Whisper without model selection
return html`
${config.name} (Local STT)
${this.apiKeys[id] === 'local' ? html`
✓ Whisper is enabled
this.handleClearKey(id)}>
Disable Whisper
` : html`
this.handleSaveKey(id)}>
Enable Whisper STT
`}
`;
}
// Regular providers
return html`
`;
})}
`;
const getModelName = (type, id) => {
const models = type === 'llm' ? this.availableLlmModels : this.availableSttModels;
const model = models.find(m => m.id === id);
return model ? model.name : id;
}
const modelSelectionHTML = html`
LLM Model: ${getModelName('llm', this.selectedLlm) || 'Not Set'}
this.toggleModelList('llm')} ?disabled=${this.saving || this.availableLlmModels.length === 0}>
Change LLM Model
${this.isLlmListVisible ? html`
${this.availableLlmModels.map(model => {
const isOllama = this.getProviderForModel('llm', model.id) === 'ollama';
const ollamaModel = isOllama ? this.ollamaModels.find(m => m.name === model.id) : null;
const isInstalling = this.installingModels[model.id] !== undefined;
const installProgress = this.installingModels[model.id] || 0;
return html`
this.selectModel('llm', model.id)}>
${model.name}
${isOllama ? html`
${isInstalling ? html`
` : ollamaModel?.installed ? html`
✓ Installed
` : html`
Click to install
`}
` : ''}
`;
})}
` : ''}
STT Model: ${getModelName('stt', this.selectedStt) || 'Not Set'}
this.toggleModelList('stt')} ?disabled=${this.saving || this.availableSttModels.length === 0}>
Change STT Model
${this.isSttListVisible ? html`
${this.availableSttModels.map(model => {
const isWhisper = this.getProviderForModel('stt', model.id) === 'whisper';
const whisperModel = isWhisper && this.providerConfig?.whisper?.sttModels
? this.providerConfig.whisper.sttModels.find(m => m.id === model.id)
: null;
const isInstalling = this.installingModels[model.id] !== undefined;
const installProgress = this.installingModels[model.id] || 0;
return html`
this.selectModel('stt', model.id)}>
${model.name}
${isWhisper ? html`
${isInstalling ? html`
` : whisperModel?.installed ? html`
✓ Installed
` : html`
Not Installed
`}
` : ''}
`;
})}
` : ''}
`;
return html`
${apiKeyManagementHTML}
${modelSelectionHTML}
Edit Shortcuts
${this.getMainShortcuts().map(shortcut => html`
${shortcut.name}
${this.renderShortcutKeys(shortcut.accelerator)}
`)}
${this.presets.filter(p => p.is_default === 0).length === 0 ? html`
No custom presets yet.
Create your first preset
` : this.presets.filter(p => p.is_default === 0).map(preset => html`
this.handlePresetSelect(preset)}>
${preset.title}
${this.selectedPreset?.id === preset.id ? html`Selected ` : ''}
`)}
`;
}
//////// after_modelStateService ////////
}
customElements.define('settings-view', SettingsView);
================================================
FILE: src/ui/settings/ShortCutSettingsView.js
================================================
import { html, css, LitElement } from '../../ui/assets/lit-core-2.7.4.min.js';
const commonSystemShortcuts = new Set([
'Cmd+Q', 'Cmd+W', 'Cmd+A', 'Cmd+S', 'Cmd+Z', 'Cmd+X', 'Cmd+C', 'Cmd+V', 'Cmd+P', 'Cmd+F', 'Cmd+G', 'Cmd+H', 'Cmd+M', 'Cmd+N', 'Cmd+O', 'Cmd+T',
'Ctrl+Q', 'Ctrl+W', 'Ctrl+A', 'Ctrl+S', 'Ctrl+Z', 'Ctrl+X', 'Ctrl+C', 'Ctrl+V', 'Ctrl+P', 'Ctrl+F', 'Ctrl+G', 'Ctrl+H', 'Ctrl+M', 'Ctrl+N', 'Ctrl+O', 'Ctrl+T'
]);
const displayNameMap = {
nextStep: 'Ask Anything',
moveUp: 'Move Up Window',
moveDown: 'Move Down Window',
scrollUp: 'Scroll Up Response',
scrollDown: 'Scroll Down Response',
};
export class ShortcutSettingsView extends LitElement {
static styles = css`
* { font-family:'Helvetica Neue',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
cursor:default; user-select:none; box-sizing:border-box; }
:host { display:flex; width:100%; height:100%; color:white; }
.container { display:flex; flex-direction:column; height:100%;
background:rgba(20,20,20,.9); border-radius:12px;
outline:.5px rgba(255,255,255,.2) solid; outline-offset:-1px;
position:relative; overflow:hidden; padding:12px; }
.close-button{position:absolute;top:10px;right:10px;inline-size:14px;block-size:14px;
background:rgba(255,255,255,.1);border:none;border-radius:3px;
color:rgba(255,255,255,.7);display:grid;place-items:center;
font-size:14px;line-height:0;cursor:pointer;transition:.15s;z-index:10;}
.close-button:hover{background:rgba(255,255,255,.2);color:rgba(255,255,255,.9);}
.title{font-size:14px;font-weight:500;margin:0 0 8px;padding-bottom:8px;
border-bottom:1px solid rgba(255,255,255,.1);text-align:center;}
.scroll-area{flex:1 1 auto;overflow-y:auto;margin:0 -4px;padding:4px;}
.shortcut-entry{display:flex;align-items:center;width:100%;gap:8px;
margin-bottom:8px;font-size:12px;padding:4px;}
.shortcut-name{flex:1 1 auto;color:rgba(255,255,255,.9);font-weight:300;
white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.action-btn{background:none;border:none;color:rgba(0,122,255,.8);
font-size:11px;padding:0 4px;cursor:pointer;transition:.15s;}
.action-btn:hover{color:#0a84ff;text-decoration:underline;}
.shortcut-input{inline-size:120px;background:rgba(0,0,0,.2);
border:1px solid rgba(255,255,255,.2);border-radius:4px;
padding:4px 6px;font:11px 'SF Mono','Menlo',monospace;
color:white;text-align:right;cursor:text;margin-left:auto;}
.shortcut-input:focus,.shortcut-input.capturing{
outline:none;border-color:rgba(0,122,255,.6);
box-shadow:0 0 0 1px rgba(0,122,255,.3);}
.feedback{font-size:10px;margin-top:2px;min-height:12px;}
.feedback.error{color:#ef4444;}
.feedback.success{color:#22c55e;}
.actions{display:flex;gap:4px;padding-top:8px;border-top:1px solid rgba(255,255,255,.1);}
.settings-button{flex:1;background:rgba(255,255,255,.1);
border:1px solid rgba(255,255,255,.2);border-radius:4px;
color:white;padding:5px 10px;font-size:11px;cursor:pointer;transition:.15s;}
.settings-button:hover{background:rgba(255,255,255,.15);}
.settings-button.primary{background:rgba(0,122,255,.25);border-color:rgba(0,122,255,.6);}
.settings-button.primary:hover{background:rgba(0,122,255,.35);}
.settings-button.danger{background:rgba(255,59,48,.1);border-color:rgba(255,59,48,.3);
color:rgba(255,59,48,.9);}
.settings-button.danger:hover{background:rgba(255,59,48,.15);
}
/* ────────────────[ GLASS BYPASS ]─────────────── */
:host-context(body.has-glass) {
animation: none !important;
transition: none !important;
transform: none !important;
will-change: auto !important;
}
:host-context(body.has-glass) * {
background: transparent !important; /* 요청한 투명 처리 */
filter: none !important;
backdrop-filter: none !important;
box-shadow: none !important;
outline: none !important;
border: none !important;
border-radius: 0 !important;
transition: none !important;
animation: none !important;
}
`;
static properties = {
shortcuts: { type: Object, state: true },
isLoading: { type: Boolean, state: true },
capturingKey: { type: String, state: true },
feedback: { type:Object, state:true }
};
constructor() {
super();
this.shortcuts = {};
this.feedback = {};
this.isLoading = true;
this.capturingKey = null;
}
connectedCallback() {
super.connectedCallback();
if (!window.api) return;
this.loadShortcutsHandler = (event, keybinds) => {
this.shortcuts = keybinds;
this.isLoading = false;
};
window.api.shortcutSettingsView.onLoadShortcuts(this.loadShortcutsHandler);
}
disconnectedCallback() {
super.disconnectedCallback();
if (window.api && this.loadShortcutsHandler) {
window.api.shortcutSettingsView.removeOnLoadShortcuts(this.loadShortcutsHandler);
}
}
handleKeydown(e, shortcutKey){
e.preventDefault(); e.stopPropagation();
const result = this._parseAccelerator(e);
if(!result) return; // modifier키만 누른 상태
const {accel, error} = result;
if(error){
this.feedback = {...this.feedback, [shortcutKey]:{type:'error',msg:error}};
return;
}
// 성공
this.shortcuts = {...this.shortcuts, [shortcutKey]:accel};
this.feedback = {...this.feedback, [shortcutKey]:{type:'success',msg:'Shortcut set'}};
this.stopCapture();
}
_parseAccelerator(e){
/* returns {accel?, error?} */
const parts=[]; if(e.metaKey) parts.push('Cmd');
if(e.ctrlKey) parts.push('Ctrl');
if(e.altKey) parts.push('Alt');
if(e.shiftKey) parts.push('Shift');
const isModifier=['Meta','Control','Alt','Shift'].includes(e.key);
if(isModifier) return null;
const map={ArrowUp:'Up',ArrowDown:'Down',ArrowLeft:'Left',ArrowRight:'Right',' ':'Space'};
parts.push(e.key.length===1? e.key.toUpperCase() : (map[e.key]||e.key));
const accel=parts.join('+');
/* ---- validation ---- */
if(parts.length===1) return {error:'Invalid shortcut: needs a modifier'};
if(parts.length>4) return {error:'Invalid shortcut: max 4 keys'};
if(commonSystemShortcuts.has(accel)) return {error:'Invalid shortcut: system reserved'};
return {accel};
}
startCapture(key){ this.capturingKey = key; this.feedback = {...this.feedback, [key]:undefined}; }
disableShortcut(key){
this.shortcuts = {...this.shortcuts, [key]:''}; // 공백 => 작동 X
this.feedback = {...this.feedback, [key]:{type:'success',msg:'Shortcut disabled'}};
}
stopCapture() {
this.capturingKey = null;
}
async handleSave() {
if (!window.api) return;
this.feedback = {};
const result = await window.api.shortcutSettingsView.saveShortcuts(this.shortcuts);
if (!result.success) {
alert('Failed to save shortcuts: ' + result.error);
}
}
handleClose() {
if (!window.api) return;
this.feedback = {};
window.api.shortcutSettingsView.closeShortcutSettingsWindow();
}
async handleResetToDefault() {
if (!window.api) return;
const confirmation = confirm("Are you sure you want to reset all shortcuts to their default values?");
if (!confirmation) return;
try {
const defaultShortcuts = await window.api.shortcutSettingsView.getDefaultShortcuts();
this.shortcuts = defaultShortcuts;
} catch (error) {
alert('Failed to load default settings.');
}
}
formatShortcutName(name) {
if (displayNameMap[name]) {
return displayNameMap[name];
}
const result = name.replace(/([A-Z])/g, " $1");
return result.charAt(0).toUpperCase() + result.slice(1);
}
render(){
if(this.isLoading){
return html``;
}
return html`
×
Edit Shortcuts
Cancel
Reset to Default
Save
`;
}
}
customElements.define('shortcut-settings-view', ShortcutSettingsView);
================================================
FILE: src/ui/styles/glass-bypass.css
================================================
/*
이 파일은 body.has-glass 클래스가 적용되었을 때 모든 애니메이션, 트랜지션,
배경, 테두리 등을 비활성화하여 깨끗한 투명 효과(Glass)를 보장합니다.
*/
body.has-glass * {
animation: none !important;
transition: none !important;
background: transparent !important;
border: none !important;
box-shadow: none !important;
backdrop-filter: none !important;
}
================================================
FILE: src/window/smoothMovementManager.js
================================================
const { screen } = require('electron');
class SmoothMovementManager {
constructor(windowPool) {
this.windowPool = windowPool;
this.stepSize = 80;
this.animationDuration = 300;
this.headerPosition = { x: 0, y: 0 };
this.isAnimating = false;
this.hiddenPosition = null;
this.lastVisiblePosition = null;
this.currentDisplayId = null;
this.animationFrameId = null;
this.animationTimers = new Map();
}
/**
* @param {BrowserWindow} win
* @returns {boolean}
*/
_isWindowValid(win) {
if (!win || win.isDestroyed()) {
// 해당 창의 타이머가 있으면 정리
if (this.animationTimers.has(win)) {
clearTimeout(this.animationTimers.get(win));
this.animationTimers.delete(win);
}
return false;
}
return true;
}
/**
*
* @param {BrowserWindow} win
* @param {number} targetX
* @param {number} targetY
* @param {object} [options]
* @param {object} [options.sizeOverride]
* @param {function} [options.onComplete]
* @param {number} [options.duration]
*/
animateWindow(win, targetX, targetY, options = {}) {
if (!this._isWindowValid(win)) {
if (options.onComplete) options.onComplete();
return;
}
const { sizeOverride, onComplete, duration: animDuration } = options;
const start = win.getBounds();
const startTime = Date.now();
const duration = animDuration || this.animationDuration;
const { width, height } = sizeOverride || start;
const step = () => {
if (!this._isWindowValid(win)) {
if (onComplete) onComplete();
return;
}
const p = Math.min((Date.now() - startTime) / duration, 1);
const eased = 1 - Math.pow(1 - p, 3); // ease-out-cubic
const x = start.x + (targetX - start.x) * eased;
const y = start.y + (targetY - start.y) * eased;
win.setBounds({ x: Math.round(x), y: Math.round(y), width, height });
if (p < 1) {
setTimeout(step, 8);
} else {
this.layoutManager.updateLayout();
if (onComplete) {
onComplete();
}
}
};
step();
}
fade(win, { from, to, duration = 250, onComplete }) {
if (!this._isWindowValid(win)) {
if (onComplete) onComplete();
return;
}
const startOpacity = from ?? win.getOpacity();
const startTime = Date.now();
const step = () => {
if (!this._isWindowValid(win)) {
if (onComplete) onComplete(); return;
}
const progress = Math.min(1, (Date.now() - startTime) / duration);
const eased = 1 - Math.pow(1 - progress, 3);
win.setOpacity(startOpacity + (to - startOpacity) * eased);
if (progress < 1) {
setTimeout(step, 8);
} else {
win.setOpacity(to);
if (onComplete) onComplete();
}
};
step();
}
animateWindowBounds(win, targetBounds, options = {}) {
if (this.animationTimers.has(win)) {
clearTimeout(this.animationTimers.get(win));
}
if (!this._isWindowValid(win)) {
if (options.onComplete) options.onComplete();
return;
}
this.isAnimating = true;
const startBounds = win.getBounds();
const startTime = Date.now();
const duration = options.duration || this.animationDuration;
const step = () => {
if (!this._isWindowValid(win)) {
if (options.onComplete) options.onComplete();
return;
}
const progress = Math.min(1, (Date.now() - startTime) / duration);
const eased = 1 - Math.pow(1 - progress, 3);
const newBounds = {
x: Math.round(startBounds.x + (targetBounds.x - startBounds.x) * eased),
y: Math.round(startBounds.y + (targetBounds.y - startBounds.y) * eased),
width: Math.round(startBounds.width + ((targetBounds.width ?? startBounds.width) - startBounds.width) * eased),
height: Math.round(startBounds.height + ((targetBounds.height ?? startBounds.height) - startBounds.height) * eased),
};
win.setBounds(newBounds);
if (progress < 1) {
const timerId = setTimeout(step, 8);
this.animationTimers.set(win, timerId);
} else {
win.setBounds(targetBounds);
this.animationTimers.delete(win);
if (this.animationTimers.size === 0) {
this.isAnimating = false;
}
if (options.onComplete) options.onComplete();
}
};
step();
}
animateWindowPosition(win, targetPosition, options = {}) {
if (!this._isWindowValid(win)) {
if (options.onComplete) options.onComplete();
return;
}
const currentBounds = win.getBounds();
const targetBounds = { ...currentBounds, ...targetPosition };
this.animateWindowBounds(win, targetBounds, options);
}
animateLayout(layout, animated = true) {
if (!layout) return;
for (const winName in layout) {
const win = this.windowPool.get(winName);
const targetBounds = layout[winName];
if (win && !win.isDestroyed() && targetBounds) {
if (animated) {
this.animateWindowBounds(win, targetBounds);
} else {
win.setBounds(targetBounds);
}
}
}
}
destroy() {
if (this.animationFrameId) {
clearTimeout(this.animationFrameId);
this.animationFrameId = null;
}
this.isAnimating = false;
console.log('[Movement] Manager destroyed');
}
}
module.exports = SmoothMovementManager;
================================================
FILE: src/window/windowLayoutManager.js
================================================
const { screen } = require('electron');
/**
*
* @param {BrowserWindow} window
* @returns {Display}
*/
function getCurrentDisplay(window) {
if (!window || window.isDestroyed()) return screen.getPrimaryDisplay();
const windowBounds = window.getBounds();
const windowCenter = {
x: windowBounds.x + windowBounds.width / 2,
y: windowBounds.y + windowBounds.height / 2,
};
return screen.getDisplayNearestPoint(windowCenter);
}
class WindowLayoutManager {
/**
* @param {Map} windowPool - 관리할 창들의 맵
*/
constructor(windowPool) {
this.windowPool = windowPool;
this.isUpdating = false;
this.PADDING = 80;
}
getHeaderPosition = () => {
const header = this.windowPool.get('header');
if (header) {
const [x, y] = header.getPosition();
return { x, y };
}
return { x: 0, y: 0 };
};
/**
*
* @returns {{name: string, primary: string, secondary: string}}
*/
determineLayoutStrategy(headerBounds, screenWidth, screenHeight, relativeX, relativeY, workAreaX, workAreaY) {
const headerRelX = headerBounds.x - workAreaX;
const headerRelY = headerBounds.y - workAreaY;
const spaceBelow = screenHeight - (headerRelY + headerBounds.height);
const spaceAbove = headerRelY;
const spaceLeft = headerRelX;
const spaceRight = screenWidth - (headerRelX + headerBounds.width);
if (spaceBelow >= 400) {
return { name: 'below', primary: 'below', secondary: relativeX < 0.5 ? 'right' : 'left' };
} else if (spaceAbove >= 400) {
return { name: 'above', primary: 'above', secondary: relativeX < 0.5 ? 'right' : 'left' };
} else if (relativeX < 0.3 && spaceRight >= 800) {
return { name: 'right-side', primary: 'right', secondary: spaceBelow > spaceAbove ? 'below' : 'above' };
} else if (relativeX > 0.7 && spaceLeft >= 800) {
return { name: 'left-side', primary: 'left', secondary: spaceBelow > spaceAbove ? 'below' : 'above' };
} else {
return { name: 'adaptive', primary: spaceBelow > spaceAbove ? 'below' : 'above', secondary: spaceRight > spaceLeft ? 'right' : 'left' };
}
}
/**
* @returns {{x: number, y: number} | null}
*/
calculateSettingsWindowPosition() {
const header = this.windowPool.get('header');
const settings = this.windowPool.get('settings');
if (!header || header.isDestroyed() || !settings || settings.isDestroyed()) {
return null;
}
const headerBounds = header.getBounds();
const settingsBounds = settings.getBounds();
const display = getCurrentDisplay(header);
const { x: workAreaX, y: workAreaY, width: screenWidth, height: screenHeight } = display.workArea;
const PAD = 5;
const buttonPadding = 170;
const x = headerBounds.x + headerBounds.width - settingsBounds.width + buttonPadding;
const y = headerBounds.y + headerBounds.height + PAD;
const clampedX = Math.max(workAreaX + 10, Math.min(workAreaX + screenWidth - settingsBounds.width - 10, x));
const clampedY = Math.max(workAreaY + 10, Math.min(workAreaY + screenHeight - settingsBounds.height - 10, y));
return { x: Math.round(clampedX), y: Math.round(clampedY) };
}
calculateHeaderResize(header, { width, height }) {
if (!header) return null;
const currentBounds = header.getBounds();
const centerX = currentBounds.x + currentBounds.width / 2;
const newX = Math.round(centerX - width / 2);
const display = getCurrentDisplay(header);
const { x: workAreaX, width: workAreaWidth } = display.workArea;
const clampedX = Math.max(workAreaX, Math.min(workAreaX + workAreaWidth - width, newX));
return { x: clampedX, y: currentBounds.y, width, height };
}
calculateClampedPosition(header, { x: newX, y: newY }) {
if (!header) return null;
const targetDisplay = screen.getDisplayNearestPoint({ x: newX, y: newY });
const { x: workAreaX, y: workAreaY, width, height } = targetDisplay.workArea;
const headerBounds = header.getBounds();
const clampedX = Math.max(workAreaX, Math.min(newX, workAreaX + width - headerBounds.width));
const clampedY = Math.max(workAreaY, Math.min(newY, workAreaY + height - headerBounds.height));
return { x: clampedX, y: clampedY };
}
calculateWindowHeightAdjustment(senderWindow, targetHeight) {
if (!senderWindow) return null;
const currentBounds = senderWindow.getBounds();
const minHeight = senderWindow.getMinimumSize()[1];
const maxHeight = senderWindow.getMaximumSize()[1];
let adjustedHeight = Math.max(minHeight, targetHeight);
if (maxHeight > 0) {
adjustedHeight = Math.min(maxHeight, adjustedHeight);
}
console.log(`[Layout Debug] calculateWindowHeightAdjustment: targetHeight=${targetHeight}`);
return { ...currentBounds, height: adjustedHeight };
}
// 기존 getTargetBoundsForFeatureWindows를 이 함수로 대체합니다.
calculateFeatureWindowLayout(visibility, headerBoundsOverride = null) {
const header = this.windowPool.get('header');
const headerBounds = headerBoundsOverride || (header ? header.getBounds() : null);
if (!headerBounds) return {};
let display;
if (headerBoundsOverride) {
const boundsCenter = {
x: headerBounds.x + headerBounds.width / 2,
y: headerBounds.y + headerBounds.height / 2,
};
display = screen.getDisplayNearestPoint(boundsCenter);
} else {
display = getCurrentDisplay(header);
}
const { width: screenWidth, height: screenHeight, x: workAreaX, y: workAreaY } = display.workArea;
const ask = this.windowPool.get('ask');
const listen = this.windowPool.get('listen');
const askVis = visibility.ask && ask && !ask.isDestroyed();
const listenVis = visibility.listen && listen && !listen.isDestroyed();
if (!askVis && !listenVis) return {};
const PAD = 8;
const headerTopRel = headerBounds.y - workAreaY;
const headerBottomRel = headerTopRel + headerBounds.height;
const headerCenterXRel = headerBounds.x - workAreaX + headerBounds.width / 2;
const relativeX = headerCenterXRel / screenWidth;
const relativeY = (headerBounds.y - workAreaY) / screenHeight;
const strategy = this.determineLayoutStrategy(headerBounds, screenWidth, screenHeight, relativeX, relativeY, workAreaX, workAreaY);
const askB = askVis ? ask.getBounds() : null;
const listenB = listenVis ? listen.getBounds() : null;
if (askVis) {
console.log(`[Layout Debug] Ask Window Bounds: height=${askB.height}, width=${askB.width}`);
}
if (listenVis) {
console.log(`[Layout Debug] Listen Window Bounds: height=${listenB.height}, width=${listenB.width}`);
}
const layout = {};
if (askVis && listenVis) {
let askXRel = headerCenterXRel - (askB.width / 2);
let listenXRel = askXRel - listenB.width - PAD;
if (listenXRel < PAD) {
listenXRel = PAD;
askXRel = listenXRel + listenB.width + PAD;
}
if (askXRel + askB.width > screenWidth - PAD) {
askXRel = screenWidth - PAD - askB.width;
listenXRel = askXRel - listenB.width - PAD;
}
if (strategy.primary === 'above') {
const windowBottomAbs = headerBounds.y - PAD;
layout.ask = { x: Math.round(askXRel + workAreaX), y: Math.round(windowBottomAbs - askB.height), width: askB.width, height: askB.height };
layout.listen = { x: Math.round(listenXRel + workAreaX), y: Math.round(windowBottomAbs - listenB.height), width: listenB.width, height: listenB.height };
} else { // 'below'
const yAbs = headerBounds.y + headerBounds.height + PAD;
layout.ask = { x: Math.round(askXRel + workAreaX), y: Math.round(yAbs), width: askB.width, height: askB.height };
layout.listen = { x: Math.round(listenXRel + workAreaX), y: Math.round(yAbs), width: listenB.width, height: listenB.height };
}
} else { // Single window
const winName = askVis ? 'ask' : 'listen';
const winB = askVis ? askB : listenB;
if (!winB) return {};
let xRel = headerCenterXRel - winB.width / 2;
xRel = Math.max(PAD, Math.min(screenWidth - winB.width - PAD, xRel));
let yPos;
if (strategy.primary === 'above') {
yPos = (headerBounds.y - workAreaY) - PAD - winB.height;
} else { // 'below'
yPos = (headerBounds.y - workAreaY) + headerBounds.height + PAD;
}
layout[winName] = { x: Math.round(xRel + workAreaX), y: Math.round(yPos + workAreaY), width: winB.width, height: winB.height };
}
return layout;
}
calculateShortcutSettingsWindowPosition() {
const header = this.windowPool.get('header');
const shortcutSettings = this.windowPool.get('shortcut-settings');
if (!header || !shortcutSettings) return null;
const headerBounds = header.getBounds();
const shortcutBounds = shortcutSettings.getBounds();
const { workArea } = getCurrentDisplay(header);
let newX = Math.round(headerBounds.x + (headerBounds.width / 2) - (shortcutBounds.width / 2));
let newY = Math.round(headerBounds.y);
newX = Math.max(workArea.x, Math.min(newX, workArea.x + workArea.width - shortcutBounds.width));
newY = Math.max(workArea.y, Math.min(newY, workArea.y + workArea.height - shortcutBounds.height));
return { x: newX, y: newY, width: shortcutBounds.width, height: shortcutBounds.height };
}
calculateStepMovePosition(header, direction) {
if (!header) return null;
const currentBounds = header.getBounds();
const stepSize = 80; // 이동 간격
let targetX = currentBounds.x;
let targetY = currentBounds.y;
switch (direction) {
case 'left': targetX -= stepSize; break;
case 'right': targetX += stepSize; break;
case 'up': targetY -= stepSize; break;
case 'down': targetY += stepSize; break;
}
return this.calculateClampedPosition(header, { x: targetX, y: targetY });
}
calculateEdgePosition(header, direction) {
if (!header) return null;
const display = getCurrentDisplay(header);
const { workArea } = display;
const currentBounds = header.getBounds();
let targetX = currentBounds.x;
let targetY = currentBounds.y;
switch (direction) {
case 'left': targetX = workArea.x; break;
case 'right': targetX = workArea.x + workArea.width - currentBounds.width; break;
case 'up': targetY = workArea.y; break;
case 'down': targetY = workArea.y + workArea.height - currentBounds.height; break;
}
return { x: targetX, y: targetY };
}
calculateNewPositionForDisplay(window, targetDisplayId) {
if (!window) return null;
const targetDisplay = screen.getAllDisplays().find(d => d.id === targetDisplayId);
if (!targetDisplay) return null;
const currentBounds = window.getBounds();
const currentDisplay = getCurrentDisplay(window);
if (currentDisplay.id === targetDisplay.id) return { x: currentBounds.x, y: currentBounds.y };
const relativeX = (currentBounds.x - currentDisplay.workArea.x) / currentDisplay.workArea.width;
const relativeY = (currentBounds.y - currentDisplay.workArea.y) / currentDisplay.workArea.height;
const targetX = targetDisplay.workArea.x + targetDisplay.workArea.width * relativeX;
const targetY = targetDisplay.workArea.y + targetDisplay.workArea.height * relativeY;
const clampedX = Math.max(targetDisplay.workArea.x, Math.min(targetX, targetDisplay.workArea.x + targetDisplay.workArea.width - currentBounds.width));
const clampedY = Math.max(targetDisplay.workArea.y, Math.min(targetY, targetDisplay.workArea.y + targetDisplay.workArea.height - currentBounds.height));
return { x: Math.round(clampedX), y: Math.round(clampedY) };
}
/**
* @param {Rectangle} bounds1
* @param {Rectangle} bounds2
* @returns {boolean}
*/
boundsOverlap(bounds1, bounds2) {
const margin = 10;
return !(
bounds1.x + bounds1.width + margin < bounds2.x ||
bounds2.x + bounds2.width + margin < bounds1.x ||
bounds1.y + bounds1.height + margin < bounds2.y ||
bounds2.y + bounds2.height + margin < bounds1.y
);
}
}
module.exports = WindowLayoutManager;
================================================
FILE: src/window/windowManager.js
================================================
const { BrowserWindow, globalShortcut, screen, app, shell } = require('electron');
const WindowLayoutManager = require('./windowLayoutManager');
const SmoothMovementManager = require('./smoothMovementManager');
const path = require('node:path');
const os = require('os');
const shortcutsService = require('../features/shortcuts/shortcutsService');
const internalBridge = require('../bridge/internalBridge');
const permissionRepository = require('../features/common/repositories/permission');
/* ────────────────[ GLASS BYPASS ]─────────────── */
let liquidGlass;
const isLiquidGlassSupported = () => {
if (process.platform !== 'darwin') {
return false;
}
const majorVersion = parseInt(os.release().split('.')[0], 10);
// return majorVersion >= 25; // macOS 26+ (Darwin 25+)
return majorVersion >= 26; // See you soon!
};
let shouldUseLiquidGlass = isLiquidGlassSupported();
if (shouldUseLiquidGlass) {
try {
liquidGlass = require('electron-liquid-glass');
} catch (e) {
console.warn('Could not load optional dependency "electron-liquid-glass". The feature will be disabled.');
shouldUseLiquidGlass = false;
}
}
/* ────────────────[ GLASS BYPASS ]─────────────── */
let isContentProtectionOn = true;
let lastVisibleWindows = new Set(['header']);
let currentHeaderState = 'apikey';
const windowPool = new Map();
let settingsHideTimer = null;
let layoutManager = null;
let movementManager = null;
function updateChildWindowLayouts(animated = true) {
// if (movementManager.isAnimating) return;
const visibleWindows = {};
const listenWin = windowPool.get('listen');
const askWin = windowPool.get('ask');
if (listenWin && !listenWin.isDestroyed() && listenWin.isVisible()) {
visibleWindows.listen = true;
}
if (askWin && !askWin.isDestroyed() && askWin.isVisible()) {
visibleWindows.ask = true;
}
if (Object.keys(visibleWindows).length === 0) return;
const newLayout = layoutManager.calculateFeatureWindowLayout(visibleWindows);
movementManager.animateLayout(newLayout, animated);
}
const showSettingsWindow = () => {
internalBridge.emit('window:requestVisibility', { name: 'settings', visible: true });
};
const hideSettingsWindow = () => {
internalBridge.emit('window:requestVisibility', { name: 'settings', visible: false });
};
const cancelHideSettingsWindow = () => {
internalBridge.emit('window:requestVisibility', { name: 'settings', visible: true });
};
const moveWindowStep = (direction) => {
internalBridge.emit('window:moveStep', { direction });
};
const resizeHeaderWindow = ({ width, height }) => {
internalBridge.emit('window:resizeHeaderWindow', { width, height });
};
const handleHeaderAnimationFinished = (state) => {
internalBridge.emit('window:headerAnimationFinished', state);
};
const getHeaderPosition = () => {
return new Promise((resolve) => {
internalBridge.emit('window:getHeaderPosition', (position) => {
resolve(position);
});
});
};
const moveHeaderTo = (newX, newY) => {
internalBridge.emit('window:moveHeaderTo', { newX, newY });
};
const adjustWindowHeight = (winName, targetHeight) => {
internalBridge.emit('window:adjustWindowHeight', { winName, targetHeight });
};
function setupWindowController(windowPool, layoutManager, movementManager) {
internalBridge.on('window:requestVisibility', ({ name, visible }) => {
handleWindowVisibilityRequest(windowPool, layoutManager, movementManager, name, visible);
});
internalBridge.on('window:requestToggleAllWindowsVisibility', ({ targetVisibility }) => {
changeAllWindowsVisibility(windowPool, targetVisibility);
});
internalBridge.on('window:moveToDisplay', ({ displayId }) => {
// movementManager.moveToDisplay(displayId);
const header = windowPool.get('header');
if (header) {
const newPosition = layoutManager.calculateNewPositionForDisplay(header, displayId);
if (newPosition) {
movementManager.animateWindowPosition(header, newPosition, {
onComplete: () => updateChildWindowLayouts(true)
});
}
}
});
internalBridge.on('window:moveToEdge', ({ direction }) => {
const header = windowPool.get('header');
if (header) {
const newPosition = layoutManager.calculateEdgePosition(header, direction);
movementManager.animateWindowPosition(header, newPosition, {
onComplete: () => updateChildWindowLayouts(true)
});
}
});
internalBridge.on('window:moveStep', ({ direction }) => {
const header = windowPool.get('header');
if (header) {
const newHeaderPosition = layoutManager.calculateStepMovePosition(header, direction);
if (!newHeaderPosition) return;
const futureHeaderBounds = { ...header.getBounds(), ...newHeaderPosition };
const visibleWindows = {};
const listenWin = windowPool.get('listen');
const askWin = windowPool.get('ask');
if (listenWin && !listenWin.isDestroyed() && listenWin.isVisible()) {
visibleWindows.listen = true;
}
if (askWin && !askWin.isDestroyed() && askWin.isVisible()) {
visibleWindows.ask = true;
}
const newChildLayout = layoutManager.calculateFeatureWindowLayout(visibleWindows, futureHeaderBounds);
movementManager.animateWindowPosition(header, newHeaderPosition);
movementManager.animateLayout(newChildLayout);
}
});
internalBridge.on('window:resizeHeaderWindow', ({ width, height }) => {
const header = windowPool.get('header');
if (!header || movementManager.isAnimating) return;
const newHeaderBounds = layoutManager.calculateHeaderResize(header, { width, height });
const wasResizable = header.isResizable();
if (!wasResizable) header.setResizable(true);
movementManager.animateWindowBounds(header, newHeaderBounds, {
onComplete: () => {
if (!wasResizable) header.setResizable(false);
updateChildWindowLayouts(true);
}
});
});
internalBridge.on('window:headerAnimationFinished', (state) => {
const header = windowPool.get('header');
if (!header || header.isDestroyed()) return;
if (state === 'hidden') {
header.hide();
} else if (state === 'visible') {
updateChildWindowLayouts(false);
}
});
internalBridge.on('window:getHeaderPosition', (reply) => {
const header = windowPool.get('header');
if (header && !header.isDestroyed()) {
reply(header.getBounds());
} else {
reply({ x: 0, y: 0, width: 0, height: 0 });
}
});
internalBridge.on('window:moveHeaderTo', ({ newX, newY }) => {
const header = windowPool.get('header');
if (header) {
const newPosition = layoutManager.calculateClampedPosition(header, { x: newX, y: newY });
header.setPosition(newPosition.x, newPosition.y);
}
});
internalBridge.on('window:adjustWindowHeight', ({ winName, targetHeight }) => {
console.log(`[Layout Debug] adjustWindowHeight: targetHeight=${targetHeight}`);
const senderWindow = windowPool.get(winName);
if (senderWindow) {
const newBounds = layoutManager.calculateWindowHeightAdjustment(senderWindow, targetHeight);
const wasResizable = senderWindow.isResizable();
if (!wasResizable) senderWindow.setResizable(true);
movementManager.animateWindowBounds(senderWindow, newBounds, {
onComplete: () => {
if (!wasResizable) senderWindow.setResizable(false);
updateChildWindowLayouts(true);
}
});
}
});
}
function changeAllWindowsVisibility(windowPool, targetVisibility) {
const header = windowPool.get('header');
if (!header) return;
if (typeof targetVisibility === 'boolean' &&
header.isVisible() === targetVisibility) {
return;
}
if (header.isVisible()) {
lastVisibleWindows.clear();
windowPool.forEach((win, name) => {
if (win && !win.isDestroyed() && win.isVisible()) {
lastVisibleWindows.add(name);
}
});
lastVisibleWindows.forEach(name => {
if (name === 'header') return;
const win = windowPool.get(name);
if (win && !win.isDestroyed()) win.hide();
});
header.hide();
return;
}
lastVisibleWindows.forEach(name => {
const win = windowPool.get(name);
if (win && !win.isDestroyed())
win.show();
});
}
/**
*
* @param {Map} windowPool
* @param {WindowLayoutManager} layoutManager
* @param {SmoothMovementManager} movementManager
* @param {'listen' | 'ask' | 'settings' | 'shortcut-settings'} name
* @param {boolean} shouldBeVisible
*/
async function handleWindowVisibilityRequest(windowPool, layoutManager, movementManager, name, shouldBeVisible) {
console.log(`[WindowManager] Request: set '${name}' visibility to ${shouldBeVisible}`);
const win = windowPool.get(name);
if (!win || win.isDestroyed()) {
console.warn(`[WindowManager] Window '${name}' not found or destroyed.`);
return;
}
if (name !== 'settings') {
const isCurrentlyVisible = win.isVisible();
if (isCurrentlyVisible === shouldBeVisible) {
console.log(`[WindowManager] Window '${name}' is already in the desired state.`);
return;
}
}
const disableClicks = (selectedWindow) => {
for (const [name, win] of windowPool) {
if (win !== selectedWindow && !win.isDestroyed()) {
win.setIgnoreMouseEvents(true, { forward: true });
}
}
};
const restoreClicks = () => {
for (const [, win] of windowPool) {
if (!win.isDestroyed()) win.setIgnoreMouseEvents(false);
}
};
if (name === 'settings') {
if (shouldBeVisible) {
// Cancel any pending hide operations
if (settingsHideTimer) {
clearTimeout(settingsHideTimer);
settingsHideTimer = null;
}
const position = layoutManager.calculateSettingsWindowPosition();
if (position) {
win.setBounds(position);
win.__lockedByButton = true;
win.show();
win.moveTop();
win.setAlwaysOnTop(true);
} else {
console.warn('[WindowManager] Could not calculate settings window position.');
}
} else {
// Hide after a delay
if (settingsHideTimer) {
clearTimeout(settingsHideTimer);
}
settingsHideTimer = setTimeout(() => {
if (win && !win.isDestroyed()) {
win.setAlwaysOnTop(false);
win.hide();
}
settingsHideTimer = null;
}, 200);
win.__lockedByButton = false;
}
return;
}
if (name === 'shortcut-settings') {
if (shouldBeVisible) {
// layoutManager.positionShortcutSettingsWindow();
const newBounds = layoutManager.calculateShortcutSettingsWindowPosition();
if (newBounds) win.setBounds(newBounds);
if (process.platform === 'darwin') {
win.setAlwaysOnTop(true, 'screen-saver');
} else {
win.setAlwaysOnTop(true);
}
// globalShortcut.unregisterAll();
disableClicks(win);
win.show();
} else {
if (process.platform === 'darwin') {
win.setAlwaysOnTop(false, 'screen-saver');
} else {
win.setAlwaysOnTop(false);
}
restoreClicks();
win.hide();
}
return;
}
if (name === 'listen' || name === 'ask') {
const win = windowPool.get(name);
const otherName = name === 'listen' ? 'ask' : 'listen';
const otherWin = windowPool.get(otherName);
const isOtherWinVisible = otherWin && !otherWin.isDestroyed() && otherWin.isVisible();
const ANIM_OFFSET_X = 50;
const ANIM_OFFSET_Y = 20;
const finalVisibility = {
listen: (name === 'listen' && shouldBeVisible) || (otherName === 'listen' && isOtherWinVisible),
ask: (name === 'ask' && shouldBeVisible) || (otherName === 'ask' && isOtherWinVisible),
};
if (!shouldBeVisible) {
finalVisibility[name] = false;
}
const targetLayout = layoutManager.calculateFeatureWindowLayout(finalVisibility);
if (shouldBeVisible) {
if (!win) return;
const targetBounds = targetLayout[name];
if (!targetBounds) return;
const startPos = { ...targetBounds };
if (name === 'listen') startPos.x -= ANIM_OFFSET_X;
else if (name === 'ask') startPos.y -= ANIM_OFFSET_Y;
win.setOpacity(0);
win.setBounds(startPos);
win.show();
movementManager.fade(win, { to: 1 });
movementManager.animateLayout(targetLayout);
} else {
if (!win || !win.isVisible()) return;
const currentBounds = win.getBounds();
const targetPos = { ...currentBounds };
if (name === 'listen') targetPos.x -= ANIM_OFFSET_X;
else if (name === 'ask') targetPos.y -= ANIM_OFFSET_Y;
movementManager.fade(win, { to: 0, onComplete: () => win.hide() });
movementManager.animateWindowPosition(win, targetPos);
// 다른 창들도 새 레이아웃으로 애니메이션
const otherWindowsLayout = { ...targetLayout };
delete otherWindowsLayout[name];
movementManager.animateLayout(otherWindowsLayout);
}
}
}
const setContentProtection = (status) => {
isContentProtectionOn = status;
console.log(`[Protection] Content protection toggled to: ${isContentProtectionOn}`);
windowPool.forEach(win => {
if (win && !win.isDestroyed()) {
win.setContentProtection(isContentProtectionOn);
}
});
};
const getContentProtectionStatus = () => isContentProtectionOn;
const toggleContentProtection = () => {
const newStatus = !getContentProtectionStatus();
setContentProtection(newStatus);
return newStatus;
};
const openLoginPage = () => {
const webUrl = process.env.pickleglass_WEB_URL || 'http://localhost:3000';
const personalizeUrl = `${webUrl}/personalize?desktop=true`;
shell.openExternal(personalizeUrl);
console.log('Opening personalization page:', personalizeUrl);
};
function createFeatureWindows(header, namesToCreate) {
// if (windowPool.has('listen')) return;
const commonChildOptions = {
parent: header,
show: false,
frame: false,
transparent: true,
vibrancy: false,
hasShadow: false,
skipTaskbar: true,
hiddenInMissionControl: true,
resizable: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, '../preload.js'),
},
};
const createFeatureWindow = (name) => {
if (windowPool.has(name)) return;
switch (name) {
case 'listen': {
const listen = new BrowserWindow({
...commonChildOptions, width:400,minWidth:400,maxWidth:900,
maxHeight:900,
});
listen.setContentProtection(isContentProtectionOn);
listen.setVisibleOnAllWorkspaces(true,{visibleOnFullScreen:true});
if (process.platform === 'darwin') {
listen.setWindowButtonVisibility(false);
}
const listenLoadOptions = { query: { view: 'listen' } };
if (!shouldUseLiquidGlass) {
listen.loadFile(path.join(__dirname, '../ui/app/content.html'), listenLoadOptions);
}
else {
listenLoadOptions.query.glass = 'true';
listen.loadFile(path.join(__dirname, '../ui/app/content.html'), listenLoadOptions);
listen.webContents.once('did-finish-load', () => {
const viewId = liquidGlass.addView(listen.getNativeWindowHandle());
if (viewId !== -1) {
liquidGlass.unstable_setVariant(viewId, liquidGlass.GlassMaterialVariant.bubbles);
// liquidGlass.unstable_setScrim(viewId, 1);
// liquidGlass.unstable_setSubdued(viewId, 1);
}
});
}
if (!app.isPackaged) {
listen.webContents.openDevTools({ mode: 'detach' });
}
windowPool.set('listen', listen);
break;
}
// ask
case 'ask': {
const ask = new BrowserWindow({ ...commonChildOptions, width:600 });
ask.setContentProtection(isContentProtectionOn);
ask.setVisibleOnAllWorkspaces(true,{visibleOnFullScreen:true});
if (process.platform === 'darwin') {
ask.setWindowButtonVisibility(false);
}
const askLoadOptions = { query: { view: 'ask' } };
if (!shouldUseLiquidGlass) {
ask.loadFile(path.join(__dirname, '../ui/app/content.html'), askLoadOptions);
}
else {
askLoadOptions.query.glass = 'true';
ask.loadFile(path.join(__dirname, '../ui/app/content.html'), askLoadOptions);
ask.webContents.once('did-finish-load', () => {
const viewId = liquidGlass.addView(ask.getNativeWindowHandle());
if (viewId !== -1) {
liquidGlass.unstable_setVariant(viewId, liquidGlass.GlassMaterialVariant.bubbles);
// liquidGlass.unstable_setScrim(viewId, 1);
// liquidGlass.unstable_setSubdued(viewId, 1);
}
});
}
// Open DevTools in development
if (!app.isPackaged) {
ask.webContents.openDevTools({ mode: 'detach' });
}
windowPool.set('ask', ask);
break;
}
// settings
case 'settings': {
const settings = new BrowserWindow({ ...commonChildOptions, width:240, maxHeight:400, parent:undefined });
settings.setContentProtection(isContentProtectionOn);
settings.setVisibleOnAllWorkspaces(true,{visibleOnFullScreen:true});
if (process.platform === 'darwin') {
settings.setWindowButtonVisibility(false);
}
const settingsLoadOptions = { query: { view: 'settings' } };
if (!shouldUseLiquidGlass) {
settings.loadFile(path.join(__dirname,'../ui/app/content.html'), settingsLoadOptions)
.catch(console.error);
}
else {
settingsLoadOptions.query.glass = 'true';
settings.loadFile(path.join(__dirname,'../ui/app/content.html'), settingsLoadOptions)
.catch(console.error);
settings.webContents.once('did-finish-load', () => {
const viewId = liquidGlass.addView(settings.getNativeWindowHandle());
if (viewId !== -1) {
liquidGlass.unstable_setVariant(viewId, liquidGlass.GlassMaterialVariant.bubbles);
// liquidGlass.unstable_setScrim(viewId, 1);
// liquidGlass.unstable_setSubdued(viewId, 1);
}
});
}
windowPool.set('settings', settings);
if (!app.isPackaged) {
settings.webContents.openDevTools({ mode: 'detach' });
}
break;
}
case 'shortcut-settings': {
const shortcutEditor = new BrowserWindow({
...commonChildOptions,
width: 353,
height: 720,
modal: false,
parent: undefined,
alwaysOnTop: true,
titleBarOverlay: false,
});
shortcutEditor.setContentProtection(isContentProtectionOn);
shortcutEditor.setVisibleOnAllWorkspaces(true,{visibleOnFullScreen:true});
if (process.platform === 'darwin') {
shortcutEditor.setWindowButtonVisibility(false);
}
const loadOptions = { query: { view: 'shortcut-settings' } };
if (!shouldUseLiquidGlass) {
shortcutEditor.loadFile(path.join(__dirname, '../ui/app/content.html'), loadOptions);
} else {
loadOptions.query.glass = 'true';
shortcutEditor.loadFile(path.join(__dirname, '../ui/app/content.html'), loadOptions);
shortcutEditor.webContents.once('did-finish-load', () => {
const viewId = liquidGlass.addView(shortcutEditor.getNativeWindowHandle());
if (viewId !== -1) {
liquidGlass.unstable_setVariant(viewId, liquidGlass.GlassMaterialVariant.bubbles);
}
});
}
windowPool.set('shortcut-settings', shortcutEditor);
if (!app.isPackaged) {
shortcutEditor.webContents.openDevTools({ mode: 'detach' });
}
break;
}
}
};
if (Array.isArray(namesToCreate)) {
namesToCreate.forEach(name => createFeatureWindow(name));
} else if (typeof namesToCreate === 'string') {
createFeatureWindow(namesToCreate);
} else {
createFeatureWindow('listen');
createFeatureWindow('ask');
createFeatureWindow('settings');
createFeatureWindow('shortcut-settings');
}
}
function destroyFeatureWindows() {
const featureWindows = ['listen','ask','settings','shortcut-settings'];
if (settingsHideTimer) {
clearTimeout(settingsHideTimer);
settingsHideTimer = null;
}
featureWindows.forEach(name=>{
const win = windowPool.get(name);
if (win && !win.isDestroyed()) win.destroy();
windowPool.delete(name);
});
}
function getCurrentDisplay(window) {
if (!window || window.isDestroyed()) return screen.getPrimaryDisplay();
const windowBounds = window.getBounds();
const windowCenter = {
x: windowBounds.x + windowBounds.width / 2,
y: windowBounds.y + windowBounds.height / 2,
};
return screen.getDisplayNearestPoint(windowCenter);
}
function createWindows() {
const HEADER_HEIGHT = 47;
const DEFAULT_WINDOW_WIDTH = 353;
const primaryDisplay = screen.getPrimaryDisplay();
const { y: workAreaY, width: screenWidth } = primaryDisplay.workArea;
const initialX = Math.round((screenWidth - DEFAULT_WINDOW_WIDTH) / 2);
const initialY = workAreaY + 21;
const header = new BrowserWindow({
width: DEFAULT_WINDOW_WIDTH,
height: HEADER_HEIGHT,
x: initialX,
y: initialY,
frame: false,
transparent: true,
vibrancy: false,
hasShadow: false,
alwaysOnTop: true,
skipTaskbar: true,
hiddenInMissionControl: true,
resizable: false,
focusable: true,
acceptFirstMouse: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, '../preload.js'),
backgroundThrottling: false,
webSecurity: false,
enableRemoteModule: false,
// Ensure proper rendering and prevent pixelation
experimentalFeatures: false,
},
// Prevent pixelation and ensure proper rendering
useContentSize: true,
disableAutoHideCursor: true,
});
if (process.platform === 'darwin') {
header.setWindowButtonVisibility(false);
}
const headerLoadOptions = {};
if (!shouldUseLiquidGlass) {
header.loadFile(path.join(__dirname, '../ui/app/header.html'), headerLoadOptions);
}
else {
headerLoadOptions.query = { glass: 'true' };
header.loadFile(path.join(__dirname, '../ui/app/header.html'), headerLoadOptions);
header.webContents.once('did-finish-load', () => {
const viewId = liquidGlass.addView(header.getNativeWindowHandle());
if (viewId !== -1) {
liquidGlass.unstable_setVariant(viewId, liquidGlass.GlassMaterialVariant.bubbles);
// liquidGlass.unstable_setScrim(viewId, 1);
// liquidGlass.unstable_setSubdued(viewId, 1);
}
});
}
windowPool.set('header', header);
layoutManager = new WindowLayoutManager(windowPool);
movementManager = new SmoothMovementManager(windowPool);
header.on('moved', () => {
if (movementManager.isAnimating) {
return;
}
updateChildWindowLayouts(false);
});
header.webContents.once('dom-ready', () => {
shortcutsService.initialize(windowPool);
shortcutsService.registerShortcuts();
});
setupIpcHandlers(windowPool, layoutManager);
setupWindowController(windowPool, layoutManager, movementManager);
if (currentHeaderState === 'main') {
createFeatureWindows(header, ['listen', 'ask', 'settings', 'shortcut-settings']);
}
header.setContentProtection(isContentProtectionOn);
header.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
// Open DevTools in development
if (!app.isPackaged) {
header.webContents.openDevTools({ mode: 'detach' });
}
header.on('focus', () => {
console.log('[WindowManager] Header gained focus');
});
header.on('blur', () => {
console.log('[WindowManager] Header lost focus');
});
header.webContents.on('before-input-event', (event, input) => {
if (input.type === 'mouseDown') {
const target = input.target;
if (target && (target.includes('input') || target.includes('apikey'))) {
header.focus();
}
}
});
header.on('resize', () => updateChildWindowLayouts(false));
return windowPool;
}
function setupIpcHandlers(windowPool, layoutManager) {
screen.on('display-added', (event, newDisplay) => {
console.log('[Display] New display added:', newDisplay.id);
});
screen.on('display-removed', (event, oldDisplay) => {
console.log('[Display] Display removed:', oldDisplay.id);
const header = windowPool.get('header');
if (header && getCurrentDisplay(header).id === oldDisplay.id) {
const primaryDisplay = screen.getPrimaryDisplay();
const newPosition = layoutManager.calculateNewPositionForDisplay(header, primaryDisplay.id);
if (newPosition) {
// 복구 상황이므로 애니메이션 없이 즉시 이동
header.setPosition(newPosition.x, newPosition.y, false);
updateChildWindowLayouts(false);
}
}
});
screen.on('display-metrics-changed', (event, display, changedMetrics) => {
// 레이아웃 업데이트 함수를 새 버전으로 호출
updateChildWindowLayouts(false);
});
}
const handleHeaderStateChanged = (state) => {
console.log(`[WindowManager] Header state changed to: ${state}`);
currentHeaderState = state;
if (state === 'main') {
createFeatureWindows(windowPool.get('header'));
} else { // 'apikey' | 'permission'
destroyFeatureWindows();
}
internalBridge.emit('reregister-shortcuts');
};
module.exports = {
createWindows,
windowPool,
toggleContentProtection,
resizeHeaderWindow,
getContentProtectionStatus,
showSettingsWindow,
hideSettingsWindow,
cancelHideSettingsWindow,
openLoginPage,
moveWindowStep,
handleHeaderStateChanged,
handleHeaderAnimationFinished,
getHeaderPosition,
moveHeaderTo,
adjustWindowHeight,
};