mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-06-01 18:05:32 +08:00
Compare commits
8 Commits
refactor/a
...
6be7045f17
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6be7045f17 | ||
|
|
d032a37c01 | ||
|
|
5d55e65727 | ||
|
|
909ff05118 | ||
|
|
b5bbf11524 | ||
|
|
bc52d9ea28 | ||
|
|
8339b8e624 | ||
|
|
061f0fd297 |
@@ -17,7 +17,7 @@
|
||||
|
||||
# Backend server port (Express API + WebSocket server)
|
||||
#API server
|
||||
SERVER_PORT=3001
|
||||
PORT=3001
|
||||
#Frontend port
|
||||
VITE_PORT=5173
|
||||
|
||||
@@ -42,4 +42,4 @@ HOST=0.0.0.0
|
||||
VITE_CONTEXT_WINDOW=160000
|
||||
CONTEXT_WINDOW=160000
|
||||
|
||||
|
||||
# VITE_IS_PLATFORM=false
|
||||
|
||||
41
.github/ISSUE_TEMPLATE/bug_report.md
vendored
41
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,41 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
type: Bug
|
||||
|
||||
---
|
||||
|
||||
**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.
|
||||
|
||||
**Error message**
|
||||
If applicable, add the error message you see to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
19
.github/ISSUE_TEMPLATE/feature_request.md
vendored
19
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -1,19 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: "[Feature]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
type: Feature
|
||||
|
||||
---
|
||||
|
||||
**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.
|
||||
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
22
.github/workflows/discord-release.yml
vendored
22
.github/workflows/discord-release.yml
vendored
@@ -1,22 +0,0 @@
|
||||
name: Discord Release Notification
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
github-releases-to-discord:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: Github Releases To Discord
|
||||
uses: SethCohen/github-releases-to-discord@v1.19.0
|
||||
with:
|
||||
webhook_url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
color: "2105893"
|
||||
username: "Release Changelog"
|
||||
avatar_url: "https://cdn.discordapp.com/avatars/487431320314576937/bd64361e4ba6313d561d54e78c9e7171.png"
|
||||
content: "||@everyone||"
|
||||
footer_title: "Changelog"
|
||||
reduce_headings: true
|
||||
50
.github/workflows/release.yml
vendored
50
.github/workflows/release.yml
vendored
@@ -1,50 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
increment:
|
||||
description: 'Version bump: patch, minor, major, or explicit (e.g. 1.27.0)'
|
||||
required: true
|
||||
default: 'patch'
|
||||
type: string
|
||||
release_name:
|
||||
description: 'Custom release name (optional, defaults to "CloudCLI UI vX.Y.Z")'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.RELEASE_PAT }}
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: git config
|
||||
run: |
|
||||
git config user.name "${GITHUB_ACTOR}"
|
||||
git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Release
|
||||
run: |
|
||||
ARGS="--ci --increment=${{ inputs.increment }}"
|
||||
if [ -n "${{ inputs.release_name }}" ]; then
|
||||
ARGS="$ARGS --github.releaseName=\"${{ inputs.release_name }}\""
|
||||
fi
|
||||
npx release-it $ARGS
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.RELEASE_PAT }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -8,7 +8,6 @@ lerna-debug.log*
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
dist-server/
|
||||
dist-ssr/
|
||||
build/
|
||||
out/
|
||||
@@ -109,7 +108,7 @@ temp/
|
||||
.serena/
|
||||
CLAUDE.md
|
||||
.mcp.json
|
||||
.gemini/
|
||||
|
||||
|
||||
# Database files
|
||||
*.db
|
||||
@@ -131,12 +130,3 @@ dev-debug.log
|
||||
# Task files
|
||||
tasks.json
|
||||
tasks/
|
||||
|
||||
# Translations
|
||||
!src/i18n/locales/en/tasks.json
|
||||
!src/i18n/locales/ja/tasks.json
|
||||
!src/i18n/locales/ru/tasks.json
|
||||
!src/i18n/locales/de/tasks.json
|
||||
|
||||
# Git worktrees
|
||||
.worktrees/
|
||||
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@@ -1,3 +0,0 @@
|
||||
[submodule "plugins/starter"]
|
||||
path = plugins/starter
|
||||
url = https://github.com/cloudcli-ai/cloudcli-plugin-starter.git
|
||||
@@ -1 +0,0 @@
|
||||
npx commitlint --edit $1
|
||||
@@ -1 +0,0 @@
|
||||
npx lint-staged
|
||||
@@ -1,13 +1,12 @@
|
||||
{
|
||||
"git": {
|
||||
"commitMessage": "chore(release): v${version}",
|
||||
"commitMessage": "Release ${version}",
|
||||
"tagName": "v${version}",
|
||||
"requireBranch": "main",
|
||||
"requireCleanWorkingDir": true
|
||||
},
|
||||
"npm": {
|
||||
"publish": true,
|
||||
"publishArgs": ["--access public"]
|
||||
"publish": true
|
||||
},
|
||||
"github": {
|
||||
"release": true,
|
||||
|
||||
200
CHANGELOG.md
200
CHANGELOG.md
@@ -3,206 +3,6 @@
|
||||
All notable changes to CloudCLI UI will be documented in this file.
|
||||
|
||||
|
||||
## [1.29.5](https://github.com/siteboon/claudecodeui/compare/v1.29.4...v1.29.5) (2026-04-16)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* update node-pty to latest version ([6a13e17](https://github.com/siteboon/claudecodeui/commit/6a13e1773b145049ade512aa6e5cac21c2e5c4de))
|
||||
|
||||
## [1.29.4](https://github.com/siteboon/claudecodeui/compare/v1.29.3...v1.29.4) (2026-04-16)
|
||||
|
||||
### New Features
|
||||
|
||||
* deleting from sidebar will now ask whether to remove all data as well ([e9c7a50](https://github.com/siteboon/claudecodeui/commit/e9c7a5041c31a6f7b2032f06abe19c52d3d4cd8c))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* pass pathToClaudeCodeExecutable to SDK when CLAUDE_CLI_PATH is set ([4c106a5](https://github.com/siteboon/claudecodeui/commit/4c106a5083d90989bbeedaefdbb68f5b3fa6fd58)), closes [#468](https://github.com/siteboon/claudecodeui/issues/468)
|
||||
|
||||
### Refactoring
|
||||
|
||||
* remove the sqlite3 dependency ([2895208](https://github.com/siteboon/claudecodeui/commit/289520814cf3ca36403056739ef22021f78c6033))
|
||||
* **server:** extract URL detection and color utils from index.js ([#657](https://github.com/siteboon/claudecodeui/issues/657)) ([63e996b](https://github.com/siteboon/claudecodeui/commit/63e996bb77cfa97b1f55f6bdccc50161a75a3eee))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* upgrade commit lint to 20.5.0 ([0948601](https://github.com/siteboon/claudecodeui/commit/09486016e67d97358c228ebc6eb4502ccb0012e4))
|
||||
|
||||
## [1.29.3](https://github.com/siteboon/claudecodeui/compare/v1.29.2...v1.29.3) (2026-04-15)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **version-upgrade-modal:** implement reload countdown and update UI messages ([#655](https://github.com/siteboon/claudecodeui/issues/655)) ([6413042](https://github.com/siteboon/claudecodeui/commit/641304242d7705b54aab65faa4a7673438c92c60))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* remove unused route (migrated to providers already) ([31f28a2](https://github.com/siteboon/claudecodeui/commit/31f28a2c183f6ead50941027632d7ab64b7bb2d4))
|
||||
|
||||
## [1.29.2](https://github.com/siteboon/claudecodeui/compare/v1.29.1...v1.29.2) (2026-04-14)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **sandbox:** use backgrounded sbx run to keep sandbox alive ([9b11c03](https://github.com/siteboon/claudecodeui/commit/9b11c034d9a19710a23b56c62dcf07c21a17bd97))
|
||||
|
||||
## [1.29.1](https://github.com/siteboon/claudecodeui/compare/v1.29.0...v1.29.1) (2026-04-14)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add latest tag to docker npx command and change the detach mode to work without spawn ([4a56972](https://github.com/siteboon/claudecodeui/commit/4a569725dae320a505753359d8edfd8ca79f0fd7))
|
||||
|
||||
## [1.29.0](https://github.com/siteboon/claudecodeui/compare/v1.28.1...v1.29.0) (2026-04-14)
|
||||
|
||||
### New Features
|
||||
|
||||
* adding docker sandbox environments ([13e97e2](https://github.com/siteboon/claudecodeui/commit/13e97e2c71254de7a60afb5495b21064c4bc4241))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **thinking-mode:** fix dropdown positioning ([#646](https://github.com/siteboon/claudecodeui/issues/646)) ([c7a5baf](https://github.com/siteboon/claudecodeui/commit/c7a5baf1479404bd40e23aa58bd9f677df9a04c6))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* update release flow node version ([e2459cb](https://github.com/siteboon/claudecodeui/commit/e2459cb0f8b35f54827778a7b444e6c3ca326506))
|
||||
|
||||
## [1.28.1](https://github.com/siteboon/claudecodeui/compare/v1.28.0...v1.28.1) (2026-04-10)
|
||||
|
||||
### New Features
|
||||
|
||||
* add branding, community links, GitHub star badge, and About settings tab ([2207d05](https://github.com/siteboon/claudecodeui/commit/2207d05c1ca229214aa9c2e2c9f4d0827d421574))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* corrupted binary downloads ([#634](https://github.com/siteboon/claudecodeui/issues/634)) ([e61f8a5](https://github.com/siteboon/claudecodeui/commit/e61f8a543d63fe7c24a04b3d2186085a06dcbcdb))
|
||||
* **ui:** remove mobile bottom nav, unify processing indicator, and improve tooltip behavior on mobile ([#632](https://github.com/siteboon/claudecodeui/issues/632)) ([a8dab0e](https://github.com/siteboon/claudecodeui/commit/a8dab0edcf949ae610820bae9500c433781f7c73))
|
||||
|
||||
### Refactoring
|
||||
|
||||
* remove unused whispher transcribe logic ([#637](https://github.com/siteboon/claudecodeui/issues/637)) ([590dd42](https://github.com/siteboon/claudecodeui/commit/590dd42649424ab990353fcf59ce0965036d3d25))
|
||||
|
||||
## [1.28.0](https://github.com/siteboon/claudecodeui/compare/v1.27.1...v1.28.0) (2026-04-03)
|
||||
|
||||
### New Features
|
||||
|
||||
* adding session resume in the api ([8f1042c](https://github.com/siteboon/claudecodeui/commit/8f1042cf256be282f009adcceeb55ab2dddf3fba))
|
||||
* moving new session button higher ([1628868](https://github.com/siteboon/claudecodeui/commit/16288684702dec894cf054291ca3d545ddb8214b))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* changing package name to @cloudcli-ai/cloudcli ([ef51de2](https://github.com/siteboon/claudecodeui/commit/ef51de259ea2b963bc15f058b084e11220bc216a))
|
||||
|
||||
## [1.27.1](https://github.com/siteboon/claudecodeui/compare/v1.26.3...v1.27.1) (2026-03-29)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* prevent split on undefined([#491](https://github.com/siteboon/claudecodeui/issues/491)) ([#563](https://github.com/siteboon/claudecodeui/issues/563)) ([b54cdf8](https://github.com/siteboon/claudecodeui/commit/b54cdf8168fc224e9907796e4229ae8ed34e6885))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* add release-it github action ([42a1313](https://github.com/siteboon/claudecodeui/commit/42a131389a6954df0d2c3bedd2cb6d3406c5ebc1))
|
||||
* add terminal plugin in the plugins list ([004135e](https://github.com/siteboon/claudecodeui/commit/004135ef0187023e1da29c4a7137a28a42ebf9af))
|
||||
* release tokens ([f1063fd](https://github.com/siteboon/claudecodeui/commit/f1063fd33964ccb517f5ebcdd14526ed162e1138))
|
||||
* relicense to AGPL-3.0-or-later ([27cd124](https://github.com/siteboon/claudecodeui/commit/27cd12432b7d3237981f86acd9cc99532d843d4a))
|
||||
|
||||
## [1.26.3](https://github.com/siteboon/claudecodeui/compare/v1.26.2...v1.26.3) (2026-03-22)
|
||||
|
||||
## [1.26.2](https://github.com/siteboon/claudecodeui/compare/v1.26.0...v1.26.2) (2026-03-21)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* change SW cache mechanism ([17d6ec5](https://github.com/siteboon/claudecodeui/commit/17d6ec54af18d333c8b04d2ffc64793e688d996e))
|
||||
* claude auth changes and adding copy on mobile ([a41d2c7](https://github.com/siteboon/claudecodeui/commit/a41d2c713e87d56f23d5884585b4bb43c43a250a))
|
||||
|
||||
## [1.26.0](https://github.com/siteboon/claudecodeui/compare/v1.25.2...v1.26.0) (2026-03-20)
|
||||
|
||||
### New Features
|
||||
|
||||
* add German (Deutsch) language support ([#525](https://github.com/siteboon/claudecodeui/issues/525)) ([a7299c6](https://github.com/siteboon/claudecodeui/commit/a7299c68237908c752d504c2e8eea91570a30203))
|
||||
* add WebSocket proxy for plugin backends ([#553](https://github.com/siteboon/claudecodeui/issues/553)) ([88c60b7](https://github.com/siteboon/claudecodeui/commit/88c60b70b031798d51ce26c8f080a0f64d824b05))
|
||||
* Browser autofill support for login form ([#521](https://github.com/siteboon/claudecodeui/issues/521)) ([72ff134](https://github.com/siteboon/claudecodeui/commit/72ff134b315b7a1d602f3cc7dd60d47c1c1c34af))
|
||||
* git panel redesign ([#535](https://github.com/siteboon/claudecodeui/issues/535)) ([adb3a06](https://github.com/siteboon/claudecodeui/commit/adb3a06d7e66a6d2dbcdfb501615e617178314af))
|
||||
* introduce notification system and claude notifications ([#450](https://github.com/siteboon/claudecodeui/issues/450)) ([45e71a0](https://github.com/siteboon/claudecodeui/commit/45e71a0e73b368309544165e4dcf8b7fd014e8dd))
|
||||
* **refactor:** move plugins to typescript ([#557](https://github.com/siteboon/claudecodeui/issues/557)) ([612390d](https://github.com/siteboon/claudecodeui/commit/612390db536417e2f68c501329bfccf5c6795e45))
|
||||
* unified message architecture with provider adapters and session store ([#558](https://github.com/siteboon/claudecodeui/issues/558)) ([a4632dc](https://github.com/siteboon/claudecodeui/commit/a4632dc4cec228a8febb7c5bae4807c358963678))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* detect Claude auth from settings env ([#527](https://github.com/siteboon/claudecodeui/issues/527)) ([95bcee0](https://github.com/siteboon/claudecodeui/commit/95bcee0ec459f186d52aeffe100ac1a024e92909))
|
||||
* remove /exit command from claude login flow during onboarding ([#552](https://github.com/siteboon/claudecodeui/issues/552)) ([4de8b78](https://github.com/siteboon/claudecodeui/commit/4de8b78c6db5d8c2c402afce0f0b4cc16d5b6496))
|
||||
|
||||
### Documentation
|
||||
|
||||
* add German language link to all README files ([#534](https://github.com/siteboon/claudecodeui/issues/534)) ([1d31c3e](https://github.com/siteboon/claudecodeui/commit/1d31c3ec8309b433a041f3099955addc8c136c35))
|
||||
* **readme:** hotfix and improve for README.jp.md ([#550](https://github.com/siteboon/claudecodeui/issues/550)) ([7413c2c](https://github.com/siteboon/claudecodeui/commit/7413c2c78422c308ac949e6a83c3e9216b24b649))
|
||||
* **README:** update translations with CloudCLI branding and feature restructuring ([#544](https://github.com/siteboon/claudecodeui/issues/544)) ([14aef73](https://github.com/siteboon/claudecodeui/commit/14aef73cc6085fbb519fe64aea7cac80b7d51285))
|
||||
|
||||
## [1.25.2](https://github.com/siteboon/claudecodeui/compare/v1.25.0...v1.25.2) (2026-03-11)
|
||||
|
||||
### New Features
|
||||
|
||||
* **i18n:** localize plugin settings for all languages ([#515](https://github.com/siteboon/claudecodeui/issues/515)) ([621853c](https://github.com/siteboon/claudecodeui/commit/621853cbfb4233b34cb8cc2e1ed10917ba424352))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* codeql user value provided path validation ([aaa14b9](https://github.com/siteboon/claudecodeui/commit/aaa14b9fc0b9b51c4fb9d1dba40fada7cbbe0356))
|
||||
* numerous bugs ([#528](https://github.com/siteboon/claudecodeui/issues/528)) ([a77f213](https://github.com/siteboon/claudecodeui/commit/a77f213dd5d0b2538dea091ab8da6e55d2002f2f))
|
||||
* **security:** disable executable gray-matter frontmatter in commands ([b9c902b](https://github.com/siteboon/claudecodeui/commit/b9c902b016f411a942c8707dd07d32b60bad087c))
|
||||
* session reconnect catch-up, always-on input, frozen session recovery ([#524](https://github.com/siteboon/claudecodeui/issues/524)) ([4d8fb6e](https://github.com/siteboon/claudecodeui/commit/4d8fb6e30aa03d7cdb92bd62b7709422f9d08e32))
|
||||
|
||||
### Refactoring
|
||||
|
||||
* new settings page design and new pill component ([8ddeeb0](https://github.com/siteboon/claudecodeui/commit/8ddeeb0ce8d0642560bd3fa149236011dc6e3707))
|
||||
|
||||
## [1.25.0](https://github.com/siteboon/claudecodeui/compare/v1.24.0...v1.25.0) (2026-03-10)
|
||||
|
||||
### New Features
|
||||
|
||||
* add copy as text or markdown feature for assistant messages ([#519](https://github.com/siteboon/claudecodeui/issues/519)) ([1dc2a20](https://github.com/siteboon/claudecodeui/commit/1dc2a205dc2a3cbf960625d7669c7c63a2b6905f))
|
||||
* add full Russian language support; update Readme.md files, and .gitignore update ([#514](https://github.com/siteboon/claudecodeui/issues/514)) ([c7dcba8](https://github.com/siteboon/claudecodeui/commit/c7dcba8d9117e84db8aac7d8a7bf6a3aa683e115))
|
||||
* new plugin system ([#489](https://github.com/siteboon/claudecodeui/issues/489)) ([8afb46a](https://github.com/siteboon/claudecodeui/commit/8afb46af2e5514c9284030367281793fbb014e4f))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* resolve duplicate key issue when rendering model options ([#520](https://github.com/siteboon/claudecodeui/issues/520)) ([9bceab9](https://github.com/siteboon/claudecodeui/commit/9bceab9e1a6e063b0b4f934ed2d9f854fcc9c6a4))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* add plugins section in readme ([e581a0e](https://github.com/siteboon/claudecodeui/commit/e581a0e1ccd59fd7ec7306ca76a13e73d7c674c1))
|
||||
|
||||
## [1.24.0](https://github.com/siteboon/claudecodeui/compare/v1.23.2...v1.24.0) (2026-03-09)
|
||||
|
||||
### New Features
|
||||
|
||||
* add full-text search across conversations ([#482](https://github.com/siteboon/claudecodeui/issues/482)) ([3950c0e](https://github.com/siteboon/claudecodeui/commit/3950c0e47f41e93227af31494690818d45c8bc7a))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **git:** prevent shell injection in git routes ([86c33c1](https://github.com/siteboon/claudecodeui/commit/86c33c1c0cb34176725a38f46960213714fc3e04))
|
||||
* replace getDatabase with better-sqlite3 db in getGithubTokenById ([#501](https://github.com/siteboon/claudecodeui/issues/501)) ([cb4fd79](https://github.com/siteboon/claudecodeui/commit/cb4fd795c938b1cc86d47f401973bfccdd68fdee))
|
||||
|
||||
## [1.23.2](https://github.com/siteboon/claudecodeui/compare/v1.22.1...v1.23.2) (2026-03-06)
|
||||
|
||||
### New Features
|
||||
|
||||
* add clickable overlay buttons for CLI prompts in Shell terminal ([#480](https://github.com/siteboon/claudecodeui/issues/480)) ([2444209](https://github.com/siteboon/claudecodeui/commit/2444209723701dda2b881cea2501b239e64e51c1)), closes [#427](https://github.com/siteboon/claudecodeui/issues/427)
|
||||
* add terminal shortcuts panel for mobile ([#411](https://github.com/siteboon/claudecodeui/issues/411)) ([b0a3fdf](https://github.com/siteboon/claudecodeui/commit/b0a3fdf95ffdb961261194d10400267251e42f17))
|
||||
* implement session rename with SQLite storage ([#413](https://github.com/siteboon/claudecodeui/issues/413)) ([198e3da](https://github.com/siteboon/claudecodeui/commit/198e3da89b353780f53a91888384da9118995e81)), closes [#72](https://github.com/siteboon/claudecodeui/issues/72) [#358](https://github.com/siteboon/claudecodeui/issues/358)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **chat:** finalize terminal lifecycle to prevent stuck processing/thinking UI ([#483](https://github.com/siteboon/claudecodeui/issues/483)) ([0590c5c](https://github.com/siteboon/claudecodeui/commit/0590c5c178f4791e2b039d525ecca4d220c3dcae))
|
||||
* **codex-history:** prevent AGENTS.md/internal prompt leakage when reloading Codex sessions ([#488](https://github.com/siteboon/claudecodeui/issues/488)) ([64a96b2](https://github.com/siteboon/claudecodeui/commit/64a96b24f853acb802f700810b302f0f5cf00898))
|
||||
* preserve pending permission requests across WebSocket reconnections ([#462](https://github.com/siteboon/claudecodeui/issues/462)) ([4ee88f0](https://github.com/siteboon/claudecodeui/commit/4ee88f0eb0c648b54b05f006c6796fb7b09b0fae))
|
||||
* prevent React 18 batching from losing messages during session sync ([#461](https://github.com/siteboon/claudecodeui/issues/461)) ([688d734](https://github.com/siteboon/claudecodeui/commit/688d73477a50773e43c85addc96212aa6290aea5))
|
||||
* release it script ([dcea8a3](https://github.com/siteboon/claudecodeui/commit/dcea8a329c7d68437e1e72c8c766cf33c74637e9))
|
||||
|
||||
### Styling
|
||||
|
||||
* improve UI for processing banner ([#477](https://github.com/siteboon/claudecodeui/issues/477)) ([2320e1d](https://github.com/siteboon/claudecodeui/commit/2320e1d74b59c65b5b7fc4fa8b05fd9208f4898c))
|
||||
|
||||
### Maintenance
|
||||
|
||||
* remove logging of received WebSocket messages in production ([#487](https://github.com/siteboon/claudecodeui/issues/487)) ([9193feb](https://github.com/siteboon/claudecodeui/commit/9193feb6dc83041f3c365204648a88468bdc001b))
|
||||
|
||||
## [1.22.0](https://github.com/siteboon/claudecodeui/compare/v1.21.0...v1.22.0) (2026-03-03)
|
||||
|
||||
### New Features
|
||||
|
||||
@@ -153,4 +153,4 @@ This automatically:
|
||||
|
||||
## License
|
||||
|
||||
By contributing, you agree that your contributions will be licensed under the [AGPL-3.0-or-later License](LICENSE), including the additional terms specified in Section 7 of the LICENSE file.
|
||||
By contributing, you agree that your contributions will be licensed under the [GPL-3.0 License](LICENSE).
|
||||
13
NOTICE
13
NOTICE
@@ -1,13 +0,0 @@
|
||||
CloudCLI UI
|
||||
Copyright 2025-2026 Siteboon AI B.V. and contributors
|
||||
|
||||
This software is licensed under the GNU Affero General Public License v3.0
|
||||
or later (AGPL-3.0-or-later). See the LICENSE file for the full license text,
|
||||
including additional terms under Section 7.
|
||||
|
||||
Originally developed by Siteboon AI B.V. (https://github.com/siteboon/claudecodeui).
|
||||
|
||||
Contributions by Siteboon AI B.V. prior to commit 004135ef were originally
|
||||
published under GPL-3.0 and are hereby relicensed to AGPL-3.0-or-later.
|
||||
Contributions by other authors prior to that commit remain under GPL-3.0
|
||||
and are incorporated into this work as permitted by GPL-3.0 Section 13.
|
||||
250
README.de.md
250
README.de.md
@@ -1,250 +0,0 @@
|
||||
<div align="center">
|
||||
<img src="public/logo.svg" alt="CloudCLI UI" width="64" height="64">
|
||||
<h1>Cloud CLI (auch bekannt als Claude Code UI)</h1>
|
||||
<p>Eine Desktop- und Mobile-Oberfläche für <a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code</a>, <a href="https://docs.cursor.com/en/cli/overview">Cursor CLI</a>, <a href="https://developers.openai.com/codex">Codex</a> und <a href="https://geminicli.com/">Gemini-CLI</a>.<br>Lokal oder remote nutzbar – verwalte deine aktiven Projekte und Sitzungen von überall.</p>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://cloudcli.ai/docs">Dokumentation</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">Fehler melden</a> · <a href="CONTRIBUTING.md">Mitwirken</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai"><img src="https://img.shields.io/badge/☁️_CloudCLI_Cloud-Try_Now-0066FF?style=for-the-badge" alt="CloudCLI Cloud"></a>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join_Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join Community"></a>
|
||||
<br><br>
|
||||
<a href="https://trendshift.io/repositories/15586" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15586" alt="siteboon%2Fclaudecodeui | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
<div align="right"><i><a href="./README.md">English</a> · <a href="./README.ru.md">Русский</a> · <b>Deutsch</b> · <a href="./README.ko.md">한국어</a> · <a href="./README.zh-CN.md">中文</a> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
---
|
||||
|
||||
## Screenshots
|
||||
|
||||
<div align="center">
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h3>Desktop-Ansicht</h3>
|
||||
<img src="public/screenshots/desktop-main.png" alt="Desktop-Oberfläche" width="400">
|
||||
<br>
|
||||
<em>Hauptoberfläche mit Projektübersicht und Chat</em>
|
||||
</td>
|
||||
<td align="center">
|
||||
<h3>Mobile-Erfahrung</h3>
|
||||
<img src="public/screenshots/mobile-chat.png" alt="Mobile-Oberfläche" width="250">
|
||||
<br>
|
||||
<em>Responsives mobiles Design mit Touch-Navigation</em>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" colspan="2">
|
||||
<h3>CLI-Auswahl</h3>
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI-Auswahl" width="400">
|
||||
<br>
|
||||
<em>Wähle zwischen Claude Code, Gemini, Cursor CLI und Codex</em>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## Funktionen
|
||||
|
||||
- **Responsives Design** – Funktioniert nahtlos auf Desktop, Tablet und Mobilgerät, sodass du Agents auch vom Smartphone aus nutzen kannst
|
||||
- **Interaktives Chat-Interface** – Eingebaute Chat-Oberfläche für die reibungslose Kommunikation mit den Agents
|
||||
- **Integriertes Shell-Terminal** – Direkter Zugriff auf die Agents CLI über die eingebaute Shell-Funktionalität
|
||||
- **Datei-Explorer** – Interaktiver Dateibaum mit Syntaxhervorhebung und Live-Bearbeitung
|
||||
- **Git-Explorer** – Änderungen anzeigen, stagen und committen. Branches wechseln ebenfalls möglich
|
||||
- **Sitzungsverwaltung** – Gespräche fortsetzen, mehrere Sitzungen verwalten und Verlauf nachverfolgen
|
||||
- **Plugin-System** – CloudCLI mit eigenen Plugins erweitern – neue Tabs, Backend-Dienste und Integrationen hinzufügen. [Eigenes Plugin erstellen →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)
|
||||
- **TaskMaster AI Integration** *(Optional)* – Erweitertes Projektmanagement mit KI-gestützter Aufgabenplanung, PRD-Parsing und Workflow-Automatisierung
|
||||
- **Modell-Kompatibilität** – Funktioniert mit Claude, GPT und Gemini (vollständige Liste unterstützter Modelle in [`shared/modelConstants.js`](shared/modelConstants.js))
|
||||
|
||||
|
||||
## Schnellstart
|
||||
|
||||
### CloudCLI Cloud (Empfohlen)
|
||||
|
||||
Der schnellste Einstieg – keine lokale Einrichtung erforderlich. Erhalte eine vollständig verwaltete, containerisierte Entwicklungsumgebung, die über Web, Mobile App, API oder deine bevorzugte IDE erreichbar ist.
|
||||
|
||||
**[Mit CloudCLI Cloud starten](https://cloudcli.ai)**
|
||||
|
||||
|
||||
### Self-Hosted (Open Source)
|
||||
|
||||
#### npm
|
||||
|
||||
CloudCLI UI sofort mit **npx** ausprobieren (erfordert **Node.js** v22+):
|
||||
|
||||
```bash
|
||||
npx @cloudcli-ai/cloudcli
|
||||
```
|
||||
|
||||
Oder **global** installieren für regelmäßige Nutzung:
|
||||
|
||||
```bash
|
||||
npm install -g @cloudcli-ai/cloudcli
|
||||
cloudcli
|
||||
```
|
||||
|
||||
Öffne `http://localhost:3001` – alle vorhandenen Sitzungen werden automatisch erkannt.
|
||||
|
||||
Die **[Dokumentation →](https://cloudcli.ai/docs)** enthält weitere Konfigurationsoptionen, PM2, Remote-Server-Einrichtung und mehr.
|
||||
|
||||
#### Docker Sandboxes (Experimentell)
|
||||
|
||||
Agents in isolierten Sandboxes mit Hypervisor-Isolation ausführen. Standardmäßig wird Claude Code gestartet. Erfordert die [`sbx` CLI](https://docs.docker.com/ai/sandboxes/get-started/).
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project
|
||||
```
|
||||
|
||||
Unterstützt Claude Code, Codex und Gemini CLI. Weitere Details in der [Sandbox-Dokumentation](docker/).
|
||||
|
||||
---
|
||||
|
||||
## Welche Option passt zu dir?
|
||||
|
||||
CloudCLI UI ist die Open-Source-UI-Schicht, die CloudCLI Cloud antreibt. Du kannst es auf deinem eigenen Rechner selbst hosten oder CloudCLI Cloud nutzen, das darauf aufbaut und eine vollständig verwaltete Cloud-Umgebung, Team-Funktionen und tiefere Integrationen bietet.
|
||||
|
||||
| | CloudCLI UI (Self-hosted) | CloudCLI Cloud |
|
||||
|---|---|---|
|
||||
| **Am besten für** | Entwickler:innen, die eine vollständige UI für lokale Agent-Sitzungen auf ihrem eigenen Rechner möchten | Teams und Entwickler:innen, die Agents in der Cloud betreiben möchten, überall erreichbar |
|
||||
| **Zugriff** | Browser via `[deineIP]:port` | Browser, jede IDE, REST API, n8n |
|
||||
| **Einrichtung** | `npx @cloudcli-ai/cloudcli` | Keine Einrichtung erforderlich |
|
||||
| **Rechner muss laufen** | Ja | Nein |
|
||||
| **Mobiler Zugriff** | Jeder Browser im Netzwerk | Jedes Gerät, native App in Entwicklung |
|
||||
| **Verfügbare Sitzungen** | Alle Sitzungen automatisch aus `~/.claude` erkannt | Alle Sitzungen in deiner Cloud-Umgebung |
|
||||
| **Unterstützte Agents** | Claude Code, Cursor CLI, Codex, Gemini CLI | Claude Code, Cursor CLI, Codex, Gemini CLI |
|
||||
| **Datei-Explorer und Git** | Ja, direkt in der UI | Ja, direkt in der UI |
|
||||
| **MCP-Konfiguration** | Über UI verwaltet, synchronisiert mit lokalem `~/.claude` | Über UI verwaltet |
|
||||
| **IDE-Zugriff** | Deine lokale IDE | Jede IDE, die mit deiner Cloud-Umgebung verbunden ist |
|
||||
| **REST API** | Ja | Ja |
|
||||
| **n8n-Node** | Nein | Ja |
|
||||
| **Team-Sharing** | Nein | Ja |
|
||||
| **Plattformkosten** | Kostenlos, Open Source | Ab $7/Monat |
|
||||
|
||||
> Beide Optionen verwenden deine eigenen KI-Abonnements (Claude, Cursor usw.) – CloudCLI stellt die Umgebung bereit, nicht die KI.
|
||||
|
||||
---
|
||||
|
||||
## Sicherheit & Tool-Konfiguration
|
||||
|
||||
**🔒 Wichtiger Hinweis**: Alle Claude Code Tools sind **standardmäßig deaktiviert**. Dies verhindert, dass potenziell schädliche Operationen automatisch ausgeführt werden.
|
||||
|
||||
### Tools aktivieren
|
||||
|
||||
Um den vollen Funktionsumfang von Claude Code zu nutzen, müssen Tools manuell aktiviert werden:
|
||||
|
||||
1. **Tool-Einstellungen öffnen** – Klicke auf das Zahnrad-Symbol in der Seitenleiste
|
||||
2. **Selektiv aktivieren** – Nur die benötigten Tools einschalten
|
||||
3. **Einstellungen übernehmen** – Deine Einstellungen werden lokal gespeichert
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
*Tool-Einstellungen – nur aktivieren, was benötigt wird*
|
||||
|
||||
</div>
|
||||
|
||||
**Empfohlene Vorgehensweise**: Mit grundlegenden Tools starten und bei Bedarf weitere hinzufügen. Die Einstellungen können jederzeit angepasst werden.
|
||||
|
||||
---
|
||||
|
||||
## Plugins
|
||||
|
||||
CloudCLI verfügt über ein Plugin-System, mit dem benutzerdefinierte Tabs mit eigener Frontend-UI und optionalem Node.js-Backend hinzugefügt werden können. Plugins können direkt in **Einstellungen > Plugins** aus Git-Repos installiert oder selbst entwickelt werden.
|
||||
|
||||
### Verfügbare Plugins
|
||||
|
||||
| Plugin | Beschreibung |
|
||||
|---|---|
|
||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Zeigt Dateianzahl, Codezeilen, Dateityp-Aufschlüsselung, größte Dateien und zuletzt geänderte Dateien des aktuellen Projekts |
|
||||
|
||||
### Eigenes Plugin erstellen
|
||||
|
||||
**[Plugin-Starter-Vorlage →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** – Forke dieses Repository, um ein eigenes Plugin zu erstellen. Es enthält ein funktionierendes Beispiel mit Frontend-Rendering, Live-Kontext-Updates und RPC-Kommunikation zu einem Backend-Server.
|
||||
|
||||
**[Plugin-Dokumentation →](https://cloudcli.ai/docs/plugin-overview)** – Vollständige Anleitung zur Plugin-API, zum Manifest-Format, zum Sicherheitsmodell und mehr.
|
||||
|
||||
---
|
||||
## FAQ
|
||||
|
||||
<details>
|
||||
<summary>Wie unterscheidet sich das von Claude Code Remote Control?</summary>
|
||||
|
||||
Claude Code Remote Control ermöglicht es, Nachrichten an eine bereits im lokalen Terminal laufende Sitzung zu senden. Der Rechner muss eingeschaltet bleiben, das Terminal muss offen bleiben, und Sitzungen laufen nach etwa 10 Minuten ohne Netzwerkverbindung ab.
|
||||
|
||||
CloudCLI UI und CloudCLI Cloud erweitern Claude Code, anstatt neben ihm zu laufen – MCP-Server, Berechtigungen, Einstellungen und Sitzungen sind exakt dieselben, die Claude Code nativ verwendet. Nichts wird dupliziert oder separat verwaltet.
|
||||
|
||||
Das bedeutet in der Praxis:
|
||||
|
||||
- **Alle Sitzungen, nicht nur eine** – CloudCLI UI erkennt automatisch jede Sitzung aus dem `~/.claude`-Ordner. Remote Control stellt nur die einzelne aktive Sitzung bereit, um sie in der Claude Mobile App verfügbar zu machen.
|
||||
- **Deine Einstellungen sind deine Einstellungen** – MCP-Server, Tool-Berechtigungen und Projektkonfiguration, die in CloudCLI UI geändert werden, werden direkt in die Claude Code-Konfiguration geschrieben und treten sofort in Kraft – und umgekehrt.
|
||||
- **Funktioniert mit mehr Agents** – Claude Code, Cursor CLI, Codex und Gemini CLI, nicht nur Claude Code.
|
||||
- **Vollständige UI, nicht nur ein Chat-Fenster** – Datei-Explorer, Git-Integration, MCP-Verwaltung und ein Shell-Terminal sind alle eingebaut.
|
||||
- **CloudCLI Cloud läuft in der Cloud** – Laptop zuklappen, der Agent läuft weiter. Kein Terminal zu überwachen, kein Rechner, der laufen muss.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Muss ich ein KI-Abonnement separat bezahlen?</summary>
|
||||
|
||||
Ja. CloudCLI stellt die Umgebung bereit, nicht die KI. Du bringst dein eigenes Claude-, Cursor-, Codex- oder Gemini-Abonnement mit. CloudCLI Cloud beginnt bei $7/Monat für die gehostete Umgebung zusätzlich dazu.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Kann ich CloudCLI UI auf meinem Smartphone nutzen?</summary>
|
||||
|
||||
Ja. Bei Self-Hosted: Server auf dem eigenen Rechner starten und `[deineIP]:port` in einem beliebigen Browser im Netzwerk öffnen. Bei CloudCLI Cloud: Von jedem Gerät aus öffnen – kein VPN, keine Portweiterleitung, keine Einrichtung. Eine native App ist ebenfalls in Entwicklung.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Wirken sich Änderungen in der UI auf mein lokales Claude Code-Setup aus?</summary>
|
||||
|
||||
Ja, bei Self-Hosted. CloudCLI UI liest aus und schreibt in dieselbe `~/.claude`-Konfiguration, die Claude Code nativ verwendet. MCP-Server, die über die UI hinzugefügt werden, erscheinen sofort in Claude Code und umgekehrt.
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Community & Support
|
||||
|
||||
- **[Dokumentation](https://cloudcli.ai/docs)** — Installation, Konfiguration, Funktionen und Fehlerbehebung
|
||||
- **[Discord](https://discord.gg/buxwujPNRE)** — Hilfe erhalten und mit anderen Nutzer:innen in Kontakt treten
|
||||
- **[GitHub Issues](https://github.com/siteboon/claudecodeui/issues)** — Fehlerberichte und Feature-Anfragen
|
||||
- **[Beitragsrichtlinien](CONTRIBUTING.md)** — So kannst du zum Projekt beitragen
|
||||
|
||||
## Lizenz
|
||||
|
||||
GNU General Public License v3.0 – siehe [LICENSE](LICENSE)-Datei für Details.
|
||||
|
||||
Dieses Projekt ist Open Source und kann unter der GPL v3-Lizenz kostenlos genutzt, modifiziert und verteilt werden.
|
||||
|
||||
## Danksagungen
|
||||
|
||||
### Erstellt mit
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropics offizielle CLI
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursors offizielle CLI
|
||||
- **[Codex](https://developers.openai.com/codex)** - OpenAI Codex
|
||||
- **[Gemini-CLI](https://geminicli.com/)** - Google Gemini CLI
|
||||
- **[React](https://react.dev/)** - UI-Bibliothek
|
||||
- **[Vite](https://vitejs.dev/)** - Schnelles Build-Tool und Dev-Server
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - Utility-first CSS-Framework
|
||||
- **[CodeMirror](https://codemirror.net/)** - Erweiterter Code-Editor
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(Optional)* - KI-gestütztes Projektmanagement und Aufgabenplanung
|
||||
|
||||
|
||||
### Sponsoren
|
||||
- [Siteboon - KI-gestützter Website-Builder](https://siteboon.ai)
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<strong>Mit Sorgfalt für die Claude Code-, Cursor- und Codex-Community erstellt.</strong>
|
||||
</div>
|
||||
352
README.ja.md
352
README.ja.md
@@ -1,23 +1,12 @@
|
||||
<div align="center">
|
||||
<img src="public/logo.svg" alt="CloudCLI UI" width="64" height="64">
|
||||
<h1>Cloud CLI(別名 Claude Code UI)</h1>
|
||||
<p><a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code</a>、<a href="https://docs.cursor.com/en/cli/overview">Cursor CLI</a>、<a href="https://developers.openai.com/codex">Codex</a>、<a href="https://geminicli.com/">Gemini-CLI</a> のためのデスクトップ/モバイル UI。<br>ローカルでもリモートでも使え、アクティブなプロジェクトとセッションをどこからでも閲覧できます。</p>
|
||||
<img src="public/logo.svg" alt="Claude Code UI" width="64" height="64">
|
||||
<h1>Cloud CLI (別名 Claude Code UI)</h1>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://cloudcli.ai/docs">ドキュメント</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">バグ報告</a> · <a href="CONTRIBUTING.md">コントリビュート</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai"><img src="https://img.shields.io/badge/☁️_CloudCLI_Cloud-Try_Now-0066FF?style=for-the-badge" alt="CloudCLI Cloud"></a>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord コミュニティに参加"></a>
|
||||
<br><br>
|
||||
<a href="https://trendshift.io/repositories/15586" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15586" alt="siteboon%2Fclaudecodeui | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
[Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[Cursor CLI](https://docs.cursor.com/en/cli/overview)、[Codex](https://developers.openai.com/codex) 向けのデスクトップ・モバイル UI です。ローカルまたはリモートで使用して、Claude Code、Cursor、Codex のアクティブなプロジェクトやセッションを確認し、どこからでも(モバイルやデスクトップから)変更を加えることができます。どこでも使える適切なインターフェースを提供します。
|
||||
|
||||
<div align="right"><i><a href="./README.md">English</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ko.md">한국어</a> · <a href="./README.zh-CN.md">中文</a> · <b>日本語</b></i></div>
|
||||
|
||||
---
|
||||
<div align="right"><i><a href="./README.md">English</a> · <a href="./README.ko.md">한국어</a> · <a href="./README.zh-CN.md">中文</a></i></div>
|
||||
|
||||
## スクリーンショット
|
||||
|
||||
@@ -27,23 +16,23 @@
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h3>デスクトップビュー</h3>
|
||||
<img src="public/screenshots/desktop-main.png" alt="デスクトップインターフェース" width="400">
|
||||
<img src="public/screenshots/desktop-main.png" alt="Desktop Interface" width="400">
|
||||
<br>
|
||||
<em>プロジェクト概要とチャットを表示するメイン画面</em>
|
||||
<em>プロジェクト概要とチャットを表示するメインインターフェース</em>
|
||||
</td>
|
||||
<td align="center">
|
||||
<h3>モバイル体験</h3>
|
||||
<img src="public/screenshots/mobile-chat.png" alt="モバイルインターフェース" width="250">
|
||||
<img src="public/screenshots/mobile-chat.png" alt="Mobile Interface" width="250">
|
||||
<br>
|
||||
<em>タッチ操作に対応したレスポンシブなモバイルデザイン</em>
|
||||
<em>タッチナビゲーション対応のレスポンシブモバイルデザイン</em>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" colspan="2">
|
||||
<h3>CLI 選択</h3>
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI 選択" width="400">
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI Selection" width="400">
|
||||
<br>
|
||||
<em>Claude Code、Gemini、Cursor CLI、Codex から選択</em>
|
||||
<em>Claude Code、Cursor CLI、Codex から選択</em>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -54,187 +43,302 @@
|
||||
|
||||
## 機能
|
||||
|
||||
- **レスポンシブデザイン** - デスクトップ/タブレット/モバイルでシームレスに動作し、モバイルからも Agents を利用可能
|
||||
- **インタラクティブチャット UI** - Agents とスムーズにやり取りできる内蔵チャット UI
|
||||
- **統合シェルターミナル** - 内蔵シェル機能で Agents の CLI に直接アクセス
|
||||
- **ファイルエクスプローラー** - シンタックスハイライトとライブ編集に対応したインタラクティブなファイルツリー
|
||||
- **Git エクスプローラー** - 変更の表示、ステージ、コミット。ブランチ切り替えも可能
|
||||
- **レスポンシブデザイン** - デスクトップ、タブレット、モバイルでシームレスに動作し、モバイルからも Claude Code、Cursor、Codex を使用可能
|
||||
- **インタラクティブチャットインターフェース** - Claude Code、Cursor、Codex とシームレスに通信する組み込みチャットインターフェース
|
||||
- **統合シェルターミナル** - 組み込みシェル機能による Claude Code、Cursor CLI、Codex への直接アクセス
|
||||
- **ファイルエクスプローラー** - シンタックスハイライトとライブ編集対応のインタラクティブファイルツリー
|
||||
- **Git エクスプローラー** - 変更の確認、ステージング、コミット。ブランチの切り替えも可能
|
||||
- **セッション管理** - 会話の再開、複数セッションの管理、履歴の追跡
|
||||
- **プラグインシステム** - カスタムプラグインで CloudCLI を拡張 — 新しいタブ、バックエンドサービス、連携を追加できます。[自分で構築する →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)
|
||||
- **TaskMaster AI 統合** *(オプション)* - AI 駆動のタスク計画、PRD 解析、ワークフロー自動化による高度なプロジェクト管理
|
||||
- **モデル互換性** - Claude Sonnet 4.5、Opus 4.5、GPT-5.2 に対応
|
||||
|
||||
|
||||
## クイックスタート
|
||||
|
||||
### CloudCLI Cloud(推奨)
|
||||
### 前提条件
|
||||
|
||||
最速で始める方法 — ローカルのセットアップは不要です。Web、モバイルアプリ、API、またはお気に入りの IDE からアクセスできる、フルマネージドでコンテナ化された開発環境を利用できます。
|
||||
- [Node.js](https://nodejs.org/) v22 以上
|
||||
- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) のインストールと設定、および/または
|
||||
- [Cursor CLI](https://docs.cursor.com/en/cli/overview) のインストールと設定、および/または
|
||||
- [Codex](https://developers.openai.com/codex) のインストールと設定
|
||||
|
||||
**[CloudCLI Cloud を始める](https://cloudcli.ai)**
|
||||
### ワンクリック実行(推奨)
|
||||
|
||||
### セルフホスト(オープンソース)
|
||||
|
||||
#### npm
|
||||
|
||||
**npx** で今すぐ CloudCLI UI を試せます(**Node.js** v22+ が必要):
|
||||
インストール不要、直接実行:
|
||||
|
||||
```bash
|
||||
npx @cloudcli-ai/cloudcli
|
||||
npx @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
または、普段使いするなら **グローバル** にインストール:
|
||||
サーバーが起動し、`http://localhost:3001`(または設定した PORT)でアクセスできます。
|
||||
|
||||
**再起動**: サーバーを停止した後、同じ `npx` コマンドを再度実行するだけです
|
||||
### グローバルインストール(定期的に使用する場合)
|
||||
|
||||
頻繁に使用する場合は、一度だけグローバルインストール:
|
||||
|
||||
```bash
|
||||
npm install -g @cloudcli-ai/cloudcli
|
||||
cloudcli
|
||||
npm install -g @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
`http://localhost:3001` を開いてください — 既存のセッションは自動的に検出されます。
|
||||
シンプルなコマンドで起動:
|
||||
|
||||
より詳細な設定オプション、PM2、リモートサーバー設定などについては **[ドキュメントはこちら →](https://cloudcli.ai/docs)** を参照してください。
|
||||
|
||||
#### Docker Sandboxes(実験的)
|
||||
|
||||
ハイパーバイザーレベルの分離でエージェントをサンドボックスで実行します。デフォルトでは Claude Code が起動します。[`sbx` CLI](https://docs.docker.com/ai/sandboxes/get-started/) が必要です。
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project
|
||||
```bash
|
||||
claude-code-ui
|
||||
```
|
||||
|
||||
Claude Code、Codex、Gemini CLI に対応。詳細は[サンドボックスのドキュメント](docker/)をご覧ください。
|
||||
|
||||
---
|
||||
**再起動**: Ctrl+C で停止し、`claude-code-ui` を再度実行します。
|
||||
|
||||
## どちらの選択肢が適していますか?
|
||||
**アップデート**:
|
||||
```bash
|
||||
cloudcli update
|
||||
```
|
||||
|
||||
CloudCLI UI は、CloudCLI Cloud を支えるオープンソースの UI レイヤーです。自分のマシンにセルフホストすることも、フルマネージドのクラウド環境、チーム機能、より深い統合を備えた CloudCLI Cloud を使うこともできます。
|
||||
### CLI の使い方
|
||||
|
||||
| | CloudCLI UI(セルフホスト) | CloudCLI Cloud |
|
||||
|---|---|---|
|
||||
| **対象ユーザー** | 自分のマシン上でローカルの agent セッションに対してフル UI を使いたい開発者 | クラウド上で動く agents をどこからでも利用したいチーム/開発者 |
|
||||
| **アクセス方法** | ブラウザ(`[yourip]:port`) | ブラウザ、任意の IDE、REST API、n8n |
|
||||
| **セットアップ** | `npx @cloudcli-ai/cloudcli` | セットアップ不要 |
|
||||
| **マシンの稼働継続** | はい | いいえ |
|
||||
| **モバイルアクセス** | 同一ネットワーク内の任意のブラウザ | 任意のデバイス(ネイティブアプリも準備中) |
|
||||
| **利用可能なセッション** | `~/.claude` から全セッションを自動検出 | クラウド環境内の全セッション |
|
||||
| **対応エージェント** | Claude Code、Cursor CLI、Codex、Gemini CLI | Claude Code、Cursor CLI、Codex、Gemini CLI |
|
||||
| **ファイルエクスプローラとGit** | はい(UI に内蔵) | はい(UI に内蔵) |
|
||||
| **MCP設定** | UI で管理し、ローカルの `~/.claude` 設定と同期 | UI で管理 |
|
||||
| **IDEアクセス** | ローカル IDE | クラウド環境に接続された任意の IDE |
|
||||
| **REST API** | はい | はい |
|
||||
| **n8n ノード** | いいえ | はい |
|
||||
| **チーム共有** | いいえ | はい |
|
||||
| **料金プラン** | 無料(オープンソース) | 月 $7〜 |
|
||||
グローバルインストール後、`claude-code-ui` と `cloudcli` コマンドが使用できます:
|
||||
|
||||
> どちらの選択肢でも、AI のサブスクリプション(Claude、Cursor など)はご自身のものを使用します — CloudCLI が提供するのは環境であり、AI そのものではありません。
|
||||
| コマンド / オプション | 短縮形 | 説明 |
|
||||
|------------------|-------|-------------|
|
||||
| `cloudcli` または `claude-code-ui` | | サーバーを起動(デフォルト) |
|
||||
| `cloudcli start` | | サーバーを明示的に起動 |
|
||||
| `cloudcli status` | | 設定とデータの場所を表示 |
|
||||
| `cloudcli update` | | 最新バージョンに更新 |
|
||||
| `cloudcli help` | | ヘルプ情報を表示 |
|
||||
| `cloudcli version` | | バージョン情報を表示 |
|
||||
| `--port <port>` | `-p` | サーバーポートを設定(デフォルト: 3001) |
|
||||
| `--database-path <path>` | | カスタムデータベースの場所を設定 |
|
||||
|
||||
---
|
||||
**例:**
|
||||
```bash
|
||||
cloudcli # デフォルト設定で起動
|
||||
cloudcli -p 8080 # カスタムポートで起動
|
||||
cloudcli status # 現在の設定を表示
|
||||
```
|
||||
|
||||
### バックグラウンドサービスとして実行(本番環境推奨)
|
||||
|
||||
本番環境では、PM2(Process Manager 2)を使用して Claude Code UI をバックグラウンドサービスとして実行します:
|
||||
|
||||
#### PM2 のインストール
|
||||
|
||||
```bash
|
||||
npm install -g pm2
|
||||
```
|
||||
|
||||
#### バックグラウンドサービスとして起動
|
||||
|
||||
```bash
|
||||
# バックグラウンドでサーバーを起動
|
||||
pm2 start claude-code-ui --name "claude-code-ui"
|
||||
|
||||
# または短いエイリアスを使用
|
||||
pm2 start cloudcli --name "claude-code-ui"
|
||||
|
||||
# カスタムポートで起動
|
||||
pm2 start cloudcli --name "claude-code-ui" -- --port 8080
|
||||
```
|
||||
|
||||
|
||||
#### システム起動時の自動起動
|
||||
|
||||
システム起動時に Claude Code UI を自動的に起動するには:
|
||||
|
||||
```bash
|
||||
# プラットフォーム用の起動スクリプトを生成
|
||||
pm2 startup
|
||||
|
||||
# 現在のプロセスリストを保存
|
||||
pm2 save
|
||||
```
|
||||
|
||||
|
||||
### ローカル開発インストール
|
||||
|
||||
1. **リポジトリをクローン:**
|
||||
```bash
|
||||
git clone https://github.com/siteboon/claudecodeui.git
|
||||
cd claudecodeui
|
||||
```
|
||||
|
||||
2. **依存関係をインストール:**
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. **環境を設定:**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# お好みの設定で .env を編集
|
||||
```
|
||||
|
||||
4. **アプリケーションを起動:**
|
||||
```bash
|
||||
# 開発モード(ホットリロード付き)
|
||||
npm run dev
|
||||
|
||||
```
|
||||
アプリケーションは .env で指定したポートで起動します
|
||||
|
||||
5. **ブラウザを開く:**
|
||||
- 開発: `http://localhost:3001`
|
||||
|
||||
## セキュリティとツール設定
|
||||
|
||||
**🔒 重要なお知らせ** すべての Claude Code ツールは **デフォルトで無効** です。これにより、潜在的に有害な操作が自動的に実行されることを防ぎます。
|
||||
**重要なお知らせ**: すべての Claude Code ツールは**デフォルトで無効**になっています。これにより、潜在的に有害な操作が自動的に実行されることを防ぎます。
|
||||
|
||||
### ツールの有効化
|
||||
|
||||
Claude Code の全機能を使用するには、手動でツールを有効にする必要があります:
|
||||
|
||||
1. **ツール設定を開く** - サイドバーの歯車アイコンをクリック
|
||||
2. **必要なツールだけを選んで有効化** - 本当に使うものだけをオンにする
|
||||
3. **設定を適用** - 設定内容はローカルに保存されます
|
||||
3. **選択的に有効化** - 必要なツールのみを有効にする
|
||||
4. **設定を適用** - 環境設定はローカルに保存されます
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
*Tools 設定画面 - 必要なものだけを有効にしてください*
|
||||
*ツール設定インターフェース - 必要なものだけを有効にしましょう*
|
||||
|
||||
</div>
|
||||
|
||||
**推奨アプローチ**: まずは基本ツールだけを有効にし、必要に応じて追加してください。これらの設定は後からいつでも調整できます。
|
||||
**推奨アプローチ**: 基本的なツールから有効にし、必要に応じて追加してください。これらの設定はいつでも調整できます。
|
||||
|
||||
---
|
||||
## TaskMaster AI 統合 *(オプション)*
|
||||
|
||||
## プラグイン
|
||||
Claude Code UI は、高度なプロジェクト管理と AI 駆動のタスク計画のための **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)**(別名 claude-task-master)統合をサポートしています。
|
||||
|
||||
CloudCLI にはプラグインシステムがあり、独自のフロントエンド UI と(必要に応じて)Node.js バックエンドを持つカスタムタブを追加できます。プラグインは **Settings > Plugins** から git リポジトリを直接指定してインストールするか、自作できます。
|
||||
提供機能
|
||||
- PRD(製品要件ドキュメント)からの AI 駆動タスク生成
|
||||
- スマートなタスク分解と依存関係管理
|
||||
- ビジュアルタスクボードと進捗追跡
|
||||
|
||||
### 利用可能なプラグイン
|
||||
**セットアップとドキュメント**: インストール手順、設定ガイド、使用例は [TaskMaster AI GitHub リポジトリ](https://github.com/eyaltoledano/claude-task-master)をご覧ください。
|
||||
インストール後、設定から有効にできます
|
||||
|
||||
| プラグイン | 説明 |
|
||||
|---|---|
|
||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 現在のプロジェクトについて、ファイル数、コード行数、ファイル種別の内訳、最大ファイル、最近変更されたファイルを表示 |
|
||||
|
||||
### 自作する
|
||||
## 使用ガイド
|
||||
|
||||
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — このリポジトリを fork して独自プラグインを作れます。フロントエンド描画、ライブコンテキスト更新、バックエンドサーバーへの RPC 通信を含む動作例が入っています。
|
||||
### 主要機能
|
||||
|
||||
**[プラグインのドキュメント →](https://cloudcli.ai/docs/plugin-overview)** — プラグイン API、manifest 形式、セキュリティモデルなどの完全ガイド。
|
||||
#### プロジェクト管理
|
||||
Claude Code、Cursor、Codex のセッションが利用可能な場合、自動的に検出しプロジェクトとしてグループ化します
|
||||
- **プロジェクト操作** - プロジェクトの名前変更、削除、整理
|
||||
- **スマートナビゲーション** - 最近のプロジェクトやセッションへのクイックアクセス
|
||||
- **MCP サポート** - UI から独自の MCP サーバーを追加
|
||||
|
||||
---
|
||||
## FAQ
|
||||
#### チャットインターフェース
|
||||
- **レスポンシブチャットまたは Claude Code/Cursor CLI/Codex CLI を使用** - アダプティブチャットインターフェースを使用するか、シェルボタンで選択した CLI に接続できます
|
||||
- **リアルタイム通信** - WebSocket 接続で選択した CLI(Claude Code/Cursor/Codex)からレスポンスをストリーミング
|
||||
- **セッション管理** - 以前の会話を再開、または新しいセッションを開始
|
||||
- **メッセージ履歴** - タイムスタンプとメタデータ付きの完全な会話履歴
|
||||
- **マルチフォーマット対応** - テキスト、コードブロック、ファイル参照
|
||||
|
||||
<details>
|
||||
<summary>Claude Code Remote Control とはどう違いますか?</summary>
|
||||
#### ファイルエクスプローラーとエディター
|
||||
- **インタラクティブファイルツリー** - 展開/折りたたみナビゲーションでプロジェクト構造を閲覧
|
||||
- **ライブファイル編集** - インターフェースで直接ファイルの読み取り、変更、保存
|
||||
- **シンタックスハイライト** - 複数のプログラミング言語に対応
|
||||
- **ファイル操作** - ファイルやディレクトリの作成、名前変更、削除
|
||||
|
||||
Claude Code Remote Control は、ローカル端末で既に動作しているセッションへメッセージを送れる仕組みです。マシンを起動したままにし、端末も開いたままにする必要があり、ネットワーク接続がない状態が約 10 分続くとセッションがタイムアウトします。
|
||||
#### Git エクスプローラー
|
||||
|
||||
CloudCLI UI と CloudCLI Cloud は、Claude Code の横に別物として存在するのではなく、Claude Code を拡張します — MCP サーバー、権限、設定、セッションは Claude Code がネイティブに使うものと完全に同一です。複製したり、別系統で管理したりしません。
|
||||
|
||||
- **すべてのセッションにアクセス** — CloudCLI UI は `~/.claude` フォルダのすべてのセッションを自動検出します。Remote Control は、Claude モバイルアプリで利用可能にするため、1つのアクティブセッションだけを公開します。
|
||||
- **設定はあなたの設定** — CloudCLI UI で変更した MCP サーバー、ツール権限、プロジェクト構成は、Claude Code の設定に直接書き込まれて即座に反映され、その逆(Claude Code での変更が UI に反映)も同様です。
|
||||
- **対応エージェントがさらに充実** — Claude Code に加えて Cursor CLI、Codex、Gemini CLI にも対応しています。
|
||||
- **チャット窓だけではない完全な UI** — ファイルエクスプローラー、Git 統合、MCP 管理、シェル端末などがすべて組み込まれています。
|
||||
- **CloudCLI Cloud はクラウド上で稼働** — ノートパソコンを閉じてもエージェントは動き続けます。監視が要る端末も、スリープ防止も不要です。
|
||||
#### TaskMaster AI 統合 *(オプション)*
|
||||
- **ビジュアルタスクボード** - 開発タスク管理のためのカンバンスタイルインターフェース
|
||||
- **PRD パーサー** - 製品要件ドキュメントを作成し、構造化されたタスクに変換
|
||||
- **進捗追跡** - リアルタイムのステータス更新と完了追跡
|
||||
|
||||
</details>
|
||||
#### セッション管理
|
||||
- **セッション永続化** - すべての会話を自動保存
|
||||
- **セッション整理** - プロジェクトとタイムスタンプでセッションをグループ化
|
||||
- **セッション操作** - 会話履歴の名前変更、削除、エクスポート
|
||||
- **クロスデバイス同期** - どのデバイスからでもセッションにアクセス
|
||||
|
||||
<details>
|
||||
<summary>AI のサブスクリプションは別途支払いが必要ですか?</summary>
|
||||
### モバイルアプリ
|
||||
- **レスポンシブデザイン** - すべての画面サイズに最適化
|
||||
- **タッチフレンドリーインターフェース** - スワイプジェスチャーとタッチナビゲーション
|
||||
- **モバイルナビゲーション** - 親指で操作しやすいボトムタブバー
|
||||
- **アダプティブレイアウト** - 折りたたみ可能なサイドバーとスマートコンテンツ優先順位
|
||||
- **ホーム画面にショートカットを追加** - ホーム画面にショートカットを追加すると、アプリが PWA のように動作します
|
||||
|
||||
はい。CloudCLI は環境を提供するものであり、AI は含まれません。Claude、Cursor、Codex、または Gemini のサブスクリプションはご自身でご用意ください。CloudCLI Cloud のホスティング環境はそれに加えて月額 $7 から提供されます。
|
||||
## アーキテクチャ
|
||||
|
||||
</details>
|
||||
### システム概要
|
||||
|
||||
<details>
|
||||
<summary>CloudCLI UI をスマホで使えますか?</summary>
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Frontend │ │ Backend │ │ Agent │
|
||||
│ (React/Vite) │◄──►│ (Express/WS) │◄──►│ Integration │
|
||||
│ │ │ │ │ │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
はい。セルフホストの場合は、自身のマシンでサーバーを起動し、ネットワーク内のブラウザで `[yourip]:port` を開いてください。CloudCLI Cloud を使う場合は、任意のデバイスからアクセスできます。VPN もポートフォワーディングも不要で、セットアップも不要です。ネイティブアプリも開発中です。
|
||||
### バックエンド (Node.js + Express)
|
||||
- **Express サーバー** - 静的ファイル配信付きの RESTful API
|
||||
- **WebSocket サーバー** - チャットとプロジェクト更新のための通信
|
||||
- **エージェント統合 (Claude Code / Cursor CLI / Codex)** - プロセスの生成と管理
|
||||
- **ファイルシステム API** - プロジェクト向けファイルブラウザの公開
|
||||
|
||||
</details>
|
||||
### フロントエンド (React + Vite)
|
||||
- **React 18** - hooks を使用したモダンなコンポーネントアーキテクチャ
|
||||
- **CodeMirror** - シンタックスハイライト対応の高度なコードエディター
|
||||
|
||||
<details>
|
||||
<summary>UI で加えた変更はローカルの Claude Code 設定に影響しますか?</summary>
|
||||
|
||||
はい、セルフホストの場合です。CloudCLI UI は Claude Code がネイティブに使う `~/.claude` 設定を読み書きします。UI から追加した MCP サーバーは即座に Claude Code に反映され、その逆も同様です。
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
### コントリビューション
|
||||
|
||||
## コミュニティとサポート
|
||||
コントリビューションを歓迎します!コミット規約、開発ワークフロー、リリースプロセスの詳細は [Contributing Guide](CONTRIBUTING.md) をご覧ください。
|
||||
|
||||
## トラブルシューティング
|
||||
|
||||
### よくある問題と解決方法
|
||||
|
||||
|
||||
#### 「Claude プロジェクトが見つかりません」
|
||||
**問題**: UI にプロジェクトが表示されない、またはプロジェクトリストが空
|
||||
**解決方法**:
|
||||
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code) が正しくインストールされていることを確認
|
||||
- 少なくとも1つのプロジェクトディレクトリで `claude` コマンドを実行して初期化
|
||||
- `~/.claude/projects/` ディレクトリが存在し、適切な権限があることを確認
|
||||
|
||||
#### ファイルエクスプローラーの問題
|
||||
**問題**: ファイルが読み込まれない、権限エラー、空のディレクトリ
|
||||
**解決方法**:
|
||||
- プロジェクトディレクトリの権限を確認(ターミナルで `ls -la`)
|
||||
- プロジェクトパスが存在しアクセス可能であることを確認
|
||||
- 詳細なエラーメッセージについてはサーバーコンソールログを確認
|
||||
- プロジェクト範囲外のシステムディレクトリにアクセスしていないことを確認
|
||||
|
||||
- **[ドキュメント](https://cloudcli.ai/docs)** — インストール、設定、機能、トラブルシューティング
|
||||
- **[Discord](https://discord.gg/buxwujPNRE)** — ヘルプを得たり、ユーザー同士で交流したりできます
|
||||
- **[GitHub Issues](https://github.com/siteboon/claudecodeui/issues)** — バグ報告と機能要望
|
||||
- **[コントリビューションガイド](CONTRIBUTING.md)** — プロジェクトへの貢献方法
|
||||
|
||||
## ライセンス
|
||||
|
||||
GNU General Public License v3.0 - 詳細は [LICENSE](LICENSE) ファイルを参照してください。
|
||||
GNU General Public License v3.0 - 詳細は [LICENSE](LICENSE) ファイルをご覧ください。
|
||||
|
||||
このプロジェクトはオープンソースであり、GPL v3 ライセンスの下で無料で使用、修正、再配布できます。
|
||||
このプロジェクトはオープンソースであり、GPL v3 ライセンスの下で自由に使用、変更、配布できます。
|
||||
|
||||
## 謝辞
|
||||
|
||||
### 使用技術
|
||||
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic の公式 CLI
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursor の公式 CLI
|
||||
- **[Codex](https://developers.openai.com/codex)** - OpenAI Codex
|
||||
- **[Gemini-CLI](https://geminicli.com/)** - Google Gemini CLI
|
||||
- **[React](https://react.dev/)** - ユーザーインターフェースライブラリ
|
||||
- **[Vite](https://vitejs.dev/)** - 高速ビルドツールと開発サーバー
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - ユーティリティファーストの CSS フレームワーク
|
||||
- **[CodeMirror](https://codemirror.net/)** - 高度なコードエディタ
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(オプション)* - AI を活用したプロジェクト管理とタスク計画
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - ユーティリティファースト CSS フレームワーク
|
||||
- **[CodeMirror](https://codemirror.net/)** - 高度なコードエディター
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(オプション)* - AI 駆動のプロジェクト管理とタスク計画
|
||||
|
||||
## スポンサー
|
||||
- [Siteboon - AI を活用したウェブサイトビルダー](https://siteboon.ai)
|
||||
## サポートとコミュニティ
|
||||
|
||||
### 最新情報を入手
|
||||
- このリポジトリに **Star** をつけてサポートを表明
|
||||
- **Watch** で更新や新リリースを確認
|
||||
- プロジェクトを **Follow** してお知らせを受け取る
|
||||
|
||||
### スポンサー
|
||||
- [Siteboon - AI powered website builder](https://siteboon.ai)
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
353
README.ko.md
353
README.ko.md
@@ -1,23 +1,12 @@
|
||||
<div align="center">
|
||||
<img src="public/logo.svg" alt="CloudCLI UI" width="64" height="64">
|
||||
<img src="public/logo.svg" alt="Claude Code UI" width="64" height="64">
|
||||
<h1>Cloud CLI (일명 Claude Code UI)</h1>
|
||||
<p><a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code</a>, <a href="https://docs.cursor.com/en/cli/overview">Cursor CLI</a>, <a href="https://developers.openai.com/codex">Codex</a>, <a href="https://geminicli.com/">Gemini-CLI</a> 용 데스크톱 및 모바일 UI입니다.<br>로컬 또는 원격에서 실행하여 어디서나 활성 프로젝트와 세션을 확인하세요.</p>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://cloudcli.ai/docs">문서</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">버그 신고</a> · <a href="CONTRIBUTING.md">기여 안내</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai"><img src="https://img.shields.io/badge/☁️_CloudCLI_Cloud-Try_Now-0066FF?style=for-the-badge" alt="CloudCLI Cloud"></a>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord 커뮤니티"></a>
|
||||
<br><br>
|
||||
<a href="https://trendshift.io/repositories/15586" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15586" alt="siteboon%2Fclaudecodeui | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
[Claude Code](https://docs.anthropic.com/en/docs/claude-code), [Cursor CLI](https://docs.cursor.com/en/cli/overview) 및 [Codex](https://developers.openai.com/codex)를 위한 데스크톱 및 모바일 UI입니다. 로컬 또는 원격으로 사용하여 Claude Code, Cursor 또는 Codex의 활성 프로젝트와 세션을 확인하고, 어디서든(모바일 또는 데스크톱) 변경할 수 있습니다. 어디서든 작동하는 적절한 인터페이스를 제공합니다.
|
||||
|
||||
<div align="right"><i><a href="./README.md">English</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.de.md">Deutsch</a> · <b>한국어</b> · <a href="./README.zh-CN.md">中文</a> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
---
|
||||
<div align="right"><i><a href="./README.md">English</a> · <a href="./README.zh-CN.md">中文</a> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
## 스크린샷
|
||||
|
||||
@@ -26,14 +15,14 @@
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h3>데스크톱 보기</h3>
|
||||
<img src="public/screenshots/desktop-main.png" alt="데스크톱 인터페이스" width="400">
|
||||
<h3>데스크톱 뷰</h3>
|
||||
<img src="public/screenshots/desktop-main.png" alt="Desktop Interface" width="400">
|
||||
<br>
|
||||
<em>프로젝트 개요와 채팅을 보여주는 메인 인터페이스</em>
|
||||
</td>
|
||||
<td align="center">
|
||||
<h3>모바일 경험</h3>
|
||||
<img src="public/screenshots/mobile-chat.png" alt="모바일 인터페이스" width="250">
|
||||
<img src="public/screenshots/mobile-chat.png" alt="Mobile Interface" width="250">
|
||||
<br>
|
||||
<em>터치 내비게이션이 포함된 반응형 모바일 디자인</em>
|
||||
</td>
|
||||
@@ -41,202 +30,316 @@
|
||||
<tr>
|
||||
<td align="center" colspan="2">
|
||||
<h3>CLI 선택</h3>
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI 선택" width="400">
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI Selection" width="400">
|
||||
<br>
|
||||
<em>Claude Code, Gemini, Cursor CLI 및 Codex 중 선택</em>
|
||||
<em>Claude Code, Cursor CLI, Codex 중 선택</em>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## 기능
|
||||
|
||||
- **반응형 디자인** - 데스크톱, 태블릿, 모바일을 아우르는 매끄러운 경험으로 어디서든 Agents를 사용할 수 있습니다
|
||||
- **대화형 채팅 인터페이스** - 내장된 채팅 UI를 통해 에이전트와 자연스럽게 소통
|
||||
- **통합 셸 터미널** - 셸 기능을 통해 Agents CLI에 직접 접근
|
||||
- **파일 탐색기** - 구문 강조 및 실시간 편집을 갖춘 인터랙티브 파일 트리
|
||||
- **Git 탐색기** - 변경 사항 보기, 스테이징 및 커밋. 브랜치 전환 기능 포함
|
||||
- **세션 관리** - 대화를 재개하고, 여러 세션을 관리하며 기록을 추적
|
||||
- **플러그인 시스템** - 커스텀 탭, 백엔드 서비스, 통합을 추가하여 CloudCLI 확장. [직접 빌드 →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)
|
||||
- **TaskMaster AI 통합** *(선택사항)* - AI 중심의 작업 계획, PRD 파싱, 워크플로 자동화를 통한 고급 프로젝트 관리
|
||||
- **모델 호환성** - Claude, GPT, Gemini 모델 계열에서 작동 (`shared/modelConstants.js`에서 전체 지원 모델 확인)
|
||||
- **반응형 디자인** - 데스크톱, 태블릿, 모바일에서 원활하게 작동하여 모바일에서도 Claude Code, Cursor 또는 Codex를 사용할 수 있습니다
|
||||
- **대화형 채팅 인터페이스** - Claude Code, Cursor 또는 Codex와 원활하게 소통하는 내장 채팅 인터페이스
|
||||
- **통합 셸 터미널** - 내장 셸 기능을 통한 Claude Code, Cursor CLI 또는 Codex 직접 접근
|
||||
- **파일 탐색기** - 구문 강조 및 실시간 편집이 가능한 대화형 파일 트리
|
||||
- **Git 탐색기** - 변경사항 보기, 스테이징 및 커밋. 브랜치 전환도 가능
|
||||
- **세션 관리** - 대화 재개, 여러 세션 관리 및 기록 추적
|
||||
- **TaskMaster AI 통합** *(선택사항)* - AI 기반 작업 계획, PRD 분석 및 워크플로우 자동화를 통한 고급 프로젝트 관리
|
||||
- **모델 호환성** - Claude Sonnet 4.5, Opus 4.5 및 GPT-5.2 지원
|
||||
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
### CloudCLI Cloud (추천)
|
||||
### 사전 요구사항
|
||||
|
||||
가장 빠르게 시작하는 방법 — 로컬 설정 없이도 가능합니다. 웹, 모바일 앱, API 또는 선호하는 IDE에서 이용할 수 있는 완전 관리형 컨테이너화된 개발 환경을 제공합니다.
|
||||
- [Node.js](https://nodejs.org/) v22 이상
|
||||
- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) 설치 및 구성, 그리고/또는
|
||||
- [Cursor CLI](https://docs.cursor.com/en/cli/overview) 설치 및 구성, 그리고/또는
|
||||
- [Codex](https://developers.openai.com/codex) 설치 및 구성
|
||||
|
||||
**[CloudCLI Cloud 시작하기](https://cloudcli.ai)**
|
||||
### 원클릭 실행 (권장)
|
||||
|
||||
### 셀프 호스트 (오픈 소스)
|
||||
|
||||
#### npm
|
||||
|
||||
**npx**로 즉시 CloudCLI UI를 실행하세요 (Node.js v22+ 필요):
|
||||
설치 없이 바로 실행:
|
||||
|
||||
```bash
|
||||
npx @cloudcli-ai/cloudcli
|
||||
npx @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
**정기적으로 사용한다면 전역 설치:**
|
||||
서버가 시작되면 `http://localhost:3001` (또는 설정한 PORT)에서 접근할 수 있습니다.
|
||||
|
||||
**재시작**: 서버를 중지한 후 동일한 `npx` 명령을 다시 실행하면 됩니다
|
||||
### 전역 설치 (정기적 사용 시)
|
||||
|
||||
자주 사용하는 경우 한 번만 전역 설치:
|
||||
|
||||
```bash
|
||||
npm install -g @cloudcli-ai/cloudcli
|
||||
cloudcli
|
||||
npm install -g @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
`http://localhost:3001`을 열면 기존 세션이 자동으로 발견됩니다.
|
||||
간단한 명령으로 시작:
|
||||
|
||||
자세한 구성 옵션, PM2, 원격 서버 설정 등은 **[문서 →](https://cloudcli.ai/docs)**를 참고하세요.
|
||||
|
||||
#### Docker Sandboxes (실험적)
|
||||
|
||||
하이퍼바이저 수준 격리로 에이전트를 샌드박스에서 실행합니다. 기본 에이전트는 Claude Code입니다. [`sbx` CLI](https://docs.docker.com/ai/sandboxes/get-started/)가 필요합니다.
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project
|
||||
```bash
|
||||
claude-code-ui
|
||||
```
|
||||
|
||||
Claude Code, Codex, Gemini CLI를 지원합니다. 자세한 내용은 [샌드박스 문서](docker/)를 참고하세요.
|
||||
|
||||
---
|
||||
**재시작**: Ctrl+C로 중지한 후 `claude-code-ui`를 다시 실행합니다.
|
||||
|
||||
## 어느 옵션이 적합한가요?
|
||||
**업데이트**:
|
||||
```bash
|
||||
cloudcli update
|
||||
```
|
||||
|
||||
CloudCLI UI는 CloudCLI Cloud를 구동하는 오픈 소스 UI 계층입니다. 로컬 머신에서 직접 셀프 호스트하거나, CloudCLI Cloud(완전 관리형 클라우드 환경, 팀 기능, 심화 통합 제공)를 사용할 수 있습니다.
|
||||
### CLI 사용법
|
||||
|
||||
| | CloudCLI UI (셀프 호스트) | CloudCLI Cloud |
|
||||
|---|---|---|
|
||||
| **적합한 대상** | 로컬 에이전트 세션을 위한 전체 UI가 필요한 개발자 | 어디서든 접근 가능한 클라우드에서 에이전트를 운영하고자 하는 팀 및 개발자 |
|
||||
| **접근 방법** | `[yourip]:port`를 통해 브라우저 접속 | 브라우저, IDE, REST API, n8n |
|
||||
| **설정** | `npx @cloudcli-ai/cloudcli` | 설정 불필요 |
|
||||
| **기기 유지 필요 여부** | 예 (머신 켜둬야 함) | 아니오 |
|
||||
| **모바일 접근** | 네트워크 내 브라우저 | 모든 기기 (네이티브 앱 예정) |
|
||||
| **세션 접근** | `~/.claude`에서 자동 발견 | 클라우드 환경 내 세션 |
|
||||
| **지원 에이전트** | Claude Code, Cursor CLI, Codex, Gemini CLI | Claude Code, Cursor CLI, Codex, Gemini CLI |
|
||||
| **파일 탐색기 및 Git** | UI에 통합됨 | UI에 통합됨 |
|
||||
| **MCP 구성** | UI에서 관리, 로컬 `~/.claude` 설정과 동기화됨 | UI에서 관리 |
|
||||
| **IDE 접근** | 로컬 IDE | 클라우드 환경에 연결된 모든 IDE |
|
||||
| **REST API** | 예 | 예 |
|
||||
| **n8n 노드** | 아니오 | 예 |
|
||||
| **팀 공유** | 아니오 | 예 |
|
||||
| **플랫폼 비용** | 무료, 오픈 소스 | 월 $7부터 |
|
||||
전역 설치 후 `claude-code-ui`와 `cloudcli` 명령을 사용할 수 있습니다:
|
||||
|
||||
> 둘 다 자체 AI 구독(Claude, Cursor 등)을 그대로 사용합니다 — CloudCLI는 환경만 제공합니다.
|
||||
| 명령 / 옵션 | 약어 | 설명 |
|
||||
|------------------|-------|-------------|
|
||||
| `cloudcli` 또는 `claude-code-ui` | | 서버 시작 (기본값) |
|
||||
| `cloudcli start` | | 서버 명시적 시작 |
|
||||
| `cloudcli status` | | 구성 및 데이터 위치 표시 |
|
||||
| `cloudcli update` | | 최신 버전으로 업데이트 |
|
||||
| `cloudcli help` | | 도움말 정보 표시 |
|
||||
| `cloudcli version` | | 버전 정보 표시 |
|
||||
| `--port <port>` | `-p` | 서버 포트 설정 (기본값: 3001) |
|
||||
| `--database-path <path>` | | 사용자 지정 데이터베이스 위치 설정 |
|
||||
|
||||
---
|
||||
**예시:**
|
||||
```bash
|
||||
cloudcli # 기본 설정으로 시작
|
||||
cloudcli -p 8080 # 사용자 지정 포트로 시작
|
||||
cloudcli status # 현재 구성 표시
|
||||
```
|
||||
|
||||
## 보안 및 도구 구성
|
||||
### 백그라운드 서비스로 실행 (프로덕션 권장)
|
||||
|
||||
**🔒 중요 공지**: 모든 Claude Code 도구는 **기본적으로 비활성화**되어 있습니다. 이는 잠재적인 유해 작업이 자동 실행되는 것을 방지하기 위한 조치입니다.
|
||||
프로덕션 환경에서는 PM2(Process Manager 2)를 사용하여 Claude Code UI를 백그라운드 서비스로 실행하세요:
|
||||
|
||||
#### PM2 설치
|
||||
|
||||
```bash
|
||||
npm install -g pm2
|
||||
```
|
||||
|
||||
#### 백그라운드 서비스로 시작
|
||||
|
||||
```bash
|
||||
# 백그라운드에서 서버 시작
|
||||
pm2 start claude-code-ui --name "claude-code-ui"
|
||||
|
||||
# 또는 짧은 별칭 사용
|
||||
pm2 start cloudcli --name "claude-code-ui"
|
||||
|
||||
# 사용자 지정 포트로 시작
|
||||
pm2 start cloudcli --name "claude-code-ui" -- --port 8080
|
||||
```
|
||||
|
||||
|
||||
#### 시스템 부팅 시 자동 시작
|
||||
|
||||
시스템 부팅 시 Claude Code UI를 자동으로 시작하려면:
|
||||
|
||||
```bash
|
||||
# 플랫폼에 맞는 시작 스크립트 생성
|
||||
pm2 startup
|
||||
|
||||
# 현재 프로세스 목록 저장
|
||||
pm2 save
|
||||
```
|
||||
|
||||
|
||||
### 로컬 개발 설치
|
||||
|
||||
1. **리포지토리 클론:**
|
||||
```bash
|
||||
git clone https://github.com/siteboon/claudecodeui.git
|
||||
cd claudecodeui
|
||||
```
|
||||
|
||||
2. **의존성 설치:**
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. **환경 구성:**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# 원하는 설정으로 .env 파일 편집
|
||||
```
|
||||
|
||||
4. **애플리케이션 시작:**
|
||||
```bash
|
||||
# 개발 모드 (핫 리로드 포함)
|
||||
npm run dev
|
||||
|
||||
```
|
||||
애플리케이션은 .env에서 지정한 포트에서 시작됩니다
|
||||
|
||||
5. **브라우저 열기:**
|
||||
- 개발: `http://localhost:3001`
|
||||
|
||||
## 보안 및 도구 설정
|
||||
|
||||
**🔒 중요 공지**: 모든 Claude Code 도구는 **기본적으로 비활성화**되어 있습니다. 이는 잠재적으로 유해한 작업이 자동으로 실행되는 것을 방지합니다.
|
||||
|
||||
### 도구 활성화
|
||||
|
||||
1. **도구 설정 열기** - 사이드바의 톱니바퀴 아이콘 클릭
|
||||
2. **선택적으로 활성화** - 필요한 도구만 켜기
|
||||
3. **설정 적용** - 선호도는 로컬에 저장됨
|
||||
Claude Code의 전체 기능을 사용하려면 수동으로 도구를 활성화해야 합니다:
|
||||
|
||||
1. **도구 설정 열기** - 사이드바의 톱니바퀴 아이콘을 클릭
|
||||
3. **선택적으로 활성화** - 필요한 도구만 활성화
|
||||
4. **설정 적용** - 환경설정은 로컬에 저장됩니다
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
*도구 설정 인터페이스 - 필요한 것만 켜세요*
|
||||
*도구 설정 인터페이스 - 필요한 것만 활성화하세요*
|
||||
|
||||
</div>
|
||||
|
||||
**권장 방법**: 기본 도구를 먼저 켜고 필요할 때 추가하세요. 언제든지 조정 가능합니다.
|
||||
**권장 접근법**: 기본 도구부터 활성화하고 필요에 따라 추가하세요. 언제든지 이 설정을 조정할 수 있습니다.
|
||||
|
||||
---
|
||||
## TaskMaster AI 통합 *(선택사항)*
|
||||
|
||||
## 플러그인
|
||||
Claude Code UI는 고급 프로젝트 관리 및 AI 기반 작업 계획을 위한 **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)**(일명 claude-task-master) 통합을 지원합니다.
|
||||
|
||||
CloudCLI는 커스텀 탭과 선택적 Node.js 백엔드가 포함된 플러그인 시스템을 제공합니다. Settings > Plugins에서 Git 저장소에서 플러그인을 설치하거나 직접 빌드할 수 있습니다.
|
||||
제공 기능
|
||||
- PRD(제품 요구사항 문서)에서 AI 기반 작업 생성
|
||||
- 스마트 작업 분해 및 의존성 관리
|
||||
- 시각적 작업 보드 및 진행 상황 추적
|
||||
|
||||
### 이용 가능한 플러그인
|
||||
**설정 및 문서**: 설치 지침, 구성 가이드 및 사용 예시는 [TaskMaster AI GitHub 리포지토리](https://github.com/eyaltoledano/claude-task-master)를 방문하세요.
|
||||
설치 후 설정에서 활성화할 수 있습니다
|
||||
|
||||
| 플러그인 | 설명 |
|
||||
|---|---|
|
||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 현재 프로젝트의 파일 수, 코드 줄 수, 파일 유형 분포, 가장 큰 파일, 최근 수정 파일을 표시 |
|
||||
|
||||
### 직접 만들기
|
||||
## 사용 가이드
|
||||
|
||||
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — 이 저장소를 포크하여 플러그인 구축. 프런트엔드 렌더링, 실시간 컨텍스트 업데이트, RPC 통신 예제 포함.
|
||||
### 핵심 기능
|
||||
|
||||
**[플러그인 문서 →](https://cloudcli.ai/docs/plugin-overview)** — 플러그인 API, 매니페스트 포맷, 보안 모델 등을 설명.
|
||||
#### 프로젝트 관리
|
||||
Claude Code, Cursor 또는 Codex 세션을 사용할 수 있을 때 자동으로 발견하고 프로젝트로 그룹화합니다
|
||||
- **프로젝트 작업** - 프로젝트 이름 변경, 삭제 및 정리
|
||||
- **스마트 내비게이션** - 최근 프로젝트 및 세션에 빠르게 접근
|
||||
- **MCP 지원** - UI를 통해 자체 MCP 서버 추가
|
||||
|
||||
---
|
||||
#### 채팅 인터페이스
|
||||
- **반응형 채팅 또는 Claude Code/Cursor CLI/Codex CLI 사용** - 적응형 채팅 인터페이스를 사용하거나 셸 버튼을 사용하여 선택한 CLI에 연결할 수 있습니다
|
||||
- **실시간 통신** - WebSocket 연결을 통해 선택한 CLI(Claude Code/Cursor/Codex)에서 응답 스트리밍
|
||||
- **세션 관리** - 이전 대화 재개 또는 새 세션 시작
|
||||
- **메시지 기록** - 타임스탬프 및 메타데이터가 포함된 전체 대화 기록
|
||||
- **다중 형식 지원** - 텍스트, 코드 블록 및 파일 참조
|
||||
|
||||
## FAQ
|
||||
#### 파일 탐색기 및 편집기
|
||||
- **대화형 파일 트리** - 확장/축소 내비게이션으로 프로젝트 구조 탐색
|
||||
- **실시간 파일 편집** - 인터페이스에서 직접 파일 읽기, 수정 및 저장
|
||||
- **구문 강조** - 다양한 프로그래밍 언어 지원
|
||||
- **파일 작업** - 파일 및 디렉토리 생성, 이름 변경, 삭제
|
||||
|
||||
<details>
|
||||
<summary>Claude Code Remote Control과 어떻게 다른가요?</summary>
|
||||
#### Git 탐색기
|
||||
|
||||
Claude Code Remote Control은 이미 로컬 터미널에서 실행 중인 세션으로 메시지를 전송합니다. 이 경우 기계가 켜져 있어야 하고 터미널을 열어 둬야 하며, 네트워크 연결 없이 약 10분 후 타임아웃됩니다.
|
||||
|
||||
CloudCLI UI와 CloudCLI Cloud는 Claude Code를 확장하며 별도로 존재하지 않습니다 — MCP 서버, 권한, 설정, 세션은 Claude Code에서 그대로 사용됩니다.
|
||||
#### TaskMaster AI 통합 *(선택사항)*
|
||||
- **시각적 작업 보드** - 개발 작업 관리를 위한 칸반 스타일 인터페이스
|
||||
- **PRD 파서** - 제품 요구사항 문서를 생성하고 구조화된 작업으로 변환
|
||||
- **진행 상황 추적** - 실시간 상태 업데이트 및 완료 추적
|
||||
|
||||
- **모든 세션을 다룬다** — CloudCLI UI는 `~/.claude` 폴더에서 모든 세션을 자동 발견합니다. Remote Control은 단일 활성 세션만 노출합니다.
|
||||
- **설정은 그대로** — CloudCLI UI에서 변경한 MCP, 도구 권한, 프로젝트 설정은 Claude Code에 즉시 반영됩니다.
|
||||
- **지원 에이전트가 더 많음** — Claude Code, Cursor CLI, Codex, Gemini CLI 지원.
|
||||
- **전체 UI 제공** — 단일 채팅 창이 아닌 파일 탐색기, Git 통합, MCP 관리 및 셸 터미널 포함.
|
||||
- **CloudCLI Cloud는 클라우드에서 실행** — 노트북을 닫아도 에이전트가 실행됩니다. 터미널을 계속 확인할 필요 없음.
|
||||
#### 세션 관리
|
||||
- **세션 지속성** - 모든 대화 자동 저장
|
||||
- **세션 정리** - 프로젝트 및 타임스탬프별 세션 그룹화
|
||||
- **세션 작업** - 대화 기록 이름 변경, 삭제 및 내보내기
|
||||
- **크로스 디바이스 동기화** - 모든 기기에서 세션 접근
|
||||
|
||||
</details>
|
||||
### 모바일 앱
|
||||
- **반응형 디자인** - 모든 화면 크기에 최적화
|
||||
- **터치 친화적 인터페이스** - 스와이프 제스처 및 터치 내비게이션
|
||||
- **모바일 내비게이션** - 엄지 내비게이션을 위한 하단 탭 바
|
||||
- **적응형 레이아웃** - 접을 수 있는 사이드바 및 스마트 콘텐츠 우선순위
|
||||
- **홈 화면 바로가기 추가** - 홈 화면에 바로가기를 추가하면 앱이 PWA처럼 작동합니다
|
||||
|
||||
<details>
|
||||
<summary>AI 구독을 별도로 결제해야 하나요?</summary>
|
||||
## 아키텍처
|
||||
|
||||
네. CloudCLI는 환경만 제공합니다. Claude, Cursor, Codex, Gemini 구독 비용은 별도로 부과됩니다. CloudCLI Cloud는 관리형 환경을 월 $7부터 제공합니다.
|
||||
### 시스템 개요
|
||||
|
||||
</details>
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Frontend │ │ Backend │ │ Agent │
|
||||
│ (React/Vite) │◄──►│ (Express/WS) │◄──►│ Integration │
|
||||
│ │ │ │ │ │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>CloudCLI UI를 휴대폰에서 사용할 수 있나요?</summary>
|
||||
### 백엔드 (Node.js + Express)
|
||||
- **Express 서버** - 정적 파일 제공이 포함된 RESTful API
|
||||
- **WebSocket 서버** - 채팅 및 프로젝트 새로고침을 위한 통신
|
||||
- **에이전트 통합 (Claude Code / Cursor CLI / Codex)** - 프로세스 생성 및 관리
|
||||
- **파일 시스템 API** - 프로젝트를 위한 파일 브라우저 노출
|
||||
|
||||
네. 셀프 호스트인 경우 기계에서 서버를 실행하고 네트워크의 아무 브라우저에서 `[yourip]:port`를 열면 됩니다. CloudCLI Cloud는 어떤 기기에서도 열 수 있으며, 네이티브 앱도 준비 중입니다.
|
||||
### 프론트엔드 (React + Vite)
|
||||
- **React 18** - hooks를 사용한 현대적 컴포넌트 아키텍처
|
||||
- **CodeMirror** - 구문 강조를 지원하는 고급 코드 편집기
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>UI에서 변경하면 로컬 Claude Code 설정에 영향을 주나요?</summary>
|
||||
|
||||
네, 셀프 호스트에서는 그렇습니다. CloudCLI UI는 Claude Code가 사용하는 동일한 `~/.claude` 설정을 읽고 씁니다. UI에서 추가한 MCP 서버가 Claude Code에 즉시 나타납니다.
|
||||
### 기여하기
|
||||
|
||||
</details>
|
||||
기여를 환영합니다! 커밋 규칙, 개발 워크플로우, 릴리스 프로세스에 대한 자세한 내용은 [Contributing Guide](CONTRIBUTING.md)를 참조해주세요.
|
||||
|
||||
---
|
||||
## 문제 해결
|
||||
|
||||
## 커뮤니티 및 지원
|
||||
### 일반적인 문제 및 해결 방법
|
||||
|
||||
|
||||
#### "Claude 프로젝트를 찾을 수 없음"
|
||||
**문제**: UI에 프로젝트가 없거나 프로젝트 목록이 비어 있음
|
||||
**해결 방법**:
|
||||
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code)가 올바르게 설치되었는지 확인
|
||||
- 초기화를 위해 최소 하나의 프로젝트 디렉토리에서 `claude` 명령 실행
|
||||
- `~/.claude/projects/` 디렉토리가 존재하고 적절한 권한이 있는지 확인
|
||||
|
||||
#### 파일 탐색기 문제
|
||||
**문제**: 파일이 로드되지 않음, 권한 오류, 빈 디렉토리
|
||||
**해결 방법**:
|
||||
- 프로젝트 디렉토리 권한 확인 (터미널에서 `ls -la`)
|
||||
- 프로젝트 경로가 존재하고 접근 가능한지 확인
|
||||
- 자세한 오류 메시지는 서버 콘솔 로그 검토
|
||||
- 프로젝트 범위 밖의 시스템 디렉토리에 접근하지 않는지 확인
|
||||
|
||||
- **[문서](https://cloudcli.ai/docs)** — 설치, 구성, 기능, 문제 해결 안내
|
||||
- **[Discord](https://discord.gg/buxwujPNRE)** — 도움 및 커뮤니티 참여
|
||||
- **[GitHub Issues](https://github.com/siteboon/claudecodeui/issues)** — 버그 보고 및 기능 요청
|
||||
- **[기여 안내](CONTRIBUTING.md)** — 프로젝트 참여 방법
|
||||
|
||||
## 라이선스
|
||||
|
||||
GNU General Public License v3.0 - 자세한 내용은 [LICENSE](LICENSE) 파일 참조.
|
||||
GNU General Public License v3.0 - 자세한 내용은 [LICENSE](LICENSE) 파일을 참조하세요.
|
||||
|
||||
이 프로젝트는 GPL v3 라이선스 하에 오픈 소스로 공개되어 있으며 자유롭게 사용, 수정, 배포할 수 있습니다.
|
||||
이 프로젝트는 오픈 소스이며 GPL v3 라이선스에 따라 자유롭게 사용, 수정 및 배포할 수 있습니다.
|
||||
|
||||
## 감사의 말
|
||||
|
||||
### 사용 기술
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic 공식 CLI
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursor 공식 CLI
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic의 공식 CLI
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursor의 공식 CLI
|
||||
- **[Codex](https://developers.openai.com/codex)** - OpenAI Codex
|
||||
- **[Gemini-CLI](https://geminicli.com/)** - Google Gemini CLI
|
||||
- **[React](https://react.dev/)** - 사용자 인터페이스 라이브러리
|
||||
- **[Vite](https://vitejs.dev/)** - 빠른 빌드 도구 및 개발 서버
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - 유틸리티 우선 CSS 프레임워크
|
||||
- **[CodeMirror](https://codemirror.net/)** - 고급 코드 에디터
|
||||
- **[CodeMirror](https://codemirror.net/)** - 고급 코드 편집기
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(선택사항)* - AI 기반 프로젝트 관리 및 작업 계획
|
||||
|
||||
## 지원 및 커뮤니티
|
||||
|
||||
### 최신 정보 받기
|
||||
- 이 리포지토리에 **Star**를 눌러 지지를 표시하세요
|
||||
- **Watch**로 업데이트 및 새 릴리스를 확인하세요
|
||||
- 프로젝트를 **Follow**하여 공지사항을 받으세요
|
||||
|
||||
### 스폰서
|
||||
- [Siteboon - AI powered website builder](https://siteboon.ai)
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<strong>Claude Code, Cursor, Codex 커뮤니티를 위해 정성껏 제작되었습니다.</strong>
|
||||
<strong>Claude Code, Cursor 및 Codex 커뮤니티를 위해 정성껏 만들었습니다.</strong>
|
||||
</div>
|
||||
|
||||
311
README.md
311
README.md
@@ -1,23 +1,21 @@
|
||||
<div align="center">
|
||||
<img src="public/logo.svg" alt="CloudCLI UI" width="64" height="64">
|
||||
<h1>Cloud CLI (aka Claude Code UI)</h1>
|
||||
<p>A desktop and mobile UI for <a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code</a>, <a href="https://docs.cursor.com/en/cli/overview">Cursor CLI</a>, <a href="https://developers.openai.com/codex">Codex</a>, and <a href="https://geminicli.com/">Gemini-CLI</a>.<br>Use it locally or remotely to view your active projects and sessions from everywhere.</p>
|
||||
</div>
|
||||
|
||||
|
||||
A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [Cursor CLI](https://docs.cursor.com/en/cli/overview), [Codex](https://developers.openai.com/codex), and [Gemini-CLI](https://geminicli.com/). You can use it locally or remotely to view your active projects and sessions and make changes to them from everywhere (mobile or desktop). This gives you a proper interface that works everywhere.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://cloudcli.ai/docs">Documentation</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">Bug Reports</a> · <a href="CONTRIBUTING.md">Contributing</a>
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">Bug Reports</a> · <a href="CONTRIBUTING.md">Contributing</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai"><img src="https://img.shields.io/badge/☁️_CloudCLI_Cloud-Try_Now-0066FF?style=for-the-badge" alt="CloudCLI Cloud"></a>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join our Discord"></a>
|
||||
<br><br>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join%20Community-5865F2?logo=discord&logoColor=white" alt="Join our Discord"></a>
|
||||
<a href="https://trendshift.io/repositories/15586" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15586" alt="siteboon%2Fclaudecodeui | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
<div align="right"><i><b>English</b> · <a href="./README.ru.md">Русский</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ko.md">한국어</a> · <a href="./README.zh-CN.md">中文</a> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
---
|
||||
<div align="right"><i><b>English</b> · <a href="./README.ko.md">한국어</a> · <a href="./README.zh-CN.md">中文</a> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -43,7 +41,7 @@
|
||||
<h3>CLI Selection</h3>
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI Selection" width="400">
|
||||
<br>
|
||||
<em>Select between Claude Code, Gemini, Cursor CLI and Codex</em>
|
||||
<em>Select between Claude Code, Cursor CLI and Codex</em>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -60,9 +58,8 @@
|
||||
- **File Explorer** - Interactive file tree with syntax highlighting and live editing
|
||||
- **Git Explorer** - View, stage and commit your changes. You can also switch branches
|
||||
- **Session Management** - Resume conversations, manage multiple sessions, and track history
|
||||
- **Plugin System** - Extend CloudCLI with custom plugins — add new tabs, backend services, and integrations. [Build your own →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)
|
||||
- **TaskMaster AI Integration** *(Optional)* - Advanced project management with AI-powered task planning, PRD parsing, and workflow automation
|
||||
- **Model Compatibility** - Works with Claude, GPT, and Gemini model families (see [`shared/modelConstants.js`](shared/modelConstants.js) for the full list of supported models)
|
||||
- **Model Compatibility** - Works with Claude Sonnet 4.5, Opus 4.5, GPT-5.2, and Gemini.
|
||||
|
||||
|
||||
## Quick Start
|
||||
@@ -73,63 +70,137 @@ The fastest way to get started — no local setup required. Get a fully managed,
|
||||
|
||||
**[Get started with CloudCLI Cloud](https://cloudcli.ai)**
|
||||
|
||||
### Self-Hosted (Open Source)
|
||||
|
||||
### Self-Hosted (Open source)
|
||||
#### Prerequisites
|
||||
|
||||
#### npm
|
||||
- [Node.js](https://nodejs.org/) v22 or higher
|
||||
- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) installed and configured, and/or
|
||||
- [Cursor CLI](https://docs.cursor.com/en/cli/overview) installed and configured, and/or
|
||||
- [Codex](https://developers.openai.com/codex) installed and configured, and/or
|
||||
- [Gemini-CLI](https://geminicli.com/) installed and configured
|
||||
|
||||
Try CloudCLI UI instantly with **npx** (requires **Node.js** v22+):
|
||||
#### One-click Operation
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli
|
||||
No installation required, direct operation:
|
||||
|
||||
```bash
|
||||
npx @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
Or install **globally** for regular use:
|
||||
The server will start and be accessible at `http://localhost:3001` (or your configured PORT).
|
||||
|
||||
```
|
||||
npm install -g @cloudcli-ai/cloudcli
|
||||
cloudcli
|
||||
**To restart**: Simply run the same `npx` command again after stopping the server
|
||||
### Global Installation (For Regular Use)
|
||||
|
||||
For frequent use, install globally once:
|
||||
|
||||
```bash
|
||||
npm install -g @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
Open `http://localhost:3001` — all your existing sessions are discovered automatically.
|
||||
Then start with a simple command:
|
||||
|
||||
Visit the **[documentation →](https://cloudcli.ai/docs)** for full configuration options, PM2, remote server setup and more.
|
||||
|
||||
#### Docker Sandboxes (Experimental)
|
||||
|
||||
Run agents in isolated sandboxes with hypervisor-level isolation. Starts Claude Code by default. Requires the [`sbx` CLI](https://docs.docker.com/ai/sandboxes/get-started/).
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project
|
||||
```bash
|
||||
claude-code-ui
|
||||
```
|
||||
|
||||
Supports Claude Code, Codex, and Gemini CLI. See the [sandbox docs](docker/) for setup and advanced options.
|
||||
|
||||
**To restart**: Stop with Ctrl+C and run `claude-code-ui` again.
|
||||
|
||||
**To update**:
|
||||
```bash
|
||||
cloudcli update
|
||||
```
|
||||
|
||||
### CLI Usage
|
||||
|
||||
After global installation, you have access to both `claude-code-ui` and `cloudcli` commands:
|
||||
|
||||
| Command / Option | Short | Description |
|
||||
|------------------|-------|-------------|
|
||||
| `cloudcli` or `claude-code-ui` | | Start the server (default) |
|
||||
| `cloudcli start` | | Start the server explicitly |
|
||||
| `cloudcli status` | | Show configuration and data locations |
|
||||
| `cloudcli update` | | Update to the latest version |
|
||||
| `cloudcli help` | | Show help information |
|
||||
| `cloudcli version` | | Show version information |
|
||||
| `--port <port>` | `-p` | Set server port (default: 3001) |
|
||||
| `--database-path <path>` | | Set custom database location |
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
cloudcli # Start with defaults
|
||||
cloudcli -p 8080 # Start on custom port
|
||||
cloudcli status # Show current configuration
|
||||
```
|
||||
|
||||
### Run as Background Service (Recommended for Production)
|
||||
|
||||
For production use, run CloudCLI as a background service using PM2 (Process Manager 2):
|
||||
|
||||
#### Install PM2
|
||||
|
||||
```bash
|
||||
npm install -g pm2
|
||||
```
|
||||
|
||||
#### Start as Background Service
|
||||
|
||||
```bash
|
||||
# Start the server in background
|
||||
pm2 start claude-code-ui --name "claude-code-ui"
|
||||
|
||||
# Or using the shorter alias
|
||||
pm2 start cloudcli --name "claude-code-ui"
|
||||
|
||||
# Start on a custom port
|
||||
pm2 start cloudcli --name "claude-code-ui" -- --port 8080
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
#### Auto-Start on System Boot
|
||||
|
||||
## Which option is right for you?
|
||||
To make CloudCLI UI start automatically when your system boots:
|
||||
|
||||
CloudCLI UI is the open source UI layer that powers CloudCLI Cloud. You can self-host it on your own machine, run it in a Docker sandbox for isolation, or use CloudCLI Cloud for a fully managed environment.
|
||||
```bash
|
||||
# Generate startup script for your platform
|
||||
pm2 startup
|
||||
|
||||
| | Self-Hosted (npm) | Self-Hosted (Docker Sandbox) *(Experimental)* | CloudCLI Cloud |
|
||||
|---|---|---|---|
|
||||
| **Best for** | Local agent sessions on your own machine | Isolated agents with web/mobile IDE | Teams who want agents in the cloud |
|
||||
| **How you access it** | Browser via `[yourip]:port` | Browser via `localhost:port` | Browser, any IDE, REST API, n8n |
|
||||
| **Setup** | `npx @cloudcli-ai/cloudcli` | `npx @cloudcli-ai/cloudcli@latest sandbox ~/project` | No setup required |
|
||||
| **Isolation** | Runs on your host | Hypervisor-level sandbox (microVM) | Full cloud isolation |
|
||||
| **Machine needs to stay on** | Yes | Yes | No |
|
||||
| **Mobile access** | Any browser on your network | Any browser on your network | Any device, native app coming |
|
||||
| **Agents supported** | Claude Code, Cursor CLI, Codex, Gemini CLI | Claude Code, Codex, Gemini CLI | Claude Code, Cursor CLI, Codex, Gemini CLI |
|
||||
| **File explorer and Git** | Yes | Yes | Yes |
|
||||
| **MCP configuration** | Synced with `~/.claude` | Managed via UI | Managed via UI |
|
||||
| **REST API** | Yes | Yes | Yes |
|
||||
| **Team sharing** | No | No | Yes |
|
||||
| **Platform cost** | Free, open source | Free, open source | Starts at $7/month |
|
||||
# Save current process list
|
||||
pm2 save
|
||||
```
|
||||
|
||||
> All options use your own AI subscriptions (Claude, Cursor, etc.) — CloudCLI provides the environment, not the AI.
|
||||
|
||||
---
|
||||
### Local Development Installation
|
||||
|
||||
1. **Clone the repository:**
|
||||
```bash
|
||||
git clone https://github.com/siteboon/claudecodeui.git
|
||||
cd claudecodeui
|
||||
```
|
||||
|
||||
2. **Install dependencies:**
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. **Configure environment:**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env with your preferred settings
|
||||
```
|
||||
|
||||
4. **Start the application:**
|
||||
```bash
|
||||
# Development mode (with hot reload)
|
||||
npm run dev
|
||||
|
||||
```
|
||||
The application will start at the port you specified in your .env
|
||||
|
||||
5. **Open your browser:**
|
||||
- Development: `http://localhost:3001`
|
||||
|
||||
## Security & Tools Configuration
|
||||
|
||||
@@ -140,8 +211,8 @@ CloudCLI UI is the open source UI layer that powers CloudCLI Cloud. You can self
|
||||
To use Claude Code's full functionality, you'll need to manually enable tools:
|
||||
|
||||
1. **Open Tools Settings** - Click the gear icon in the sidebar
|
||||
2. **Enable Selectively** - Turn on only the tools you need
|
||||
3. **Apply Settings** - Your preferences are saved locally
|
||||
3. **Enable Selectively** - Turn on only the tools you need
|
||||
4. **Apply Settings** - Your preferences are saved locally
|
||||
|
||||
<div align="center">
|
||||
|
||||
@@ -152,82 +223,120 @@ To use Claude Code's full functionality, you'll need to manually enable tools:
|
||||
|
||||
**Recommended approach**: Start with basic tools enabled and add more as needed. You can always adjust these settings later.
|
||||
|
||||
---
|
||||
## TaskMaster AI Integration *(Optional)*
|
||||
|
||||
## Plugins
|
||||
CloudCLI UI supports **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** (aka claude-task-master) integration for advanced project management and AI-powered task planning.
|
||||
|
||||
CloudCLI has a plugin system that lets you add custom tabs with their own frontend UI and optional Node.js backend. Install plugins from git repos directly in **Settings > Plugins**, or build your own.
|
||||
It provides
|
||||
- AI-powered task generation from PRDs (Product Requirements Documents)
|
||||
- Smart task breakdown and dependency management
|
||||
- Visual task boards and progress tracking
|
||||
|
||||
### Available Plugins
|
||||
**Setup & Documentation**: Visit the [TaskMaster AI GitHub repository](https://github.com/eyaltoledano/claude-task-master) for installation instructions, configuration guides, and usage examples.
|
||||
After installing it you should be able to enable it from the Settings
|
||||
|
||||
| Plugin | Description |
|
||||
|---|---|
|
||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Shows file counts, lines of code, file-type breakdown, largest files, and recently modified files for your current project |
|
||||
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Full xterm.js terminal with multi-tab support|
|
||||
|
||||
### Build Your Own
|
||||
## Usage Guide
|
||||
|
||||
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — fork this repo to create your own plugin. It includes a working example with frontend rendering, live context updates, and RPC communication to a backend server.
|
||||
### Core Features
|
||||
|
||||
**[Plugin Documentation →](https://cloudcli.ai/docs/plugin-overview)** — full guide to the plugin API, manifest format, security model, and more.
|
||||
#### Project Management
|
||||
It automatically discovers Claude Code, Cursor or Codex sessions when available and groups them together into projects
|
||||
session counts
|
||||
- **Project Actions** - Rename, delete, and organize projects
|
||||
- **Smart Navigation** - Quick access to recent projects and sessions
|
||||
- **MCP support** - Add your own MCP servers through the UI
|
||||
|
||||
---
|
||||
## FAQ
|
||||
#### Chat Interface
|
||||
- **Use responsive chat or Claude Code/Cursor CLI/Codex CLI** - You can either use the adapted chat interface or use the shell button to connect to your selected CLI.
|
||||
- **Real-time Communication** - Stream responses from your selected CLI (Claude Code/Cursor/Codex) with WebSocket connection
|
||||
- **Session Management** - Resume previous conversations or start fresh sessions
|
||||
- **Message History** - Complete conversation history with timestamps and metadata
|
||||
- **Multi-format Support** - Text, code blocks, and file references
|
||||
|
||||
<details>
|
||||
<summary>How is this different from Claude Code Remote Control?</summary>
|
||||
#### File Explorer & Editor
|
||||
- **Interactive File Tree** - Browse project structure with expand/collapse navigation
|
||||
- **Live File Editing** - Read, modify, and save files directly in the interface
|
||||
- **Syntax Highlighting** - Support for multiple programming languages
|
||||
- **File Operations** - Create, rename, delete files and directories
|
||||
|
||||
Claude Code Remote Control lets you send messages to a session already running in your local terminal. Your machine has to stay on, your terminal has to stay open, and sessions time out after roughly 10 minutes without a network connection.
|
||||
#### Git Explorer
|
||||
|
||||
CloudCLI UI and CloudCLI Cloud extend Claude Code rather than sit alongside it — your MCP servers, permissions, settings, and sessions are the exact same ones Claude Code uses natively. Nothing is duplicated or managed separately.
|
||||
|
||||
Here's what that means in practice:
|
||||
#### TaskMaster AI Integration *(Optional)*
|
||||
- **Visual Task Board** - Kanban-style interface for managing development tasks
|
||||
- **PRD Parser** - Create Product Requirements Documents and parse them into structured tasks
|
||||
- **Progress Tracking** - Real-time status updates and completion tracking
|
||||
|
||||
- **All your sessions, not just one** — CloudCLI UI auto-discovers every session from your `~/.claude` folder. Remote Control only exposes the single active session to make it available in the Claude mobile app.
|
||||
- **Your settings are your settings** — MCP servers, tool permissions, and project config you change in CloudCLI UI are written directly to your Claude Code config and take effect immediately, and vice versa.
|
||||
- **Works with more agents** — Claude Code, Cursor CLI, Codex, and Gemini CLI, not just Claude Code.
|
||||
- **Full UI, not just a chat window** — file explorer, Git integration, MCP management, and a shell terminal are all built in.
|
||||
- **CloudCLI Cloud runs in the cloud** — close your laptop, the agent keeps running. No terminal to babysit, no machine to keep awake.
|
||||
#### Session Management
|
||||
- **Session Persistence** - All conversations automatically saved
|
||||
- **Session Organization** - Group sessions by project and timestamp
|
||||
- **Session Actions** - Rename, delete, and export conversation history
|
||||
- **Cross-device Sync** - Access sessions from any device
|
||||
|
||||
</details>
|
||||
### Mobile App
|
||||
- **Responsive Design** - Optimized for all screen sizes
|
||||
- **Touch-friendly Interface** - Swipe gestures and touch navigation
|
||||
- **Mobile Navigation** - Bottom tab bar for easy thumb navigation
|
||||
- **Adaptive Layout** - Collapsible sidebar and smart content prioritization
|
||||
- **Add shortcut to Home Screen** - Add a shortcut to your home screen and the app will behave like a PWA
|
||||
|
||||
<details>
|
||||
<summary>Do I need to pay for an AI subscription separately?</summary>
|
||||
## Architecture
|
||||
|
||||
Yes. CloudCLI provides the environment, not the AI. You bring your own Claude, Cursor, Codex, or Gemini subscription. CloudCLI Cloud starts at $7/month for the hosted environment on top of that.
|
||||
### System Overview
|
||||
|
||||
</details>
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Frontend │ │ Backend │ │ Agent │
|
||||
│ (React/Vite) │◄──►│ (Express/WS) │◄──►│ Integration │
|
||||
│ │ │ │ │ │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Can I use CloudCLI UI on my phone?</summary>
|
||||
### Backend (Node.js + Express)
|
||||
- **Express Server** - RESTful API with static file serving
|
||||
- **WebSocket Server** - Communication for chats and project refresh
|
||||
- **Agent Integration (Claude Code / Cursor CLI / Codex / Gemini CLI)** - Process spawning and management
|
||||
- **File System API** - Exposing file browser for projects
|
||||
|
||||
Yes. For self-hosted, run the server on your machine and open `[yourip]:port` in any browser on your network. For CloudCLI Cloud, open it from any device — no VPN, no port forwarding, no setup. A native app is also in the works.
|
||||
### Frontend (React + Vite)
|
||||
- **React 18** - Modern component architecture with hooks
|
||||
- **CodeMirror** - Advanced code editor with syntax highlighting
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Will changes I make in the UI affect my local Claude Code setup?</summary>
|
||||
|
||||
Yes, for self-hosted. CloudCLI UI reads from and writes to the same `~/.claude` config that Claude Code uses natively. MCP servers you add via the UI show up in Claude Code immediately and vice versa.
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
### Contributing
|
||||
|
||||
## Community & Support
|
||||
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details on commit conventions, development workflow, and release process.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues & Solutions
|
||||
|
||||
|
||||
#### "No Claude projects found"
|
||||
**Problem**: The UI shows no projects or empty project list
|
||||
**Solutions**:
|
||||
- Ensure [Claude Code](https://docs.anthropic.com/en/docs/claude-code) is properly installed
|
||||
- Run `claude` command in at least one project directory to initialize
|
||||
- Verify `~/.claude/projects/` directory exists and has proper permissions
|
||||
|
||||
#### File Explorer Issues
|
||||
**Problem**: Files not loading, permission errors, empty directories
|
||||
**Solutions**:
|
||||
- Check project directory permissions (`ls -la` in terminal)
|
||||
- Verify the project path exists and is accessible
|
||||
- Review server console logs for detailed error messages
|
||||
- Ensure you're not trying to access system directories outside project scope
|
||||
|
||||
- **[Documentation](https://cloudcli.ai/docs)** — installation, configuration, features, and troubleshooting
|
||||
- **[Discord](https://discord.gg/buxwujPNRE)** — get help and connect with other users
|
||||
- **[GitHub Issues](https://github.com/siteboon/claudecodeui/issues)** — bug reports and feature requests
|
||||
- **[Contributing Guide](CONTRIBUTING.md)** — how to contribute to the project
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later) — see [LICENSE](LICENSE) for the full text, including additional terms under Section 7.
|
||||
GNU General Public License v3.0 - see [LICENSE](LICENSE) file for details.
|
||||
|
||||
This project is open source and free to use, modify, and distribute under the AGPL-3.0-or-later license. If you modify this software and run it as a network service, you must make your modified source code available to users of that service.
|
||||
|
||||
CloudCLI UI - (https://cloudcli.ai).
|
||||
This project is open source and free to use, modify, and distribute under the GPL v3 license.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
@@ -242,6 +351,14 @@ CloudCLI UI - (https://cloudcli.ai).
|
||||
- **[CodeMirror](https://codemirror.net/)** - Advanced code editor
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(Optional)* - AI-powered project management and task planning
|
||||
|
||||
## Support & Community
|
||||
|
||||
### Stay Updated
|
||||
- **[Join our Discord](https://discord.gg/buxwujPNRE)** - Get help, share feedback, and connect with the community
|
||||
- **[CloudCLI Cloud](https://cloudcli.ai)** - Try the hosted cloud version
|
||||
- **Star** this repository to show support
|
||||
- **Watch** for updates and new releases
|
||||
- **Follow** the project for announcements
|
||||
|
||||
### Sponsors
|
||||
- [Siteboon - AI powered website builder](https://siteboon.ai)
|
||||
|
||||
250
README.ru.md
250
README.ru.md
@@ -1,250 +0,0 @@
|
||||
<div align="center">
|
||||
<img src="public/logo.svg" alt="CloudCLI UI" width="64" height="64">
|
||||
<h1>Cloud CLI (aka Claude Code UI)</h1>
|
||||
<p>Десктопный и мобильный UI для <a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code</a>, <a href="https://docs.cursor.com/en/cli/overview">Cursor CLI</a>, <a href="https://developers.openai.com/codex">Codex</a> и <a href="https://geminicli.com/">Gemini-CLI</a>.<br>Используйте локально или удалённо, чтобы просматривать активные проекты и сессии отовсюду.</p>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://cloudcli.ai/docs">Документация</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">Сообщить об ошибке</a> · <a href="CONTRIBUTING.md">Участие в разработке</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai"><img src="https://img.shields.io/badge/☁️_CloudCLI_Cloud-Try_Now-0066FF?style=for-the-badge" alt="CloudCLI Cloud"></a>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join our Discord"></a>
|
||||
<br><br>
|
||||
<a href="https://trendshift.io/repositories/15586" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15586" alt="siteboon%2Fclaudecodeui | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
<div align="right"><i><a href="./README.md">English</a> · <b>Русский</b> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ko.md">한국어</a> · <a href="./README.zh-CN.md">中文</a> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
---
|
||||
|
||||
## Скриншоты
|
||||
|
||||
<div align="center">
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h3>Версия для десктопа</h3>
|
||||
<img src="public/screenshots/desktop-main.png" alt="Desktop Interface" width="400">
|
||||
<br>
|
||||
<em>Основной интерфейс с обзором проекта и чатом</em>
|
||||
</td>
|
||||
<td align="center">
|
||||
<h3>Мобильный режим</h3>
|
||||
<img src="public/screenshots/mobile-chat.png" alt="Mobile Interface" width="250">
|
||||
<br>
|
||||
<em>Адаптивный мобильный дизайн с сенсорной навигацией</em>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" colspan="2">
|
||||
<h3>Выбор CLI</h3>
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI Selection" width="400">
|
||||
<br>
|
||||
<em>Выбирайте между Claude Code, Gemini, Cursor CLI и Codex</em>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## Возможности
|
||||
|
||||
- **Адаптивный дизайн** - одинаково хорошо работает на десктопе, планшете и телефоне, поэтому можно пользоваться агентами и с мобильных устройств
|
||||
- **Интерактивный чат-интерфейс** - встроенный чат для бесшовного общения с агентами
|
||||
- **Интегрированный shell-терминал** - прямой доступ к CLI агентов через встроенную оболочку
|
||||
- **Проводник файлов** - интерактивное дерево файлов с подсветкой синтаксиса и редактированием в реальном времени
|
||||
- **Git Explorer** - просмотр, stage и commit изменений. Также можно переключать ветки
|
||||
- **Управление сессиями** - возобновляйте диалоги, управляйте несколькими сессиями и отслеживайте историю
|
||||
- **Система плагинов** - расширяйте CloudCLI кастомными плагинами — добавляйте новые вкладки, бэкенд-сервисы и интеграции. [Создать свой →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)
|
||||
- **Интеграция с TaskMaster AI** *(опционально)* - продвинутое управление проектами с планированием задач на базе AI, разбором PRD и автоматизацией workflow
|
||||
- **Совместимость с моделями** - работает с семействами моделей Claude, GPT и Gemini (см. [`shared/modelConstants.js`](shared/modelConstants.js) для полного списка поддерживаемых моделей)
|
||||
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### CloudCLI Cloud (рекомендуется)
|
||||
|
||||
Самый быстрый способ начать — локальная настройка не требуется. Получите полностью управляемую контейнеризированную среду разработки с доступом из веба, мобильного приложения, API или вашей любимой IDE.
|
||||
|
||||
**[Начать с CloudCLI Cloud](https://cloudcli.ai)**
|
||||
|
||||
|
||||
### Self-Hosted (Open source)
|
||||
|
||||
#### npm
|
||||
|
||||
Попробовать CloudCLI UI можно сразу через **npx** (требуется **Node.js** v22+):
|
||||
|
||||
```bash
|
||||
npx @cloudcli-ai/cloudcli
|
||||
```
|
||||
|
||||
Или установить **глобально** для регулярного использования:
|
||||
|
||||
```bash
|
||||
npm install -g @cloudcli-ai/cloudcli
|
||||
cloudcli
|
||||
```
|
||||
|
||||
Откройте `http://localhost:3001` — все ваши существующие сессии будут обнаружены автоматически.
|
||||
|
||||
Посетите **[документацию →](https://cloudcli.ai/docs)**, чтобы узнать про дополнительные варианты конфигурации, PM2, настройку удалённого сервера и многое другое.
|
||||
|
||||
#### Docker Sandboxes (Экспериментально)
|
||||
|
||||
Запускайте агентов в изолированных песочницах с гипервизорной изоляцией. По умолчанию запускается Claude Code. Требуется [`sbx` CLI](https://docs.docker.com/ai/sandboxes/get-started/).
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project
|
||||
```
|
||||
|
||||
Поддерживаются Claude Code, Codex и Gemini CLI. Подробнее в [документации sandbox](docker/).
|
||||
|
||||
---
|
||||
|
||||
## Какой вариант подходит вам?
|
||||
|
||||
CloudCLI UI — это open source UI-слой, на котором построен CloudCLI Cloud. Вы можете развернуть его на своей машине или использовать CloudCLI Cloud, который добавляет полностью управляемую облачную среду, командные функции и более глубокие интеграции.
|
||||
|
||||
| | CloudCLI UI (Self-hosted) | CloudCLI Cloud |
|
||||
|---|---|---|
|
||||
| **Лучше всего подходит для** | Разработчиков, которым нужен полноценный UI для локальных агентских сессий на своей машине | Команд и разработчиков, которым нужны агенты в облаке с доступом откуда угодно |
|
||||
| **Как вы получаете доступ** | Браузер через `[yourip]:port` | Браузер, любая IDE, REST API, n8n |
|
||||
| **Настройка** | `npx @cloudcli-ai/cloudcli` | Настройка не требуется |
|
||||
| **Машина должна оставаться включённой** | Да | Нет |
|
||||
| **Доступ с мобильных устройств** | Любой браузер в вашей сети | Любое устройство, нативное приложение в разработке |
|
||||
| **Доступные сессии** | Все сессии автоматически обнаруживаются из `~/.claude` | Все сессии внутри вашей облачной среды |
|
||||
| **Поддерживаемые агенты** | Claude Code, Cursor CLI, Codex, Gemini CLI | Claude Code, Cursor CLI, Codex, Gemini CLI |
|
||||
| **Проводник файлов и Git** | Да, встроены в UI | Да, встроены в UI |
|
||||
| **Конфигурация MCP** | Управляется через UI, синхронизируется с вашим локальным конфигом `~/.claude` | Управляется через UI |
|
||||
| **Доступ из IDE** | Ваша локальная IDE | Любая IDE, подключенная к вашей облачной среде |
|
||||
| **REST API** | Да | Да |
|
||||
| **n8n node** | Нет | Да |
|
||||
| **Совместная работа** | Нет | Да |
|
||||
| **Стоимость платформы** | Бесплатно, open source | От $7/месяц |
|
||||
|
||||
> В обоих вариантах используются ваши собственные AI-подписки (Claude, Cursor и т.д.) — CloudCLI предоставляет среду, а не сам AI.
|
||||
|
||||
---
|
||||
|
||||
## Безопасность и конфигурация инструментов
|
||||
|
||||
**🔒 Важное примечание**: все инструменты Claude Code **по умолчанию отключены**. Это предотвращает автоматический запуск потенциально опасных операций.
|
||||
|
||||
### Включение инструментов
|
||||
|
||||
Чтобы использовать всю функциональность Claude Code, вам нужно вручную включить инструменты:
|
||||
|
||||
1. **Откройте настройки инструментов** - нажмите на иконку шестерёнки в боковой панели
|
||||
2. **Включайте выборочно** - активируйте только те инструменты, которые вам нужны
|
||||
3. **Примените настройки** - ваши предпочтения сохраняются локально
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
*Интерфейс настройки инструментов — включайте только то, что вам нужно*
|
||||
|
||||
</div>
|
||||
|
||||
**Рекомендуемый подход**: начните с базовых инструментов и добавляйте остальные по мере необходимости. Эти настройки всегда можно изменить позже.
|
||||
|
||||
---
|
||||
|
||||
## Плагины
|
||||
|
||||
У CloudCLI есть система плагинов, которая позволяет добавлять кастомные вкладки со своим frontend UI и (опционально) Node.js бэкендом. Устанавливайте плагины напрямую из git-репозиториев в **Settings > Plugins** или создавайте свои.
|
||||
|
||||
### Доступные плагины
|
||||
|
||||
| Плагин | Описание |
|
||||
|---|---|
|
||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Показывает количество файлов, строки кода, разбивку по типам файлов, самые большие файлы и недавно изменённые файлы для текущего проекта |
|
||||
|
||||
### Создать свой
|
||||
|
||||
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — сделайте форк этого репозитория, чтобы создать свой плагин. В шаблоне есть рабочий пример с рендерингом на фронтенде, live-обновлением контекста и RPC-коммуникацией с бэкенд-сервером.
|
||||
|
||||
**[Plugin Documentation →](https://cloudcli.ai/docs/plugin-overview)** — полный гайд по plugin API, формату манифеста, модели безопасности и другому.
|
||||
|
||||
---
|
||||
## FAQ
|
||||
|
||||
<details>
|
||||
<summary>Чем это отличается от Claude Code Remote Control?</summary>
|
||||
|
||||
Claude Code Remote Control позволяет отправлять сообщения в сессию, которая уже запущена в вашем локальном терминале. Ваша машина должна оставаться включённой, терминал — открытым, а сессии завершаются примерно через 10 минут без сетевого соединения.
|
||||
|
||||
CloudCLI UI и CloudCLI Cloud расширяют Claude Code, а не работают рядом с ним — ваши MCP-серверы, разрешения, настройки и сессии остаются теми же самыми, что и в нативном Claude Code. Ничего не дублируется и не управляется отдельно.
|
||||
|
||||
Вот что это означает на практике:
|
||||
|
||||
- **Все ваши сессии, а не одна** — CloudCLI UI автоматически находит каждую сессию из папки `~/.claude`. Remote Control предоставляет только одну активную сессию, чтобы сделать её доступной в мобильном приложении Claude.
|
||||
- **Ваши настройки — это ваши настройки** — MCP-серверы, права инструментов и конфигурация проекта, изменённые в CloudCLI UI, записываются напрямую в конфиг Claude Code и вступают в силу сразу же, и наоборот.
|
||||
- **Работает с большим числом агентов** — Claude Code, Cursor CLI, Codex и Gemini CLI, а не только Claude Code.
|
||||
- **Полноценный UI, а не просто окно чата** — проводник файлов, Git-интеграция, управление MCP и shell-терминал — всё встроено.
|
||||
- **CloudCLI Cloud работает в облаке** — закройте ноутбук, и агент продолжит работать. Не нужно следить за терминалом и держать машину постоянно активной.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Нужно ли отдельно платить за AI-подписку?</summary>
|
||||
|
||||
Да. CloudCLI предоставляет среду, а не сам AI. Вы приносите свою подписку Claude, Cursor, Codex или Gemini. CloudCLI Cloud начинается от $7/месяц за хостируемую среду поверх этого.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Можно ли пользоваться CloudCLI UI с телефона?</summary>
|
||||
|
||||
Да. Для self-hosted запустите сервер на своей машине и откройте `[yourip]:port` в любом браузере в вашей сети. Для CloudCLI Cloud откройте сервис с любого устройства — без VPN, проброса портов и дополнительной настройки. Нативное приложение тоже в разработке.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Повлияют ли изменения, сделанные в UI, на мой локальный Claude Code?</summary>
|
||||
|
||||
Да, в self-hosted режиме. CloudCLI UI читает и записывает тот же конфиг `~/.claude`, который Claude Code использует нативно. MCP-серверы, добавленные через UI, сразу появляются в Claude Code, и наоборот.
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Сообщество и поддержка
|
||||
|
||||
- **[Документация](https://cloudcli.ai/docs)** — установка, настройка, возможности и устранение неполадок
|
||||
- **[Discord](https://discord.gg/buxwujPNRE)** — помощь и общение с другими пользователями
|
||||
- **[GitHub Issues](https://github.com/siteboon/claudecodeui/issues)** — сообщения об ошибках и запросы новых функций
|
||||
- **[Руководство для контрибьюторов](CONTRIBUTING.md)** — как участвовать в развитии проекта
|
||||
|
||||
## Лицензия
|
||||
|
||||
GNU General Public License v3.0 - подробности в файле [LICENSE](LICENSE).
|
||||
|
||||
Этот проект open source и бесплатен для использования, модификации и распространения в рамках лицензии GPL v3.
|
||||
|
||||
## Благодарности
|
||||
|
||||
### Используется
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - официальный CLI от Anthropic
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - официальный CLI от Cursor
|
||||
- **[Codex](https://developers.openai.com/codex)** - OpenAI Codex
|
||||
- **[Gemini-CLI](https://geminicli.com/)** - Google Gemini CLI
|
||||
- **[React](https://react.dev/)** - библиотека пользовательских интерфейсов
|
||||
- **[Vite](https://vitejs.dev/)** - быстрый инструмент сборки и dev-сервер
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - utility-first CSS framework
|
||||
- **[CodeMirror](https://codemirror.net/)** - продвинутый редактор кода
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(опционально)* - AI-управление проектами и планирование задач
|
||||
|
||||
|
||||
### Спонсоры
|
||||
- [Siteboon - AI powered website builder](https://siteboon.ai)
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<strong>Сделано с заботой для сообщества Claude Code, Cursor и Codex.</strong>
|
||||
</div>
|
||||
367
README.zh-CN.md
367
README.zh-CN.md
@@ -1,23 +1,12 @@
|
||||
<div align="center">
|
||||
<img src="public/logo.svg" alt="CloudCLI UI" width="64" height="64">
|
||||
<h1>Cloud CLI(又名 Claude Code UI)</h1>
|
||||
<p><a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code</a>、<a href="https://docs.cursor.com/en/cli/overview">Cursor CLI</a>、<a href="https://developers.openai.com/codex">Codex</a> 和 <a href="https://geminicli.com/">Gemini-CLI</a> 的桌面和移动端 UI。可在本地或远程使用,从任何地方查看激活的项目与会话。</p>
|
||||
<img src="public/logo.svg" alt="Claude Code UI" width="64" height="64">
|
||||
<h1>Cloud CLI (又名 Claude Code UI)</h1>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://cloudcli.ai/docs">文档</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">Bug 报告</a> · <a href="CONTRIBUTING.md">贡献指南</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai"><img src="https://img.shields.io/badge/☁️_CloudCLI_Cloud-Try_Now-0066FF?style=for-the-badge" alt="CloudCLI Cloud"></a>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="加入 Discord 社区"></a>
|
||||
<br><br>
|
||||
<a href="https://trendshift.io/repositories/15586" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15586" alt="siteboon%2Fclaudecodeui | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
[Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[Cursor CLI](https://docs.cursor.com/en/cli/overview) 和 [Codex](https://developers.openai.com/codex) 的桌面端和移动端界面。您可以在本地或远程使用它来查看 Claude Code、Cursor 或 Codex 中的活跃项目和会话,并从任何地方(移动端或桌面端)对它们进行修改。这为您提供了一个在任何地方都能正常使用的合适界面。
|
||||
|
||||
<div align="right"><i><a href="./README.md">English</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ko.md">한국어</a> · <b>中文</b> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
---
|
||||
<div align="right"><i><a href="./README.md">English</a> · <a href="./README.ko.md">한국어</a> · <a href="./README.ja.md">日本語</a></i></div>
|
||||
|
||||
## 截图
|
||||
|
||||
@@ -27,211 +16,327 @@
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h3>桌面视图</h3>
|
||||
<img src="public/screenshots/desktop-main.png" alt="桌面界面" width="400">
|
||||
<img src="public/screenshots/desktop-main.png" alt="Desktop Interface" width="400">
|
||||
<br>
|
||||
<em>显示项目概览和聊天的主界面</em>
|
||||
<em>显示项目概览和聊天界面的主界面</em>
|
||||
</td>
|
||||
<td align="center">
|
||||
<h3>移动体验</h3>
|
||||
<img src="public/screenshots/mobile-chat.png" alt="移动界面" width="250">
|
||||
<h3>移动端体验</h3>
|
||||
<img src="public/screenshots/mobile-chat.png" alt="Mobile Interface" width="250">
|
||||
<br>
|
||||
<em>具有触控导航的响应式移动设计</em>
|
||||
<em>具有触摸导航的响应式移动设计</em>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" colspan="2">
|
||||
<h3>CLI 选择</h3>
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI 选择" width="400">
|
||||
<img src="public/screenshots/cli-selection.png" alt="CLI Selection" width="400">
|
||||
<br>
|
||||
<em>在 Claude Code、Gemini、Cursor CLI 与 Codex 之间进行选择</em>
|
||||
<em>在 Claude Code、Cursor CLI 和 Codex 之间选择</em>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## 功能
|
||||
## 功能特性
|
||||
|
||||
- **响应式设计** - 在桌面、平板和移动设备上无缝运行,让您随时随地使用 Agents
|
||||
- **交互聊天界面** - 内置聊天 UI,轻松与 Agents 交流
|
||||
- **集成 Shell 终端** - 通过内置 shell 功能直接访问 Agents CLI
|
||||
- **文件浏览器** - 交互式文件树,支持语法高亮与实时编辑
|
||||
- **Git 浏览器** - 查看、暂存并提交更改,还可切换分支
|
||||
- **响应式设计** - 在桌面、平板和移动设备上无缝运行,您也可以在移动端使用 Claude Code、Cursor 或 Codex
|
||||
- **交互式聊天界面** - 内置聊天界面,与 Claude Code、Cursor 或 Codex 无缝通信
|
||||
- **集成 Shell 终端** - 通过内置 shell 功能直接访问 Claude Code、Cursor CLI 或 Codex
|
||||
- **文件浏览器** - 交互式文件树,支持语法高亮和实时编辑
|
||||
- **Git 浏览器** - 查看、暂存和提交您的更改。您还可以切换分支
|
||||
- **会话管理** - 恢复对话、管理多个会话并跟踪历史记录
|
||||
- **插件系统** - 通过自定义选项卡、后端服务与集成扩展 CloudCLI。 [开始构建 →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)
|
||||
- **TaskMaster AI 集成** *(可选)* - 结合 AI 任务规划、PRD 分析与工作流自动化,实现高级项目管理
|
||||
- **模型兼容性** - 支持 Claude、GPT、Gemini 模型家族(完整支持列表见 [`shared/modelConstants.js`](shared/modelConstants.js))
|
||||
- **TaskMaster AI 集成** *(可选)* - 通过 AI 驱动的任务规划、PRD 解析和工作流自动化实现高级项目管理
|
||||
- **模型兼容性** - 适用于 Claude Sonnet 4.5、Opus 4.5 和 GPT-5.2
|
||||
|
||||
|
||||
## 快速开始
|
||||
|
||||
### CloudCLI Cloud(推荐)
|
||||
### 前置要求
|
||||
|
||||
无需本地设置即可快速启动。提供可通过网络浏览器、移动应用、API 或喜欢的 IDE 访问的完全集装式托管开发环境。
|
||||
- [Node.js](https://nodejs.org/) v22 或更高版本
|
||||
- 已安装并配置 [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code),和/或
|
||||
- 已安装并配置 [Cursor CLI](https://docs.cursor.com/en/cli/overview),和/或
|
||||
- 已安装并配置 [Codex](https://developers.openai.com/codex)
|
||||
|
||||
**[立即开始 CloudCLI Cloud](https://cloudcli.ai)**
|
||||
### 一键操作(推荐)
|
||||
|
||||
### 自托管(开源)
|
||||
|
||||
#### npm
|
||||
|
||||
启动 CloudCLI UI,只需一行 `npx`(需要 Node.js v22+):
|
||||
无需安装,直接运行:
|
||||
|
||||
```bash
|
||||
npx @cloudcli-ai/cloudcli
|
||||
npx @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
或进行全局安装,便于日常使用:
|
||||
服务器将启动并可通过 `http://localhost:3001`(或您配置的 PORT)访问。
|
||||
|
||||
**重启**: 停止服务器后只需再次运行相同的 `npx` 命令
|
||||
|
||||
### 全局安装(供常规使用)
|
||||
|
||||
为了频繁使用,一次性全局安装:
|
||||
|
||||
```bash
|
||||
npm install -g @cloudcli-ai/cloudcli
|
||||
cloudcli
|
||||
npm install -g @siteboon/claude-code-ui
|
||||
```
|
||||
|
||||
打开 `http://localhost:3001`,系统会自动发现所有现有会话。
|
||||
然后使用简单命令启动:
|
||||
|
||||
更多配置选项、PM2、远程服务器设置等,请参阅 **[文档 →](https://cloudcli.ai/docs)**。
|
||||
|
||||
#### Docker Sandboxes(实验性)
|
||||
|
||||
在隔离的沙箱中运行代理,具有虚拟机管理程序级别的隔离。默认启动 Claude Code。需要 [`sbx` CLI](https://docs.docker.com/ai/sandboxes/get-started/)。
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project
|
||||
```bash
|
||||
claude-code-ui
|
||||
```
|
||||
|
||||
支持 Claude Code、Codex 和 Gemini CLI。详情请参阅 [沙箱文档](docker/)。
|
||||
|
||||
---
|
||||
**重启**: 使用 Ctrl+C 停止,然后再次运行 `claude-code-ui`。
|
||||
|
||||
## 哪个选项更适合你?
|
||||
**更新**:
|
||||
```bash
|
||||
cloudcli update
|
||||
```
|
||||
|
||||
CloudCLI UI 是 CloudCLI Cloud 的开源 UI 层。你可以在本地机器上自托管它,也可以使用提供团队功能与深入集成的 CloudCLI Cloud。
|
||||
### CLI 使用方法
|
||||
|
||||
| | CloudCLI UI(自托管) | CloudCLI Cloud |
|
||||
|---|---|---|
|
||||
| **适合对象** | 需要为本地代理会话提供完整 UI 的开发者 | 需要部署在云端,随时从任何地方访问代理的团队与开发者 |
|
||||
| **访问方式** | 通过 `[yourip]:port` 在浏览器中访问 | 浏览器、任意 IDE、REST API、n8n |
|
||||
| **设置** | `npx @cloudcli-ai/cloudcli` | 无需设置 |
|
||||
| **机器需保持开机吗** | 是 | 否 |
|
||||
| **移动端访问** | 网络内任意浏览器 | 任意设备(原生应用即将推出) |
|
||||
| **可用会话** | 自动发现 `~/.claude` 中的所有会话 | 云端环境内的会话 |
|
||||
| **支持的 Agents** | Claude Code、Cursor CLI、Codex、Gemini CLI | Claude Code、Cursor CLI、Codex、Gemini CLI |
|
||||
| **文件浏览与 Git** | 内置于 UI | 内置于 UI |
|
||||
| **MCP 配置** | UI 管理,与本地 `~/.claude` 配置同步 | UI 管理 |
|
||||
| **IDE 访问** | 本地 IDE | 任何连接到云环境的 IDE |
|
||||
| **REST API** | 是 | 是 |
|
||||
| **n8n 节点** | 否 | 是 |
|
||||
| **团队共享** | 否 | 是 |
|
||||
| **平台费用** | 免费开源 | 起价 $7/月 |
|
||||
全局安装后,您可以访问 `claude-code-ui` 和 `cloudcli` 命令:
|
||||
|
||||
> 两种方式都使用你自己的 AI 订阅(Claude、Cursor 等)— CloudCLI 提供环境,而非 AI。
|
||||
| 命令 / 选项 | 简写 | 描述 |
|
||||
|------------------|-------|-------------|
|
||||
| `cloudcli` 或 `claude-code-ui` | | 启动服务器(默认) |
|
||||
| `cloudcli start` | | 显式启动服务器 |
|
||||
| `cloudcli status` | | 显示配置和数据位置 |
|
||||
| `cloudcli update` | | 更新到最新版本 |
|
||||
| `cloudcli help` | | 显示帮助信息 |
|
||||
| `cloudcli version` | | 显示版本信息 |
|
||||
| `--port <port>` | `-p` | 设置服务器端口(默认: 3001) |
|
||||
| `--database-path <path>` | | 设置自定义数据库位置 |
|
||||
|
||||
---
|
||||
**示例:**
|
||||
```bash
|
||||
cloudcli # 使用默认设置启动
|
||||
cloudcli -p 8080 # 在自定义端口启动
|
||||
cloudcli status # 显示当前配置
|
||||
```
|
||||
|
||||
### 作为后台服务运行(推荐用于生产环境)
|
||||
|
||||
在生产环境中,使用 PM2(Process Manager 2)将 Claude Code UI 作为后台服务运行:
|
||||
|
||||
#### 安装 PM2
|
||||
|
||||
```bash
|
||||
npm install -g pm2
|
||||
```
|
||||
|
||||
#### 作为后台服务启动
|
||||
|
||||
```bash
|
||||
# 在后台启动服务器
|
||||
pm2 start claude-code-ui --name "claude-code-ui"
|
||||
|
||||
# 或使用更短的别名
|
||||
pm2 start cloudcli --name "claude-code-ui"
|
||||
|
||||
# 在自定义端口启动
|
||||
pm2 start cloudcli --name "claude-code-ui" -- --port 8080
|
||||
```
|
||||
|
||||
|
||||
#### 系统启动时自动启动
|
||||
|
||||
要使 Claude Code UI 在系统启动时自动启动:
|
||||
|
||||
```bash
|
||||
# 为您的平台生成启动脚本
|
||||
pm2 startup
|
||||
|
||||
# 保存当前进程列表
|
||||
pm2 save
|
||||
```
|
||||
|
||||
|
||||
### 本地开发安装
|
||||
|
||||
1. **克隆仓库:**
|
||||
```bash
|
||||
git clone https://github.com/siteboon/claudecodeui.git
|
||||
cd claudecodeui
|
||||
```
|
||||
|
||||
2. **安装依赖:**
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. **配置环境:**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# 使用您喜欢的设置编辑 .env
|
||||
```
|
||||
|
||||
4. **启动应用程序:**
|
||||
```bash
|
||||
# 开发模式(支持热重载)
|
||||
npm run dev
|
||||
|
||||
```
|
||||
应用程序将在您在 .env 中指定的端口启动
|
||||
|
||||
5. **打开浏览器:**
|
||||
- 开发环境: `http://localhost:3001`
|
||||
|
||||
## 安全与工具配置
|
||||
|
||||
**🔒 重要提示**: 所有 Claude Code 工具默认**禁用**,可防止潜在的有害操作自动运行。
|
||||
**🔒 重要提示**: 所有 Claude Code 工具**默认禁用**。这可以防止潜在的有害操作自动运行。
|
||||
|
||||
### 启用工具
|
||||
|
||||
1. **打开工具设置** - 点击侧边栏齿轮图标
|
||||
2. **选择性启用** - 仅启用所需工具
|
||||
3. **应用设置** - 偏好设置保存在本地
|
||||
要使用 Claude Code 的完整功能,您需要手动启用工具:
|
||||
|
||||
1. **打开工具设置** - 点击侧边栏中的齿轮图标
|
||||
3. **选择性启用** - 仅打开您需要的工具
|
||||
4. **应用设置** - 您的偏好设置将保存在本地
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
*工具设置界面 - 只启用你需要的内容*
|
||||

|
||||
*工具设置界面 - 仅启用您需要的内容*
|
||||
|
||||
</div>
|
||||
|
||||
**推荐做法**: 先启用基础工具,再根据需要添加其他工具。随时可以调整。
|
||||
**推荐方法**: 首先启用基本工具,然后根据需要添加更多。您可以随时调整这些设置。
|
||||
|
||||
---
|
||||
## TaskMaster AI 集成 *(可选)*
|
||||
|
||||
## 插件
|
||||
Claude Code UI 支持 **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)**(aka claude-task-master)集成,用于高级项目管理和 AI 驱动的任务规划。
|
||||
|
||||
CloudCLI 配备插件系统,允许你添加带自定义前端 UI 和可选 Node.js 后端的选项卡。在 Settings > Plugins 中直接从 Git 仓库安装插件,或自行开发。
|
||||
它提供
|
||||
- 从 PRD(产品需求文档)生成 AI 驱动的任务
|
||||
- 智能任务分解和依赖管理
|
||||
- 可视化任务板和进度跟踪
|
||||
|
||||
### 可用插件
|
||||
**设置与文档**: 访问 [TaskMaster AI GitHub 仓库](https://github.com/eyaltoledano/claude-task-master)获取安装说明、配置指南和使用示例。
|
||||
安装后,您应该能够从设置中启用它
|
||||
|
||||
| 插件 | 描述 |
|
||||
|---|---|
|
||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 展示当前项目的文件数、代码行数、文件类型分布、最大文件以及最近修改的文件 |
|
||||
|
||||
### 自行构建
|
||||
## 使用指南
|
||||
|
||||
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — Fork 该仓库以构建自己的插件。示例包括前端渲染、实时上下文更新和 RPC 通信。
|
||||
### 核心功能
|
||||
|
||||
**[插件文档 →](https://cloudcli.ai/docs/plugin-overview)** — 提供插件 API、清单格式、安全模型等完整指南。
|
||||
#### 项目管理
|
||||
当可用时,它会自动发现 Claude Code、Cursor 或 Codex 会话并将它们分组到项目中
|
||||
- **项目操作** - 重命名、删除和组织项目
|
||||
- **智能导航** - 快速访问最近的项目和会话
|
||||
- **MCP 支持** - 通过 UI 添加您自己的 MCP 服务器
|
||||
|
||||
---
|
||||
#### 聊天界面
|
||||
- **使用响应式聊天或 Claude Code/Cursor CLI/Codex CLI** - 您可以使用自适应聊天界面或使用 shell 按钮连接到您选择的 CLI
|
||||
- **实时通信** - 通过 WebSocket 连接从您选择的 CLI(Claude Code/Cursor/Codex)流式传输响应
|
||||
- **会话管理** - 恢复之前的对话或启动新会话
|
||||
- **消息历史** - 带有时间戳和元数据的完整对话历史
|
||||
- **多格式支持** - 文本、代码块和文件引用
|
||||
|
||||
## 常见问题
|
||||
#### 文件浏览器与编辑器
|
||||
- **交互式文件树** - 使用展开/折叠导航浏览项目结构
|
||||
- **实时文件编辑** - 直接在界面中读取、修改和保存文件
|
||||
- **语法高亮** - 支持多种编程语言
|
||||
- **文件操作** - 创建、重命名、删除文件和目录
|
||||
|
||||
<details>
|
||||
<summary>与 Claude Code Remote Control 有何不同?</summary>
|
||||
#### Git 浏览器
|
||||
|
||||
Claude Code Remote Control 让你发送消息到本地终端中已经运行的会话。该方式要求你的机器保持开机,终端保持开启,断开网络后约 10 分钟会话会超时。
|
||||
|
||||
CloudCLI UI 与 CloudCLI Cloud 是对 Claude Code 的扩展,而非旁观 — MCP 服务器、权限、设置、会话与 Claude Code 完全一致。
|
||||
#### TaskMaster AI 集成 *(可选)*
|
||||
- **可视化任务板** - 用于管理开发任务的看板风格界面
|
||||
- **PRD 解析器** - 创建产品需求文档并将其解析为结构化任务
|
||||
- **进度跟踪** - 实时状态更新和完成跟踪
|
||||
|
||||
- **覆盖全部会话** — CloudCLI UI 会自动扫描 `~/.claude` 文件夹中的每个会话。Remote Control 只暴露当前活动的会话。
|
||||
- **设置统一** — 在 CloudCLI UI 中修改的 MCP、工具权限等设置会立即写入 Claude Code。
|
||||
- **支持更多 Agents** — Claude Code、Cursor CLI、Codex、Gemini CLI。
|
||||
- **完整 UI** — 除了聊天界面,还包括文件浏览器、Git 集成、MCP 管理和 Shell 终端。
|
||||
- **CloudCLI Cloud 保持运行于云端** — 关闭本地设备也不会中断代理运行,无需监控终端。
|
||||
#### 会话管理
|
||||
- **会话持久化** - 所有对话自动保存
|
||||
- **会话组织** - 按项目和 timestamp 分组会话
|
||||
- **会话操作** - 重命名、删除和导出对话历史
|
||||
- **跨设备同步** - 从任何设备访问会话
|
||||
|
||||
</details>
|
||||
### 移动应用
|
||||
- **响应式设计** - 针对所有屏幕尺寸进行优化
|
||||
- **触摸友好界面** - 滑动手势和触摸导航
|
||||
- **移动导航** - 底部选项卡栏,方便拇指导航
|
||||
- **自适应布局** - 可折叠侧边栏和智能内容优先级
|
||||
- **添加到主屏幕快捷方式** - 添加快捷方式到主屏幕,应用程序将像 PWA 一样运行
|
||||
|
||||
<details>
|
||||
<summary>需要额外购买 AI 订阅吗?</summary>
|
||||
## 架构
|
||||
|
||||
需要。CloudCLI 只提供环境。你仍需自行获取 Claude、Cursor、Codex 或 Gemini 订阅。CloudCLI Cloud 从 $7/月起提供托管环境。
|
||||
### 系统概览
|
||||
|
||||
</details>
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Frontend │ │ Backend │ │ Agent │
|
||||
│ (React/Vite) │◄──►│ (Express/WS) │◄──►│ Integration │
|
||||
│ │ │ │ │ │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>能在手机上使用 CloudCLI UI 吗?</summary>
|
||||
### 后端 (Node.js + Express)
|
||||
- **Express 服务器** - 具有静态文件服务的 RESTful API
|
||||
- **WebSocket 服务器** - 用于聊天和项目刷新的通信
|
||||
- **Agent 集成 (Claude Code / Cursor CLI / Codex)** - 进程生成和管理
|
||||
- **文件系统 API** - 为项目公开文件浏览器
|
||||
|
||||
可以。自托管时,在你的设备上运行服务器,然后在网络中的任意浏览器打开 `[yourip]:port`。CloudCLI Cloud 可从任意设备访问,内置原生应用也在开发中。
|
||||
### 前端 (React + Vite)
|
||||
- **React 18** - 带有 hooks 的现代组件架构
|
||||
- **CodeMirror** - 具有语法高亮的高级代码编辑器
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>UI 中的更改会影响本地 Claude Code 配置吗?</summary>
|
||||
|
||||
会的。自托管模式下,CloudCLI UI 读取并写入 Claude Code 使用的 `~/.claude` 配置。通过 UI 添加的 MCP 服务器会立即在 Claude Code 中可见。
|
||||
|
||||
</details>
|
||||
### 贡献
|
||||
|
||||
---
|
||||
我们欢迎贡献!有关提交规范、开发流程和发布流程的详细信息,请参阅 [Contributing Guide](CONTRIBUTING.md)。
|
||||
|
||||
## 社区与支持
|
||||
## 故障排除
|
||||
|
||||
### 常见问题与解决方案
|
||||
|
||||
|
||||
#### "未找到 Claude 项目"
|
||||
**问题**: UI 显示没有项目或项目列表为空
|
||||
**解决方案**:
|
||||
- 确保已正确安装 [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
|
||||
- 至少在一个项目目录中运行 `claude` 命令以进行初始化
|
||||
- 验证 `~/.claude/projects/` 目录存在并具有适当的权限
|
||||
|
||||
#### 文件浏览器问题
|
||||
**问题**: 文件无法加载、权限错误、空目录
|
||||
**解决方案**:
|
||||
- 检查项目目录权限(在终端中使用 `ls -la`)
|
||||
- 验证项目路径存在且可访问
|
||||
- 查看服务器控制台日志以获取详细错误消息
|
||||
- 确保您未尝试访问项目范围之外的系统目录
|
||||
|
||||
- **[文档](https://cloudcli.ai/docs)** — 安装、配置、功能与故障排除指南
|
||||
- **[Discord](https://discord.gg/buxwujPNRE)** — 获取帮助并与社区交流
|
||||
- **[GitHub Issues](https://github.com/siteboon/claudecodeui/issues)** — 报告 Bug 与建议功能
|
||||
- **[贡献指南](CONTRIBUTING.md)** — 如何参与项目贡献
|
||||
|
||||
## 许可证
|
||||
|
||||
GNU 通用公共许可证 v3.0 - 详见 [LICENSE](LICENSE) 文件。
|
||||
GNU General Public License v3.0 - 详见 [LICENSE](LICENSE) 文件。
|
||||
|
||||
该项目为开源软件,在 GPL v3 许可证下可自由使用、修改与分发。
|
||||
本项目是开源的,在 GPL v3 许可下可自由使用、修改和分发。
|
||||
|
||||
## 致谢
|
||||
|
||||
### 使用技术
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic 官方 CLI
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursor 官方 CLI
|
||||
### 构建工具
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic 的官方 CLI
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursor 的官方 CLI
|
||||
- **[Codex](https://developers.openai.com/codex)** - OpenAI Codex
|
||||
- **[Gemini-CLI](https://geminicli.com/)** - Google Gemini CLI
|
||||
- **[React](https://react.dev/)** - 用户界面库
|
||||
- **[Vite](https://vitejs.dev/)** - 快速构建工具与开发服务器
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - 实用先行 CSS 框架
|
||||
- **[Vite](https://vitejs.dev/)** - 快速构建工具和开发服务器
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - 实用优先的 CSS 框架
|
||||
- **[CodeMirror](https://codemirror.net/)** - 高级代码编辑器
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(可选)* - AI 驱动的项目管理与任务规划
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(可选)* - AI 驱动的项目管理和任务规划
|
||||
|
||||
## 支持与社区
|
||||
|
||||
### 保持更新
|
||||
- **Star** 此仓库以表示支持
|
||||
- **Watch** 以获取更新和新版本
|
||||
- **Follow** 项目以获取公告
|
||||
|
||||
### 赞助商
|
||||
- [Siteboon - AI powered website builder](https://siteboon.ai)
|
||||
@@ -239,4 +344,4 @@ GNU 通用公共许可证 v3.0 - 详见 [LICENSE](LICENSE) 文件。
|
||||
|
||||
<div align="center">
|
||||
<strong>为 Claude Code、Cursor 和 Codex 社区精心打造。</strong>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,3 +0,0 @@
|
||||
export default {
|
||||
extends: ["@commitlint/config-conventional"],
|
||||
};
|
||||
160
docker/README.md
160
docker/README.md
@@ -1,160 +0,0 @@
|
||||
<!-- Docker Hub short description (100 chars max): -->
|
||||
<!-- Sandbox templates for running AI coding agents with a web & mobile IDE (Claude Code, Codex, Gemini) -->
|
||||
|
||||
# Sandboxed coding agents with a web & mobile IDE (CloudCLI)
|
||||
|
||||
[Docker Sandbox](https://docs.docker.com/ai/sandboxes/) templates that add [CloudCLI](https://cloudcli.ai) on top of Claude Code, Codex, and Gemini CLI. You get a full web and mobile IDE accessible from any browser on any device.
|
||||
|
||||
## Get started
|
||||
|
||||
### 1. Install the sbx CLI
|
||||
|
||||
Docker Sandboxes run agents in isolated microVMs. Install the `sbx` CLI:
|
||||
|
||||
- **macOS**: `brew install docker/tap/sbx`
|
||||
- **Windows**: `winget install -h Docker.sbx`
|
||||
- **Linux**: `sudo apt-get install docker-sbx`
|
||||
|
||||
Full instructions: [docs.docker.com/ai/sandboxes/get-started](https://docs.docker.com/ai/sandboxes/get-started/)
|
||||
|
||||
### 2. Store your API key
|
||||
|
||||
`sbx` manages credentials securely — your API key never enters the sandbox. Store it once:
|
||||
|
||||
```bash
|
||||
sbx login
|
||||
sbx secret set -g anthropic
|
||||
```
|
||||
|
||||
### 3. Launch Claude Code
|
||||
|
||||
```bash
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project
|
||||
```
|
||||
|
||||
Open **http://localhost:3001**. Set a password on first visit. Start building.
|
||||
|
||||
### Using a different agent
|
||||
|
||||
Store the matching API key and pass `--agent`:
|
||||
|
||||
```bash
|
||||
# OpenAI Codex
|
||||
sbx secret set -g openai
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project --agent codex
|
||||
|
||||
# Gemini CLI
|
||||
sbx secret set -g google
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project --agent gemini
|
||||
```
|
||||
|
||||
### Available templates
|
||||
|
||||
| Agent | Template |
|
||||
|-------|----------|
|
||||
| **Claude Code** (default) | `docker.io/cloudcliai/sandbox:claude-code` |
|
||||
| OpenAI Codex | `docker.io/cloudcliai/sandbox:codex` |
|
||||
| Gemini CLI | `docker.io/cloudcliai/sandbox:gemini` |
|
||||
|
||||
These are used with `--template` when running `sbx` directly (see [Advanced usage](#advanced-usage)).
|
||||
|
||||
## Managing sandboxes
|
||||
|
||||
```bash
|
||||
sbx ls # List all sandboxes
|
||||
sbx stop my-project # Stop (preserves state)
|
||||
sbx start my-project # Restart a stopped sandbox
|
||||
sbx rm my-project # Remove everything
|
||||
sbx exec my-project bash # Open a shell inside the sandbox
|
||||
```
|
||||
|
||||
If you install CloudCLI globally (`npm install -g @cloudcli-ai/cloudcli`), you can also use:
|
||||
|
||||
```bash
|
||||
cloudcli sandbox ls
|
||||
cloudcli sandbox start my-project # Restart and re-launch web UI
|
||||
cloudcli sandbox logs my-project # View server logs
|
||||
```
|
||||
|
||||
## What you get
|
||||
|
||||
- **Chat** — Markdown rendering, code blocks, message history
|
||||
- **Files** — File tree with syntax-highlighted editor
|
||||
- **Git** — Diff viewer, staging, branch switching, commits
|
||||
- **Shell** — Built-in terminal emulator
|
||||
- **MCP** — Configure Model Context Protocol servers visually
|
||||
- **Mobile** — Works on tablet and phone browsers
|
||||
|
||||
Your project directory is mounted bidirectionally — edits propagate in real time, both ways.
|
||||
|
||||
## Configuration
|
||||
|
||||
Set variables at creation time with `--env`:
|
||||
|
||||
```bash
|
||||
npx @cloudcli-ai/cloudcli@latest sandbox ~/my-project --env SERVER_PORT=8080
|
||||
```
|
||||
|
||||
Or inside a running sandbox:
|
||||
|
||||
```bash
|
||||
sbx exec my-project bash -c 'echo "export SERVER_PORT=8080" >> /etc/sandbox-persistent.sh'
|
||||
```
|
||||
|
||||
Restart CloudCLI for changes to take effect:
|
||||
|
||||
```bash
|
||||
sbx exec my-project bash -c 'pkill -f "server/index.js"'
|
||||
sbx exec -d my-project cloudcli start --port 3001
|
||||
```
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `SERVER_PORT` | `3001` | Web UI port |
|
||||
| `HOST` | `0.0.0.0` | Bind address (must be `0.0.0.0` for `sbx ports`) |
|
||||
| `DATABASE_PATH` | `~/.cloudcli/auth.db` | SQLite database location |
|
||||
|
||||
## Advanced usage
|
||||
|
||||
For branch mode, multiple workspaces, memory limits, or the terminal agent experience, use `sbx` with the template:
|
||||
|
||||
```bash
|
||||
# Terminal agent + web UI
|
||||
sbx run --template docker.io/cloudcliai/sandbox:claude-code claude ~/my-project --name my-project
|
||||
sbx ports my-project --publish 3001:3001
|
||||
|
||||
# Branch mode (Git worktree isolation)
|
||||
sbx run --template docker.io/cloudcliai/sandbox:claude-code claude ~/my-project --branch my-feature
|
||||
|
||||
# Multiple workspaces
|
||||
sbx run --template docker.io/cloudcliai/sandbox:claude-code claude ~/project ~/shared-libs:ro
|
||||
|
||||
# Pass a prompt directly
|
||||
sbx run --template docker.io/cloudcliai/sandbox:claude-code claude ~/my-project -- "Fix the auth bug"
|
||||
```
|
||||
|
||||
CloudCLI auto-starts via `.bashrc` when using `sbx run`.
|
||||
|
||||
Full options in the [Docker Sandboxes usage guide](https://docs.docker.com/ai/sandboxes/usage/).
|
||||
|
||||
## Network policies
|
||||
|
||||
Sandboxes restrict outbound access by default. To reach host services from inside the sandbox:
|
||||
|
||||
```bash
|
||||
sbx policy allow network localhost:11434
|
||||
# Inside the sandbox: curl http://host.docker.internal:11434
|
||||
```
|
||||
|
||||
The web UI itself doesn't need a policy — access it via `sbx ports`.
|
||||
|
||||
## Links
|
||||
|
||||
- [CloudCLI Cloud](https://cloudcli.ai) — fully managed, no setup required
|
||||
- [Documentation](https://cloudcli.ai/docs) — full configuration guide
|
||||
- [Discord](https://discord.gg/buxwujPNRE) — community support
|
||||
- [GitHub](https://github.com/siteboon/claudecodeui) — source code and issues
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0-or-later
|
||||
@@ -1,11 +0,0 @@
|
||||
FROM docker/sandbox-templates:claude-code
|
||||
|
||||
USER root
|
||||
COPY shared/install-cloudcli.sh /tmp/install-cloudcli.sh
|
||||
RUN chmod +x /tmp/install-cloudcli.sh && /tmp/install-cloudcli.sh
|
||||
|
||||
USER agent
|
||||
RUN npm install -g @cloudcli-ai/cloudcli && cloudcli --version
|
||||
|
||||
COPY --chown=agent:agent shared/start-cloudcli.sh /home/agent/.cloudcli-start.sh
|
||||
RUN echo '. ~/.cloudcli-start.sh' >> /home/agent/.bashrc
|
||||
@@ -1,11 +0,0 @@
|
||||
FROM docker/sandbox-templates:codex
|
||||
|
||||
USER root
|
||||
COPY shared/install-cloudcli.sh /tmp/install-cloudcli.sh
|
||||
RUN chmod +x /tmp/install-cloudcli.sh && /tmp/install-cloudcli.sh
|
||||
|
||||
USER agent
|
||||
RUN npm install -g @cloudcli-ai/cloudcli && cloudcli --version
|
||||
|
||||
COPY --chown=agent:agent shared/start-cloudcli.sh /home/agent/.cloudcli-start.sh
|
||||
RUN echo '. ~/.cloudcli-start.sh' >> /home/agent/.bashrc
|
||||
@@ -1,11 +0,0 @@
|
||||
FROM docker/sandbox-templates:gemini
|
||||
|
||||
USER root
|
||||
COPY shared/install-cloudcli.sh /tmp/install-cloudcli.sh
|
||||
RUN chmod +x /tmp/install-cloudcli.sh && /tmp/install-cloudcli.sh
|
||||
|
||||
USER agent
|
||||
RUN npm install -g @cloudcli-ai/cloudcli && cloudcli --version
|
||||
|
||||
COPY --chown=agent:agent shared/start-cloudcli.sh /home/agent/.cloudcli-start.sh
|
||||
RUN echo '. ~/.cloudcli-start.sh' >> /home/agent/.bashrc
|
||||
@@ -1,11 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Install build tools needed for native modules (node-pty, better-sqlite3, bcrypt)
|
||||
# Node.js is already provided by the sandbox base image
|
||||
apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential python3 python3-setuptools \
|
||||
jq ripgrep sqlite3 zip unzip tree vim-tiny
|
||||
|
||||
# Clean up apt cache to reduce image size
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Auto-start CloudCLI server in background if not already running.
|
||||
# This script is sourced from ~/.bashrc on sandbox shell open.
|
||||
|
||||
if ! pgrep -f "server/index.js" > /dev/null 2>&1; then
|
||||
nohup cloudcli start --port 3001 > /tmp/cloudcli-ui.log 2>&1 &
|
||||
disown
|
||||
|
||||
echo ""
|
||||
echo " CloudCLI is starting on port 3001..."
|
||||
echo ""
|
||||
echo " Forward the port from another terminal:"
|
||||
echo " sbx ports <sandbox-name> --publish 3001:3001"
|
||||
echo ""
|
||||
echo " Then open: http://localhost:3001"
|
||||
echo ""
|
||||
fi
|
||||
230
eslint.config.js
230
eslint.config.js
@@ -1,230 +0,0 @@
|
||||
import js from "@eslint/js";
|
||||
import tseslint from "typescript-eslint";
|
||||
import react from "eslint-plugin-react";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import reactRefresh from "eslint-plugin-react-refresh";
|
||||
import { createNodeResolver, importX } from "eslint-plugin-import-x";
|
||||
import { createTypeScriptImportResolver } from "eslint-import-resolver-typescript";
|
||||
import boundaries from "eslint-plugin-boundaries";
|
||||
import tailwindcss from "eslint-plugin-tailwindcss";
|
||||
import unusedImports from "eslint-plugin-unused-imports";
|
||||
import globals from "globals";
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ["dist/**", "node_modules/**", "public/**"],
|
||||
},
|
||||
{
|
||||
files: ["src/**/*.{ts,tsx,js,jsx}"],
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
plugins: {
|
||||
react,
|
||||
"react-hooks": reactHooks, // for following React rules such as dependencies in hooks, keys in lists, etc.
|
||||
"react-refresh": reactRefresh, // for Vite HMR compatibility
|
||||
"import-x": importX, // for import order/sorting. It also detercts circular dependencies and duplicate imports.
|
||||
tailwindcss, // for detecting invalid Tailwind classnames and enforcing classname order
|
||||
"unused-imports": unusedImports, // for detecting unused imports
|
||||
},
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
},
|
||||
parserOptions: {
|
||||
ecmaFeatures: { jsx: true },
|
||||
},
|
||||
},
|
||||
settings: {
|
||||
react: { version: "detect" },
|
||||
},
|
||||
rules: {
|
||||
// --- Unused imports/vars ---
|
||||
"unused-imports/no-unused-imports": "warn",
|
||||
"unused-imports/no-unused-vars": [
|
||||
"warn",
|
||||
{
|
||||
vars: "all",
|
||||
varsIgnorePattern: "^_",
|
||||
args: "after-used",
|
||||
argsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
|
||||
// --- React ---
|
||||
"react/jsx-key": "warn",
|
||||
"react/jsx-no-duplicate-props": "error",
|
||||
"react/jsx-no-undef": "error",
|
||||
"react/no-children-prop": "warn",
|
||||
"react/no-danger-with-children": "error",
|
||||
"react/no-direct-mutation-state": "error",
|
||||
"react/no-unknown-property": "warn",
|
||||
"react/react-in-jsx-scope": "off",
|
||||
|
||||
// --- React Hooks ---
|
||||
"react-hooks/rules-of-hooks": "error",
|
||||
"react-hooks/exhaustive-deps": "warn",
|
||||
|
||||
// --- React Refresh (Vite HMR) ---
|
||||
"react-refresh/only-export-components": [
|
||||
"warn",
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
|
||||
// --- Import ordering & hygiene ---
|
||||
"import-x/no-duplicates": "warn",
|
||||
"import-x/order": [
|
||||
"warn",
|
||||
{
|
||||
groups: [
|
||||
"builtin",
|
||||
"external",
|
||||
"internal",
|
||||
"parent",
|
||||
"sibling",
|
||||
"index",
|
||||
],
|
||||
"newlines-between": "always",
|
||||
},
|
||||
],
|
||||
|
||||
// --- Tailwind CSS ---
|
||||
"tailwindcss/classnames-order": "warn",
|
||||
"tailwindcss/no-contradicting-classname": "warn",
|
||||
"tailwindcss/no-unnecessary-arbitrary-value": "warn",
|
||||
|
||||
// --- Disabled base rules ---
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-require-imports": "off",
|
||||
"no-case-declarations": "off",
|
||||
"no-control-regex": "off",
|
||||
"no-useless-escape": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["server/**/*.{js,ts}"], // apply this block only to backend source files
|
||||
ignores: ["server/**/*.d.ts"], // skip generated declaration files in backend linting
|
||||
plugins: {
|
||||
boundaries, // enforce backend architecture boundaries (module-to-module contracts)
|
||||
"import-x": importX, // keep import hygiene rules (duplicates, unresolved paths, etc.)
|
||||
"unused-imports": unusedImports, // remove dead imports/variables from backend files
|
||||
},
|
||||
languageOptions: {
|
||||
parser: tseslint.parser, // parse both JS and TS syntax in backend files
|
||||
parserOptions: {
|
||||
ecmaVersion: "latest", // support modern ECMAScript syntax in backend code
|
||||
sourceType: "module", // treat backend files as ESM modules
|
||||
},
|
||||
globals: {
|
||||
...globals.node, // expose Node.js globals such as process, Buffer, and __dirname equivalents
|
||||
},
|
||||
},
|
||||
settings: {
|
||||
"boundaries/include": ["server/**/*.{js,ts}"], // only analyze dependency boundaries inside backend files
|
||||
"import/resolver": {
|
||||
// boundaries resolves imports through eslint-module-utils, which reads the classic
|
||||
// import/resolver setting instead of import-x/resolver-next.
|
||||
typescript: {
|
||||
project: ["server/tsconfig.json"], // resolve backend aliases using the canonical backend tsconfig
|
||||
alwaysTryTypes: true, // keep normal TS package/type resolution working alongside aliases
|
||||
},
|
||||
node: {
|
||||
extensions: [".mjs", ".cjs", ".js", ".json", ".node", ".ts", ".tsx"], // preserve Node-style fallback resolution for plain files
|
||||
},
|
||||
},
|
||||
"import-x/resolver-next": [
|
||||
// ESLint's import plugin does not read tsconfig path aliases on its own.
|
||||
// This resolver teaches import-x how to understand the backend-only "@/*"
|
||||
// mapping defined in server/tsconfig.json, which fixes false no-unresolved errors in editors.
|
||||
createTypeScriptImportResolver({
|
||||
project: ["server/tsconfig.json"], // point the resolver at the canonical backend tsconfig instead of the frontend one
|
||||
alwaysTryTypes: true, // keep standard TypeScript package resolution working while backend aliases are enabled
|
||||
}),
|
||||
// Keep Node-style resolution available for normal package imports and plain relative JS files.
|
||||
// The TypeScript resolver handles aliases, while the Node resolver preserves the expected fallback behavior.
|
||||
createNodeResolver({
|
||||
extensions: [".mjs", ".cjs", ".js", ".json", ".node", ".ts", ".tsx"],
|
||||
}),
|
||||
],
|
||||
"boundaries/elements": [
|
||||
{
|
||||
type: "backend-shared-types", // shared backend type contract that modules may consume without creating runtime coupling
|
||||
pattern: ["server/shared/types.{js,ts}"], // support the current shared types path
|
||||
mode: "file", // treat the types file itself as the boundary element instead of the whole folder
|
||||
},
|
||||
{
|
||||
type: "backend-module", // logical element name used by boundaries rules below
|
||||
pattern: "server/modules/*", // each direct folder in server/modules is treated as one module boundary
|
||||
mode: "folder", // classify dependencies at folder-module level (not per individual file)
|
||||
capture: ["moduleName"], // capture the module folder name for messages/debugging/template use
|
||||
},
|
||||
],
|
||||
},
|
||||
rules: {
|
||||
// --- Unused imports/vars (backend) ---
|
||||
"unused-imports/no-unused-imports": "warn", // warn when imports are not used so they can be cleaned up
|
||||
"unused-imports/no-unused-vars": "off", // keep backend signal focused on dead imports instead of local unused variables
|
||||
|
||||
// --- Import hygiene (backend) ---
|
||||
"import-x/no-duplicates": "warn", // prevent duplicate import lines from the same module
|
||||
"import-x/order": [
|
||||
"warn", // keep backend import grouping/order consistent with the frontend config
|
||||
{
|
||||
groups: [
|
||||
"builtin", // Node built-ins such as fs, path, and url come first
|
||||
"external", // third-party packages come after built-ins
|
||||
"internal", // aliased internal imports such as @/... come next
|
||||
"parent", // ../ imports come after aliased internal imports
|
||||
"sibling", // ./foo imports come after parent imports
|
||||
"index", // bare ./ imports stay last
|
||||
],
|
||||
"newlines-between": "always", // require a blank line between import groups in backend files too
|
||||
},
|
||||
],
|
||||
"import-x/no-unresolved": "error", // fail when an import path cannot be resolved
|
||||
"import-x/no-useless-path-segments": "warn", // prefer cleaner paths (remove redundant ./ and ../ segments)
|
||||
"import-x/no-absolute-path": "error", // disallow absolute filesystem imports in backend files
|
||||
|
||||
// --- General safety/style (backend) ---
|
||||
eqeqeq: ["warn", "always", { null: "ignore" }], // avoid accidental coercion while still allowing x == null checks
|
||||
|
||||
// --- Architecture boundaries (backend modules) ---
|
||||
"boundaries/dependencies": [
|
||||
"error", // treat architecture violations as lint errors
|
||||
{
|
||||
default: "allow", // allow normal imports unless a rule below explicitly disallows them
|
||||
checkInternals: false, // do not apply these cross-module rules to imports inside the same module
|
||||
rules: [
|
||||
{
|
||||
from: { type: "backend-module" }, // modules may depend on the shared types contract only as erased type-only imports
|
||||
to: { type: "backend-shared-types" },
|
||||
disallow: {
|
||||
dependency: { kind: ["value", "typeof"] },
|
||||
}, // block runtime imports so shared types stay a compile-time contract instead of a hidden shared module
|
||||
message:
|
||||
"Backend modules may only use `import type` when importing from server/shared/types.ts (or server/types.ts).",
|
||||
},
|
||||
{
|
||||
to: { type: "backend-module" }, // when importing anything that belongs to another backend module
|
||||
disallow: { to: { internalPath: "**" } }, // block all direct/deep imports into module internals by default
|
||||
message:
|
||||
"Cross-module imports must go through that module's barrel file (server/modules/<module>/index.ts or index.js).", // explicit error message for architecture violations
|
||||
},
|
||||
{
|
||||
to: { type: "backend-module" }, // same target scope as the disallow rule above
|
||||
allow: {
|
||||
to: {
|
||||
internalPath: [
|
||||
"index", // allow extensionless barrel imports resolved as module root index
|
||||
"index.{js,mjs,cjs,ts,tsx}", // allow explicit index.* barrel file imports
|
||||
],
|
||||
},
|
||||
}, // re-allow only public module entry points (barrel files)
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
"boundaries/no-unknown": "error", // fail fast if boundaries cannot classify a dependency, which prevents silent rule bypasses
|
||||
},
|
||||
}
|
||||
);
|
||||
@@ -8,7 +8,7 @@
|
||||
<title>CloudCLI UI</title>
|
||||
|
||||
<!-- PWA Manifest -->
|
||||
<link rel="manifest" href="/manifest.json" crossorigin="use-credentials" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
|
||||
<!-- iOS Safari PWA Meta Tags -->
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
@@ -45,4 +45,4 @@
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
6160
package-lock.json
generated
6160
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
74
package.json
74
package.json
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"name": "@cloudcli-ai/cloudcli",
|
||||
"version": "1.29.5",
|
||||
"name": "@siteboon/claude-code-ui",
|
||||
"version": "1.22.0",
|
||||
"description": "A web-based UI for Claude Code CLI",
|
||||
"type": "module",
|
||||
"main": "dist-server/server/index.js",
|
||||
"main": "server/index.js",
|
||||
"bin": {
|
||||
"cloudcli": "dist-server/server/cli.js"
|
||||
"claude-code-ui": "server/cli.js",
|
||||
"cloudcli": "server/cli.js"
|
||||
},
|
||||
"files": [
|
||||
"server/",
|
||||
"shared/",
|
||||
"dist/",
|
||||
"dist-server/",
|
||||
"scripts/",
|
||||
"README.md"
|
||||
],
|
||||
@@ -24,46 +24,26 @@
|
||||
"url": "https://github.com/siteboon/claudecodeui/issues"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "concurrently --kill-others \"npm run server:dev\" \"npm run client\"",
|
||||
"server": "node dist-server/server/index.js",
|
||||
"server:dev": "tsx --tsconfig server/tsconfig.json server/index.js",
|
||||
"server:dev-watch": "tsx watch --tsconfig server/tsconfig.json server/index.js",
|
||||
"client": "vite",
|
||||
"build": "npm run build:client && npm run build:server",
|
||||
"build:client": "vite build",
|
||||
"prebuild:server": "node -e \"require('node:fs').rmSync('dist-server', { recursive: true, force: true })\"",
|
||||
"build:server": "tsc -p server/tsconfig.json && tsc-alias -p server/tsconfig.json",
|
||||
"dev": "concurrently --kill-others \"npm run server\" \"npm run client\"",
|
||||
"server": "node server/index.js",
|
||||
"client": "vite --host",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p server/tsconfig.json",
|
||||
"lint": "eslint src/ server/",
|
||||
"lint:fix": "eslint src/ server/ --fix",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"start": "npm run build && npm run server",
|
||||
"release": "./release.sh",
|
||||
"prepublishOnly": "npm run build",
|
||||
"postinstall": "node scripts/fix-node-pty.js",
|
||||
"prepare": "husky",
|
||||
"update:platform": "./update-platform.sh"
|
||||
"postinstall": "node scripts/fix-node-pty.js"
|
||||
},
|
||||
"keywords": [
|
||||
"claude code",
|
||||
"claude-code",
|
||||
"claude-code-ui",
|
||||
"cloudcli",
|
||||
"codex",
|
||||
"gemini",
|
||||
"gemini-cli",
|
||||
"cursor",
|
||||
"cursor-cli",
|
||||
"ai",
|
||||
"anthropic",
|
||||
"openai",
|
||||
"google",
|
||||
"coding-agent",
|
||||
"web-ui",
|
||||
"ui",
|
||||
"mobile IDE"
|
||||
"mobile"
|
||||
],
|
||||
"author": "CloudCLI UI Contributors",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.59",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
@@ -104,7 +84,7 @@
|
||||
"mime-types": "^3.0.1",
|
||||
"multer": "^2.0.1",
|
||||
"node-fetch": "^2.7.0",
|
||||
"node-pty": "^1.2.0-beta.12",
|
||||
"node-pty": "^1.1.0-beta34",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-dropzone": "^14.2.3",
|
||||
@@ -117,14 +97,13 @@
|
||||
"rehype-raw": "^7.0.0",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"remark-math": "^6.0.0",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"web-push": "^3.6.7",
|
||||
"ws": "^8.14.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/cli": "^20.5.0",
|
||||
"@commitlint/config-conventional": "^20.5.0",
|
||||
"@eslint/js": "^9.39.3",
|
||||
"@release-it/conventional-changelog": "^10.0.5",
|
||||
"@types/node": "^22.19.7",
|
||||
"@types/react": "^18.2.43",
|
||||
@@ -133,31 +112,12 @@
|
||||
"auto-changelog": "^2.5.0",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"concurrently": "^8.2.2",
|
||||
"eslint": "^9.39.3",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-boundaries": "^6.0.2",
|
||||
"eslint-plugin-import-x": "^4.16.1",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"eslint-plugin-tailwindcss": "^3.18.2",
|
||||
"eslint-plugin-unused-imports": "^4.4.1",
|
||||
"globals": "^17.4.0",
|
||||
"husky": "^9.1.7",
|
||||
"lint-staged": "^16.3.2",
|
||||
"node-gyp": "^10.0.0",
|
||||
"postcss": "^8.4.32",
|
||||
"release-it": "^19.0.5",
|
||||
"sharp": "^0.34.2",
|
||||
"tailwindcss": "^3.4.0",
|
||||
"tsc-alias": "^1.8.16",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.56.1",
|
||||
"vite": "^7.0.4"
|
||||
},
|
||||
"lint-staged": {
|
||||
"src/**/*.{ts,tsx,js,jsx}": "eslint",
|
||||
"server/**/*.{js,ts}": "eslint"
|
||||
}
|
||||
}
|
||||
|
||||
Submodule plugins/starter deleted from 4895cd3fd3
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>CloudCLI - API Documentation</title>
|
||||
<title>Claude Code UI - API Documentation</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
|
||||
@@ -418,7 +418,7 @@
|
||||
</svg>
|
||||
</div>
|
||||
<div class="brand-text">
|
||||
<h1>CloudCLI</h1>
|
||||
<h1>Claude Code UI</h1>
|
||||
<div class="subtitle">API Documentation</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 340 KiB After Width: | Height: | Size: 171 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 506 KiB After Width: | Height: | Size: 192 KiB |
95
public/sw.js
95
public/sw.js
@@ -1,8 +1,8 @@
|
||||
// Service Worker for CloudCLI PWA
|
||||
// Cache only manifest (needed for PWA install). HTML and JS are never pre-cached
|
||||
// so a rebuild + refresh always picks up the latest assets.
|
||||
const CACHE_NAME = 'claude-ui-v2';
|
||||
// Service Worker for Claude Code UI PWA
|
||||
const CACHE_NAME = 'claude-ui-v1';
|
||||
const urlsToCache = [
|
||||
'/',
|
||||
'/index.html',
|
||||
'/manifest.json'
|
||||
];
|
||||
|
||||
@@ -10,63 +10,44 @@ const urlsToCache = [
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME)
|
||||
.then(cache => cache.addAll(urlsToCache))
|
||||
.then(cache => {
|
||||
return cache.addAll(urlsToCache);
|
||||
})
|
||||
);
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
// Fetch event — network-first for everything except hashed assets
|
||||
// Fetch event
|
||||
self.addEventListener('fetch', event => {
|
||||
const url = event.request.url;
|
||||
|
||||
// Never intercept API requests or WebSocket upgrades
|
||||
if (url.includes('/api/') || url.includes('/ws')) {
|
||||
// Never cache API requests or WebSocket upgrades
|
||||
if (event.request.url.includes('/api/') || event.request.url.includes('/ws')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigation requests (HTML) — always go to network, no caching
|
||||
if (event.request.mode === 'navigate') {
|
||||
event.respondWith(
|
||||
fetch(event.request).catch(() => caches.match('/manifest.json').then(() =>
|
||||
new Response('<h1>Offline</h1><p>Please check your connection.</p>', {
|
||||
headers: { 'Content-Type': 'text/html' }
|
||||
})
|
||||
))
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Hashed assets (JS/CSS in /assets/) — cache-first since filenames change per build
|
||||
if (url.includes('/assets/')) {
|
||||
event.respondWith(
|
||||
caches.match(event.request).then(cached => {
|
||||
if (cached) return cached;
|
||||
return fetch(event.request).then(response => {
|
||||
const clone = response.clone();
|
||||
caches.open(CACHE_NAME).then(cache => cache.put(event.request, clone));
|
||||
return response;
|
||||
});
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Everything else — network-first
|
||||
event.respondWith(
|
||||
fetch(event.request).catch(() => caches.match(event.request))
|
||||
caches.match(event.request)
|
||||
.then(response => {
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
return fetch(event.request);
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
// Activate event — purge old caches
|
||||
// Activate event
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(
|
||||
caches.keys().then(cacheNames =>
|
||||
Promise.all(
|
||||
cacheNames
|
||||
.filter(name => name !== CACHE_NAME)
|
||||
.map(name => caches.delete(name))
|
||||
)
|
||||
)
|
||||
caches.keys().then(cacheNames => {
|
||||
return Promise.all(
|
||||
cacheNames.map(cacheName => {
|
||||
if (cacheName !== CACHE_NAME) {
|
||||
return caches.delete(cacheName);
|
||||
}
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
@@ -79,7 +60,7 @@ self.addEventListener('push', event => {
|
||||
try {
|
||||
payload = event.data.json();
|
||||
} catch {
|
||||
payload = { title: 'CloudCLI', body: event.data.text() };
|
||||
payload = { title: 'Claude Code UI', body: event.data.text() };
|
||||
}
|
||||
|
||||
const options = {
|
||||
@@ -87,12 +68,12 @@ self.addEventListener('push', event => {
|
||||
icon: '/logo-256.png',
|
||||
badge: '/logo-128.png',
|
||||
data: payload.data || {},
|
||||
tag: payload.data?.tag || `${payload.data?.sessionId || 'global'}:${payload.data?.code || 'default'}`,
|
||||
tag: payload.data?.code || 'default',
|
||||
renotify: true
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(payload.title || 'CloudCLI', options)
|
||||
self.registration.showNotification(payload.title || 'Claude Code UI', options)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -101,20 +82,16 @@ self.addEventListener('notificationclick', event => {
|
||||
event.notification.close();
|
||||
|
||||
const sessionId = event.notification.data?.sessionId;
|
||||
const provider = event.notification.data?.provider || null;
|
||||
const urlPath = sessionId ? `/session/${sessionId}` : '/';
|
||||
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(async clientList => {
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(clientList => {
|
||||
for (const client of clientList) {
|
||||
if (client.url.includes(self.location.origin)) {
|
||||
await client.focus();
|
||||
client.postMessage({
|
||||
type: 'notification:navigate',
|
||||
sessionId: sessionId || null,
|
||||
provider,
|
||||
urlPath
|
||||
});
|
||||
client.focus();
|
||||
if (sessionId) {
|
||||
client.navigate(self.location.origin + urlPath);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
<div align="center">
|
||||
|
||||
> ## This package has moved to [`@cloudcli-ai/cloudcli`](https://www.npmjs.com/package/@cloudcli-ai/cloudcli)
|
||||
>
|
||||
> ```bash
|
||||
> npm install -g @cloudcli-ai/cloudcli
|
||||
> ```
|
||||
>
|
||||
> This package (`@siteboon/claude-code-ui`) is now a thin wrapper that installs the new package automatically.
|
||||
> For new installations, use `@cloudcli-ai/cloudcli` directly.
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/siteboon/claudecodeui/main/public/logo.svg" alt="CloudCLI UI" width="64" height="64">
|
||||
<h1>Cloud CLI (aka Claude Code UI)</h1>
|
||||
<p>A desktop and mobile UI for <a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code</a>, <a href="https://docs.cursor.com/en/cli/overview">Cursor CLI</a>, <a href="https://developers.openai.com/codex">Codex</a>, and <a href="https://geminicli.com/">Gemini-CLI</a>.<br>Use it locally or remotely to view your active projects and sessions from everywhere.</p>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai">CloudCLI Cloud</a> · <a href="https://cloudcli.ai/docs">Documentation</a> · <a href="https://discord.gg/buxwujPNRE">Discord</a> · <a href="https://github.com/siteboon/claudecodeui/issues">Bug Reports</a> · <a href="https://github.com/siteboon/claudecodeui/blob/main/CONTRIBUTING.md">Contributing</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cloudcli.ai"><img src="https://img.shields.io/badge/☁️_CloudCLI_Cloud-Try_Now-0066FF?style=for-the-badge" alt="CloudCLI Cloud"></a>
|
||||
<a href="https://discord.gg/buxwujPNRE"><img src="https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join our Discord"></a>
|
||||
<br><br>
|
||||
<a href="https://trendshift.io/repositories/15586" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15586" alt="siteboon%2Fclaudecodeui | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## Screenshots
|
||||
|
||||
<div align="center">
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h3>Desktop View</h3>
|
||||
<img src="https://raw.githubusercontent.com/siteboon/claudecodeui/main/public/screenshots/desktop-main.png" alt="Desktop Interface" width="400">
|
||||
<br>
|
||||
<em>Main interface showing project overview and chat</em>
|
||||
</td>
|
||||
<td align="center">
|
||||
<h3>Mobile Experience</h3>
|
||||
<img src="https://raw.githubusercontent.com/siteboon/claudecodeui/main/public/screenshots/mobile-chat.png" alt="Mobile Interface" width="250">
|
||||
<br>
|
||||
<em>Responsive mobile design with touch navigation</em>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" colspan="2">
|
||||
<h3>CLI Selection</h3>
|
||||
<img src="https://raw.githubusercontent.com/siteboon/claudecodeui/main/public/screenshots/cli-selection.png" alt="CLI Selection" width="400">
|
||||
<br>
|
||||
<em>Select between Claude Code, Gemini, Cursor CLI and Codex</em>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## Features
|
||||
|
||||
- **Responsive Design** - Works seamlessly across desktop, tablet, and mobile so you can also use Agents from mobile
|
||||
- **Interactive Chat Interface** - Built-in chat interface for seamless communication with the Agents
|
||||
- **Integrated Shell Terminal** - Direct access to the Agents CLI through built-in shell functionality
|
||||
- **File Explorer** - Interactive file tree with syntax highlighting and live editing
|
||||
- **Git Explorer** - View, stage and commit your changes. You can also switch branches
|
||||
- **Session Management** - Resume conversations, manage multiple sessions, and track history
|
||||
- **Plugin System** - Extend CloudCLI with custom plugins — add new tabs, backend services, and integrations. [Build your own →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)
|
||||
- **TaskMaster AI Integration** *(Optional)* - Advanced project management with AI-powered task planning, PRD parsing, and workflow automation
|
||||
- **Model Compatibility** - Works with Claude, GPT, and Gemini model families (see [`shared/modelConstants.js`](https://github.com/siteboon/claudecodeui/blob/main/shared/modelConstants.js) for the full list of supported models)
|
||||
|
||||
|
||||
## Quick Start
|
||||
|
||||
### CloudCLI Cloud (Recommended)
|
||||
|
||||
The fastest way to get started — no local setup required. Get a fully managed, containerized development environment accessible from the web, mobile app, API, or your favorite IDE.
|
||||
|
||||
**[Get started with CloudCLI Cloud](https://cloudcli.ai)**
|
||||
|
||||
|
||||
### Self-Hosted (Open source)
|
||||
|
||||
Try CloudCLI UI instantly with **npx** (requires **Node.js** v22+):
|
||||
|
||||
```
|
||||
npx @cloudcli-ai/cloudcli
|
||||
```
|
||||
|
||||
Or install **globally** for regular use:
|
||||
|
||||
```
|
||||
npm install -g @cloudcli-ai/cloudcli
|
||||
cloudcli
|
||||
```
|
||||
|
||||
Open `http://localhost:3001` — all your existing sessions are discovered automatically.
|
||||
|
||||
Visit the **[documentation →](https://cloudcli.ai/docs)** for more full configuration options, PM2, remote server setup and more
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Which option is right for you?
|
||||
|
||||
CloudCLI UI is the open source UI layer that powers CloudCLI Cloud. You can self-host it on your own machine, or use CloudCLI Cloud which builds on top of it with a full managed cloud environment, team features, and deeper integrations.
|
||||
|
||||
| | CloudCLI UI (Self-hosted) | CloudCLI Cloud |
|
||||
|---|---|---|
|
||||
| **Best for** | Developers who want a full UI for local agent sessions on their own machine | Teams and developers who want agents running in the cloud, accessible from anywhere |
|
||||
| **How you access it** | Browser via `[yourip]:port` | Browser, any IDE, REST API, n8n |
|
||||
| **Setup** | `npx @cloudcli-ai/cloudcli` | No setup required |
|
||||
| **Machine needs to stay on** | Yes | No |
|
||||
| **Mobile access** | Any browser on your network | Any device, native app coming |
|
||||
| **Sessions available** | All sessions auto-discovered from `~/.claude` | All sessions within your cloud environment |
|
||||
| **Agents supported** | Claude Code, Cursor CLI, Codex, Gemini CLI | Claude Code, Cursor CLI, Codex, Gemini CLI |
|
||||
| **File explorer and Git** | Yes, built into the UI | Yes, built into the UI |
|
||||
| **MCP configuration** | Managed via UI, synced with your local `~/.claude` config | Managed via UI |
|
||||
| **IDE access** | Your local IDE | Any IDE connected to your cloud environment |
|
||||
| **REST API** | Yes | Yes |
|
||||
| **n8n node** | No | Yes |
|
||||
| **Team sharing** | No | Yes |
|
||||
| **Platform cost** | Free, open source | Starts at $7/month |
|
||||
|
||||
> Both options use your own AI subscriptions (Claude, Cursor, etc.) — CloudCLI provides the environment, not the AI.
|
||||
|
||||
---
|
||||
|
||||
## Security & Tools Configuration
|
||||
|
||||
**Important Notice**: All Claude Code tools are **disabled by default**. This prevents potentially harmful operations from running automatically.
|
||||
|
||||
### Enabling Tools
|
||||
|
||||
To use Claude Code's full functionality, you'll need to manually enable tools:
|
||||
|
||||
1. **Open Tools Settings** - Click the gear icon in the sidebar
|
||||
2. **Enable Selectively** - Turn on only the tools you need
|
||||
3. **Apply Settings** - Your preferences are saved locally
|
||||
|
||||
**Recommended approach**: Start with basic tools enabled and add more as needed. You can always adjust these settings later.
|
||||
|
||||
---
|
||||
|
||||
## Plugins
|
||||
|
||||
CloudCLI has a plugin system that lets you add custom tabs with their own frontend UI and optional Node.js backend. Install plugins from git repos directly in **Settings > Plugins**, or build your own.
|
||||
|
||||
### Available Plugins
|
||||
|
||||
| Plugin | Description |
|
||||
|---|---|
|
||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Shows file counts, lines of code, file-type breakdown, largest files, and recently modified files for your current project |
|
||||
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Full xterm.js terminal with multi-tab support|
|
||||
|
||||
### Build Your Own
|
||||
|
||||
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — fork this repo to create your own plugin. It includes a working example with frontend rendering, live context updates, and RPC communication to a backend server.
|
||||
|
||||
**[Plugin Documentation →](https://cloudcli.ai/docs/plugin-overview)** — full guide to the plugin API, manifest format, security model, and more.
|
||||
|
||||
---
|
||||
## FAQ
|
||||
|
||||
<details>
|
||||
<summary>How is this different from Claude Code Remote Control?</summary>
|
||||
|
||||
Claude Code Remote Control lets you send messages to a session already running in your local terminal. Your machine has to stay on, your terminal has to stay open, and sessions time out after roughly 10 minutes without a network connection.
|
||||
|
||||
CloudCLI UI and CloudCLI Cloud extend Claude Code rather than sit alongside it — your MCP servers, permissions, settings, and sessions are the exact same ones Claude Code uses natively. Nothing is duplicated or managed separately.
|
||||
|
||||
Here's what that means in practice:
|
||||
|
||||
- **All your sessions, not just one** — CloudCLI UI auto-discovers every session from your `~/.claude` folder. Remote Control only exposes the single active session to make it available in the Claude mobile app.
|
||||
- **Your settings are your settings** — MCP servers, tool permissions, and project config you change in CloudCLI UI are written directly to your Claude Code config and take effect immediately, and vice versa.
|
||||
- **Works with more agents** — Claude Code, Cursor CLI, Codex, and Gemini CLI, not just Claude Code.
|
||||
- **Full UI, not just a chat window** — file explorer, Git integration, MCP management, and a shell terminal are all built in.
|
||||
- **CloudCLI Cloud runs in the cloud** — close your laptop, the agent keeps running. No terminal to babysit, no machine to keep awake.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Do I need to pay for an AI subscription separately?</summary>
|
||||
|
||||
Yes. CloudCLI provides the environment, not the AI. You bring your own Claude, Cursor, Codex, or Gemini subscription. CloudCLI Cloud starts at $7/month for the hosted environment on top of that.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Can I use CloudCLI UI on my phone?</summary>
|
||||
|
||||
Yes. For self-hosted, run the server on your machine and open `[yourip]:port` in any browser on your network. For CloudCLI Cloud, open it from any device — no VPN, no port forwarding, no setup. A native app is also in the works.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Will changes I make in the UI affect my local Claude Code setup?</summary>
|
||||
|
||||
Yes, for self-hosted. CloudCLI UI reads from and writes to the same `~/.claude` config that Claude Code uses natively. MCP servers you add via the UI show up in Claude Code immediately and vice versa.
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Community & Support
|
||||
|
||||
- **[Documentation](https://cloudcli.ai/docs)** — installation, configuration, features, and troubleshooting
|
||||
- **[Discord](https://discord.gg/buxwujPNRE)** — get help and connect with other users
|
||||
- **[GitHub Issues](https://github.com/siteboon/claudecodeui/issues)** — bug reports and feature requests
|
||||
- **[Contributing Guide](https://github.com/siteboon/claudecodeui/blob/main/CONTRIBUTING.md)** — how to contribute to the project
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later) — see [LICENSE](https://github.com/siteboon/claudecodeui/blob/main/LICENSE) for the full text, including additional terms under Section 7.
|
||||
|
||||
This project is open source and free to use, modify, and distribute under the AGPL-3.0-or-later license. If you modify this software and run it as a network service, you must make your modified source code available to users of that service.
|
||||
|
||||
CloudCLI UI - (https://cloudcli.ai).
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
### Built With
|
||||
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic's official CLI
|
||||
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursor's official CLI
|
||||
- **[Codex](https://developers.openai.com/codex)** - OpenAI Codex
|
||||
- **[Gemini-CLI](https://geminicli.com/)** - Google Gemini CLI
|
||||
- **[React](https://react.dev/)** - User interface library
|
||||
- **[Vite](https://vitejs.dev/)** - Fast build tool and dev server
|
||||
- **[Tailwind CSS](https://tailwindcss.com/)** - Utility-first CSS framework
|
||||
- **[CodeMirror](https://codemirror.net/)** - Advanced code editor
|
||||
- **[TaskMaster AI](https://github.com/eyaltoledano/claude-task-master)** *(Optional)* - AI-powered project management and task planning
|
||||
|
||||
|
||||
### Sponsors
|
||||
- [Siteboon - AI powered website builder](https://siteboon.ai)
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<strong>Made with care for the Claude Code, Cursor and Codex community.</strong>
|
||||
</div>
|
||||
@@ -1,2 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import('@cloudcli-ai/cloudcli/dist-server/server/cli.js');
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from '@cloudcli-ai/cloudcli';
|
||||
export { default } from '@cloudcli-ai/cloudcli';
|
||||
@@ -1,43 +0,0 @@
|
||||
{
|
||||
"name": "@siteboon/claude-code-ui",
|
||||
"version": "2.0.0",
|
||||
"description": "This package has moved to @cloudcli-ai/cloudcli",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"bin": {
|
||||
"claude-code-ui": "./bin.js",
|
||||
"cloudcli": "./bin.js"
|
||||
},
|
||||
"homepage": "https://cloudcli.ai",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/siteboon/claudecodeui.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/siteboon/claudecodeui/issues"
|
||||
},
|
||||
"keywords": [
|
||||
"claude code",
|
||||
"claude-code",
|
||||
"claude-code-ui",
|
||||
"cloudcli",
|
||||
"codex",
|
||||
"gemini",
|
||||
"gemini-cli",
|
||||
"cursor",
|
||||
"cursor-cli",
|
||||
"anthropic",
|
||||
"openai",
|
||||
"google",
|
||||
"coding-agent",
|
||||
"web-ui",
|
||||
"ui",
|
||||
"mobile IDE"
|
||||
],
|
||||
"author": "CloudCLI UI Contributors",
|
||||
"dependencies": {
|
||||
"@cloudcli-ai/cloudcli": "*"
|
||||
},
|
||||
"deprecated": "This package has been renamed to @cloudcli-ai/cloudcli. Please install @cloudcli-ai/cloudcli instead.",
|
||||
"license": "AGPL-3.0-or-later"
|
||||
}
|
||||
@@ -18,22 +18,14 @@ import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { CLAUDE_MODELS } from '../shared/modelConstants.js';
|
||||
import {
|
||||
createNotificationEvent,
|
||||
notifyRunFailed,
|
||||
notifyRunStopped,
|
||||
notifyUserIfEnabled
|
||||
} from './services/notification-orchestrator.js';
|
||||
import { claudeAdapter } from './providers/claude/adapter.js';
|
||||
import { createNormalizedMessage } from './providers/types.js';
|
||||
import { getStatusChecker } from './providers/registry.js';
|
||||
import { createNotificationEvent, notifyUserIfEnabled } from './services/notification-orchestrator.js';
|
||||
|
||||
const activeSessions = new Map();
|
||||
const pendingToolApprovals = new Map();
|
||||
|
||||
const TOOL_APPROVAL_TIMEOUT_MS = parseInt(process.env.CLAUDE_TOOL_APPROVAL_TIMEOUT_MS, 10) || 55000;
|
||||
|
||||
const TOOLS_REQUIRING_INTERACTION = new Set(['AskUserQuestion', 'ExitPlanMode']);
|
||||
const TOOLS_REQUIRING_INTERACTION = new Set(['AskUserQuestion']);
|
||||
|
||||
function createRequestId() {
|
||||
if (typeof crypto.randomUUID === 'function') {
|
||||
@@ -43,7 +35,7 @@ function createRequestId() {
|
||||
}
|
||||
|
||||
function waitForToolApproval(requestId, options = {}) {
|
||||
const { timeoutMs = TOOL_APPROVAL_TIMEOUT_MS, signal, onCancel, metadata } = options;
|
||||
const { timeoutMs = TOOL_APPROVAL_TIMEOUT_MS, signal, onCancel } = options;
|
||||
|
||||
return new Promise(resolve => {
|
||||
let settled = false;
|
||||
@@ -87,14 +79,9 @@ function waitForToolApproval(requestId, options = {}) {
|
||||
signal.addEventListener('abort', abortHandler, { once: true });
|
||||
}
|
||||
|
||||
const resolver = (decision) => {
|
||||
pendingToolApprovals.set(requestId, (decision) => {
|
||||
finalize(decision);
|
||||
};
|
||||
// Attach metadata for getPendingApprovalsForSession lookup
|
||||
if (metadata) {
|
||||
Object.assign(resolver, metadata);
|
||||
}
|
||||
pendingToolApprovals.set(requestId, resolver);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -145,14 +132,10 @@ function matchesToolPermission(entry, toolName, input) {
|
||||
* @returns {Object} SDK-compatible options
|
||||
*/
|
||||
function mapCliOptionsToSDK(options = {}) {
|
||||
const { sessionId, cwd, toolsSettings, permissionMode } = options;
|
||||
const { sessionId, cwd, toolsSettings, permissionMode, images } = options;
|
||||
|
||||
const sdkOptions = {};
|
||||
|
||||
if (process.env.CLAUDE_CLI_PATH) {
|
||||
sdkOptions.pathToClaudeCodeExecutable = process.env.CLAUDE_CLI_PATH;
|
||||
}
|
||||
|
||||
// Map working directory
|
||||
if (cwd) {
|
||||
sdkOptions.cwd = cwd;
|
||||
@@ -200,7 +183,7 @@ function mapCliOptionsToSDK(options = {}) {
|
||||
// Map model (default to sonnet)
|
||||
// Valid models: sonnet, opus, haiku, opusplan, sonnet[1m]
|
||||
sdkOptions.model = options.model || CLAUDE_MODELS.DEFAULT;
|
||||
// Model logged at query start below
|
||||
console.log(`Using model: ${sdkOptions.model}`);
|
||||
|
||||
// Map system prompt configuration
|
||||
sdkOptions.systemPrompt = {
|
||||
@@ -227,14 +210,13 @@ function mapCliOptionsToSDK(options = {}) {
|
||||
* @param {Array<string>} tempImagePaths - Temp image file paths for cleanup
|
||||
* @param {string} tempDir - Temp directory for cleanup
|
||||
*/
|
||||
function addSession(sessionId, queryInstance, tempImagePaths = [], tempDir = null, writer = null) {
|
||||
function addSession(sessionId, queryInstance, tempImagePaths = [], tempDir = null) {
|
||||
activeSessions.set(sessionId, {
|
||||
instance: queryInstance,
|
||||
startTime: Date.now(),
|
||||
status: 'active',
|
||||
tempImagePaths,
|
||||
tempDir,
|
||||
writer
|
||||
tempDir
|
||||
});
|
||||
}
|
||||
|
||||
@@ -311,7 +293,7 @@ function extractTokenBudget(resultMessage) {
|
||||
// This is the user's budget limit, not the model's context window
|
||||
const contextWindow = parseInt(process.env.CONTEXT_WINDOW) || 160000;
|
||||
|
||||
// Token calc logged via token-budget WS event
|
||||
console.log(`Token calculation: input=${inputTokens}, output=${outputTokens}, cache=${cacheReadTokens + cacheCreationTokens}, total=${totalUsed}/${contextWindow}`);
|
||||
|
||||
return {
|
||||
used: totalUsed,
|
||||
@@ -367,7 +349,7 @@ async function handleImages(command, images, cwd) {
|
||||
modifiedCommand = command + imageNote;
|
||||
}
|
||||
|
||||
// Images processed
|
||||
console.log(`Processed ${tempImagePaths.length} images to temp directory: ${tempDir}`);
|
||||
return { modifiedCommand, tempImagePaths, tempDir };
|
||||
} catch (error) {
|
||||
console.error('Error processing images for SDK:', error);
|
||||
@@ -400,7 +382,7 @@ async function cleanupTempFiles(tempImagePaths, tempDir) {
|
||||
);
|
||||
}
|
||||
|
||||
// Temp files cleaned
|
||||
console.log(`Cleaned up ${tempImagePaths.length} temp image files`);
|
||||
} catch (error) {
|
||||
console.error('Error during temp file cleanup:', error);
|
||||
}
|
||||
@@ -420,7 +402,7 @@ async function loadMcpConfig(cwd) {
|
||||
await fs.access(claudeConfigPath);
|
||||
} catch (error) {
|
||||
// File doesn't exist, return null
|
||||
// No config file
|
||||
console.log('No ~/.claude.json found, proceeding without MCP servers');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -440,7 +422,7 @@ async function loadMcpConfig(cwd) {
|
||||
// Add global MCP servers
|
||||
if (claudeConfig.mcpServers && typeof claudeConfig.mcpServers === 'object') {
|
||||
mcpServers = { ...claudeConfig.mcpServers };
|
||||
// Global MCP servers loaded
|
||||
console.log(`Loaded ${Object.keys(mcpServers).length} global MCP servers`);
|
||||
}
|
||||
|
||||
// Add/override with project-specific MCP servers
|
||||
@@ -448,14 +430,17 @@ async function loadMcpConfig(cwd) {
|
||||
const projectConfig = claudeConfig.claudeProjects[cwd];
|
||||
if (projectConfig && projectConfig.mcpServers && typeof projectConfig.mcpServers === 'object') {
|
||||
mcpServers = { ...mcpServers, ...projectConfig.mcpServers };
|
||||
// Project MCP servers merged
|
||||
console.log(`Loaded ${Object.keys(projectConfig.mcpServers).length} project-specific MCP servers`);
|
||||
}
|
||||
}
|
||||
|
||||
// Return null if no servers found
|
||||
if (Object.keys(mcpServers).length === 0) {
|
||||
console.log('No MCP servers configured');
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log(`Total MCP servers loaded: ${Object.keys(mcpServers).length}`);
|
||||
return mcpServers;
|
||||
} catch (error) {
|
||||
console.error('Error loading MCP config:', error.message);
|
||||
@@ -471,7 +456,7 @@ async function loadMcpConfig(cwd) {
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function queryClaudeSDK(command, options = {}, ws) {
|
||||
const { sessionId, sessionSummary } = options;
|
||||
const { sessionId } = options;
|
||||
let capturedSessionId = sessionId;
|
||||
let sessionCreatedSent = false;
|
||||
let tempImagePaths = [];
|
||||
@@ -511,13 +496,29 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
sessionId: capturedSessionId || sessionId || null,
|
||||
kind: 'action_required',
|
||||
code: 'agent.notification',
|
||||
meta: { message, sessionName: sessionSummary },
|
||||
meta: { message },
|
||||
severity: 'warning',
|
||||
requiresUserAction: true,
|
||||
dedupeKey: `claude:hook:notification:${capturedSessionId || sessionId || 'none'}:${message}`
|
||||
}));
|
||||
return {};
|
||||
}]
|
||||
}],
|
||||
Stop: [{
|
||||
matcher: '',
|
||||
hooks: [async (input) => {
|
||||
const stopReason = typeof input?.stop_reason === 'string' ? input.stop_reason : 'completed';
|
||||
emitNotification(createNotificationEvent({
|
||||
provider: 'claude',
|
||||
sessionId: capturedSessionId || sessionId || null,
|
||||
kind: 'stop',
|
||||
code: 'run.stopped',
|
||||
meta: { stopReason },
|
||||
severity: 'info',
|
||||
dedupeKey: `claude:hook:stop:${capturedSessionId || sessionId || 'none'}:${stopReason}`
|
||||
}));
|
||||
return {};
|
||||
}]
|
||||
}]
|
||||
};
|
||||
|
||||
@@ -545,13 +546,19 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
}
|
||||
|
||||
const requestId = createRequestId();
|
||||
ws.send(createNormalizedMessage({ kind: 'permission_request', requestId, toolName, input, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
|
||||
ws.send({
|
||||
type: 'claude-permission-request',
|
||||
requestId,
|
||||
toolName,
|
||||
input,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
emitNotification(createNotificationEvent({
|
||||
provider: 'claude',
|
||||
sessionId: capturedSessionId || sessionId || null,
|
||||
kind: 'action_required',
|
||||
code: 'permission.required',
|
||||
meta: { toolName, sessionName: sessionSummary },
|
||||
meta: { toolName },
|
||||
severity: 'warning',
|
||||
requiresUserAction: true,
|
||||
dedupeKey: `claude:permission:${capturedSessionId || sessionId || 'none'}:${requestId}`
|
||||
@@ -560,14 +567,13 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
const decision = await waitForToolApproval(requestId, {
|
||||
timeoutMs: requiresInteraction ? 0 : undefined,
|
||||
signal: context?.signal,
|
||||
metadata: {
|
||||
_sessionId: capturedSessionId || sessionId || null,
|
||||
_toolName: toolName,
|
||||
_input: input,
|
||||
_receivedAt: new Date(),
|
||||
},
|
||||
onCancel: (reason) => {
|
||||
ws.send(createNormalizedMessage({ kind: 'permission_cancelled', requestId, reason, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
|
||||
ws.send({
|
||||
type: 'claude-permission-cancelled',
|
||||
requestId,
|
||||
reason,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
}
|
||||
});
|
||||
if (!decision) {
|
||||
@@ -623,7 +629,7 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
|
||||
// Track the query instance for abort capability
|
||||
if (capturedSessionId) {
|
||||
addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
|
||||
addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir);
|
||||
}
|
||||
|
||||
// Process streaming messages
|
||||
@@ -633,7 +639,7 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
if (message.session_id && !capturedSessionId) {
|
||||
|
||||
capturedSessionId = message.session_id;
|
||||
addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
|
||||
addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir);
|
||||
|
||||
// Set session ID on writer
|
||||
if (ws.setSessionId && typeof ws.setSessionId === 'function') {
|
||||
@@ -643,35 +649,39 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
// Send session-created event only once for new sessions
|
||||
if (!sessionId && !sessionCreatedSent) {
|
||||
sessionCreatedSent = true;
|
||||
ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'claude' }));
|
||||
ws.send({
|
||||
type: 'session-created',
|
||||
sessionId: capturedSessionId
|
||||
});
|
||||
} else {
|
||||
console.log('Not sending session-created. sessionId:', sessionId, 'sessionCreatedSent:', sessionCreatedSent);
|
||||
}
|
||||
} else {
|
||||
// session_id already captured
|
||||
console.log('No session_id in message or already captured. message.session_id:', message.session_id, 'capturedSessionId:', capturedSessionId);
|
||||
}
|
||||
|
||||
// Transform and normalize message via adapter
|
||||
// Transform and send message to WebSocket
|
||||
const transformedMessage = transformMessage(message);
|
||||
const sid = capturedSessionId || sessionId || null;
|
||||
|
||||
// Use adapter to normalize SDK events into NormalizedMessage[]
|
||||
const normalized = claudeAdapter.normalizeMessage(transformedMessage, sid);
|
||||
for (const msg of normalized) {
|
||||
// Preserve parentToolUseId from SDK wrapper for subagent tool grouping
|
||||
if (transformedMessage.parentToolUseId && !msg.parentToolUseId) {
|
||||
msg.parentToolUseId = transformedMessage.parentToolUseId;
|
||||
}
|
||||
ws.send(msg);
|
||||
}
|
||||
ws.send({
|
||||
type: 'claude-response',
|
||||
data: transformedMessage,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
|
||||
// Extract and send token budget updates from result messages
|
||||
if (message.type === 'result') {
|
||||
const models = Object.keys(message.modelUsage || {});
|
||||
if (models.length > 0) {
|
||||
// Model info available in result message
|
||||
console.log("---> Model was sent using:", models);
|
||||
}
|
||||
const tokenBudgetData = extractTokenBudget(message);
|
||||
if (tokenBudgetData) {
|
||||
ws.send(createNormalizedMessage({ kind: 'status', text: 'token_budget', tokenBudget: tokenBudgetData, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
|
||||
const tokenBudget = extractTokenBudget(message);
|
||||
if (tokenBudget) {
|
||||
console.log('Token budget from modelUsage:', tokenBudget);
|
||||
ws.send({
|
||||
type: 'token-budget',
|
||||
data: tokenBudget,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -685,15 +695,14 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
await cleanupTempFiles(tempImagePaths, tempDir);
|
||||
|
||||
// Send completion event
|
||||
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: 0, isNewSession: !sessionId && !!command, sessionId: capturedSessionId, provider: 'claude' }));
|
||||
notifyRunStopped({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'claude',
|
||||
sessionId: capturedSessionId || sessionId || null,
|
||||
sessionName: sessionSummary,
|
||||
stopReason: 'completed'
|
||||
console.log('Streaming complete, sending claude-complete event');
|
||||
ws.send({
|
||||
type: 'claude-complete',
|
||||
sessionId: capturedSessionId,
|
||||
exitCode: 0,
|
||||
isNewSession: !sessionId && !!command
|
||||
});
|
||||
// Complete
|
||||
console.log('claude-complete event sent');
|
||||
|
||||
} catch (error) {
|
||||
console.error('SDK query error:', error);
|
||||
@@ -706,21 +715,23 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
||||
// Clean up temporary image files on error
|
||||
await cleanupTempFiles(tempImagePaths, tempDir);
|
||||
|
||||
// Check if Claude CLI is installed for a clearer error message
|
||||
const installed = getStatusChecker('claude')?.checkInstalled() ?? true;
|
||||
const errorContent = !installed
|
||||
? 'Claude Code is not installed. Please install it first: https://docs.anthropic.com/en/docs/claude-code'
|
||||
: error.message;
|
||||
|
||||
// Send error to WebSocket
|
||||
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
|
||||
notifyRunFailed({
|
||||
userId: ws?.userId || null,
|
||||
ws.send({
|
||||
type: 'claude-error',
|
||||
error: error.message,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
emitNotification(createNotificationEvent({
|
||||
provider: 'claude',
|
||||
sessionId: capturedSessionId || sessionId || null,
|
||||
sessionName: sessionSummary,
|
||||
error
|
||||
});
|
||||
kind: 'error',
|
||||
code: 'run.failed',
|
||||
meta: { error: error.message },
|
||||
severity: 'error',
|
||||
dedupeKey: `claude:error:${capturedSessionId || sessionId || 'none'}:${error.message}`
|
||||
}));
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -777,50 +788,11 @@ function getActiveClaudeSDKSessions() {
|
||||
return getAllSessions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pending tool approvals for a specific session.
|
||||
* @param {string} sessionId - The session ID
|
||||
* @returns {Array} Array of pending permission request objects
|
||||
*/
|
||||
function getPendingApprovalsForSession(sessionId) {
|
||||
const pending = [];
|
||||
for (const [requestId, resolver] of pendingToolApprovals.entries()) {
|
||||
if (resolver._sessionId === sessionId) {
|
||||
pending.push({
|
||||
requestId,
|
||||
toolName: resolver._toolName || 'UnknownTool',
|
||||
input: resolver._input,
|
||||
context: resolver._context,
|
||||
sessionId,
|
||||
receivedAt: resolver._receivedAt || new Date(),
|
||||
});
|
||||
}
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconnect a session's WebSocketWriter to a new raw WebSocket.
|
||||
* Called when client reconnects (e.g. page refresh) while SDK is still running.
|
||||
* @param {string} sessionId - The session ID
|
||||
* @param {Object} newRawWs - The new raw WebSocket connection
|
||||
* @returns {boolean} True if writer was successfully reconnected
|
||||
*/
|
||||
function reconnectSessionWriter(sessionId, newRawWs) {
|
||||
const session = getSession(sessionId);
|
||||
if (!session?.writer?.updateWebSocket) return false;
|
||||
session.writer.updateWebSocket(newRawWs);
|
||||
console.log(`[RECONNECT] Writer swapped for session ${sessionId}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Export public API
|
||||
export {
|
||||
queryClaudeSDK,
|
||||
abortClaudeSDKSession,
|
||||
isClaudeSDKSessionActive,
|
||||
getActiveClaudeSDKSessions,
|
||||
resolveToolApproval,
|
||||
getPendingApprovalsForSession,
|
||||
reconnectSessionWriter
|
||||
resolveToolApproval
|
||||
};
|
||||
|
||||
416
server/cli.js
416
server/cli.js
@@ -1,13 +1,12 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* CloudCLI CLI
|
||||
* Claude Code UI CLI
|
||||
*
|
||||
* Provides command-line utilities for managing CloudCLI
|
||||
* Provides command-line utilities for managing Claude Code UI
|
||||
*
|
||||
* Commands:
|
||||
* (no args) - Start the server (default)
|
||||
* start - Start the server
|
||||
* sandbox - Manage Docker sandbox environments
|
||||
* status - Show configuration and data locations
|
||||
* help - Show help information
|
||||
* version - Show version information
|
||||
@@ -16,12 +15,11 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname } from 'path';
|
||||
|
||||
const __dirname = getModuleDir(import.meta.url);
|
||||
// The CLI is compiled into dist-server/server, but it still needs to read the top-level
|
||||
// package.json and .env file. Resolving the app root once keeps those lookups stable.
|
||||
const APP_ROOT = findAppRoot(__dirname);
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
// ANSI color codes for terminal output
|
||||
const colors = {
|
||||
@@ -51,16 +49,13 @@ const c = {
|
||||
};
|
||||
|
||||
// Load package.json for version info
|
||||
const packageJsonPath = path.join(APP_ROOT, 'package.json');
|
||||
const packageJsonPath = path.join(__dirname, '../package.json');
|
||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
||||
// Match the runtime fallback in load-env.js so "cloudcli status" reports the same default
|
||||
// database location that the backend will actually use when no DATABASE_PATH is configured.
|
||||
const DEFAULT_DATABASE_PATH = path.join(os.homedir(), '.cloudcli', 'auth.db');
|
||||
|
||||
// Load environment variables from .env file if it exists
|
||||
function loadEnvFile() {
|
||||
try {
|
||||
const envPath = path.join(APP_ROOT, '.env');
|
||||
const envPath = path.join(__dirname, '../.env');
|
||||
const envFile = fs.readFileSync(envPath, 'utf8');
|
||||
envFile.split('\n').forEach(line => {
|
||||
const trimmedLine = line.trim();
|
||||
@@ -79,17 +74,17 @@ function loadEnvFile() {
|
||||
// Get the database path (same logic as db.js)
|
||||
function getDatabasePath() {
|
||||
loadEnvFile();
|
||||
return process.env.DATABASE_PATH || DEFAULT_DATABASE_PATH;
|
||||
return process.env.DATABASE_PATH || path.join(__dirname, 'database', 'auth.db');
|
||||
}
|
||||
|
||||
// Get the installation directory
|
||||
function getInstallDir() {
|
||||
return APP_ROOT;
|
||||
return path.join(__dirname, '..');
|
||||
}
|
||||
|
||||
// Show status command
|
||||
function showStatus() {
|
||||
console.log(`\n${c.bright('CloudCLI UI - Status')}\n`);
|
||||
console.log(`\n${c.bright('Claude Code UI - Status')}\n`);
|
||||
console.log(c.dim('═'.repeat(60)));
|
||||
|
||||
// Version info
|
||||
@@ -115,7 +110,7 @@ function showStatus() {
|
||||
|
||||
// Environment variables
|
||||
console.log(`\n${c.info('[INFO]')} Configuration:`);
|
||||
console.log(` SERVER_PORT: ${c.bright(process.env.SERVER_PORT || process.env.PORT || '3001')} ${c.dim(process.env.SERVER_PORT || process.env.PORT ? '' : '(default)')}`);
|
||||
console.log(` PORT: ${c.bright(process.env.PORT || '3001')} ${c.dim(process.env.PORT ? '' : '(default)')}`);
|
||||
console.log(` DATABASE_PATH: ${c.dim(process.env.DATABASE_PATH || '(using default location)')}`);
|
||||
console.log(` CLAUDE_CLI_PATH: ${c.dim(process.env.CLAUDE_CLI_PATH || 'claude (default)')}`);
|
||||
console.log(` CONTEXT_WINDOW: ${c.dim(process.env.CONTEXT_WINDOW || '160000 (default)')}`);
|
||||
@@ -128,7 +123,7 @@ function showStatus() {
|
||||
console.log(` Status: ${projectsExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not found')}`);
|
||||
|
||||
// Config file location
|
||||
const envFilePath = path.join(APP_ROOT, '.env');
|
||||
const envFilePath = path.join(__dirname, '../.env');
|
||||
const envExists = fs.existsSync(envFilePath);
|
||||
console.log(`\n${c.info('[INFO]')} Configuration File:`);
|
||||
console.log(` ${c.dim(envFilePath)}`);
|
||||
@@ -139,14 +134,14 @@ function showStatus() {
|
||||
console.log(` ${c.dim('>')} Use ${c.bright('cloudcli --port 8080')} to run on a custom port`);
|
||||
console.log(` ${c.dim('>')} Use ${c.bright('cloudcli --database-path /path/to/db')} for custom database`);
|
||||
console.log(` ${c.dim('>')} Run ${c.bright('cloudcli help')} for all options`);
|
||||
console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
|
||||
console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.PORT || '3001'}\n`);
|
||||
}
|
||||
|
||||
// Show help
|
||||
function showHelp() {
|
||||
console.log(`
|
||||
╔═══════════════════════════════════════════════════════════════╗
|
||||
║ CloudCLI - Command Line Tool ║
|
||||
║ Claude Code UI - Command Line Tool ║
|
||||
╚═══════════════════════════════════════════════════════════════╝
|
||||
|
||||
Usage:
|
||||
@@ -154,8 +149,7 @@ Usage:
|
||||
cloudcli [command] [options]
|
||||
|
||||
Commands:
|
||||
start Start the CloudCLI server (default)
|
||||
sandbox Manage Docker sandbox environments
|
||||
start Start the Claude Code UI server (default)
|
||||
status Show configuration and data locations
|
||||
update Update to the latest version
|
||||
help Show this help information
|
||||
@@ -170,12 +164,12 @@ Options:
|
||||
Examples:
|
||||
$ cloudcli # Start with defaults
|
||||
$ cloudcli --port 8080 # Start on port 8080
|
||||
$ cloudcli sandbox ~/my-project # Run in a Docker sandbox
|
||||
$ cloudcli -p 3000 # Short form for port
|
||||
$ cloudcli start --port 4000 # Explicit start command
|
||||
$ cloudcli status # Show configuration
|
||||
|
||||
Environment Variables:
|
||||
SERVER_PORT Set server port (default: 3001)
|
||||
PORT Set server port (default: 3001) (LEGACY)
|
||||
PORT Set server port (default: 3001)
|
||||
DATABASE_PATH Set custom database location
|
||||
CLAUDE_CLI_PATH Set custom Claude CLI path
|
||||
CONTEXT_WINDOW Set context window size (default: 160000)
|
||||
@@ -208,7 +202,7 @@ function isNewerVersion(v1, v2) {
|
||||
async function checkForUpdates(silent = false) {
|
||||
try {
|
||||
const { execSync } = await import('child_process');
|
||||
const latestVersion = execSync('npm show @cloudcli-ai/cloudcli version', { encoding: 'utf8' }).trim();
|
||||
const latestVersion = execSync('npm show @siteboon/claude-code-ui version', { encoding: 'utf8' }).trim();
|
||||
const currentVersion = packageJson.version;
|
||||
|
||||
if (isNewerVersion(latestVersion, currentVersion)) {
|
||||
@@ -241,361 +235,14 @@ async function updatePackage() {
|
||||
}
|
||||
|
||||
console.log(`${c.info('[INFO]')} Updating from ${currentVersion} to ${latestVersion}...`);
|
||||
execSync('npm update -g @cloudcli-ai/cloudcli', { stdio: 'inherit' });
|
||||
execSync('npm update -g @siteboon/claude-code-ui', { stdio: 'inherit' });
|
||||
console.log(`${c.ok('[OK]')} Update complete! Restart cloudcli to use the new version.`);
|
||||
} catch (e) {
|
||||
console.error(`${c.error('[ERROR]')} Update failed: ${e.message}`);
|
||||
console.log(`${c.tip('[TIP]')} Try running manually: npm update -g @cloudcli-ai/cloudcli`);
|
||||
console.log(`${c.tip('[TIP]')} Try running manually: npm update -g @siteboon/claude-code-ui`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Sandbox command ─────────────────────────────────────────
|
||||
|
||||
const SANDBOX_TEMPLATES = {
|
||||
claude: 'docker.io/cloudcliai/sandbox:claude-code',
|
||||
codex: 'docker.io/cloudcliai/sandbox:codex',
|
||||
gemini: 'docker.io/cloudcliai/sandbox:gemini',
|
||||
};
|
||||
|
||||
const SANDBOX_SECRETS = {
|
||||
claude: 'anthropic',
|
||||
codex: 'openai',
|
||||
gemini: 'google',
|
||||
};
|
||||
|
||||
function parseSandboxArgs(args) {
|
||||
const result = {
|
||||
subcommand: null,
|
||||
workspace: null,
|
||||
agent: 'claude',
|
||||
name: null,
|
||||
port: 3001,
|
||||
template: null,
|
||||
env: [],
|
||||
};
|
||||
|
||||
const subcommands = ['ls', 'stop', 'start', 'rm', 'logs', 'help'];
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (i === 0 && subcommands.includes(arg)) {
|
||||
result.subcommand = arg;
|
||||
} else if (arg === '--agent' || arg === '-a') {
|
||||
result.agent = args[++i];
|
||||
} else if (arg === '--name' || arg === '-n') {
|
||||
result.name = args[++i];
|
||||
} else if (arg === '--port') {
|
||||
result.port = parseInt(args[++i], 10);
|
||||
} else if (arg === '--template' || arg === '-t') {
|
||||
result.template = args[++i];
|
||||
} else if (arg === '--env' || arg === '-e') {
|
||||
result.env.push(args[++i]);
|
||||
} else if (!arg.startsWith('-')) {
|
||||
if (!result.subcommand) {
|
||||
result.workspace = arg;
|
||||
} else {
|
||||
result.name = arg; // for stop/start/rm/logs <name>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Default subcommand based on what we got
|
||||
if (!result.subcommand) {
|
||||
result.subcommand = 'create';
|
||||
}
|
||||
|
||||
// Derive name from workspace path if not set
|
||||
if (!result.name && result.workspace) {
|
||||
result.name = path.basename(path.resolve(result.workspace.replace(/^~/, os.homedir())));
|
||||
}
|
||||
|
||||
// Default template from agent
|
||||
if (!result.template) {
|
||||
result.template = SANDBOX_TEMPLATES[result.agent] || SANDBOX_TEMPLATES.claude;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function showSandboxHelp() {
|
||||
console.log(`
|
||||
${c.bright('CloudCLI Sandbox')} — Run CloudCLI inside Docker Sandboxes
|
||||
|
||||
Usage:
|
||||
cloudcli sandbox <workspace> Create and start a sandbox
|
||||
cloudcli sandbox <subcommand> [name] Manage sandboxes
|
||||
|
||||
Subcommands:
|
||||
${c.bright('(default)')} Create a sandbox and start the web UI
|
||||
${c.bright('ls')} List all sandboxes
|
||||
${c.bright('start')} Restart a stopped sandbox and re-launch the web UI
|
||||
${c.bright('stop')} Stop a sandbox (preserves state)
|
||||
${c.bright('rm')} Remove a sandbox
|
||||
${c.bright('logs')} Show CloudCLI server logs
|
||||
${c.bright('help')} Show this help
|
||||
|
||||
Options:
|
||||
-a, --agent <agent> Agent to use: claude, codex, gemini (default: claude)
|
||||
-n, --name <name> Sandbox name (default: derived from workspace folder)
|
||||
-t, --template <image> Custom template image
|
||||
-e, --env <KEY=VALUE> Set environment variable (repeatable)
|
||||
--port <port> Host port for the web UI (default: 3001)
|
||||
|
||||
Examples:
|
||||
$ cloudcli sandbox ~/my-project
|
||||
$ cloudcli sandbox ~/my-project --agent codex --port 8080
|
||||
$ cloudcli sandbox ~/my-project --env SERVER_PORT=8080 --env HOST=0.0.0.0
|
||||
$ cloudcli sandbox ls
|
||||
$ cloudcli sandbox stop my-project
|
||||
$ cloudcli sandbox start my-project
|
||||
$ cloudcli sandbox rm my-project
|
||||
|
||||
Prerequisites:
|
||||
1. Install sbx CLI: https://docs.docker.com/ai/sandboxes/get-started/
|
||||
2. Authenticate and store your API key:
|
||||
sbx login
|
||||
sbx secret set -g anthropic # for Claude
|
||||
sbx secret set -g openai # for Codex
|
||||
sbx secret set -g google # for Gemini
|
||||
|
||||
Advanced usage:
|
||||
For branch mode, multiple workspaces, memory limits, network policies,
|
||||
or passing prompts to the agent, use sbx directly with the template:
|
||||
|
||||
sbx run --template docker.io/cloudcliai/sandbox:claude-code claude ~/my-project --branch my-feature
|
||||
sbx run --template docker.io/cloudcliai/sandbox:claude-code claude ~/project ~/libs:ro --memory 8g
|
||||
|
||||
Full Docker Sandboxes docs: https://docs.docker.com/ai/sandboxes/usage/
|
||||
`);
|
||||
}
|
||||
|
||||
async function sandboxCommand(args) {
|
||||
const { execFileSync, spawn: spawnProcess } = await import('child_process');
|
||||
|
||||
// Safe execution — uses execFileSync (no shell) to prevent injection
|
||||
const sbx = (subcmd, opts = {}) => {
|
||||
const result = execFileSync('sbx', subcmd, {
|
||||
encoding: 'utf8',
|
||||
stdio: opts.inherit ? 'inherit' : 'pipe',
|
||||
});
|
||||
return result || '';
|
||||
};
|
||||
|
||||
const opts = parseSandboxArgs(args);
|
||||
|
||||
if (opts.subcommand === 'help') {
|
||||
showSandboxHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate name (alphanumeric, hyphens, underscores only)
|
||||
if (opts.name && !/^[\w-]+$/.test(opts.name)) {
|
||||
console.error(`\n${c.error('❌')} Invalid sandbox name: ${opts.name}`);
|
||||
console.log(` Names may only contain letters, numbers, hyphens, and underscores.\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Check sbx is installed
|
||||
try {
|
||||
sbx(['version']);
|
||||
} catch {
|
||||
console.error(`\n${c.error('❌')} ${c.bright('sbx')} CLI not found.\n`);
|
||||
console.log(` Install it from: ${c.info('https://docs.docker.com/ai/sandboxes/get-started/')}`);
|
||||
console.log(` Then run: ${c.bright('sbx login')}`);
|
||||
console.log(` And store your API key: ${c.bright('sbx secret set -g anthropic')}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
switch (opts.subcommand) {
|
||||
|
||||
case 'ls':
|
||||
sbx(['ls'], { inherit: true });
|
||||
break;
|
||||
|
||||
case 'stop':
|
||||
if (!opts.name) {
|
||||
console.error(`\n${c.error('❌')} Sandbox name required: cloudcli sandbox stop <name>\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
sbx(['stop', opts.name], { inherit: true });
|
||||
break;
|
||||
|
||||
case 'rm':
|
||||
if (!opts.name) {
|
||||
console.error(`\n${c.error('❌')} Sandbox name required: cloudcli sandbox rm <name>\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
sbx(['rm', opts.name], { inherit: true });
|
||||
break;
|
||||
|
||||
case 'logs':
|
||||
if (!opts.name) {
|
||||
console.error(`\n${c.error('❌')} Sandbox name required: cloudcli sandbox logs <name>\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
sbx(['exec', opts.name, 'bash', '-c', 'cat /tmp/cloudcli-ui.log'], { inherit: true });
|
||||
} catch (e) {
|
||||
console.error(`\n${c.error('❌')} Could not read logs: ${e.message || 'Is the sandbox running?'}\n`);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'start': {
|
||||
if (!opts.name) {
|
||||
console.error(`\n${c.error('❌')} Sandbox name required: cloudcli sandbox start <name>\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`\n${c.info('▶')} Starting sandbox ${c.bright(opts.name)}...`);
|
||||
const restartRun = spawnProcess('sbx', ['run', opts.name], {
|
||||
detached: true,
|
||||
stdio: ['ignore', 'ignore', 'ignore'],
|
||||
});
|
||||
restartRun.unref();
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
console.log(`${c.info('▶')} Launching CloudCLI web server...`);
|
||||
sbx(['exec', opts.name, 'bash', '-c', 'cloudcli start --port 3001 &']);
|
||||
|
||||
console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
|
||||
try {
|
||||
sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
|
||||
} catch (e) {
|
||||
const msg = e.stdout || e.stderr || e.message || '';
|
||||
if (msg.includes('address already in use')) {
|
||||
const altPort = opts.port + 1;
|
||||
console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
|
||||
try {
|
||||
sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
|
||||
opts.port = altPort;
|
||||
} catch {
|
||||
console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n${c.ok('✔')} ${c.bright('CloudCLI is ready!')}`);
|
||||
console.log(` ${c.info('→')} ${c.bright(`http://localhost:${opts.port}`)}\n`);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'create': {
|
||||
if (!opts.workspace) {
|
||||
console.error(`\n${c.error('❌')} Workspace path required: cloudcli sandbox <path>\n`);
|
||||
console.log(` Example: ${c.bright('cloudcli sandbox ~/my-project')}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const workspace = opts.workspace.startsWith('~')
|
||||
? opts.workspace.replace(/^~/, os.homedir())
|
||||
: path.resolve(opts.workspace);
|
||||
|
||||
if (!fs.existsSync(workspace)) {
|
||||
console.error(`\n${c.error('❌')} Workspace path not found: ${c.dim(workspace)}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const secret = SANDBOX_SECRETS[opts.agent] || 'anthropic';
|
||||
|
||||
// Check if the required secret is stored
|
||||
try {
|
||||
const secretList = sbx(['secret', 'ls']);
|
||||
if (!secretList.includes(secret)) {
|
||||
console.error(`\n${c.error('❌')} No ${c.bright(secret)} API key found.\n`);
|
||||
console.log(` Run: ${c.bright(`sbx secret set -g ${secret}`)}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
} catch { /* sbx secret ls not available, skip check */ }
|
||||
|
||||
console.log(`\n${c.bright('CloudCLI Sandbox')}`);
|
||||
console.log(c.dim('─'.repeat(50)));
|
||||
console.log(` Agent: ${c.info(opts.agent)} ${c.dim(`(${secret} credentials)`)}`);
|
||||
console.log(` Workspace: ${c.dim(workspace)}`);
|
||||
console.log(` Name: ${c.dim(opts.name)}`);
|
||||
console.log(` Template: ${c.dim(opts.template)}`);
|
||||
console.log(` Port: ${c.dim(String(opts.port))}`);
|
||||
if (opts.env.length > 0) {
|
||||
console.log(` Env: ${c.dim(opts.env.join(', '))}`);
|
||||
}
|
||||
console.log(c.dim('─'.repeat(50)));
|
||||
|
||||
// Step 1: Launch sandbox with sbx run in background.
|
||||
// sbx run creates the sandbox (or reconnects) AND holds an active session,
|
||||
// which prevents the sandbox from auto-stopping.
|
||||
console.log(`\n${c.info('▶')} Creating sandbox ${c.bright(opts.name)}...`);
|
||||
const bgRun = spawnProcess('sbx', [
|
||||
'run', '--template', opts.template, '--name', opts.name, opts.agent, workspace,
|
||||
], {
|
||||
detached: true,
|
||||
stdio: ['ignore', 'ignore', 'ignore'],
|
||||
});
|
||||
bgRun.unref();
|
||||
// Wait for sandbox to be ready
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
// Step 2: Inject environment variables
|
||||
if (opts.env.length > 0) {
|
||||
console.log(`${c.info('▶')} Setting environment variables...`);
|
||||
const exports = opts.env
|
||||
.filter(e => /^\w+=.+$/.test(e))
|
||||
.map(e => `export ${e}`)
|
||||
.join('\n');
|
||||
if (exports) {
|
||||
sbx(['exec', opts.name, 'bash', '-c', `echo '${exports}' >> /etc/sandbox-persistent.sh`]);
|
||||
}
|
||||
const invalid = opts.env.filter(e => !/^\w+=.+$/.test(e));
|
||||
if (invalid.length > 0) {
|
||||
console.log(`${c.warn('⚠')} Skipped invalid env vars: ${invalid.join(', ')} (expected KEY=VALUE)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Start CloudCLI inside the sandbox
|
||||
console.log(`${c.info('▶')} Launching CloudCLI web server...`);
|
||||
sbx(['exec', opts.name, 'bash', '-c', 'cloudcli start --port 3001 &']);
|
||||
|
||||
// Step 4: Forward port
|
||||
console.log(`${c.info('▶')} Forwarding port ${opts.port} → 3001...`);
|
||||
try {
|
||||
sbx(['ports', opts.name, '--publish', `${opts.port}:3001`]);
|
||||
} catch (e) {
|
||||
const msg = e.stdout || e.stderr || e.message || '';
|
||||
if (msg.includes('address already in use')) {
|
||||
const altPort = opts.port + 1;
|
||||
console.log(`${c.warn('⚠')} Port ${opts.port} in use, trying ${altPort}...`);
|
||||
try {
|
||||
sbx(['ports', opts.name, '--publish', `${altPort}:3001`]);
|
||||
opts.port = altPort;
|
||||
} catch {
|
||||
console.error(`${c.error('❌')} Ports ${opts.port} and ${altPort} both in use. Use --port to specify a free port.`);
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// Done
|
||||
console.log(`\n${c.ok('✔')} ${c.bright('CloudCLI is ready!')}`);
|
||||
console.log(` ${c.info('→')} Open ${c.bright(`http://localhost:${opts.port}`)}`);
|
||||
console.log(`\n${c.dim(' Manage with:')}`);
|
||||
console.log(` ${c.dim('$')} sbx ls`);
|
||||
console.log(` ${c.dim('$')} sbx stop ${opts.name}`);
|
||||
console.log(` ${c.dim('$')} sbx start ${opts.name}`);
|
||||
console.log(` ${c.dim('$')} sbx rm ${opts.name}`);
|
||||
console.log(`\n${c.dim(' Or install globally:')} npm install -g @cloudcli-ai/cloudcli\n`);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
showSandboxHelp();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Server ──────────────────────────────────────────────────
|
||||
|
||||
// Start the server
|
||||
async function startServer() {
|
||||
// Check for updates silently on startup
|
||||
@@ -613,9 +260,9 @@ function parseArgs(args) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '--port' || arg === '-p') {
|
||||
parsed.options.serverPort = args[++i];
|
||||
parsed.options.port = args[++i];
|
||||
} else if (arg.startsWith('--port=')) {
|
||||
parsed.options.serverPort = arg.split('=')[1];
|
||||
parsed.options.port = arg.split('=')[1];
|
||||
} else if (arg === '--database-path') {
|
||||
parsed.options.databasePath = args[++i];
|
||||
} else if (arg.startsWith('--database-path=')) {
|
||||
@@ -626,10 +273,6 @@ function parseArgs(args) {
|
||||
parsed.command = 'version';
|
||||
} else if (!arg.startsWith('-')) {
|
||||
parsed.command = arg;
|
||||
if (arg === 'sandbox') {
|
||||
parsed.remainingArgs = args.slice(i + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,13 +282,11 @@ function parseArgs(args) {
|
||||
// Main CLI handler
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const { command, options, remainingArgs } = parseArgs(args);
|
||||
const { command, options } = parseArgs(args);
|
||||
|
||||
// Apply CLI options to environment variables
|
||||
if (options.serverPort) {
|
||||
process.env.SERVER_PORT = options.serverPort;
|
||||
} else if (!process.env.SERVER_PORT && process.env.PORT) {
|
||||
process.env.SERVER_PORT = process.env.PORT;
|
||||
if (options.port) {
|
||||
process.env.PORT = options.port;
|
||||
}
|
||||
if (options.databasePath) {
|
||||
process.env.DATABASE_PATH = options.databasePath;
|
||||
@@ -655,9 +296,6 @@ async function main() {
|
||||
case 'start':
|
||||
await startServer();
|
||||
break;
|
||||
case 'sandbox':
|
||||
await sandboxCommand(remainingArgs || []);
|
||||
break;
|
||||
case 'status':
|
||||
case 'info':
|
||||
showStatus();
|
||||
|
||||
@@ -1,157 +1,84 @@
|
||||
import { spawn } from 'child_process';
|
||||
import crossSpawn from 'cross-spawn';
|
||||
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
||||
import { cursorAdapter } from './providers/cursor/adapter.js';
|
||||
import { createNormalizedMessage } from './providers/types.js';
|
||||
import { getStatusChecker } from './providers/registry.js';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
// Use cross-spawn on Windows for better command execution
|
||||
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
||||
|
||||
let activeCursorProcesses = new Map(); // Track active processes by session ID
|
||||
|
||||
const WORKSPACE_TRUST_PATTERNS = [
|
||||
/workspace trust required/i,
|
||||
/do you trust the contents of this directory/i,
|
||||
/working with untrusted contents/i,
|
||||
/pass --trust,\s*--yolo,\s*or -f/i
|
||||
];
|
||||
|
||||
function isWorkspaceTrustPrompt(text = '') {
|
||||
if (!text || typeof text !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return WORKSPACE_TRUST_PATTERNS.some((pattern) => pattern.test(text));
|
||||
}
|
||||
|
||||
async function spawnCursor(command, options = {}, ws) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const { sessionId, projectPath, cwd, resume, toolsSettings, skipPermissions, model, sessionSummary } = options;
|
||||
const { sessionId, projectPath, cwd, resume, toolsSettings, skipPermissions, model, images } = options;
|
||||
let capturedSessionId = sessionId; // Track session ID throughout the process
|
||||
let sessionCreatedSent = false; // Track if we've already sent session-created event
|
||||
let hasRetriedWithTrust = false;
|
||||
let settled = false;
|
||||
|
||||
let messageBuffer = ''; // Buffer for accumulating assistant messages
|
||||
|
||||
// Use tools settings passed from frontend, or defaults
|
||||
const settings = toolsSettings || {
|
||||
allowedShellCommands: [],
|
||||
skipPermissions: false
|
||||
};
|
||||
|
||||
|
||||
// Build Cursor CLI command
|
||||
const baseArgs = [];
|
||||
|
||||
const args = [];
|
||||
|
||||
// Build flags allowing both resume and prompt together (reply in existing session)
|
||||
// Treat presence of sessionId as intention to resume, regardless of resume flag
|
||||
if (sessionId) {
|
||||
baseArgs.push('--resume=' + sessionId);
|
||||
args.push('--resume=' + sessionId);
|
||||
}
|
||||
|
||||
if (command && command.trim()) {
|
||||
// Provide a prompt (works for both new and resumed sessions)
|
||||
baseArgs.push('-p', command);
|
||||
args.push('-p', command);
|
||||
|
||||
// Add model flag if specified (only meaningful for new sessions; harmless on resume)
|
||||
if (!sessionId && model) {
|
||||
baseArgs.push('--model', model);
|
||||
args.push('--model', model);
|
||||
}
|
||||
|
||||
// Request streaming JSON when we are providing a prompt
|
||||
baseArgs.push('--output-format', 'stream-json');
|
||||
args.push('--output-format', 'stream-json');
|
||||
}
|
||||
|
||||
|
||||
// Add skip permissions flag if enabled
|
||||
if (skipPermissions || settings.skipPermissions) {
|
||||
baseArgs.push('-f');
|
||||
console.log('Using -f flag (skip permissions)');
|
||||
args.push('-f');
|
||||
console.log('⚠️ Using -f flag (skip permissions)');
|
||||
}
|
||||
|
||||
|
||||
// Use cwd (actual project directory) instead of projectPath
|
||||
const workingDir = cwd || projectPath || process.cwd();
|
||||
|
||||
|
||||
console.log('Spawning Cursor CLI:', 'cursor-agent', args.join(' '));
|
||||
console.log('Working directory:', workingDir);
|
||||
console.log('Session info - Input sessionId:', sessionId, 'Resume:', resume);
|
||||
|
||||
const cursorProcess = spawnFunction('cursor-agent', args, {
|
||||
cwd: workingDir,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: { ...process.env } // Inherit all environment variables
|
||||
});
|
||||
|
||||
// Store process reference for potential abort
|
||||
const processKey = capturedSessionId || Date.now().toString();
|
||||
|
||||
const settleOnce = (callback) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
callback();
|
||||
};
|
||||
|
||||
const runCursorProcess = (args, runReason = 'initial') => {
|
||||
const isTrustRetry = runReason === 'trust-retry';
|
||||
let runSawWorkspaceTrustPrompt = false;
|
||||
let stdoutLineBuffer = '';
|
||||
let terminalNotificationSent = false;
|
||||
|
||||
const notifyTerminalState = ({ code = null, error = null } = {}) => {
|
||||
if (terminalNotificationSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
terminalNotificationSent = true;
|
||||
|
||||
const finalSessionId = capturedSessionId || sessionId || processKey;
|
||||
if (code === 0 && !error) {
|
||||
notifyRunStopped({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'cursor',
|
||||
sessionId: finalSessionId,
|
||||
sessionName: sessionSummary,
|
||||
stopReason: 'completed'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
notifyRunFailed({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'cursor',
|
||||
sessionId: finalSessionId,
|
||||
sessionName: sessionSummary,
|
||||
error: error || `Cursor CLI exited with code ${code}`
|
||||
});
|
||||
};
|
||||
|
||||
if (isTrustRetry) {
|
||||
console.log('Retrying Cursor CLI with --trust after workspace trust prompt');
|
||||
}
|
||||
|
||||
console.log('Spawning Cursor CLI:', 'cursor-agent', args.join(' '));
|
||||
console.log('Working directory:', workingDir);
|
||||
console.log('Session info - Input sessionId:', sessionId, 'Resume:', resume);
|
||||
|
||||
const cursorProcess = spawnFunction('cursor-agent', args, {
|
||||
cwd: workingDir,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: { ...process.env } // Inherit all environment variables
|
||||
});
|
||||
|
||||
activeCursorProcesses.set(processKey, cursorProcess);
|
||||
|
||||
const shouldSuppressForTrustRetry = (text) => {
|
||||
if (hasRetriedWithTrust || args.includes('--trust')) {
|
||||
return false;
|
||||
}
|
||||
if (!isWorkspaceTrustPrompt(text)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
runSawWorkspaceTrustPrompt = true;
|
||||
return true;
|
||||
};
|
||||
|
||||
const processCursorOutputLine = (line) => {
|
||||
if (!line || !line.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
activeCursorProcesses.set(processKey, cursorProcess);
|
||||
|
||||
// Handle stdout (streaming JSON responses)
|
||||
cursorProcess.stdout.on('data', (data) => {
|
||||
const rawOutput = data.toString();
|
||||
console.log('📤 Cursor CLI stdout:', rawOutput);
|
||||
|
||||
const lines = rawOutput.split('\n').filter(line => line.trim());
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const response = JSON.parse(line);
|
||||
console.log('Parsed JSON response:', response);
|
||||
|
||||
console.log('📄 Parsed JSON response:', response);
|
||||
|
||||
// Handle different message types
|
||||
switch (response.type) {
|
||||
case 'system':
|
||||
@@ -159,14 +86,14 @@ async function spawnCursor(command, options = {}, ws) {
|
||||
// Capture session ID
|
||||
if (response.session_id && !capturedSessionId) {
|
||||
capturedSessionId = response.session_id;
|
||||
console.log('Captured session ID:', capturedSessionId);
|
||||
|
||||
console.log('📝 Captured session ID:', capturedSessionId);
|
||||
|
||||
// Update process key with captured session ID
|
||||
if (processKey !== capturedSessionId) {
|
||||
activeCursorProcesses.delete(processKey);
|
||||
activeCursorProcesses.set(capturedSessionId, cursorProcess);
|
||||
}
|
||||
|
||||
|
||||
// Set session ID on writer (for API endpoint compatibility)
|
||||
if (ws.setSessionId && typeof ws.setSessionId === 'function') {
|
||||
ws.setSessionId(capturedSessionId);
|
||||
@@ -175,150 +102,156 @@ async function spawnCursor(command, options = {}, ws) {
|
||||
// Send session-created event only once for new sessions
|
||||
if (!sessionId && !sessionCreatedSent) {
|
||||
sessionCreatedSent = true;
|
||||
ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, model: response.model, cwd: response.cwd, sessionId: capturedSessionId, provider: 'cursor' }));
|
||||
ws.send({
|
||||
type: 'session-created',
|
||||
sessionId: capturedSessionId,
|
||||
model: response.model,
|
||||
cwd: response.cwd
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// System info — no longer needed by the frontend (session-lifecycle 'created' handles nav).
|
||||
|
||||
// Send system info to frontend
|
||||
ws.send({
|
||||
type: 'cursor-system',
|
||||
data: response,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
case 'user':
|
||||
// User messages are not displayed in the UI — skip.
|
||||
// Forward user message
|
||||
ws.send({
|
||||
type: 'cursor-user',
|
||||
data: response,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
break;
|
||||
|
||||
|
||||
case 'assistant':
|
||||
// Accumulate assistant message chunks
|
||||
if (response.message && response.message.content && response.message.content.length > 0) {
|
||||
const normalized = cursorAdapter.normalizeMessage(response, capturedSessionId || sessionId || null);
|
||||
for (const msg of normalized) ws.send(msg);
|
||||
const textContent = response.message.content[0].text;
|
||||
messageBuffer += textContent;
|
||||
|
||||
// Send as Claude-compatible format for frontend
|
||||
ws.send({
|
||||
type: 'claude-response',
|
||||
data: {
|
||||
type: 'content_block_delta',
|
||||
delta: {
|
||||
type: 'text_delta',
|
||||
text: textContent
|
||||
}
|
||||
},
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case 'result': {
|
||||
// Session complete — send stream end + lifecycle complete with result payload
|
||||
|
||||
case 'result':
|
||||
// Session complete
|
||||
console.log('Cursor session result:', response);
|
||||
const resultText = typeof response.result === 'string' ? response.result : '';
|
||||
ws.send(createNormalizedMessage({
|
||||
kind: 'complete',
|
||||
exitCode: response.subtype === 'success' ? 0 : 1,
|
||||
resultText,
|
||||
isError: response.subtype !== 'success',
|
||||
sessionId: capturedSessionId || sessionId, provider: 'cursor',
|
||||
}));
|
||||
|
||||
// Send final message if we have buffered content
|
||||
if (messageBuffer) {
|
||||
ws.send({
|
||||
type: 'claude-response',
|
||||
data: {
|
||||
type: 'content_block_stop'
|
||||
},
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
}
|
||||
|
||||
// Send completion event
|
||||
ws.send({
|
||||
type: 'cursor-result',
|
||||
sessionId: capturedSessionId || sessionId,
|
||||
data: response,
|
||||
success: response.subtype === 'success'
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
default:
|
||||
// Unknown message types — ignore.
|
||||
// Forward any other message types
|
||||
ws.send({
|
||||
type: 'cursor-response',
|
||||
data: response,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.log('Non-JSON response:', line);
|
||||
|
||||
if (shouldSuppressForTrustRetry(line)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If not JSON, send as stream delta via adapter
|
||||
const normalized = cursorAdapter.normalizeMessage(line, capturedSessionId || sessionId || null);
|
||||
for (const msg of normalized) ws.send(msg);
|
||||
console.log('📄 Non-JSON response:', line);
|
||||
// If not JSON, send as raw text
|
||||
ws.send({
|
||||
type: 'cursor-output',
|
||||
data: line,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// Handle stderr
|
||||
cursorProcess.stderr.on('data', (data) => {
|
||||
console.error('Cursor CLI stderr:', data.toString());
|
||||
ws.send({
|
||||
type: 'cursor-error',
|
||||
error: data.toString(),
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
});
|
||||
|
||||
// Handle process completion
|
||||
cursorProcess.on('close', async (code) => {
|
||||
console.log(`Cursor CLI process exited with code ${code}`);
|
||||
|
||||
// Clean up process reference
|
||||
const finalSessionId = capturedSessionId || sessionId || processKey;
|
||||
activeCursorProcesses.delete(finalSessionId);
|
||||
|
||||
// Handle stdout (streaming JSON responses)
|
||||
cursorProcess.stdout.on('data', (data) => {
|
||||
const rawOutput = data.toString();
|
||||
console.log('Cursor CLI stdout:', rawOutput);
|
||||
ws.send({
|
||||
type: 'claude-complete',
|
||||
sessionId: finalSessionId,
|
||||
exitCode: code,
|
||||
isNewSession: !sessionId && !!command // Flag to indicate this was a new session
|
||||
});
|
||||
|
||||
if (code === 0) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error(`Cursor CLI exited with code ${code}`));
|
||||
}
|
||||
});
|
||||
|
||||
// Handle process errors
|
||||
cursorProcess.on('error', (error) => {
|
||||
console.error('Cursor CLI process error:', error);
|
||||
|
||||
// Clean up process reference on error
|
||||
const finalSessionId = capturedSessionId || sessionId || processKey;
|
||||
activeCursorProcesses.delete(finalSessionId);
|
||||
|
||||
// Stream chunks can split JSON objects across packets; keep trailing partial line.
|
||||
stdoutLineBuffer += rawOutput;
|
||||
const completeLines = stdoutLineBuffer.split(/\r?\n/);
|
||||
stdoutLineBuffer = completeLines.pop() || '';
|
||||
|
||||
completeLines.forEach((line) => {
|
||||
processCursorOutputLine(line.trim());
|
||||
});
|
||||
ws.send({
|
||||
type: 'cursor-error',
|
||||
error: error.message,
|
||||
sessionId: capturedSessionId || sessionId || null
|
||||
});
|
||||
|
||||
// Handle stderr
|
||||
cursorProcess.stderr.on('data', (data) => {
|
||||
const stderrText = data.toString();
|
||||
console.error('Cursor CLI stderr:', stderrText);
|
||||
|
||||
if (shouldSuppressForTrustRetry(stderrText)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ws.send(createNormalizedMessage({ kind: 'error', content: stderrText, sessionId: capturedSessionId || sessionId || null, provider: 'cursor' }));
|
||||
});
|
||||
|
||||
// Handle process completion
|
||||
cursorProcess.on('close', async (code) => {
|
||||
console.log(`Cursor CLI process exited with code ${code}`);
|
||||
|
||||
const finalSessionId = capturedSessionId || sessionId || processKey;
|
||||
activeCursorProcesses.delete(finalSessionId);
|
||||
|
||||
// Flush any final unterminated stdout line before completion handling.
|
||||
if (stdoutLineBuffer.trim()) {
|
||||
processCursorOutputLine(stdoutLineBuffer.trim());
|
||||
stdoutLineBuffer = '';
|
||||
}
|
||||
|
||||
if (
|
||||
runSawWorkspaceTrustPrompt &&
|
||||
code !== 0 &&
|
||||
!hasRetriedWithTrust &&
|
||||
!args.includes('--trust')
|
||||
) {
|
||||
hasRetriedWithTrust = true;
|
||||
runCursorProcess([...args, '--trust'], 'trust-retry');
|
||||
return;
|
||||
}
|
||||
|
||||
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'cursor' }));
|
||||
|
||||
if (code === 0) {
|
||||
notifyTerminalState({ code });
|
||||
settleOnce(() => resolve());
|
||||
} else {
|
||||
notifyTerminalState({ code });
|
||||
settleOnce(() => reject(new Error(`Cursor CLI exited with code ${code}`)));
|
||||
}
|
||||
});
|
||||
|
||||
// Handle process errors
|
||||
cursorProcess.on('error', (error) => {
|
||||
console.error('Cursor CLI process error:', error);
|
||||
|
||||
// Clean up process reference on error
|
||||
const finalSessionId = capturedSessionId || sessionId || processKey;
|
||||
activeCursorProcesses.delete(finalSessionId);
|
||||
|
||||
// Check if Cursor CLI is installed for a clearer error message
|
||||
const installed = getStatusChecker('cursor')?.checkInstalled() ?? true;
|
||||
const errorContent = !installed
|
||||
? 'Cursor CLI is not installed. Please install it from https://cursor.com'
|
||||
: error.message;
|
||||
|
||||
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'cursor' }));
|
||||
notifyTerminalState({ error });
|
||||
|
||||
settleOnce(() => reject(error));
|
||||
});
|
||||
|
||||
// Close stdin since Cursor doesn't need interactive input
|
||||
cursorProcess.stdin.end();
|
||||
};
|
||||
|
||||
runCursorProcess(baseArgs, 'initial');
|
||||
reject(error);
|
||||
});
|
||||
|
||||
// Close stdin since Cursor doesn't need interactive input
|
||||
cursorProcess.stdin.end();
|
||||
});
|
||||
}
|
||||
|
||||
function abortCursorSession(sessionId) {
|
||||
const process = activeCursorProcesses.get(sessionId);
|
||||
if (process) {
|
||||
console.log(`Aborting Cursor session: ${sessionId}`);
|
||||
console.log(`🛑 Aborting Cursor session: ${sessionId}`);
|
||||
process.kill('SIGTERM');
|
||||
activeCursorProcesses.delete(sessionId);
|
||||
return true;
|
||||
|
||||
@@ -2,21 +2,11 @@ import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import crypto from 'crypto';
|
||||
import { findAppRoot, getModuleDir } from '../utils/runtime-paths.js';
|
||||
import {
|
||||
APP_CONFIG_TABLE_SQL,
|
||||
USER_NOTIFICATION_PREFERENCES_TABLE_SQL,
|
||||
VAPID_KEYS_TABLE_SQL,
|
||||
PUSH_SUBSCRIPTIONS_TABLE_SQL,
|
||||
SESSION_NAMES_TABLE_SQL,
|
||||
SESSION_NAMES_LOOKUP_INDEX_SQL,
|
||||
DATABASE_SCHEMA_SQL
|
||||
} from './schema.js';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname } from 'path';
|
||||
|
||||
const __dirname = getModuleDir(import.meta.url);
|
||||
// The compiled backend lives under dist-server/server/database, but the install root we log
|
||||
// should still point at the project/app root. Resolving it here avoids build-layout drift.
|
||||
const APP_ROOT = findAppRoot(__dirname);
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
// ANSI color codes for terminal output
|
||||
const colors = {
|
||||
@@ -34,6 +24,7 @@ const c = {
|
||||
|
||||
// Use DATABASE_PATH environment variable if set, otherwise use default location
|
||||
const DB_PATH = process.env.DATABASE_PATH || path.join(__dirname, 'auth.db');
|
||||
const INIT_SQL_PATH = path.join(__dirname, 'init.sql');
|
||||
|
||||
// Ensure database directory exists if custom path is provided
|
||||
if (process.env.DATABASE_PATH) {
|
||||
@@ -68,13 +59,8 @@ if (DB_PATH !== LEGACY_DB_PATH && !fs.existsSync(DB_PATH) && fs.existsSync(LEGAC
|
||||
// Create database connection
|
||||
const db = new Database(DB_PATH);
|
||||
|
||||
// app_config must exist before any other module imports (auth.js reads the JWT secret at load time).
|
||||
// runMigrations() also creates this table, but it runs too late for existing installations
|
||||
// where auth.js is imported before initializeDatabase() is called.
|
||||
db.exec(APP_CONFIG_TABLE_SQL);
|
||||
|
||||
// Show app installation path prominently
|
||||
const appInstallPath = APP_ROOT;
|
||||
const appInstallPath = path.join(__dirname, '../..');
|
||||
console.log('');
|
||||
console.log(c.dim('═'.repeat(60)));
|
||||
console.log(`${c.info('[INFO]')} App Installation: ${c.bright(appInstallPath)}`);
|
||||
@@ -105,12 +91,35 @@ const runMigrations = () => {
|
||||
db.exec('ALTER TABLE users ADD COLUMN has_completed_onboarding BOOLEAN DEFAULT 0');
|
||||
}
|
||||
|
||||
db.exec(USER_NOTIFICATION_PREFERENCES_TABLE_SQL);
|
||||
db.exec(VAPID_KEYS_TABLE_SQL);
|
||||
db.exec(PUSH_SUBSCRIPTIONS_TABLE_SQL);
|
||||
db.exec(APP_CONFIG_TABLE_SQL);
|
||||
db.exec(SESSION_NAMES_TABLE_SQL);
|
||||
db.exec(SESSION_NAMES_LOOKUP_INDEX_SQL);
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS user_notification_preferences (
|
||||
user_id INTEGER PRIMARY KEY,
|
||||
preferences_json TEXT NOT NULL,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS vapid_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
public_key TEXT NOT NULL,
|
||||
private_key TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
endpoint TEXT NOT NULL UNIQUE,
|
||||
keys_p256dh TEXT NOT NULL,
|
||||
keys_auth TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
|
||||
console.log('Database migrations completed successfully');
|
||||
} catch (error) {
|
||||
@@ -122,7 +131,8 @@ const runMigrations = () => {
|
||||
// Initialize database with schema
|
||||
const initializeDatabase = async () => {
|
||||
try {
|
||||
db.exec(DATABASE_SCHEMA_SQL);
|
||||
const initSQL = fs.readFileSync(INIT_SQL_PATH, 'utf8');
|
||||
db.exec(initSQL);
|
||||
console.log('Database initialized successfully');
|
||||
runMigrations();
|
||||
} catch (error) {
|
||||
@@ -478,87 +488,6 @@ const pushSubscriptionsDb = {
|
||||
}
|
||||
};
|
||||
|
||||
// Session custom names database operations
|
||||
const sessionNamesDb = {
|
||||
// Set (insert or update) a custom session name
|
||||
setName: (sessionId, provider, customName) => {
|
||||
db.prepare(`
|
||||
INSERT INTO session_names (session_id, provider, custom_name)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(session_id, provider)
|
||||
DO UPDATE SET custom_name = excluded.custom_name, updated_at = CURRENT_TIMESTAMP
|
||||
`).run(sessionId, provider, customName);
|
||||
},
|
||||
|
||||
// Get a single custom session name
|
||||
getName: (sessionId, provider) => {
|
||||
const row = db.prepare(
|
||||
'SELECT custom_name FROM session_names WHERE session_id = ? AND provider = ?'
|
||||
).get(sessionId, provider);
|
||||
return row?.custom_name || null;
|
||||
},
|
||||
|
||||
// Batch lookup — returns Map<sessionId, customName>
|
||||
getNames: (sessionIds, provider) => {
|
||||
if (!sessionIds.length) return new Map();
|
||||
const placeholders = sessionIds.map(() => '?').join(',');
|
||||
const rows = db.prepare(
|
||||
`SELECT session_id, custom_name FROM session_names
|
||||
WHERE session_id IN (${placeholders}) AND provider = ?`
|
||||
).all(...sessionIds, provider);
|
||||
return new Map(rows.map(r => [r.session_id, r.custom_name]));
|
||||
},
|
||||
|
||||
// Delete a custom session name
|
||||
deleteName: (sessionId, provider) => {
|
||||
return db.prepare(
|
||||
'DELETE FROM session_names WHERE session_id = ? AND provider = ?'
|
||||
).run(sessionId, provider).changes > 0;
|
||||
},
|
||||
};
|
||||
|
||||
// Apply custom session names from the database (overrides CLI-generated summaries)
|
||||
function applyCustomSessionNames(sessions, provider) {
|
||||
if (!sessions?.length) return;
|
||||
try {
|
||||
const ids = sessions.map(s => s.id);
|
||||
const customNames = sessionNamesDb.getNames(ids, provider);
|
||||
for (const session of sessions) {
|
||||
const custom = customNames.get(session.id);
|
||||
if (custom) session.summary = custom;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// App config database operations
|
||||
const appConfigDb = {
|
||||
get: (key) => {
|
||||
try {
|
||||
const row = db.prepare('SELECT value FROM app_config WHERE key = ?').get(key);
|
||||
return row?.value || null;
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
set: (key, value) => {
|
||||
db.prepare(
|
||||
'INSERT INTO app_config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'
|
||||
).run(key, value);
|
||||
},
|
||||
|
||||
getOrCreateJwtSecret: () => {
|
||||
let secret = appConfigDb.get('jwt_secret');
|
||||
if (!secret) {
|
||||
secret = crypto.randomBytes(64).toString('hex');
|
||||
appConfigDb.set('jwt_secret', secret);
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
};
|
||||
|
||||
// Backward compatibility - keep old names pointing to new system
|
||||
const githubTokensDb = {
|
||||
createGithubToken: (userId, tokenName, githubToken, description = null) => {
|
||||
@@ -586,8 +515,5 @@ export {
|
||||
credentialsDb,
|
||||
notificationPreferencesDb,
|
||||
pushSubscriptionsDb,
|
||||
sessionNamesDb,
|
||||
applyCustomSessionNames,
|
||||
appConfigDb,
|
||||
githubTokensDb // Backward compatibility
|
||||
};
|
||||
|
||||
79
server/database/init.sql
Normal file
79
server/database/init.sql
Normal file
@@ -0,0 +1,79 @@
|
||||
-- Initialize authentication database
|
||||
PRAGMA foreign_keys = ON;
|
||||
|
||||
-- Users table (single user system)
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login DATETIME,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
git_name TEXT,
|
||||
git_email TEXT,
|
||||
has_completed_onboarding BOOLEAN DEFAULT 0
|
||||
);
|
||||
|
||||
-- Indexes for performance
|
||||
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
|
||||
CREATE INDEX IF NOT EXISTS idx_users_active ON users(is_active);
|
||||
|
||||
-- API Keys table for external API access
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
key_name TEXT NOT NULL,
|
||||
api_key TEXT UNIQUE NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
last_used DATETIME,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_key ON api_keys(api_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_active ON api_keys(is_active);
|
||||
|
||||
-- User credentials table for storing various tokens/credentials (GitHub, GitLab, etc.)
|
||||
CREATE TABLE IF NOT EXISTS user_credentials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
credential_name TEXT NOT NULL,
|
||||
credential_type TEXT NOT NULL, -- 'github_token', 'gitlab_token', 'bitbucket_token', etc.
|
||||
credential_value TEXT NOT NULL,
|
||||
description TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_credentials_user_id ON user_credentials(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_credentials_type ON user_credentials(credential_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_credentials_active ON user_credentials(is_active);
|
||||
|
||||
-- User notification preferences (backend-owned, provider-agnostic)
|
||||
CREATE TABLE IF NOT EXISTS user_notification_preferences (
|
||||
user_id INTEGER PRIMARY KEY,
|
||||
preferences_json TEXT NOT NULL,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- VAPID key pair for Web Push notifications
|
||||
CREATE TABLE IF NOT EXISTS vapid_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
public_key TEXT NOT NULL,
|
||||
private_key TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Browser push subscriptions
|
||||
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
endpoint TEXT NOT NULL UNIQUE,
|
||||
keys_p256dh TEXT NOT NULL,
|
||||
keys_auth TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
@@ -1,102 +0,0 @@
|
||||
export const APP_CONFIG_TABLE_SQL = `CREATE TABLE IF NOT EXISTS app_config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);`;
|
||||
|
||||
export const USER_NOTIFICATION_PREFERENCES_TABLE_SQL = `CREATE TABLE IF NOT EXISTS user_notification_preferences (
|
||||
user_id INTEGER PRIMARY KEY,
|
||||
preferences_json TEXT NOT NULL,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);`;
|
||||
|
||||
export const VAPID_KEYS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS vapid_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
public_key TEXT NOT NULL,
|
||||
private_key TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);`;
|
||||
|
||||
export const PUSH_SUBSCRIPTIONS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
endpoint TEXT NOT NULL UNIQUE,
|
||||
keys_p256dh TEXT NOT NULL,
|
||||
keys_auth TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);`;
|
||||
|
||||
export const SESSION_NAMES_TABLE_SQL = `CREATE TABLE IF NOT EXISTS session_names (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
provider TEXT NOT NULL DEFAULT 'claude',
|
||||
custom_name TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(session_id, provider)
|
||||
);`;
|
||||
|
||||
export const SESSION_NAMES_LOOKUP_INDEX_SQL = `CREATE INDEX IF NOT EXISTS idx_session_names_lookup ON session_names(session_id, provider);`;
|
||||
|
||||
export const DATABASE_SCHEMA_SQL = `PRAGMA foreign_keys = ON;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login DATETIME,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
git_name TEXT,
|
||||
git_email TEXT,
|
||||
has_completed_onboarding BOOLEAN DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
|
||||
CREATE INDEX IF NOT EXISTS idx_users_active ON users(is_active);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
key_name TEXT NOT NULL,
|
||||
api_key TEXT UNIQUE NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
last_used DATETIME,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_key ON api_keys(api_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_active ON api_keys(is_active);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_credentials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
credential_name TEXT NOT NULL,
|
||||
credential_type TEXT NOT NULL,
|
||||
credential_value TEXT NOT NULL,
|
||||
description TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
is_active BOOLEAN DEFAULT 1,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_credentials_user_id ON user_credentials(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_credentials_type ON user_credentials(credential_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_credentials_active ON user_credentials(is_active);
|
||||
|
||||
${USER_NOTIFICATION_PREFERENCES_TABLE_SQL}
|
||||
|
||||
${VAPID_KEYS_TABLE_SQL}
|
||||
|
||||
${PUSH_SUBSCRIPTIONS_TABLE_SQL}
|
||||
|
||||
${SESSION_NAMES_TABLE_SQL}
|
||||
|
||||
${SESSION_NAMES_LOOKUP_INDEX_SQL}
|
||||
|
||||
${APP_CONFIG_TABLE_SQL}
|
||||
`;
|
||||
@@ -6,16 +6,14 @@ const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { getSessions, getSessionMessages } from './projects.js';
|
||||
import sessionManager from './sessionManager.js';
|
||||
import GeminiResponseHandler from './gemini-response-handler.js';
|
||||
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
||||
import { createNormalizedMessage } from './providers/types.js';
|
||||
import { getStatusChecker } from './providers/registry.js';
|
||||
|
||||
let activeGeminiProcesses = new Map(); // Track active processes by session ID
|
||||
|
||||
async function spawnGemini(command, options = {}, ws) {
|
||||
const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary } = options;
|
||||
const { sessionId, projectPath, cwd, resume, toolsSettings, permissionMode, images } = options;
|
||||
let capturedSessionId = sessionId; // Track session ID throughout the process
|
||||
let sessionCreatedSent = false; // Track if we've already sent session-created event
|
||||
let assistantBlocks = []; // Accumulate the full response blocks including tools
|
||||
@@ -174,36 +172,6 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: { ...process.env } // Inherit all environment variables
|
||||
});
|
||||
let terminalNotificationSent = false;
|
||||
let terminalFailureReason = null;
|
||||
|
||||
const notifyTerminalState = ({ code = null, error = null } = {}) => {
|
||||
if (terminalNotificationSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
terminalNotificationSent = true;
|
||||
|
||||
const finalSessionId = capturedSessionId || sessionId || processKey;
|
||||
if (code === 0 && !error) {
|
||||
notifyRunStopped({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'gemini',
|
||||
sessionId: finalSessionId,
|
||||
sessionName: sessionSummary,
|
||||
stopReason: 'completed'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
notifyRunFailed({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'gemini',
|
||||
sessionId: finalSessionId,
|
||||
sessionName: sessionSummary,
|
||||
error: error || terminalFailureReason || `Gemini CLI exited with code ${code}`
|
||||
});
|
||||
};
|
||||
|
||||
// Attach temp file info to process for cleanup later
|
||||
geminiProcess.tempImagePaths = tempImagePaths;
|
||||
@@ -220,6 +188,7 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
geminiProcess.stdin.end();
|
||||
|
||||
// Add timeout handler
|
||||
let hasReceivedOutput = false;
|
||||
const timeoutMs = 120000; // 120 seconds for slower models
|
||||
let timeout;
|
||||
|
||||
@@ -227,8 +196,11 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
timeout = setTimeout(() => {
|
||||
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId || processKey);
|
||||
terminalFailureReason = `Gemini CLI timeout - no response received for ${timeoutMs / 1000} seconds`;
|
||||
ws.send(createNormalizedMessage({ kind: 'error', content: terminalFailureReason, sessionId: socketSessionId, provider: 'gemini' }));
|
||||
ws.send({
|
||||
type: 'gemini-error',
|
||||
sessionId: socketSessionId,
|
||||
error: `Gemini CLI timeout - no response received for ${timeoutMs / 1000} seconds`
|
||||
});
|
||||
try {
|
||||
geminiProcess.kill('SIGTERM');
|
||||
} catch (e) { }
|
||||
@@ -290,6 +262,7 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
// Handle stdout
|
||||
geminiProcess.stdout.on('data', (data) => {
|
||||
const rawOutput = data.toString();
|
||||
hasReceivedOutput = true;
|
||||
startTimeout(); // Re-arm the timeout
|
||||
|
||||
// For new sessions, create a session ID FIRST
|
||||
@@ -313,7 +286,21 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
|
||||
ws.setSessionId && typeof ws.setSessionId === 'function' && ws.setSessionId(capturedSessionId);
|
||||
|
||||
ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'gemini' }));
|
||||
ws.send({
|
||||
type: 'session-created',
|
||||
sessionId: capturedSessionId
|
||||
});
|
||||
|
||||
// Emit fake system init so the frontend immediately navigates and saves the session
|
||||
ws.send({
|
||||
type: 'claude-response',
|
||||
sessionId: capturedSessionId,
|
||||
data: {
|
||||
type: 'system',
|
||||
subtype: 'init',
|
||||
session_id: capturedSessionId
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (responseHandler) {
|
||||
@@ -326,7 +313,14 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
assistantBlocks.push({ type: 'text', text: rawOutput });
|
||||
}
|
||||
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
||||
ws.send(createNormalizedMessage({ kind: 'stream_delta', content: rawOutput, sessionId: socketSessionId, provider: 'gemini' }));
|
||||
ws.send({
|
||||
type: 'gemini-response',
|
||||
sessionId: socketSessionId,
|
||||
data: {
|
||||
type: 'message',
|
||||
content: rawOutput
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -343,7 +337,11 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
}
|
||||
|
||||
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
||||
ws.send(createNormalizedMessage({ kind: 'error', content: errorMsg, sessionId: socketSessionId, provider: 'gemini' }));
|
||||
ws.send({
|
||||
type: 'gemini-error',
|
||||
sessionId: socketSessionId,
|
||||
error: errorMsg
|
||||
});
|
||||
});
|
||||
|
||||
// Handle process completion
|
||||
@@ -365,7 +363,12 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
|
||||
}
|
||||
|
||||
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'gemini' }));
|
||||
ws.send({
|
||||
type: 'claude-complete', // Use claude-complete for compatibility with UI
|
||||
sessionId: finalSessionId,
|
||||
exitCode: code,
|
||||
isNewSession: !sessionId && !!command // Flag to indicate this was a new session
|
||||
});
|
||||
|
||||
// Clean up temporary image files if any
|
||||
if (geminiProcess.tempImagePaths && geminiProcess.tempImagePaths.length > 0) {
|
||||
@@ -378,22 +381,8 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
}
|
||||
|
||||
if (code === 0) {
|
||||
notifyTerminalState({ code });
|
||||
resolve();
|
||||
} else {
|
||||
// code 127 = shell "command not found" — check installation
|
||||
if (code === 127) {
|
||||
const installed = getStatusChecker('gemini')?.checkInstalled() ?? true;
|
||||
if (!installed) {
|
||||
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
||||
ws.send(createNormalizedMessage({ kind: 'error', content: 'Gemini CLI is not installed. Please install it first: https://github.com/google-gemini/gemini-cli', sessionId: socketSessionId, provider: 'gemini' }));
|
||||
}
|
||||
}
|
||||
|
||||
notifyTerminalState({
|
||||
code,
|
||||
error: code === null ? 'Gemini CLI process was terminated or timed out' : null
|
||||
});
|
||||
reject(new Error(code === null ? 'Gemini CLI process was terminated or timed out' : `Gemini CLI exited with code ${code}`));
|
||||
}
|
||||
});
|
||||
@@ -404,15 +393,12 @@ async function spawnGemini(command, options = {}, ws) {
|
||||
const finalSessionId = capturedSessionId || sessionId || processKey;
|
||||
activeGeminiProcesses.delete(finalSessionId);
|
||||
|
||||
// Check if Gemini CLI is installed for a clearer error message
|
||||
const installed = getStatusChecker('gemini')?.checkInstalled() ?? true;
|
||||
const errorContent = !installed
|
||||
? 'Gemini CLI is not installed. Please install it first: https://github.com/google-gemini/gemini-cli'
|
||||
: error.message;
|
||||
|
||||
const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
||||
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: errorSessionId, provider: 'gemini' }));
|
||||
notifyTerminalState({ error });
|
||||
ws.send({
|
||||
type: 'gemini-error',
|
||||
sessionId: errorSessionId,
|
||||
error: error.message
|
||||
});
|
||||
|
||||
reject(error);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
// Gemini Response Handler - JSON Stream processing
|
||||
import { geminiAdapter } from './providers/gemini/adapter.js';
|
||||
|
||||
class GeminiResponseHandler {
|
||||
constructor(ws, options = {}) {
|
||||
this.ws = ws;
|
||||
@@ -29,12 +27,13 @@ class GeminiResponseHandler {
|
||||
this.handleEvent(event);
|
||||
} catch (err) {
|
||||
// Not a JSON line, probably debug output or CLI warnings
|
||||
// console.error('[Gemini Handler] Non-JSON line ignored:', line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleEvent(event) {
|
||||
const sid = typeof this.ws.getSessionId === 'function' ? this.ws.getSessionId() : null;
|
||||
const socketSessionId = typeof this.ws.getSessionId === 'function' ? this.ws.getSessionId() : null;
|
||||
|
||||
if (event.type === 'init') {
|
||||
if (this.onInit) {
|
||||
@@ -43,26 +42,88 @@ class GeminiResponseHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// Invoke per-type callbacks for session tracking
|
||||
if (event.type === 'message' && event.role === 'assistant') {
|
||||
const content = event.content || '';
|
||||
|
||||
// Notify the parent CLI handler of accumulated text
|
||||
if (this.onContentFragment && content) {
|
||||
this.onContentFragment(content);
|
||||
}
|
||||
} else if (event.type === 'tool_use' && this.onToolUse) {
|
||||
this.onToolUse(event);
|
||||
} else if (event.type === 'tool_result' && this.onToolResult) {
|
||||
this.onToolResult(event);
|
||||
}
|
||||
|
||||
// Normalize via adapter and send all resulting messages
|
||||
const normalized = geminiAdapter.normalizeMessage(event, sid);
|
||||
for (const msg of normalized) {
|
||||
this.ws.send(msg);
|
||||
let payload = {
|
||||
type: 'gemini-response',
|
||||
data: {
|
||||
type: 'message',
|
||||
content: content,
|
||||
isPartial: event.delta === true
|
||||
}
|
||||
};
|
||||
if (socketSessionId) payload.sessionId = socketSessionId;
|
||||
this.ws.send(payload);
|
||||
}
|
||||
else if (event.type === 'tool_use') {
|
||||
if (this.onToolUse) {
|
||||
this.onToolUse(event);
|
||||
}
|
||||
let payload = {
|
||||
type: 'gemini-tool-use',
|
||||
toolName: event.tool_name,
|
||||
toolId: event.tool_id,
|
||||
parameters: event.parameters || {}
|
||||
};
|
||||
if (socketSessionId) payload.sessionId = socketSessionId;
|
||||
this.ws.send(payload);
|
||||
}
|
||||
else if (event.type === 'tool_result') {
|
||||
if (this.onToolResult) {
|
||||
this.onToolResult(event);
|
||||
}
|
||||
let payload = {
|
||||
type: 'gemini-tool-result',
|
||||
toolId: event.tool_id,
|
||||
status: event.status,
|
||||
output: event.output || ''
|
||||
};
|
||||
if (socketSessionId) payload.sessionId = socketSessionId;
|
||||
this.ws.send(payload);
|
||||
}
|
||||
else if (event.type === 'result') {
|
||||
// Send a finalize message string
|
||||
let payload = {
|
||||
type: 'gemini-response',
|
||||
data: {
|
||||
type: 'message',
|
||||
content: '',
|
||||
isPartial: false
|
||||
}
|
||||
};
|
||||
if (socketSessionId) payload.sessionId = socketSessionId;
|
||||
this.ws.send(payload);
|
||||
|
||||
if (event.stats && event.stats.total_tokens) {
|
||||
let statsPayload = {
|
||||
type: 'claude-status',
|
||||
data: {
|
||||
status: 'Complete',
|
||||
tokens: event.stats.total_tokens
|
||||
}
|
||||
};
|
||||
if (socketSessionId) statsPayload.sessionId = socketSessionId;
|
||||
this.ws.send(statsPayload);
|
||||
}
|
||||
}
|
||||
else if (event.type === 'error') {
|
||||
let payload = {
|
||||
type: 'gemini-error',
|
||||
error: event.error || event.message || 'Unknown Gemini streaming error'
|
||||
};
|
||||
if (socketSessionId) payload.sessionId = socketSessionId;
|
||||
this.ws.send(payload);
|
||||
}
|
||||
}
|
||||
|
||||
forceFlush() {
|
||||
// If the buffer has content, try to parse it one last time
|
||||
if (this.buffer.trim()) {
|
||||
try {
|
||||
const event = JSON.parse(this.buffer);
|
||||
|
||||
647
server/index.js
647
server/index.js
@@ -3,17 +3,35 @@
|
||||
import './load-env.js';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname } from 'path';
|
||||
|
||||
const __dirname = getModuleDir(import.meta.url);
|
||||
// The server source runs from /server, while the compiled output runs from /dist-server/server.
|
||||
// Resolving the app root once keeps every repo-level lookup below aligned across both layouts.
|
||||
const APP_ROOT = findAppRoot(__dirname);
|
||||
const installMode = fs.existsSync(path.join(APP_ROOT, '.git')) ? 'git' : 'npm';
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
import { c } from './utils/colors.js';
|
||||
const installMode = fs.existsSync(path.join(__dirname, '..', '.git')) ? 'git' : 'npm';
|
||||
|
||||
console.log('SERVER_PORT from env:', process.env.SERVER_PORT);
|
||||
// ANSI color codes for terminal output
|
||||
const colors = {
|
||||
reset: '\x1b[0m',
|
||||
bright: '\x1b[1m',
|
||||
cyan: '\x1b[36m',
|
||||
green: '\x1b[32m',
|
||||
yellow: '\x1b[33m',
|
||||
blue: '\x1b[34m',
|
||||
dim: '\x1b[2m',
|
||||
};
|
||||
|
||||
const c = {
|
||||
info: (text) => `${colors.cyan}${text}${colors.reset}`,
|
||||
ok: (text) => `${colors.green}${text}${colors.reset}`,
|
||||
warn: (text) => `${colors.yellow}${text}${colors.reset}`,
|
||||
tip: (text) => `${colors.blue}${text}${colors.reset}`,
|
||||
bright: (text) => `${colors.bright}${text}${colors.reset}`,
|
||||
dim: (text) => `${colors.dim}${text}${colors.reset}`,
|
||||
};
|
||||
|
||||
console.log('PORT from env:', process.env.PORT);
|
||||
|
||||
import express from 'express';
|
||||
import { WebSocketServer, WebSocket } from 'ws';
|
||||
@@ -26,8 +44,8 @@ import pty from 'node-pty';
|
||||
import fetch from 'node-fetch';
|
||||
import mime from 'mime-types';
|
||||
|
||||
import { getProjects, getSessions, renameProject, deleteSession, deleteProject, addProjectManually, extractProjectDirectory, clearProjectDirectoryCache, searchConversations } from './projects.js';
|
||||
import { queryClaudeSDK, abortClaudeSDKSession, isClaudeSDKSessionActive, getActiveClaudeSDKSessions, resolveToolApproval, getPendingApprovalsForSession, reconnectSessionWriter } from './claude-sdk.js';
|
||||
import { getProjects, getSessions, getSessionMessages, renameProject, deleteSession, deleteProject, addProjectManually, extractProjectDirectory, clearProjectDirectoryCache } from './projects.js';
|
||||
import { queryClaudeSDK, abortClaudeSDKSession, isClaudeSDKSessionActive, getActiveClaudeSDKSessions, resolveToolApproval } from './claude-sdk.js';
|
||||
import { spawnCursor, abortCursorSession, isCursorSessionActive, getActiveCursorSessions } from './cursor-cli.js';
|
||||
import { queryCodex, abortCodexSession, isCodexSessionActive, getActiveCodexSessions } from './openai-codex.js';
|
||||
import { spawnGemini, abortGeminiSession, isGeminiSessionActive, getActiveGeminiSessions } from './gemini-cli.js';
|
||||
@@ -46,17 +64,10 @@ import cliAuthRoutes from './routes/cli-auth.js';
|
||||
import userRoutes from './routes/user.js';
|
||||
import codexRoutes from './routes/codex.js';
|
||||
import geminiRoutes from './routes/gemini.js';
|
||||
import pluginsRoutes from './routes/plugins.js';
|
||||
import messagesRoutes from './routes/messages.js';
|
||||
import { createNormalizedMessage } from './providers/types.js';
|
||||
import { startEnabledPluginServers, stopAllPlugins, getPluginPort } from './utils/plugin-process-manager.js';
|
||||
import { initializeDatabase, sessionNamesDb, applyCustomSessionNames } from './database/db.js';
|
||||
import { initializeDatabase } from './database/db.js';
|
||||
import { configureWebPush } from './services/vapid-keys.js';
|
||||
import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
|
||||
import { IS_PLATFORM } from './constants/config.js';
|
||||
import { getConnectableHost } from '../shared/networkHosts.js';
|
||||
|
||||
const VALID_PROVIDERS = ['claude', 'codex', 'cursor', 'gemini'];
|
||||
|
||||
// File system watchers for provider project/session folders
|
||||
const PROVIDER_WATCH_PATHS = [
|
||||
@@ -208,7 +219,68 @@ const server = http.createServer(app);
|
||||
const ptySessionsMap = new Map();
|
||||
const PTY_SESSION_TIMEOUT = 30 * 60 * 1000;
|
||||
const SHELL_URL_PARSE_BUFFER_LIMIT = 32768;
|
||||
import { stripAnsiSequences, normalizeDetectedUrl, extractUrlsFromText, shouldAutoOpenUrlFromOutput } from './utils/url-detection.js';
|
||||
const ANSI_ESCAPE_SEQUENCE_REGEX = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
|
||||
const TRAILING_URL_PUNCTUATION_REGEX = /[)\]}>.,;:!?]+$/;
|
||||
|
||||
function stripAnsiSequences(value = '') {
|
||||
return value.replace(ANSI_ESCAPE_SEQUENCE_REGEX, '');
|
||||
}
|
||||
|
||||
function normalizeDetectedUrl(url) {
|
||||
if (!url || typeof url !== 'string') return null;
|
||||
|
||||
const cleaned = url.trim().replace(TRAILING_URL_PUNCTUATION_REGEX, '');
|
||||
if (!cleaned) return null;
|
||||
|
||||
try {
|
||||
const parsed = new URL(cleaned);
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
return null;
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function extractUrlsFromText(value = '') {
|
||||
const directMatches = value.match(/https?:\/\/[^\s<>"'`\\\x1b\x07]+/gi) || [];
|
||||
|
||||
// Handle wrapped terminal URLs split across lines by terminal width.
|
||||
const wrappedMatches = [];
|
||||
const continuationRegex = /^[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+$/;
|
||||
const lines = value.split(/\r?\n/);
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
const startMatch = line.match(/https?:\/\/[^\s<>"'`\\\x1b\x07]+/i);
|
||||
if (!startMatch) continue;
|
||||
|
||||
let combined = startMatch[0];
|
||||
let j = i + 1;
|
||||
while (j < lines.length) {
|
||||
const continuation = lines[j].trim();
|
||||
if (!continuation) break;
|
||||
if (!continuationRegex.test(continuation)) break;
|
||||
combined += continuation;
|
||||
j++;
|
||||
}
|
||||
|
||||
wrappedMatches.push(combined.replace(/\r?\n\s*/g, ''));
|
||||
}
|
||||
|
||||
return Array.from(new Set([...directMatches, ...wrappedMatches]));
|
||||
}
|
||||
|
||||
function shouldAutoOpenUrlFromOutput(value = '') {
|
||||
const normalized = value.toLowerCase();
|
||||
return (
|
||||
normalized.includes('browser didn\'t open') ||
|
||||
normalized.includes('open this url') ||
|
||||
normalized.includes('continue in your browser') ||
|
||||
normalized.includes('press enter to open') ||
|
||||
normalized.includes('open_url:')
|
||||
);
|
||||
}
|
||||
|
||||
// Single WebSocket server that handles both paths
|
||||
const wss = new WebSocketServer({
|
||||
@@ -251,7 +323,7 @@ const wss = new WebSocketServer({
|
||||
// Make WebSocket server available to routes
|
||||
app.locals.wss = wss;
|
||||
|
||||
app.use(cors({ exposedHeaders: ['X-Refreshed-Token'] }));
|
||||
app.use(cors());
|
||||
app.use(express.json({
|
||||
limit: '50mb',
|
||||
type: (req) => {
|
||||
@@ -316,21 +388,15 @@ app.use('/api/codex', authenticateToken, codexRoutes);
|
||||
// Gemini API Routes (protected)
|
||||
app.use('/api/gemini', authenticateToken, geminiRoutes);
|
||||
|
||||
// Plugins API Routes (protected)
|
||||
app.use('/api/plugins', authenticateToken, pluginsRoutes);
|
||||
|
||||
// Unified session messages route (protected)
|
||||
app.use('/api/sessions', authenticateToken, messagesRoutes);
|
||||
|
||||
// Agent API Routes (uses API key authentication)
|
||||
app.use('/api/agent', agentRoutes);
|
||||
|
||||
// Serve public files (like api-docs.html)
|
||||
app.use(express.static(path.join(APP_ROOT, 'public')));
|
||||
app.use(express.static(path.join(__dirname, '../public')));
|
||||
|
||||
// Static files served after API routes
|
||||
// Add cache control: HTML files should not be cached, but assets can be cached
|
||||
app.use(express.static(path.join(APP_ROOT, 'dist'), {
|
||||
app.use(express.static(path.join(__dirname, '../dist'), {
|
||||
setHeaders: (res, filePath) => {
|
||||
if (filePath.endsWith('.html')) {
|
||||
// Prevent HTML caching to avoid service worker issues after builds
|
||||
@@ -352,24 +418,17 @@ app.use(express.static(path.join(APP_ROOT, 'dist'), {
|
||||
app.post('/api/system/update', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
// Get the project root directory (parent of server directory)
|
||||
const projectRoot = APP_ROOT;
|
||||
const projectRoot = path.join(__dirname, '..');
|
||||
|
||||
console.log('Starting system update from directory:', projectRoot);
|
||||
|
||||
// Platform deployments use their own update workflow from the project root.
|
||||
const updateCommand = IS_PLATFORM
|
||||
// In platform, husky and dev dependencies are not needed
|
||||
? 'npm run update:platform'
|
||||
: installMode === 'git'
|
||||
? 'git checkout main && git pull && npm install'
|
||||
: 'npm install -g @cloudcli-ai/cloudcli@latest';
|
||||
|
||||
const updateCwd = IS_PLATFORM || installMode === 'git'
|
||||
? projectRoot
|
||||
: os.homedir();
|
||||
// Run the update command based on install mode
|
||||
const updateCommand = installMode === 'git'
|
||||
? 'git checkout main && git pull && npm install'
|
||||
: 'npm install -g @siteboon/claude-code-ui@latest';
|
||||
|
||||
const child = spawn('sh', ['-c', updateCommand], {
|
||||
cwd: updateCwd,
|
||||
cwd: installMode === 'git' ? projectRoot : os.homedir(),
|
||||
env: process.env
|
||||
});
|
||||
|
||||
@@ -435,13 +494,37 @@ app.get('/api/projects/:projectName/sessions', authenticateToken, async (req, re
|
||||
try {
|
||||
const { limit = 5, offset = 0 } = req.query;
|
||||
const result = await getSessions(req.params.projectName, parseInt(limit), parseInt(offset));
|
||||
applyCustomSessionNames(result.sessions, 'claude');
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get messages for a specific session
|
||||
app.get('/api/projects/:projectName/sessions/:sessionId/messages', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { projectName, sessionId } = req.params;
|
||||
const { limit, offset } = req.query;
|
||||
|
||||
// Parse limit and offset if provided
|
||||
const parsedLimit = limit ? parseInt(limit, 10) : null;
|
||||
const parsedOffset = offset ? parseInt(offset, 10) : 0;
|
||||
|
||||
const result = await getSessionMessages(projectName, sessionId, parsedLimit, parsedOffset);
|
||||
|
||||
// Handle both old and new response formats
|
||||
if (Array.isArray(result)) {
|
||||
// Backward compatibility: no pagination parameters were provided
|
||||
res.json({ messages: result });
|
||||
} else {
|
||||
// New format with pagination info
|
||||
res.json(result);
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Rename project endpoint
|
||||
app.put('/api/projects/:projectName/rename', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
@@ -459,7 +542,6 @@ app.delete('/api/projects/:projectName/sessions/:sessionId', authenticateToken,
|
||||
const { projectName, sessionId } = req.params;
|
||||
console.log(`[API] Deleting session: ${sessionId} from project: ${projectName}`);
|
||||
await deleteSession(projectName, sessionId);
|
||||
sessionNamesDb.deleteName(sessionId, 'claude');
|
||||
console.log(`[API] Session ${sessionId} deleted successfully`);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
@@ -468,41 +550,12 @@ app.delete('/api/projects/:projectName/sessions/:sessionId', authenticateToken,
|
||||
}
|
||||
});
|
||||
|
||||
// Rename session endpoint
|
||||
app.put('/api/sessions/:sessionId/rename', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { sessionId } = req.params;
|
||||
const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
|
||||
if (!safeSessionId || safeSessionId !== String(sessionId)) {
|
||||
return res.status(400).json({ error: 'Invalid sessionId' });
|
||||
}
|
||||
const { summary, provider } = req.body;
|
||||
if (!summary || typeof summary !== 'string' || summary.trim() === '') {
|
||||
return res.status(400).json({ error: 'Summary is required' });
|
||||
}
|
||||
if (summary.trim().length > 500) {
|
||||
return res.status(400).json({ error: 'Summary must not exceed 500 characters' });
|
||||
}
|
||||
if (!provider || !VALID_PROVIDERS.includes(provider)) {
|
||||
return res.status(400).json({ error: `Provider must be one of: ${VALID_PROVIDERS.join(', ')}` });
|
||||
}
|
||||
sessionNamesDb.setName(safeSessionId, provider, summary.trim());
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error(`[API] Error renaming session ${req.params.sessionId}:`, error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete project endpoint
|
||||
// force=true to allow removal even when sessions exist
|
||||
// deleteData=true to also delete session/memory files on disk (destructive)
|
||||
// Delete project endpoint (force=true to delete with sessions)
|
||||
app.delete('/api/projects/:projectName', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { projectName } = req.params;
|
||||
const force = req.query.force === 'true';
|
||||
const deleteData = req.query.deleteData === 'true';
|
||||
await deleteProject(projectName, force, deleteData);
|
||||
await deleteProject(projectName, force);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
@@ -526,51 +579,6 @@ app.post('/api/projects/create', authenticateToken, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Search conversations content (SSE streaming)
|
||||
app.get('/api/search/conversations', authenticateToken, async (req, res) => {
|
||||
const query = typeof req.query.q === 'string' ? req.query.q.trim() : '';
|
||||
const parsedLimit = Number.parseInt(String(req.query.limit), 10);
|
||||
const limit = Number.isNaN(parsedLimit) ? 50 : Math.max(1, Math.min(parsedLimit, 100));
|
||||
|
||||
if (query.length < 2) {
|
||||
return res.status(400).json({ error: 'Query must be at least 2 characters' });
|
||||
}
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
});
|
||||
|
||||
let closed = false;
|
||||
const abortController = new AbortController();
|
||||
req.on('close', () => { closed = true; abortController.abort(); });
|
||||
|
||||
try {
|
||||
await searchConversations(query, limit, ({ projectResult, totalMatches, scannedProjects, totalProjects }) => {
|
||||
if (closed) return;
|
||||
if (projectResult) {
|
||||
res.write(`event: result\ndata: ${JSON.stringify({ projectResult, totalMatches, scannedProjects, totalProjects })}\n\n`);
|
||||
} else {
|
||||
res.write(`event: progress\ndata: ${JSON.stringify({ totalMatches, scannedProjects, totalProjects })}\n\n`);
|
||||
}
|
||||
}, abortController.signal);
|
||||
if (!closed) {
|
||||
res.write(`event: done\ndata: {}\n\n`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error searching conversations:', error);
|
||||
if (!closed) {
|
||||
res.write(`event: error\ndata: ${JSON.stringify({ error: 'Search failed' })}\n\n`);
|
||||
}
|
||||
} finally {
|
||||
if (!closed) {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const expandWorkspacePath = (inputPath) => {
|
||||
if (!inputPath) return inputPath;
|
||||
if (inputPath === '~') {
|
||||
@@ -743,7 +751,7 @@ app.get('/api/projects/:projectName/file', authenticateToken, async (req, res) =
|
||||
}
|
||||
});
|
||||
|
||||
// Serve raw file bytes for previews and downloads.
|
||||
// Serve binary file content endpoint (for images, etc.)
|
||||
app.get('/api/projects/:projectName/files/content', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { projectName } = req.params;
|
||||
@@ -760,11 +768,7 @@ app.get('/api/projects/:projectName/files/content', authenticateToken, async (re
|
||||
return res.status(404).json({ error: 'Project not found' });
|
||||
}
|
||||
|
||||
// Match the text reader endpoint so callers can pass either project-relative
|
||||
// or absolute paths without changing how the bytes are served.
|
||||
const resolved = path.isAbsolute(filePath)
|
||||
? path.resolve(filePath)
|
||||
: path.resolve(projectRoot, filePath);
|
||||
const resolved = path.resolve(filePath);
|
||||
const normalizedRoot = path.resolve(projectRoot) + path.sep;
|
||||
if (!resolved.startsWith(normalizedRoot)) {
|
||||
return res.status(403).json({ error: 'Path must be under project root' });
|
||||
@@ -873,6 +877,7 @@ app.get('/api/projects/:projectName/files', authenticateToken, async (req, res)
|
||||
}
|
||||
|
||||
const files = await getFileTree(actualPath, 10, 0, true);
|
||||
const hiddenFiles = files.filter(f => f.name.startsWith('.'));
|
||||
res.json(files);
|
||||
} catch (error) {
|
||||
console.error('[ERROR] File tree error:', error.message);
|
||||
@@ -1310,50 +1315,6 @@ const uploadFilesHandler = async (req, res) => {
|
||||
|
||||
app.post('/api/projects/:projectName/files/upload', authenticateToken, uploadFilesHandler);
|
||||
|
||||
/**
|
||||
* Proxy an authenticated client WebSocket to a plugin's internal WS server.
|
||||
* Auth is enforced by verifyClient before this function is reached.
|
||||
*/
|
||||
function handlePluginWsProxy(clientWs, pathname) {
|
||||
const pluginName = pathname.replace('/plugin-ws/', '');
|
||||
if (!pluginName || /[^a-zA-Z0-9_-]/.test(pluginName)) {
|
||||
clientWs.close(4400, 'Invalid plugin name');
|
||||
return;
|
||||
}
|
||||
|
||||
const port = getPluginPort(pluginName);
|
||||
if (!port) {
|
||||
clientWs.close(4404, 'Plugin not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const upstream = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||
|
||||
upstream.on('open', () => {
|
||||
console.log(`[Plugins] WS proxy connected to "${pluginName}" on port ${port}`);
|
||||
});
|
||||
|
||||
// Relay messages bidirectionally
|
||||
upstream.on('message', (data) => {
|
||||
if (clientWs.readyState === WebSocket.OPEN) clientWs.send(data);
|
||||
});
|
||||
clientWs.on('message', (data) => {
|
||||
if (upstream.readyState === WebSocket.OPEN) upstream.send(data);
|
||||
});
|
||||
|
||||
// Propagate close in both directions
|
||||
upstream.on('close', () => { if (clientWs.readyState === WebSocket.OPEN) clientWs.close(); });
|
||||
clientWs.on('close', () => { if (upstream.readyState === WebSocket.OPEN) upstream.close(); });
|
||||
|
||||
upstream.on('error', (err) => {
|
||||
console.error(`[Plugins] WS proxy error for "${pluginName}":`, err.message);
|
||||
if (clientWs.readyState === WebSocket.OPEN) clientWs.close(4502, 'Upstream error');
|
||||
});
|
||||
clientWs.on('error', () => {
|
||||
if (upstream.readyState === WebSocket.OPEN) upstream.close();
|
||||
});
|
||||
}
|
||||
|
||||
// WebSocket connection handler that routes based on URL path
|
||||
wss.on('connection', (ws, request) => {
|
||||
const url = request.url;
|
||||
@@ -1367,8 +1328,6 @@ wss.on('connection', (ws, request) => {
|
||||
handleShellConnection(ws);
|
||||
} else if (pathname === '/ws') {
|
||||
handleChatConnection(ws, request);
|
||||
} else if (pathname.startsWith('/plugin-ws/')) {
|
||||
handlePluginWsProxy(ws, pathname);
|
||||
} else {
|
||||
console.log('[WARN] Unknown WebSocket path:', pathname);
|
||||
ws.close();
|
||||
@@ -1377,10 +1336,6 @@ wss.on('connection', (ws, request) => {
|
||||
|
||||
/**
|
||||
* WebSocket Writer - Wrapper for WebSocket to match SSEStreamWriter interface
|
||||
*
|
||||
* Provider files use `createNormalizedMessage()` from `providers/types.js` and
|
||||
* adapter `normalizeMessage()` to produce unified NormalizedMessage events.
|
||||
* The writer simply serialises and sends.
|
||||
*/
|
||||
class WebSocketWriter {
|
||||
constructor(ws, userId = null) {
|
||||
@@ -1392,14 +1347,11 @@ class WebSocketWriter {
|
||||
|
||||
send(data) {
|
||||
if (this.ws.readyState === 1) { // WebSocket.OPEN
|
||||
// Providers send raw objects, we stringify for WebSocket
|
||||
this.ws.send(JSON.stringify(data));
|
||||
}
|
||||
}
|
||||
|
||||
updateWebSocket(newRawWs) {
|
||||
this.ws = newRawWs;
|
||||
}
|
||||
|
||||
setSessionId(sessionId) {
|
||||
this.sessionId = sessionId;
|
||||
}
|
||||
@@ -1472,7 +1424,12 @@ function handleChatConnection(ws, request) {
|
||||
success = await abortClaudeSDKSession(data.sessionId);
|
||||
}
|
||||
|
||||
writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider }));
|
||||
writer.send({
|
||||
type: 'session-aborted',
|
||||
sessionId: data.sessionId,
|
||||
provider,
|
||||
success
|
||||
});
|
||||
} else if (data.type === 'claude-permission-response') {
|
||||
// Relay UI approval decisions back into the SDK control flow.
|
||||
// This does not persist permissions; it only resolves the in-flight request,
|
||||
@@ -1488,7 +1445,12 @@ function handleChatConnection(ws, request) {
|
||||
} else if (data.type === 'cursor-abort') {
|
||||
console.log('[DEBUG] Abort Cursor session:', data.sessionId);
|
||||
const success = abortCursorSession(data.sessionId);
|
||||
writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider: 'cursor' }));
|
||||
writer.send({
|
||||
type: 'session-aborted',
|
||||
sessionId: data.sessionId,
|
||||
provider: 'cursor',
|
||||
success
|
||||
});
|
||||
} else if (data.type === 'check-session-status') {
|
||||
// Check if a specific session is currently processing
|
||||
const provider = data.provider || 'claude';
|
||||
@@ -1504,11 +1466,6 @@ function handleChatConnection(ws, request) {
|
||||
} else {
|
||||
// Use Claude Agents SDK
|
||||
isActive = isClaudeSDKSessionActive(sessionId);
|
||||
if (isActive) {
|
||||
// Reconnect the session's writer to the new WebSocket so
|
||||
// subsequent SDK output flows to the refreshed client.
|
||||
reconnectSessionWriter(sessionId, ws);
|
||||
}
|
||||
}
|
||||
|
||||
writer.send({
|
||||
@@ -1517,17 +1474,6 @@ function handleChatConnection(ws, request) {
|
||||
provider,
|
||||
isProcessing: isActive
|
||||
});
|
||||
} else if (data.type === 'get-pending-permissions') {
|
||||
// Return pending permission requests for a session
|
||||
const sessionId = data.sessionId;
|
||||
if (sessionId && isClaudeSDKSessionActive(sessionId)) {
|
||||
const pending = getPendingApprovalsForSession(sessionId);
|
||||
writer.send({
|
||||
type: 'pending-permissions-response',
|
||||
sessionId,
|
||||
data: pending
|
||||
});
|
||||
}
|
||||
} else if (data.type === 'get-active-sessions') {
|
||||
// Get all currently active sessions
|
||||
const activeSessions = {
|
||||
@@ -1655,49 +1601,50 @@ function handleShellConnection(ws) {
|
||||
}));
|
||||
|
||||
try {
|
||||
// Validate projectPath — resolve to absolute and verify it exists
|
||||
const resolvedProjectPath = path.resolve(projectPath);
|
||||
try {
|
||||
const stats = fs.statSync(resolvedProjectPath);
|
||||
if (!stats.isDirectory()) {
|
||||
throw new Error('Not a directory');
|
||||
}
|
||||
} catch (pathErr) {
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'Invalid project path' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate sessionId — only allow safe characters
|
||||
const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
|
||||
if (sessionId && !safeSessionIdPattern.test(sessionId)) {
|
||||
ws.send(JSON.stringify({ type: 'error', message: 'Invalid session ID' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Build shell command — use cwd for project path (never interpolate into shell string)
|
||||
// Prepare the shell command adapted to the platform and provider
|
||||
let shellCommand;
|
||||
if (isPlainShell) {
|
||||
// Plain shell mode - run the initial command in the project directory
|
||||
shellCommand = initialCommand;
|
||||
} else if (provider === 'cursor') {
|
||||
if (hasSession && sessionId) {
|
||||
shellCommand = `cursor-agent --resume="${sessionId}"`;
|
||||
// Plain shell mode - just run the initial command in the project directory
|
||||
if (os.platform() === 'win32') {
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; ${initialCommand}`;
|
||||
} else {
|
||||
shellCommand = 'cursor-agent';
|
||||
shellCommand = `cd "${projectPath}" && ${initialCommand}`;
|
||||
}
|
||||
} else if (provider === 'codex') {
|
||||
// Use codex command; attempt to resume and fall back to a new session when the resume fails.
|
||||
if (hasSession && sessionId) {
|
||||
if (os.platform() === 'win32') {
|
||||
// PowerShell syntax for fallback
|
||||
shellCommand = `codex resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { codex }`;
|
||||
} else if (provider === 'cursor') {
|
||||
// Use cursor-agent command
|
||||
if (os.platform() === 'win32') {
|
||||
if (hasSession && sessionId) {
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; cursor-agent --resume="${sessionId}"`;
|
||||
} else {
|
||||
shellCommand = `codex resume "${sessionId}" || codex`;
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; cursor-agent`;
|
||||
}
|
||||
} else {
|
||||
shellCommand = 'codex';
|
||||
if (hasSession && sessionId) {
|
||||
shellCommand = `cd "${projectPath}" && cursor-agent --resume="${sessionId}"`;
|
||||
} else {
|
||||
shellCommand = `cd "${projectPath}" && cursor-agent`;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (provider === 'codex') {
|
||||
// Use codex command
|
||||
if (os.platform() === 'win32') {
|
||||
if (hasSession && sessionId) {
|
||||
// Try to resume session, but with fallback to a new session if it fails
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; codex resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { codex }`;
|
||||
} else {
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; codex`;
|
||||
}
|
||||
} else {
|
||||
if (hasSession && sessionId) {
|
||||
// Try to resume session, but with fallback to a new session if it fails
|
||||
shellCommand = `cd "${projectPath}" && codex resume "${sessionId}" || codex`;
|
||||
} else {
|
||||
shellCommand = `cd "${projectPath}" && codex`;
|
||||
}
|
||||
}
|
||||
} else if (provider === 'gemini') {
|
||||
// Use gemini command
|
||||
const command = initialCommand || 'gemini';
|
||||
let resumeId = sessionId;
|
||||
if (hasSession && sessionId) {
|
||||
@@ -1708,32 +1655,41 @@ function handleShellConnection(ws) {
|
||||
const sess = sessionManager.getSession(sessionId);
|
||||
if (sess && sess.cliSessionId) {
|
||||
resumeId = sess.cliSessionId;
|
||||
// Validate the looked-up CLI session ID too
|
||||
if (!safeSessionIdPattern.test(resumeId)) {
|
||||
resumeId = null;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to get Gemini CLI session ID:', err);
|
||||
}
|
||||
}
|
||||
|
||||
if (hasSession && resumeId) {
|
||||
shellCommand = `${command} --resume "${resumeId}"`;
|
||||
} else {
|
||||
shellCommand = command;
|
||||
}
|
||||
} else {
|
||||
// Claude (default provider)
|
||||
const command = initialCommand || 'claude';
|
||||
if (hasSession && sessionId) {
|
||||
if (os.platform() === 'win32') {
|
||||
shellCommand = `claude --resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { claude }`;
|
||||
if (os.platform() === 'win32') {
|
||||
if (hasSession && resumeId) {
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; ${command} --resume "${resumeId}"`;
|
||||
} else {
|
||||
shellCommand = `claude --resume "${sessionId}" || claude`;
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; ${command}`;
|
||||
}
|
||||
} else {
|
||||
shellCommand = command;
|
||||
if (hasSession && resumeId) {
|
||||
shellCommand = `cd "${projectPath}" && ${command} --resume "${resumeId}"`;
|
||||
} else {
|
||||
shellCommand = `cd "${projectPath}" && ${command}`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Use claude command (default) or initialCommand if provided
|
||||
const command = initialCommand || 'claude';
|
||||
if (os.platform() === 'win32') {
|
||||
if (hasSession && sessionId) {
|
||||
// Try to resume session, but with fallback to new session if it fails
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; claude --resume ${sessionId}; if ($LASTEXITCODE -ne 0) { claude }`;
|
||||
} else {
|
||||
shellCommand = `Set-Location -Path "${projectPath}"; ${command}`;
|
||||
}
|
||||
} else {
|
||||
if (hasSession && sessionId) {
|
||||
shellCommand = `cd "${projectPath}" && claude --resume ${sessionId} || claude`;
|
||||
} else {
|
||||
shellCommand = `cd "${projectPath}" && ${command}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1752,7 +1708,7 @@ function handleShellConnection(ws) {
|
||||
name: 'xterm-256color',
|
||||
cols: termCols,
|
||||
rows: termRows,
|
||||
cwd: resolvedProjectPath,
|
||||
cwd: os.homedir(),
|
||||
env: {
|
||||
...process.env,
|
||||
TERM: 'xterm-256color',
|
||||
@@ -1915,6 +1871,155 @@ function handleShellConnection(ws) {
|
||||
console.error('[ERROR] Shell WebSocket error:', error);
|
||||
});
|
||||
}
|
||||
// Audio transcription endpoint
|
||||
app.post('/api/transcribe', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const multer = (await import('multer')).default;
|
||||
const upload = multer({ storage: multer.memoryStorage() });
|
||||
|
||||
// Handle multipart form data
|
||||
upload.single('audio')(req, res, async (err) => {
|
||||
if (err) {
|
||||
return res.status(400).json({ error: 'Failed to process audio file' });
|
||||
}
|
||||
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: 'No audio file provided' });
|
||||
}
|
||||
|
||||
const apiKey = process.env.OPENAI_API_KEY;
|
||||
if (!apiKey) {
|
||||
return res.status(500).json({ error: 'OpenAI API key not configured. Please set OPENAI_API_KEY in server environment.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Create form data for OpenAI
|
||||
const FormData = (await import('form-data')).default;
|
||||
const formData = new FormData();
|
||||
formData.append('file', req.file.buffer, {
|
||||
filename: req.file.originalname,
|
||||
contentType: req.file.mimetype
|
||||
});
|
||||
formData.append('model', 'whisper-1');
|
||||
formData.append('response_format', 'json');
|
||||
formData.append('language', 'en');
|
||||
|
||||
// Make request to OpenAI
|
||||
const response = await fetch('https://api.openai.com/v1/audio/transcriptions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${apiKey}`,
|
||||
...formData.getHeaders()
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error?.message || `Whisper API error: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
let transcribedText = data.text || '';
|
||||
|
||||
// Check if enhancement mode is enabled
|
||||
const mode = req.body.mode || 'default';
|
||||
|
||||
// If no transcribed text, return empty
|
||||
if (!transcribedText) {
|
||||
return res.json({ text: '' });
|
||||
}
|
||||
|
||||
// If default mode, return transcribed text without enhancement
|
||||
if (mode === 'default') {
|
||||
return res.json({ text: transcribedText });
|
||||
}
|
||||
|
||||
// Handle different enhancement modes
|
||||
try {
|
||||
const OpenAI = (await import('openai')).default;
|
||||
const openai = new OpenAI({ apiKey });
|
||||
|
||||
let prompt, systemMessage, temperature = 0.7, maxTokens = 800;
|
||||
|
||||
switch (mode) {
|
||||
case 'prompt':
|
||||
systemMessage = 'You are an expert prompt engineer who creates clear, detailed, and effective prompts.';
|
||||
prompt = `You are an expert prompt engineer. Transform the following rough instruction into a clear, detailed, and context-aware AI prompt.
|
||||
|
||||
Your enhanced prompt should:
|
||||
1. Be specific and unambiguous
|
||||
2. Include relevant context and constraints
|
||||
3. Specify the desired output format
|
||||
4. Use clear, actionable language
|
||||
5. Include examples where helpful
|
||||
6. Consider edge cases and potential ambiguities
|
||||
|
||||
Transform this rough instruction into a well-crafted prompt:
|
||||
"${transcribedText}"
|
||||
|
||||
Enhanced prompt:`;
|
||||
break;
|
||||
|
||||
case 'vibe':
|
||||
case 'instructions':
|
||||
case 'architect':
|
||||
systemMessage = 'You are a helpful assistant that formats ideas into clear, actionable instructions for AI agents.';
|
||||
temperature = 0.5; // Lower temperature for more controlled output
|
||||
prompt = `Transform the following idea into clear, well-structured instructions that an AI agent can easily understand and execute.
|
||||
|
||||
IMPORTANT RULES:
|
||||
- Format as clear, step-by-step instructions
|
||||
- Add reasonable implementation details based on common patterns
|
||||
- Only include details directly related to what was asked
|
||||
- Do NOT add features or functionality not mentioned
|
||||
- Keep the original intent and scope intact
|
||||
- Use clear, actionable language an agent can follow
|
||||
|
||||
Transform this idea into agent-friendly instructions:
|
||||
"${transcribedText}"
|
||||
|
||||
Agent instructions:`;
|
||||
break;
|
||||
|
||||
default:
|
||||
// No enhancement needed
|
||||
break;
|
||||
}
|
||||
|
||||
// Only make GPT call if we have a prompt
|
||||
if (prompt) {
|
||||
const completion = await openai.chat.completions.create({
|
||||
model: 'gpt-4o-mini',
|
||||
messages: [
|
||||
{ role: 'system', content: systemMessage },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
temperature: temperature,
|
||||
max_tokens: maxTokens
|
||||
});
|
||||
|
||||
transcribedText = completion.choices[0].message.content || transcribedText;
|
||||
}
|
||||
|
||||
} catch (gptError) {
|
||||
console.error('GPT processing error:', gptError);
|
||||
// Fall back to original transcription if GPT fails
|
||||
}
|
||||
|
||||
res.json({ text: transcribedText });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Transcription error:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Endpoint error:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Image upload endpoint
|
||||
app.post('/api/projects/:projectName/upload-images', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
@@ -2009,7 +2114,7 @@ app.get('/api/projects/:projectName/sessions/:sessionId/token-usage', authentica
|
||||
|
||||
// Allow only safe characters in sessionId
|
||||
const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
|
||||
if (!safeSessionId || safeSessionId !== String(sessionId)) {
|
||||
if (!safeSessionId) {
|
||||
return res.status(400).json({ error: 'Invalid sessionId' });
|
||||
}
|
||||
|
||||
@@ -2197,7 +2302,7 @@ app.get('*', (req, res) => {
|
||||
|
||||
// Only serve index.html for HTML routes, not for static assets
|
||||
// Static assets should already be handled by express.static middleware above
|
||||
const indexPath = path.join(APP_ROOT, 'dist', 'index.html');
|
||||
const indexPath = path.join(__dirname, '../dist/index.html');
|
||||
|
||||
// Check if dist/index.html exists (production build available)
|
||||
if (fs.existsSync(indexPath)) {
|
||||
@@ -2208,8 +2313,7 @@ app.get('*', (req, res) => {
|
||||
res.sendFile(indexPath);
|
||||
} else {
|
||||
// In development, redirect to Vite dev server only if dist doesn't exist
|
||||
const redirectHost = getConnectableHost(req.hostname);
|
||||
res.redirect(`${req.protocol}://${redirectHost}:${VITE_PORT}`);
|
||||
res.redirect(`http://localhost:${process.env.VITE_PORT || 5173}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2297,10 +2401,10 @@ async function getFileTree(dirPath, maxDepth = 3, currentDepth = 0, showHidden =
|
||||
});
|
||||
}
|
||||
|
||||
const SERVER_PORT = process.env.SERVER_PORT || 3001;
|
||||
const PORT = process.env.PORT || 3001;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
const DISPLAY_HOST = getConnectableHost(HOST);
|
||||
const VITE_PORT = process.env.VITE_PORT || 5173;
|
||||
// Show localhost in URL when binding to all interfaces (0.0.0.0 isn't a connectable address)
|
||||
const DISPLAY_HOST = HOST === '0.0.0.0' ? 'localhost' : HOST;
|
||||
|
||||
// Initialize database and start server
|
||||
async function startServer() {
|
||||
@@ -2312,48 +2416,33 @@ async function startServer() {
|
||||
configureWebPush();
|
||||
|
||||
// Check if running in production mode (dist folder exists)
|
||||
const distIndexPath = path.join(APP_ROOT, 'dist', 'index.html');
|
||||
const distIndexPath = path.join(__dirname, '../dist/index.html');
|
||||
const isProduction = fs.existsSync(distIndexPath);
|
||||
|
||||
// Log Claude implementation mode
|
||||
console.log(`${c.info('[INFO]')} Using Claude Agents SDK for Claude integration`);
|
||||
console.log('');
|
||||
console.log(`${c.info('[INFO]')} Running in ${c.bright(isProduction ? 'PRODUCTION' : 'DEVELOPMENT')} mode`);
|
||||
|
||||
if (isProduction) {
|
||||
console.log(`${c.info('[INFO]')} To run in production mode, go to http://${DISPLAY_HOST}:${SERVER_PORT}`);
|
||||
if (!isProduction) {
|
||||
console.log(`${c.warn('[WARN]')} Note: Requests will be proxied to Vite dev server at ${c.dim('http://localhost:' + (process.env.VITE_PORT || 5173))}`);
|
||||
}
|
||||
|
||||
console.log(`${c.info('[INFO]')} To run in development mode with hot-module replacement, go to http://${DISPLAY_HOST}:${VITE_PORT}`);
|
||||
|
||||
server.listen(SERVER_PORT, HOST, async () => {
|
||||
const appInstallPath = APP_ROOT;
|
||||
server.listen(PORT, HOST, async () => {
|
||||
const appInstallPath = path.join(__dirname, '..');
|
||||
|
||||
console.log('');
|
||||
console.log(c.dim('═'.repeat(63)));
|
||||
console.log(` ${c.bright('CloudCLI Server - Ready')}`);
|
||||
console.log(` ${c.bright('Claude Code UI Server - Ready')}`);
|
||||
console.log(c.dim('═'.repeat(63)));
|
||||
console.log('');
|
||||
console.log(`${c.info('[INFO]')} Server URL: ${c.bright('http://' + DISPLAY_HOST + ':' + SERVER_PORT)}`);
|
||||
console.log(`${c.info('[INFO]')} Server URL: ${c.bright('http://' + DISPLAY_HOST + ':' + PORT)}`);
|
||||
console.log(`${c.info('[INFO]')} Installed at: ${c.dim(appInstallPath)}`);
|
||||
console.log(`${c.tip('[TIP]')} Run "cloudcli status" for full configuration details`);
|
||||
console.log('');
|
||||
|
||||
// Start watching the projects folder for changes
|
||||
await setupProjectsWatcher();
|
||||
|
||||
// Start server-side plugin processes for enabled plugins
|
||||
startEnabledPluginServers().catch(err => {
|
||||
console.error('[Plugins] Error during startup:', err.message);
|
||||
});
|
||||
});
|
||||
|
||||
// Clean up plugin processes on shutdown
|
||||
const shutdownPlugins = async () => {
|
||||
await stopAllPlugins();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', () => void shutdownPlugins());
|
||||
process.on('SIGINT', () => void shutdownPlugins());
|
||||
} catch (error) {
|
||||
console.error('[ERROR] Failed to start server:', error);
|
||||
process.exit(1);
|
||||
|
||||
@@ -2,15 +2,14 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname } from 'path';
|
||||
|
||||
const __dirname = getModuleDir(import.meta.url);
|
||||
// Resolve the repo/app root via the nearest /server folder so this file keeps finding the
|
||||
// same top-level .env file from both /server/load-env.js and /dist-server/server/load-env.js.
|
||||
const APP_ROOT = findAppRoot(__dirname);
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
try {
|
||||
const envPath = path.join(APP_ROOT, '.env');
|
||||
const envPath = path.join(__dirname, '../.env');
|
||||
const envFile = fs.readFileSync(envPath, 'utf8');
|
||||
envFile.split('\n').forEach(line => {
|
||||
const trimmedLine = line.trim();
|
||||
@@ -25,10 +24,6 @@ try {
|
||||
console.log('No .env file found or error reading it:', e.message);
|
||||
}
|
||||
|
||||
// Keep the default database in a stable user-level location so rebuilding dist-server
|
||||
// never changes where the backend stores auth.db when DATABASE_PATH is not set explicitly.
|
||||
const DEFAULT_DATABASE_PATH = path.join(os.homedir(), '.cloudcli', 'auth.db');
|
||||
|
||||
if (!process.env.DATABASE_PATH) {
|
||||
process.env.DATABASE_PATH = DEFAULT_DATABASE_PATH;
|
||||
process.env.DATABASE_PATH = path.join(os.homedir(), '.cloudcli', 'auth.db');
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { userDb, appConfigDb } from '../database/db.js';
|
||||
import { userDb } from '../database/db.js';
|
||||
import { IS_PLATFORM } from '../constants/config.js';
|
||||
|
||||
// Use env var if set, otherwise auto-generate a unique secret per installation
|
||||
const JWT_SECRET = process.env.JWT_SECRET || appConfigDb.getOrCreateJwtSecret();
|
||||
// Get JWT secret from environment or use default (for development)
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'claude-ui-dev-secret-change-in-production';
|
||||
|
||||
// Optional API key middleware
|
||||
const validateApiKey = (req, res, next) => {
|
||||
@@ -58,16 +58,6 @@ const authenticateToken = async (req, res, next) => {
|
||||
return res.status(401).json({ error: 'Invalid token. User not found.' });
|
||||
}
|
||||
|
||||
// Auto-refresh: if token is past halfway through its lifetime, issue a new one
|
||||
if (decoded.exp && decoded.iat) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const halfLife = (decoded.exp - decoded.iat) / 2;
|
||||
if (now > decoded.iat + halfLife) {
|
||||
const newToken = generateToken(user);
|
||||
res.setHeader('X-Refreshed-Token', newToken);
|
||||
}
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
} catch (error) {
|
||||
@@ -76,15 +66,15 @@ const authenticateToken = async (req, res, next) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Generate JWT token
|
||||
// Generate JWT token (never expires)
|
||||
const generateToken = (user) => {
|
||||
return jwt.sign(
|
||||
{
|
||||
userId: user.id,
|
||||
username: user.username
|
||||
{
|
||||
userId: user.id,
|
||||
username: user.username
|
||||
},
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '7d' }
|
||||
JWT_SECRET
|
||||
// No expiration - token lasts forever
|
||||
);
|
||||
};
|
||||
|
||||
@@ -111,12 +101,10 @@ const authenticateWebSocket = (token) => {
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
// Verify user actually exists in database (matches REST authenticateToken behavior)
|
||||
const user = userDb.getUserById(decoded.userId);
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
return { userId: user.id, username: user.username };
|
||||
return {
|
||||
...decoded,
|
||||
id: decoded.userId
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('WebSocket token verification error:', error);
|
||||
return null;
|
||||
|
||||
@@ -14,10 +14,6 @@
|
||||
*/
|
||||
|
||||
import { Codex } from '@openai/codex-sdk';
|
||||
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
||||
import { codexAdapter } from './providers/codex/adapter.js';
|
||||
import { createNormalizedMessage } from './providers/types.js';
|
||||
import { getStatusChecker } from './providers/registry.js';
|
||||
|
||||
// Track active sessions
|
||||
const activeCodexSessions = new Map();
|
||||
@@ -195,7 +191,6 @@ function mapPermissionModeToCodexOptions(permissionMode) {
|
||||
export async function queryCodex(command, options = {}, ws) {
|
||||
const {
|
||||
sessionId,
|
||||
sessionSummary,
|
||||
cwd,
|
||||
projectPath,
|
||||
model,
|
||||
@@ -208,7 +203,6 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
let codex;
|
||||
let thread;
|
||||
let currentSessionId = sessionId;
|
||||
let terminalFailure = null;
|
||||
const abortController = new AbortController();
|
||||
|
||||
try {
|
||||
@@ -244,7 +238,11 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
});
|
||||
|
||||
// Send session created event
|
||||
sendMessage(ws, createNormalizedMessage({ kind: 'session_created', newSessionId: currentSessionId, sessionId: currentSessionId, provider: 'codex' }));
|
||||
sendMessage(ws, {
|
||||
type: 'session-created',
|
||||
sessionId: currentSessionId,
|
||||
provider: 'codex'
|
||||
});
|
||||
|
||||
// Execute with streaming
|
||||
const streamedTurn = await thread.runStreamed(command, {
|
||||
@@ -264,41 +262,32 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
|
||||
const transformed = transformCodexEvent(event);
|
||||
|
||||
// Normalize the transformed event into NormalizedMessage(s) via adapter
|
||||
const normalizedMsgs = codexAdapter.normalizeMessage(transformed, currentSessionId);
|
||||
for (const msg of normalizedMsgs) {
|
||||
sendMessage(ws, msg);
|
||||
}
|
||||
|
||||
if (event.type === 'turn.failed' && !terminalFailure) {
|
||||
terminalFailure = event.error || new Error('Turn failed');
|
||||
notifyRunFailed({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'codex',
|
||||
sessionId: currentSessionId,
|
||||
sessionName: sessionSummary,
|
||||
error: terminalFailure
|
||||
});
|
||||
}
|
||||
sendMessage(ws, {
|
||||
type: 'codex-response',
|
||||
data: transformed,
|
||||
sessionId: currentSessionId
|
||||
});
|
||||
|
||||
// Extract and send token usage if available (normalized to match Claude format)
|
||||
if (event.type === 'turn.completed' && event.usage) {
|
||||
const totalTokens = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0);
|
||||
sendMessage(ws, createNormalizedMessage({ kind: 'status', text: 'token_budget', tokenBudget: { used: totalTokens, total: 200000 }, sessionId: currentSessionId, provider: 'codex' }));
|
||||
sendMessage(ws, {
|
||||
type: 'token-budget',
|
||||
data: {
|
||||
used: totalTokens,
|
||||
total: 200000 // Default context window for Codex models
|
||||
},
|
||||
sessionId: currentSessionId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Send completion event
|
||||
if (!terminalFailure) {
|
||||
sendMessage(ws, createNormalizedMessage({ kind: 'complete', actualSessionId: thread.id, sessionId: currentSessionId, provider: 'codex' }));
|
||||
notifyRunStopped({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'codex',
|
||||
sessionId: currentSessionId,
|
||||
sessionName: sessionSummary,
|
||||
stopReason: 'completed'
|
||||
});
|
||||
}
|
||||
sendMessage(ws, {
|
||||
type: 'codex-complete',
|
||||
sessionId: currentSessionId,
|
||||
actualSessionId: thread.id
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
const session = currentSessionId ? activeCodexSessions.get(currentSessionId) : null;
|
||||
@@ -309,23 +298,11 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
|
||||
if (!wasAborted) {
|
||||
console.error('[Codex] Error:', error);
|
||||
|
||||
// Check if Codex SDK is available for a clearer error message
|
||||
const installed = getStatusChecker('codex')?.checkInstalled() ?? true;
|
||||
const errorContent = !installed
|
||||
? 'Codex CLI is not configured. Please set up authentication first.'
|
||||
: error.message;
|
||||
|
||||
sendMessage(ws, createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: currentSessionId, provider: 'codex' }));
|
||||
if (!terminalFailure) {
|
||||
notifyRunFailed({
|
||||
userId: ws?.userId || null,
|
||||
provider: 'codex',
|
||||
sessionId: currentSessionId,
|
||||
sessionName: sessionSummary,
|
||||
error
|
||||
});
|
||||
}
|
||||
sendMessage(ws, {
|
||||
type: 'codex-error',
|
||||
error: error.message,
|
||||
sessionId: currentSessionId
|
||||
});
|
||||
}
|
||||
|
||||
} finally {
|
||||
|
||||
@@ -62,10 +62,10 @@ import fsSync from 'fs';
|
||||
import path from 'path';
|
||||
import readline from 'readline';
|
||||
import crypto from 'crypto';
|
||||
import Database from 'better-sqlite3';
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { open } from 'sqlite';
|
||||
import os from 'os';
|
||||
import sessionManager from './sessionManager.js';
|
||||
import { applyCustomSessionNames } from './database/db.js';
|
||||
|
||||
// Import TaskMaster detection functions
|
||||
async function detectTaskMasterFolder(projectPath) {
|
||||
@@ -458,7 +458,6 @@ async function getProjects(progressCallback = null) {
|
||||
total: 0
|
||||
};
|
||||
}
|
||||
applyCustomSessionNames(project.sessions, 'claude');
|
||||
|
||||
// Also fetch Cursor sessions for this project
|
||||
try {
|
||||
@@ -467,7 +466,6 @@ async function getProjects(progressCallback = null) {
|
||||
console.warn(`Could not load Cursor sessions for project ${entry.name}:`, e.message);
|
||||
project.cursorSessions = [];
|
||||
}
|
||||
applyCustomSessionNames(project.cursorSessions, 'cursor');
|
||||
|
||||
// Also fetch Codex sessions for this project
|
||||
try {
|
||||
@@ -478,20 +476,14 @@ async function getProjects(progressCallback = null) {
|
||||
console.warn(`Could not load Codex sessions for project ${entry.name}:`, e.message);
|
||||
project.codexSessions = [];
|
||||
}
|
||||
applyCustomSessionNames(project.codexSessions, 'codex');
|
||||
|
||||
// Also fetch Gemini sessions for this project (UI + CLI)
|
||||
// Also fetch Gemini sessions for this project
|
||||
try {
|
||||
const uiSessions = sessionManager.getProjectSessions(actualProjectDir) || [];
|
||||
const cliSessions = await getGeminiCliSessions(actualProjectDir);
|
||||
const uiIds = new Set(uiSessions.map(s => s.id));
|
||||
const mergedGemini = [...uiSessions, ...cliSessions.filter(s => !uiIds.has(s.id))];
|
||||
project.geminiSessions = mergedGemini;
|
||||
project.geminiSessions = sessionManager.getProjectSessions(actualProjectDir) || [];
|
||||
} catch (e) {
|
||||
console.warn(`Could not load Gemini sessions for project ${entry.name}:`, e.message);
|
||||
project.geminiSessions = [];
|
||||
}
|
||||
applyCustomSessionNames(project.geminiSessions, 'gemini');
|
||||
|
||||
// Add TaskMaster detection
|
||||
try {
|
||||
@@ -575,7 +567,6 @@ async function getProjects(progressCallback = null) {
|
||||
} catch (e) {
|
||||
console.warn(`Could not load Cursor sessions for manual project ${projectName}:`, e.message);
|
||||
}
|
||||
applyCustomSessionNames(project.cursorSessions, 'cursor');
|
||||
|
||||
// Try to fetch Codex sessions for manual projects too
|
||||
try {
|
||||
@@ -585,18 +576,13 @@ async function getProjects(progressCallback = null) {
|
||||
} catch (e) {
|
||||
console.warn(`Could not load Codex sessions for manual project ${projectName}:`, e.message);
|
||||
}
|
||||
applyCustomSessionNames(project.codexSessions, 'codex');
|
||||
|
||||
// Try to fetch Gemini sessions for manual projects too (UI + CLI)
|
||||
// Try to fetch Gemini sessions for manual projects too
|
||||
try {
|
||||
const uiSessions = sessionManager.getProjectSessions(actualProjectDir) || [];
|
||||
const cliSessions = await getGeminiCliSessions(actualProjectDir);
|
||||
const uiIds = new Set(uiSessions.map(s => s.id));
|
||||
project.geminiSessions = [...uiSessions, ...cliSessions.filter(s => !uiIds.has(s.id))];
|
||||
project.geminiSessions = sessionManager.getProjectSessions(actualProjectDir) || [];
|
||||
} catch (e) {
|
||||
console.warn(`Could not load Gemini sessions for manual project ${projectName}:`, e.message);
|
||||
}
|
||||
applyCustomSessionNames(project.geminiSessions, 'gemini');
|
||||
|
||||
// Add TaskMaster detection for manual projects
|
||||
try {
|
||||
@@ -1013,7 +999,7 @@ async function getSessionMessages(projectName, sessionId, limit = null, offset =
|
||||
messages.push(entry);
|
||||
}
|
||||
} catch (parseError) {
|
||||
// Silently skip malformed JSONL lines (common with concurrent writes)
|
||||
console.warn('Error parsing line:', parseError.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1085,13 +1071,10 @@ async function renameProject(projectName, newDisplayName) {
|
||||
|
||||
if (!newDisplayName || newDisplayName.trim() === '') {
|
||||
// Remove custom name if empty, will fall back to auto-generated
|
||||
if (config[projectName]) {
|
||||
delete config[projectName].displayName;
|
||||
}
|
||||
delete config[projectName];
|
||||
} else {
|
||||
// Set custom display name, preserving other properties (manuallyAdded, originalPath)
|
||||
// Set custom display name
|
||||
config[projectName] = {
|
||||
...config[projectName],
|
||||
displayName: newDisplayName.trim()
|
||||
};
|
||||
}
|
||||
@@ -1163,9 +1146,8 @@ async function isProjectEmpty(projectName) {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove a project from the UI.
|
||||
// When deleteData=true, also delete session/memory files on disk (destructive).
|
||||
async function deleteProject(projectName, force = false, deleteData = false) {
|
||||
// Delete a project (force=true to delete even with sessions)
|
||||
async function deleteProject(projectName, force = false) {
|
||||
const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
|
||||
|
||||
try {
|
||||
@@ -1175,50 +1157,48 @@ async function deleteProject(projectName, force = false, deleteData = false) {
|
||||
}
|
||||
|
||||
const config = await loadProjectConfig();
|
||||
let projectPath = config[projectName]?.path || config[projectName]?.originalPath;
|
||||
|
||||
// Destructive path: delete underlying data when explicitly requested
|
||||
if (deleteData) {
|
||||
let projectPath = config[projectName]?.path || config[projectName]?.originalPath;
|
||||
if (!projectPath) {
|
||||
projectPath = await extractProjectDirectory(projectName);
|
||||
// Fallback to extractProjectDirectory if projectPath is not in config
|
||||
if (!projectPath) {
|
||||
projectPath = await extractProjectDirectory(projectName);
|
||||
}
|
||||
|
||||
// Remove the project directory (includes all Claude sessions)
|
||||
await fs.rm(projectDir, { recursive: true, force: true });
|
||||
|
||||
// Delete all Codex sessions associated with this project
|
||||
if (projectPath) {
|
||||
try {
|
||||
const codexSessions = await getCodexSessions(projectPath, { limit: 0 });
|
||||
for (const session of codexSessions) {
|
||||
try {
|
||||
await deleteCodexSession(session.id);
|
||||
} catch (err) {
|
||||
console.warn(`Failed to delete Codex session ${session.id}:`, err.message);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to delete Codex sessions:', err.message);
|
||||
}
|
||||
|
||||
// Remove the Claude project directory (session logs, memory, subagent data)
|
||||
await fs.rm(projectDir, { recursive: true, force: true });
|
||||
|
||||
// Delete Codex sessions associated with this project
|
||||
if (projectPath) {
|
||||
try {
|
||||
const codexSessions = await getCodexSessions(projectPath, { limit: 0 });
|
||||
for (const session of codexSessions) {
|
||||
try {
|
||||
await deleteCodexSession(session.id);
|
||||
} catch (err) {
|
||||
console.warn(`Failed to delete Codex session ${session.id}:`, err.message);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to delete Codex sessions:', err.message);
|
||||
}
|
||||
|
||||
// Delete Cursor sessions directory if it exists
|
||||
try {
|
||||
const hash = crypto.createHash('md5').update(projectPath).digest('hex');
|
||||
const cursorProjectDir = path.join(os.homedir(), '.cursor', 'chats', hash);
|
||||
await fs.rm(cursorProjectDir, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
// Cursor dir may not exist, ignore
|
||||
}
|
||||
// Delete Cursor sessions directory if it exists
|
||||
try {
|
||||
const hash = crypto.createHash('md5').update(projectPath).digest('hex');
|
||||
const cursorProjectDir = path.join(os.homedir(), '.cursor', 'chats', hash);
|
||||
await fs.rm(cursorProjectDir, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
// Cursor dir may not exist, ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Always remove from project config
|
||||
// Remove from project config
|
||||
delete config[projectName];
|
||||
await saveProjectConfig(config);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(`Error removing project ${projectName}:`, error);
|
||||
console.error(`Error deleting project ${projectName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1307,10 +1287,16 @@ async function getCursorSessions(projectPath) {
|
||||
} catch (_) { }
|
||||
|
||||
// Open SQLite database
|
||||
const db = new Database(storeDbPath, { readonly: true, fileMustExist: true });
|
||||
const db = await open({
|
||||
filename: storeDbPath,
|
||||
driver: sqlite3.Database,
|
||||
mode: sqlite3.OPEN_READONLY
|
||||
});
|
||||
|
||||
// Get metadata from meta table
|
||||
const metaRows = db.prepare('SELECT key, value FROM meta').all();
|
||||
const metaRows = await db.all(`
|
||||
SELECT key, value FROM meta
|
||||
`);
|
||||
|
||||
// Parse metadata
|
||||
let metadata = {};
|
||||
@@ -1332,9 +1318,11 @@ async function getCursorSessions(projectPath) {
|
||||
}
|
||||
|
||||
// Get message count
|
||||
const messageCountResult = db.prepare('SELECT COUNT(*) as count FROM blobs').get();
|
||||
const messageCountResult = await db.get(`
|
||||
SELECT COUNT(*) as count FROM blobs
|
||||
`);
|
||||
|
||||
db.close();
|
||||
await db.close();
|
||||
|
||||
// Extract session info
|
||||
const sessionName = metadata.title || metadata.sessionTitle || 'Untitled Session';
|
||||
@@ -1491,23 +1479,6 @@ async function getCodexSessions(projectPath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
function isVisibleCodexUserMessage(payload) {
|
||||
if (!payload || payload.type !== 'user_message') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Codex logs internal context (environment, instructions) as non-plain user_message kinds.
|
||||
if (payload.kind && payload.kind !== 'plain') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof payload.message !== 'string' || payload.message.trim().length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Parse a Codex session JSONL file to extract metadata
|
||||
async function parseCodexSessionFile(filePath) {
|
||||
try {
|
||||
@@ -1543,8 +1514,8 @@ async function parseCodexSessionFile(filePath) {
|
||||
};
|
||||
}
|
||||
|
||||
// Count visible user messages and extract summary from the latest plain user input.
|
||||
if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload)) {
|
||||
// Count messages and extract user messages for summary
|
||||
if (entry.type === 'event_msg' && entry.payload?.type === 'user_message') {
|
||||
messageCount++;
|
||||
if (entry.payload.message) {
|
||||
lastUserMessage = entry.payload.message;
|
||||
@@ -1651,36 +1622,25 @@ async function getCodexSessionMessages(sessionId, limit = null, offset = 0) {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Use event_msg.user_message for user-visible inputs.
|
||||
if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload)) {
|
||||
messages.push({
|
||||
type: 'user',
|
||||
timestamp: entry.timestamp,
|
||||
message: {
|
||||
role: 'user',
|
||||
content: entry.payload.message
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// response_item.message may include internal prompts for non-assistant roles.
|
||||
// Keep only assistant output from response_item.
|
||||
if (
|
||||
entry.type === 'response_item' &&
|
||||
entry.payload?.type === 'message' &&
|
||||
entry.payload.role === 'assistant'
|
||||
) {
|
||||
// Extract messages from response_item
|
||||
if (entry.type === 'response_item' && entry.payload?.type === 'message') {
|
||||
const content = entry.payload.content;
|
||||
const role = entry.payload.role || 'assistant';
|
||||
const textContent = extractText(content);
|
||||
|
||||
// Skip system context messages (environment_context)
|
||||
if (textContent?.includes('<environment_context>')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only add if there's actual content
|
||||
if (textContent?.trim()) {
|
||||
messages.push({
|
||||
type: 'assistant',
|
||||
type: role === 'user' ? 'user' : 'assistant',
|
||||
timestamp: entry.timestamp,
|
||||
message: {
|
||||
role: 'assistant',
|
||||
role: role,
|
||||
content: textContent
|
||||
}
|
||||
});
|
||||
@@ -1863,675 +1823,6 @@ async function deleteCodexSession(sessionId) {
|
||||
}
|
||||
}
|
||||
|
||||
async function searchConversations(query, limit = 50, onProjectResult = null, signal = null) {
|
||||
const safeQuery = typeof query === 'string' ? query.trim() : '';
|
||||
const safeLimit = Math.max(1, Math.min(Number.isFinite(limit) ? limit : 50, 200));
|
||||
const claudeDir = path.join(os.homedir(), '.claude', 'projects');
|
||||
const config = await loadProjectConfig();
|
||||
const results = [];
|
||||
let totalMatches = 0;
|
||||
const words = safeQuery.toLowerCase().split(/\s+/).filter(w => w.length > 0);
|
||||
if (words.length === 0) return { results: [], totalMatches: 0, query: safeQuery };
|
||||
|
||||
const isAborted = () => signal?.aborted === true;
|
||||
|
||||
const isSystemMessage = (textContent) => {
|
||||
return typeof textContent === 'string' && (
|
||||
textContent.startsWith('<command-name>') ||
|
||||
textContent.startsWith('<command-message>') ||
|
||||
textContent.startsWith('<command-args>') ||
|
||||
textContent.startsWith('<local-command-stdout>') ||
|
||||
textContent.startsWith('<system-reminder>') ||
|
||||
textContent.startsWith('Caveat:') ||
|
||||
textContent.startsWith('This session is being continued from a previous') ||
|
||||
textContent.startsWith('Invalid API key') ||
|
||||
textContent.includes('{"subtasks":') ||
|
||||
textContent.includes('CRITICAL: You MUST respond with ONLY a JSON') ||
|
||||
textContent === 'Warmup'
|
||||
);
|
||||
};
|
||||
|
||||
const extractText = (content) => {
|
||||
if (typeof content === 'string') return content;
|
||||
if (Array.isArray(content)) {
|
||||
return content
|
||||
.filter(part => part.type === 'text' && part.text)
|
||||
.map(part => part.text)
|
||||
.join(' ');
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const wordPatterns = words.map(w => new RegExp(`(?<!\\p{L})${escapeRegex(w)}(?!\\p{L})`, 'u'));
|
||||
const allWordsMatch = (textLower) => {
|
||||
return wordPatterns.every(p => p.test(textLower));
|
||||
};
|
||||
|
||||
const buildSnippet = (text, textLower, snippetLen = 150) => {
|
||||
let firstIndex = -1;
|
||||
let firstWordLen = 0;
|
||||
for (const w of words) {
|
||||
const re = new RegExp(`(?<!\\p{L})${escapeRegex(w)}(?!\\p{L})`, 'u');
|
||||
const m = re.exec(textLower);
|
||||
if (m && (firstIndex === -1 || m.index < firstIndex)) {
|
||||
firstIndex = m.index;
|
||||
firstWordLen = w.length;
|
||||
}
|
||||
}
|
||||
if (firstIndex === -1) firstIndex = 0;
|
||||
const halfLen = Math.floor(snippetLen / 2);
|
||||
let start = Math.max(0, firstIndex - halfLen);
|
||||
let end = Math.min(text.length, firstIndex + halfLen + firstWordLen);
|
||||
let snippet = text.slice(start, end).replace(/\n/g, ' ');
|
||||
const prefix = start > 0 ? '...' : '';
|
||||
const suffix = end < text.length ? '...' : '';
|
||||
snippet = prefix + snippet + suffix;
|
||||
const snippetLower = snippet.toLowerCase();
|
||||
const highlights = [];
|
||||
for (const word of words) {
|
||||
const re = new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'gu');
|
||||
let match;
|
||||
while ((match = re.exec(snippetLower)) !== null) {
|
||||
highlights.push({ start: match.index, end: match.index + word.length });
|
||||
}
|
||||
}
|
||||
highlights.sort((a, b) => a.start - b.start);
|
||||
const merged = [];
|
||||
for (const h of highlights) {
|
||||
const last = merged[merged.length - 1];
|
||||
if (last && h.start <= last.end) {
|
||||
last.end = Math.max(last.end, h.end);
|
||||
} else {
|
||||
merged.push({ ...h });
|
||||
}
|
||||
}
|
||||
return { snippet, highlights: merged };
|
||||
};
|
||||
|
||||
try {
|
||||
await fs.access(claudeDir);
|
||||
const entries = await fs.readdir(claudeDir, { withFileTypes: true });
|
||||
const projectDirs = entries.filter(e => e.isDirectory());
|
||||
let scannedProjects = 0;
|
||||
const totalProjects = projectDirs.length;
|
||||
|
||||
for (const projectEntry of projectDirs) {
|
||||
if (totalMatches >= safeLimit || isAborted()) break;
|
||||
|
||||
const projectName = projectEntry.name;
|
||||
const projectDir = path.join(claudeDir, projectName);
|
||||
const displayName = config[projectName]?.displayName
|
||||
|| await generateDisplayName(projectName);
|
||||
|
||||
let files;
|
||||
try {
|
||||
files = await fs.readdir(projectDir);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
const jsonlFiles = files.filter(
|
||||
file => file.endsWith('.jsonl') && !file.startsWith('agent-')
|
||||
);
|
||||
|
||||
const projectResult = {
|
||||
projectName,
|
||||
projectDisplayName: displayName,
|
||||
sessions: []
|
||||
};
|
||||
|
||||
for (const file of jsonlFiles) {
|
||||
if (totalMatches >= safeLimit || isAborted()) break;
|
||||
|
||||
const filePath = path.join(projectDir, file);
|
||||
const sessionMatches = new Map();
|
||||
const sessionSummaries = new Map();
|
||||
const pendingSummaries = new Map();
|
||||
const sessionLastMessages = new Map();
|
||||
let currentSessionId = null;
|
||||
|
||||
try {
|
||||
const fileStream = fsSync.createReadStream(filePath);
|
||||
const rl = readline.createInterface({
|
||||
input: fileStream,
|
||||
crlfDelay: Infinity
|
||||
});
|
||||
|
||||
for await (const line of rl) {
|
||||
if (totalMatches >= safeLimit || isAborted()) break;
|
||||
if (!line.trim()) continue;
|
||||
|
||||
let entry;
|
||||
try {
|
||||
entry = JSON.parse(line);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.sessionId) {
|
||||
currentSessionId = entry.sessionId;
|
||||
}
|
||||
if (entry.type === 'summary' && entry.summary) {
|
||||
const sid = entry.sessionId || currentSessionId;
|
||||
if (sid) {
|
||||
sessionSummaries.set(sid, entry.summary);
|
||||
} else if (entry.leafUuid) {
|
||||
pendingSummaries.set(entry.leafUuid, entry.summary);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply pending summary via parentUuid
|
||||
if (entry.parentUuid && currentSessionId && !sessionSummaries.has(currentSessionId)) {
|
||||
const pending = pendingSummaries.get(entry.parentUuid);
|
||||
if (pending) sessionSummaries.set(currentSessionId, pending);
|
||||
}
|
||||
|
||||
// Track last user/assistant message for fallback title
|
||||
if (entry.message?.content && currentSessionId && !entry.isApiErrorMessage) {
|
||||
const role = entry.message.role;
|
||||
if (role === 'user' || role === 'assistant') {
|
||||
const text = extractText(entry.message.content);
|
||||
if (text && !isSystemMessage(text)) {
|
||||
if (!sessionLastMessages.has(currentSessionId)) {
|
||||
sessionLastMessages.set(currentSessionId, {});
|
||||
}
|
||||
const msgs = sessionLastMessages.get(currentSessionId);
|
||||
if (role === 'user') msgs.user = text;
|
||||
else msgs.assistant = text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!entry.message?.content) continue;
|
||||
if (entry.message.role !== 'user' && entry.message.role !== 'assistant') continue;
|
||||
if (entry.isApiErrorMessage) continue;
|
||||
|
||||
const text = extractText(entry.message.content);
|
||||
if (!text || isSystemMessage(text)) continue;
|
||||
|
||||
const textLower = text.toLowerCase();
|
||||
if (!allWordsMatch(textLower)) continue;
|
||||
|
||||
const sessionId = entry.sessionId || currentSessionId || file.replace('.jsonl', '');
|
||||
if (!sessionMatches.has(sessionId)) {
|
||||
sessionMatches.set(sessionId, []);
|
||||
}
|
||||
|
||||
const matches = sessionMatches.get(sessionId);
|
||||
if (matches.length < 2) {
|
||||
const { snippet, highlights } = buildSnippet(text, textLower);
|
||||
matches.push({
|
||||
role: entry.message.role,
|
||||
snippet,
|
||||
highlights,
|
||||
timestamp: entry.timestamp || null,
|
||||
provider: 'claude',
|
||||
messageUuid: entry.uuid || null
|
||||
});
|
||||
totalMatches++;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const [sessionId, matches] of sessionMatches) {
|
||||
projectResult.sessions.push({
|
||||
sessionId,
|
||||
provider: 'claude',
|
||||
sessionSummary: sessionSummaries.get(sessionId) || (() => {
|
||||
const msgs = sessionLastMessages.get(sessionId);
|
||||
const lastMsg = msgs?.user || msgs?.assistant;
|
||||
return lastMsg ? (lastMsg.length > 50 ? lastMsg.substring(0, 50) + '...' : lastMsg) : 'New Session';
|
||||
})(),
|
||||
matches
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Search Codex sessions for this project
|
||||
try {
|
||||
const actualProjectDir = await extractProjectDirectory(projectName);
|
||||
if (actualProjectDir && !isAborted() && totalMatches < safeLimit) {
|
||||
await searchCodexSessionsForProject(
|
||||
actualProjectDir, projectResult, words, allWordsMatch, extractText, isSystemMessage,
|
||||
buildSnippet, safeLimit, () => totalMatches, (n) => { totalMatches += n; }, isAborted
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Skip codex search errors
|
||||
}
|
||||
|
||||
// Search Gemini sessions for this project
|
||||
try {
|
||||
const actualProjectDir = await extractProjectDirectory(projectName);
|
||||
if (actualProjectDir && !isAborted() && totalMatches < safeLimit) {
|
||||
await searchGeminiSessionsForProject(
|
||||
actualProjectDir, projectResult, words, allWordsMatch,
|
||||
buildSnippet, safeLimit, () => totalMatches, (n) => { totalMatches += n; }
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Skip gemini search errors
|
||||
}
|
||||
|
||||
scannedProjects++;
|
||||
if (projectResult.sessions.length > 0) {
|
||||
results.push(projectResult);
|
||||
if (onProjectResult) {
|
||||
onProjectResult({ projectResult, totalMatches, scannedProjects, totalProjects });
|
||||
}
|
||||
} else if (onProjectResult && scannedProjects % 10 === 0) {
|
||||
onProjectResult({ projectResult: null, totalMatches, scannedProjects, totalProjects });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// claudeDir doesn't exist
|
||||
}
|
||||
|
||||
return { results, totalMatches, query: safeQuery };
|
||||
}
|
||||
|
||||
async function searchCodexSessionsForProject(
|
||||
projectPath, projectResult, words, allWordsMatch, extractText, isSystemMessage,
|
||||
buildSnippet, limit, getTotalMatches, addMatches, isAborted
|
||||
) {
|
||||
const normalizedProjectPath = normalizeComparablePath(projectPath);
|
||||
if (!normalizedProjectPath) return;
|
||||
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
|
||||
try {
|
||||
await fs.access(codexSessionsDir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const jsonlFiles = await findCodexJsonlFiles(codexSessionsDir);
|
||||
|
||||
for (const filePath of jsonlFiles) {
|
||||
if (getTotalMatches() >= limit || isAborted()) break;
|
||||
|
||||
try {
|
||||
const fileStream = fsSync.createReadStream(filePath);
|
||||
const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
|
||||
|
||||
// First pass: read session_meta to check project path match
|
||||
let sessionMeta = null;
|
||||
for await (const line of rl) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const entry = JSON.parse(line);
|
||||
if (entry.type === 'session_meta' && entry.payload) {
|
||||
sessionMeta = entry.payload;
|
||||
break;
|
||||
}
|
||||
} catch { continue; }
|
||||
}
|
||||
|
||||
// Skip sessions that don't belong to this project
|
||||
if (!sessionMeta) continue;
|
||||
const sessionProjectPath = normalizeComparablePath(sessionMeta.cwd);
|
||||
if (sessionProjectPath !== normalizedProjectPath) continue;
|
||||
|
||||
// Second pass: re-read file to find matching messages
|
||||
const fileStream2 = fsSync.createReadStream(filePath);
|
||||
const rl2 = readline.createInterface({ input: fileStream2, crlfDelay: Infinity });
|
||||
let lastUserMessage = null;
|
||||
const matches = [];
|
||||
|
||||
for await (const line of rl2) {
|
||||
if (getTotalMatches() >= limit || isAborted()) break;
|
||||
if (!line.trim()) continue;
|
||||
|
||||
let entry;
|
||||
try { entry = JSON.parse(line); } catch { continue; }
|
||||
|
||||
let text = null;
|
||||
let role = null;
|
||||
|
||||
if (entry.type === 'event_msg' && entry.payload?.type === 'user_message' && entry.payload.message) {
|
||||
text = entry.payload.message;
|
||||
role = 'user';
|
||||
lastUserMessage = text;
|
||||
} else if (entry.type === 'response_item' && entry.payload?.type === 'message') {
|
||||
const contentParts = entry.payload.content || [];
|
||||
if (entry.payload.role === 'user') {
|
||||
text = contentParts
|
||||
.filter(p => p.type === 'input_text' && p.text)
|
||||
.map(p => p.text)
|
||||
.join(' ');
|
||||
role = 'user';
|
||||
if (text) lastUserMessage = text;
|
||||
} else if (entry.payload.role === 'assistant') {
|
||||
text = contentParts
|
||||
.filter(p => p.type === 'output_text' && p.text)
|
||||
.map(p => p.text)
|
||||
.join(' ');
|
||||
role = 'assistant';
|
||||
}
|
||||
}
|
||||
|
||||
if (!text || !role) continue;
|
||||
const textLower = text.toLowerCase();
|
||||
if (!allWordsMatch(textLower)) continue;
|
||||
|
||||
if (matches.length < 2) {
|
||||
const { snippet, highlights } = buildSnippet(text, textLower);
|
||||
matches.push({ role, snippet, highlights, timestamp: entry.timestamp || null, provider: 'codex' });
|
||||
addMatches(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.length > 0) {
|
||||
projectResult.sessions.push({
|
||||
sessionId: sessionMeta.id,
|
||||
provider: 'codex',
|
||||
sessionSummary: lastUserMessage
|
||||
? (lastUserMessage.length > 50 ? lastUserMessage.substring(0, 50) + '...' : lastUserMessage)
|
||||
: 'Codex Session',
|
||||
matches
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function searchGeminiSessionsForProject(
|
||||
projectPath, projectResult, words, allWordsMatch,
|
||||
buildSnippet, limit, getTotalMatches, addMatches
|
||||
) {
|
||||
// 1) Search in-memory sessions (created via UI)
|
||||
for (const [sessionId, session] of sessionManager.sessions) {
|
||||
if (getTotalMatches() >= limit) break;
|
||||
if (session.projectPath !== projectPath) continue;
|
||||
|
||||
const matches = [];
|
||||
for (const msg of session.messages) {
|
||||
if (getTotalMatches() >= limit) break;
|
||||
if (msg.role !== 'user' && msg.role !== 'assistant') continue;
|
||||
|
||||
const text = typeof msg.content === 'string' ? msg.content
|
||||
: Array.isArray(msg.content) ? msg.content.filter(p => p.type === 'text').map(p => p.text).join(' ')
|
||||
: '';
|
||||
if (!text) continue;
|
||||
|
||||
const textLower = text.toLowerCase();
|
||||
if (!allWordsMatch(textLower)) continue;
|
||||
|
||||
if (matches.length < 2) {
|
||||
const { snippet, highlights } = buildSnippet(text, textLower);
|
||||
matches.push({
|
||||
role: msg.role, snippet, highlights,
|
||||
timestamp: msg.timestamp ? msg.timestamp.toISOString() : null,
|
||||
provider: 'gemini'
|
||||
});
|
||||
addMatches(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.length > 0) {
|
||||
const firstUserMsg = session.messages.find(m => m.role === 'user');
|
||||
const summary = firstUserMsg?.content
|
||||
? (typeof firstUserMsg.content === 'string'
|
||||
? (firstUserMsg.content.length > 50 ? firstUserMsg.content.substring(0, 50) + '...' : firstUserMsg.content)
|
||||
: 'Gemini Session')
|
||||
: 'Gemini Session';
|
||||
|
||||
projectResult.sessions.push({
|
||||
sessionId,
|
||||
provider: 'gemini',
|
||||
sessionSummary: summary,
|
||||
matches
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Search Gemini CLI sessions on disk (~/.gemini/tmp/<project>/chats/*.json)
|
||||
const normalizedProjectPath = normalizeComparablePath(projectPath);
|
||||
if (!normalizedProjectPath) return;
|
||||
|
||||
const geminiTmpDir = path.join(os.homedir(), '.gemini', 'tmp');
|
||||
try {
|
||||
await fs.access(geminiTmpDir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const trackedSessionIds = new Set();
|
||||
for (const [sid] of sessionManager.sessions) {
|
||||
trackedSessionIds.add(sid);
|
||||
}
|
||||
|
||||
let projectDirs;
|
||||
try {
|
||||
projectDirs = await fs.readdir(geminiTmpDir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const projectDir of projectDirs) {
|
||||
if (getTotalMatches() >= limit) break;
|
||||
|
||||
const projectRootFile = path.join(geminiTmpDir, projectDir, '.project_root');
|
||||
let projectRoot;
|
||||
try {
|
||||
projectRoot = (await fs.readFile(projectRootFile, 'utf8')).trim();
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (normalizeComparablePath(projectRoot) !== normalizedProjectPath) continue;
|
||||
|
||||
const chatsDir = path.join(geminiTmpDir, projectDir, 'chats');
|
||||
let chatFiles;
|
||||
try {
|
||||
chatFiles = await fs.readdir(chatsDir);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const chatFile of chatFiles) {
|
||||
if (getTotalMatches() >= limit) break;
|
||||
if (!chatFile.endsWith('.json')) continue;
|
||||
|
||||
try {
|
||||
const filePath = path.join(chatsDir, chatFile);
|
||||
const data = await fs.readFile(filePath, 'utf8');
|
||||
const session = JSON.parse(data);
|
||||
if (!session.messages || !Array.isArray(session.messages)) continue;
|
||||
|
||||
const cliSessionId = session.sessionId || chatFile.replace('.json', '');
|
||||
if (trackedSessionIds.has(cliSessionId)) continue;
|
||||
|
||||
const matches = [];
|
||||
let firstUserText = null;
|
||||
|
||||
for (const msg of session.messages) {
|
||||
if (getTotalMatches() >= limit) break;
|
||||
|
||||
const role = msg.type === 'user' ? 'user'
|
||||
: (msg.type === 'gemini' || msg.type === 'assistant') ? 'assistant'
|
||||
: null;
|
||||
if (!role) continue;
|
||||
|
||||
let text = '';
|
||||
if (typeof msg.content === 'string') {
|
||||
text = msg.content;
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
text = msg.content
|
||||
.filter(p => p.text)
|
||||
.map(p => p.text)
|
||||
.join(' ');
|
||||
}
|
||||
if (!text) continue;
|
||||
|
||||
if (role === 'user' && !firstUserText) firstUserText = text;
|
||||
|
||||
const textLower = text.toLowerCase();
|
||||
if (!allWordsMatch(textLower)) continue;
|
||||
|
||||
if (matches.length < 2) {
|
||||
const { snippet, highlights } = buildSnippet(text, textLower);
|
||||
matches.push({
|
||||
role, snippet, highlights,
|
||||
timestamp: msg.timestamp || null,
|
||||
provider: 'gemini'
|
||||
});
|
||||
addMatches(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.length > 0) {
|
||||
const summary = firstUserText
|
||||
? (firstUserText.length > 50 ? firstUserText.substring(0, 50) + '...' : firstUserText)
|
||||
: 'Gemini CLI Session';
|
||||
|
||||
projectResult.sessions.push({
|
||||
sessionId: cliSessionId,
|
||||
provider: 'gemini',
|
||||
sessionSummary: summary,
|
||||
matches
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function getGeminiCliSessions(projectPath) {
|
||||
const normalizedProjectPath = normalizeComparablePath(projectPath);
|
||||
if (!normalizedProjectPath) return [];
|
||||
|
||||
const geminiTmpDir = path.join(os.homedir(), '.gemini', 'tmp');
|
||||
try {
|
||||
await fs.access(geminiTmpDir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sessions = [];
|
||||
let projectDirs;
|
||||
try {
|
||||
projectDirs = await fs.readdir(geminiTmpDir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const projectDir of projectDirs) {
|
||||
const projectRootFile = path.join(geminiTmpDir, projectDir, '.project_root');
|
||||
let projectRoot;
|
||||
try {
|
||||
projectRoot = (await fs.readFile(projectRootFile, 'utf8')).trim();
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (normalizeComparablePath(projectRoot) !== normalizedProjectPath) continue;
|
||||
|
||||
const chatsDir = path.join(geminiTmpDir, projectDir, 'chats');
|
||||
let chatFiles;
|
||||
try {
|
||||
chatFiles = await fs.readdir(chatsDir);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const chatFile of chatFiles) {
|
||||
if (!chatFile.endsWith('.json')) continue;
|
||||
try {
|
||||
const filePath = path.join(chatsDir, chatFile);
|
||||
const data = await fs.readFile(filePath, 'utf8');
|
||||
const session = JSON.parse(data);
|
||||
if (!session.messages || !Array.isArray(session.messages)) continue;
|
||||
|
||||
const sessionId = session.sessionId || chatFile.replace('.json', '');
|
||||
const firstUserMsg = session.messages.find(m => m.type === 'user');
|
||||
let summary = 'Gemini CLI Session';
|
||||
if (firstUserMsg) {
|
||||
const text = Array.isArray(firstUserMsg.content)
|
||||
? firstUserMsg.content.filter(p => p.text).map(p => p.text).join(' ')
|
||||
: (typeof firstUserMsg.content === 'string' ? firstUserMsg.content : '');
|
||||
if (text) {
|
||||
summary = text.length > 50 ? text.substring(0, 50) + '...' : text;
|
||||
}
|
||||
}
|
||||
|
||||
sessions.push({
|
||||
id: sessionId,
|
||||
summary,
|
||||
messageCount: session.messages.length,
|
||||
lastActivity: session.lastUpdated || session.startTime || null,
|
||||
provider: 'gemini'
|
||||
});
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sessions.sort((a, b) =>
|
||||
new Date(b.lastActivity || 0) - new Date(a.lastActivity || 0)
|
||||
);
|
||||
}
|
||||
|
||||
async function getGeminiCliSessionMessages(sessionId) {
|
||||
const geminiTmpDir = path.join(os.homedir(), '.gemini', 'tmp');
|
||||
let projectDirs;
|
||||
try {
|
||||
projectDirs = await fs.readdir(geminiTmpDir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const projectDir of projectDirs) {
|
||||
const chatsDir = path.join(geminiTmpDir, projectDir, 'chats');
|
||||
let chatFiles;
|
||||
try {
|
||||
chatFiles = await fs.readdir(chatsDir);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const chatFile of chatFiles) {
|
||||
if (!chatFile.endsWith('.json')) continue;
|
||||
try {
|
||||
const filePath = path.join(chatsDir, chatFile);
|
||||
const data = await fs.readFile(filePath, 'utf8');
|
||||
const session = JSON.parse(data);
|
||||
const fileSessionId = session.sessionId || chatFile.replace('.json', '');
|
||||
if (fileSessionId !== sessionId) continue;
|
||||
|
||||
return (session.messages || []).map(msg => {
|
||||
const role = msg.type === 'user' ? 'user'
|
||||
: (msg.type === 'gemini' || msg.type === 'assistant') ? 'assistant'
|
||||
: msg.type;
|
||||
|
||||
let content = '';
|
||||
if (typeof msg.content === 'string') {
|
||||
content = msg.content;
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
content = msg.content.filter(p => p.text).map(p => p.text).join('\n');
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'message',
|
||||
message: { role, content },
|
||||
timestamp: msg.timestamp || null
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
export {
|
||||
getProjects,
|
||||
getSessions,
|
||||
@@ -2548,8 +1839,5 @@ export {
|
||||
clearProjectDirectoryCache,
|
||||
getCodexSessions,
|
||||
getCodexSessionMessages,
|
||||
deleteCodexSession,
|
||||
getGeminiCliSessions,
|
||||
getGeminiCliSessionMessages,
|
||||
searchConversations
|
||||
deleteCodexSession
|
||||
};
|
||||
|
||||
@@ -1,278 +0,0 @@
|
||||
/**
|
||||
* Claude provider adapter.
|
||||
*
|
||||
* Normalizes Claude SDK session history into NormalizedMessage format.
|
||||
* @module adapters/claude
|
||||
*/
|
||||
|
||||
import { getSessionMessages } from '../../projects.js';
|
||||
import { createNormalizedMessage, generateMessageId } from '../types.js';
|
||||
import { isInternalContent } from '../utils.js';
|
||||
|
||||
const PROVIDER = 'claude';
|
||||
|
||||
/**
|
||||
* Normalize a raw JSONL message or realtime SDK event into NormalizedMessage(s).
|
||||
* Handles both history entries (JSONL `{ message: { role, content } }`) and
|
||||
* realtime streaming events (`content_block_delta`, `content_block_stop`, etc.).
|
||||
* @param {object} raw - A single entry from JSONL or a live SDK event
|
||||
* @param {string} sessionId
|
||||
* @returns {import('../types.js').NormalizedMessage[]}
|
||||
*/
|
||||
export function normalizeMessage(raw, sessionId) {
|
||||
// ── Streaming events (realtime) ──────────────────────────────────────────
|
||||
if (raw.type === 'content_block_delta' && raw.delta?.text) {
|
||||
return [createNormalizedMessage({ kind: 'stream_delta', content: raw.delta.text, sessionId, provider: PROVIDER })];
|
||||
}
|
||||
if (raw.type === 'content_block_stop') {
|
||||
return [createNormalizedMessage({ kind: 'stream_end', sessionId, provider: PROVIDER })];
|
||||
}
|
||||
|
||||
// ── History / full-message events ────────────────────────────────────────
|
||||
const messages = [];
|
||||
const ts = raw.timestamp || new Date().toISOString();
|
||||
const baseId = raw.uuid || generateMessageId('claude');
|
||||
|
||||
// User message
|
||||
if (raw.message?.role === 'user' && raw.message?.content) {
|
||||
if (Array.isArray(raw.message.content)) {
|
||||
// Handle tool_result parts
|
||||
for (const part of raw.message.content) {
|
||||
if (part.type === 'tool_result') {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_tr_${part.tool_use_id}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_result',
|
||||
toolId: part.tool_use_id,
|
||||
content: typeof part.content === 'string' ? part.content : JSON.stringify(part.content),
|
||||
isError: Boolean(part.is_error),
|
||||
subagentTools: raw.subagentTools,
|
||||
toolUseResult: raw.toolUseResult,
|
||||
}));
|
||||
} else if (part.type === 'text') {
|
||||
// Regular text parts from user
|
||||
const text = part.text || '';
|
||||
if (text && !isInternalContent(text)) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_text`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: 'user',
|
||||
content: text,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no text parts were found, check if it's a pure user message
|
||||
if (messages.length === 0) {
|
||||
const textParts = raw.message.content
|
||||
.filter(p => p.type === 'text')
|
||||
.map(p => p.text)
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
if (textParts && !isInternalContent(textParts)) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_text`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: 'user',
|
||||
content: textParts,
|
||||
}));
|
||||
}
|
||||
}
|
||||
} else if (typeof raw.message.content === 'string') {
|
||||
const text = raw.message.content;
|
||||
if (text && !isInternalContent(text)) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: 'user',
|
||||
content: text,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
// Thinking message
|
||||
if (raw.type === 'thinking' && raw.message?.content) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'thinking',
|
||||
content: raw.message.content,
|
||||
}));
|
||||
return messages;
|
||||
}
|
||||
|
||||
// Tool use result (codex-style in Claude)
|
||||
if (raw.type === 'tool_use' && raw.toolName) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_use',
|
||||
toolName: raw.toolName,
|
||||
toolInput: raw.toolInput,
|
||||
toolId: raw.toolCallId || baseId,
|
||||
}));
|
||||
return messages;
|
||||
}
|
||||
|
||||
if (raw.type === 'tool_result') {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_result',
|
||||
toolId: raw.toolCallId || '',
|
||||
content: raw.output || '',
|
||||
isError: false,
|
||||
}));
|
||||
return messages;
|
||||
}
|
||||
|
||||
// Assistant message
|
||||
if (raw.message?.role === 'assistant' && raw.message?.content) {
|
||||
if (Array.isArray(raw.message.content)) {
|
||||
let partIndex = 0;
|
||||
for (const part of raw.message.content) {
|
||||
if (part.type === 'text' && part.text) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIndex}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: 'assistant',
|
||||
content: part.text,
|
||||
}));
|
||||
} else if (part.type === 'tool_use') {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIndex}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_use',
|
||||
toolName: part.name,
|
||||
toolInput: part.input,
|
||||
toolId: part.id,
|
||||
}));
|
||||
} else if (part.type === 'thinking' && part.thinking) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIndex}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'thinking',
|
||||
content: part.thinking,
|
||||
}));
|
||||
}
|
||||
partIndex++;
|
||||
}
|
||||
} else if (typeof raw.message.content === 'string') {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: 'assistant',
|
||||
content: raw.message.content,
|
||||
}));
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import('../types.js').ProviderAdapter}
|
||||
*/
|
||||
export const claudeAdapter = {
|
||||
normalizeMessage,
|
||||
|
||||
/**
|
||||
* Fetch session history from JSONL files, returning normalized messages.
|
||||
*/
|
||||
async fetchHistory(sessionId, opts = {}) {
|
||||
const { projectName, limit = null, offset = 0 } = opts;
|
||||
if (!projectName) {
|
||||
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
||||
}
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await getSessionMessages(projectName, sessionId, limit, offset);
|
||||
} catch (error) {
|
||||
console.warn(`[ClaudeAdapter] Failed to load session ${sessionId}:`, error.message);
|
||||
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
||||
}
|
||||
|
||||
// getSessionMessages returns either an array (no limit) or { messages, total, hasMore }
|
||||
const rawMessages = Array.isArray(result) ? result : (result.messages || []);
|
||||
const total = Array.isArray(result) ? rawMessages.length : (result.total || 0);
|
||||
const hasMore = Array.isArray(result) ? false : Boolean(result.hasMore);
|
||||
|
||||
// First pass: collect tool results for attachment to tool_use messages
|
||||
const toolResultMap = new Map();
|
||||
for (const raw of rawMessages) {
|
||||
if (raw.message?.role === 'user' && Array.isArray(raw.message?.content)) {
|
||||
for (const part of raw.message.content) {
|
||||
if (part.type === 'tool_result') {
|
||||
toolResultMap.set(part.tool_use_id, {
|
||||
content: part.content,
|
||||
isError: Boolean(part.is_error),
|
||||
timestamp: raw.timestamp,
|
||||
subagentTools: raw.subagentTools,
|
||||
toolUseResult: raw.toolUseResult,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: normalize all messages
|
||||
const normalized = [];
|
||||
for (const raw of rawMessages) {
|
||||
const entries = normalizeMessage(raw, sessionId);
|
||||
normalized.push(...entries);
|
||||
}
|
||||
|
||||
// Attach tool results to their corresponding tool_use messages
|
||||
for (const msg of normalized) {
|
||||
if (msg.kind === 'tool_use' && msg.toolId && toolResultMap.has(msg.toolId)) {
|
||||
const tr = toolResultMap.get(msg.toolId);
|
||||
msg.toolResult = {
|
||||
content: typeof tr.content === 'string' ? tr.content : JSON.stringify(tr.content),
|
||||
isError: tr.isError,
|
||||
toolUseResult: tr.toolUseResult,
|
||||
};
|
||||
msg.subagentTools = tr.subagentTools;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
messages: normalized,
|
||||
total,
|
||||
hasMore,
|
||||
offset,
|
||||
limit,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,136 +0,0 @@
|
||||
/**
|
||||
* Claude Provider Status
|
||||
*
|
||||
* Checks whether Claude Code CLI is installed and whether the user
|
||||
* has valid authentication credentials.
|
||||
*
|
||||
* @module providers/claude/status
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'child_process';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
/**
|
||||
* Check if Claude Code CLI is installed and available.
|
||||
* Uses CLAUDE_CLI_PATH env var if set, otherwise looks for 'claude' in PATH.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function checkInstalled() {
|
||||
const cliPath = process.env.CLAUDE_CLI_PATH || 'claude';
|
||||
try {
|
||||
execFileSync(cliPath, ['--version'], { stdio: 'ignore', timeout: 5000 });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Full status check: installation + authentication.
|
||||
* @returns {Promise<import('../types.js').ProviderStatus>}
|
||||
*/
|
||||
export async function checkStatus() {
|
||||
const installed = checkInstalled();
|
||||
|
||||
if (!installed) {
|
||||
return {
|
||||
installed,
|
||||
authenticated: false,
|
||||
email: null,
|
||||
method: null,
|
||||
error: 'Claude Code CLI is not installed'
|
||||
};
|
||||
}
|
||||
|
||||
const credentialsResult = await checkCredentials();
|
||||
|
||||
if (credentialsResult.authenticated) {
|
||||
return {
|
||||
installed,
|
||||
authenticated: true,
|
||||
email: credentialsResult.email || 'Authenticated',
|
||||
method: credentialsResult.method || null,
|
||||
error: null
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
installed,
|
||||
authenticated: false,
|
||||
email: credentialsResult.email || null,
|
||||
method: credentialsResult.method || null,
|
||||
error: credentialsResult.error || 'Not authenticated'
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
async function loadSettingsEnv() {
|
||||
try {
|
||||
const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
|
||||
const content = await fs.readFile(settingsPath, 'utf8');
|
||||
const settings = JSON.parse(content);
|
||||
|
||||
if (settings?.env && typeof settings.env === 'object') {
|
||||
return settings.env;
|
||||
}
|
||||
} catch {
|
||||
// Ignore missing or malformed settings.
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks Claude authentication credentials.
|
||||
*
|
||||
* Priority 1: ANTHROPIC_API_KEY environment variable
|
||||
* Priority 1b: ~/.claude/settings.json env values
|
||||
* Priority 2: ~/.claude/.credentials.json OAuth tokens
|
||||
*/
|
||||
async function checkCredentials() {
|
||||
if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.trim()) {
|
||||
return { authenticated: true, email: 'API Key Auth', method: 'api_key' };
|
||||
}
|
||||
|
||||
const settingsEnv = await loadSettingsEnv();
|
||||
|
||||
if (typeof settingsEnv.ANTHROPIC_API_KEY === 'string' && settingsEnv.ANTHROPIC_API_KEY.trim()) {
|
||||
return { authenticated: true, email: 'API Key Auth', method: 'api_key' };
|
||||
}
|
||||
|
||||
if (typeof settingsEnv.ANTHROPIC_AUTH_TOKEN === 'string' && settingsEnv.ANTHROPIC_AUTH_TOKEN.trim()) {
|
||||
return { authenticated: true, email: 'Configured via settings.json', method: 'api_key' };
|
||||
}
|
||||
|
||||
try {
|
||||
const credPath = path.join(os.homedir(), '.claude', '.credentials.json');
|
||||
const content = await fs.readFile(credPath, 'utf8');
|
||||
const creds = JSON.parse(content);
|
||||
|
||||
const oauth = creds.claudeAiOauth;
|
||||
if (oauth && oauth.accessToken) {
|
||||
const isExpired = oauth.expiresAt && Date.now() >= oauth.expiresAt;
|
||||
if (!isExpired) {
|
||||
return {
|
||||
authenticated: true,
|
||||
email: creds.email || creds.user || null,
|
||||
method: 'credentials_file'
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: false,
|
||||
email: creds.email || creds.user || null,
|
||||
method: 'credentials_file',
|
||||
error: 'OAuth token has expired. Please re-authenticate with claude login'
|
||||
};
|
||||
}
|
||||
|
||||
return { authenticated: false, email: null, method: null };
|
||||
} catch {
|
||||
return { authenticated: false, email: null, method: null };
|
||||
}
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
/**
|
||||
* Codex (OpenAI) provider adapter.
|
||||
*
|
||||
* Normalizes Codex SDK session history into NormalizedMessage format.
|
||||
* @module adapters/codex
|
||||
*/
|
||||
|
||||
import { getCodexSessionMessages } from '../../projects.js';
|
||||
import { createNormalizedMessage, generateMessageId } from '../types.js';
|
||||
|
||||
const PROVIDER = 'codex';
|
||||
|
||||
/**
|
||||
* Normalize a raw Codex JSONL message into NormalizedMessage(s).
|
||||
* @param {object} raw - A single parsed message from Codex JSONL
|
||||
* @param {string} sessionId
|
||||
* @returns {import('../types.js').NormalizedMessage[]}
|
||||
*/
|
||||
function normalizeCodexHistoryEntry(raw, sessionId) {
|
||||
const ts = raw.timestamp || new Date().toISOString();
|
||||
const baseId = raw.uuid || generateMessageId('codex');
|
||||
|
||||
// User message
|
||||
if (raw.message?.role === 'user') {
|
||||
const content = typeof raw.message.content === 'string'
|
||||
? raw.message.content
|
||||
: Array.isArray(raw.message.content)
|
||||
? raw.message.content.map(p => typeof p === 'string' ? p : p?.text || '').filter(Boolean).join('\n')
|
||||
: String(raw.message.content || '');
|
||||
if (!content.trim()) return [];
|
||||
return [createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: 'user',
|
||||
content,
|
||||
})];
|
||||
}
|
||||
|
||||
// Assistant message
|
||||
if (raw.message?.role === 'assistant') {
|
||||
const content = typeof raw.message.content === 'string'
|
||||
? raw.message.content
|
||||
: Array.isArray(raw.message.content)
|
||||
? raw.message.content.map(p => typeof p === 'string' ? p : p?.text || '').filter(Boolean).join('\n')
|
||||
: '';
|
||||
if (!content.trim()) return [];
|
||||
return [createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: 'assistant',
|
||||
content,
|
||||
})];
|
||||
}
|
||||
|
||||
// Thinking/reasoning
|
||||
if (raw.type === 'thinking' || raw.isReasoning) {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'thinking',
|
||||
content: raw.message?.content || '',
|
||||
})];
|
||||
}
|
||||
|
||||
// Tool use
|
||||
if (raw.type === 'tool_use' || raw.toolName) {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_use',
|
||||
toolName: raw.toolName || 'Unknown',
|
||||
toolInput: raw.toolInput,
|
||||
toolId: raw.toolCallId || baseId,
|
||||
})];
|
||||
}
|
||||
|
||||
// Tool result
|
||||
if (raw.type === 'tool_result') {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_result',
|
||||
toolId: raw.toolCallId || '',
|
||||
content: raw.output || '',
|
||||
isError: Boolean(raw.isError),
|
||||
})];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a raw Codex event (history JSONL or transformed SDK event) into NormalizedMessage(s).
|
||||
* @param {object} raw - A history entry (has raw.message.role) or transformed SDK event (has raw.type)
|
||||
* @param {string} sessionId
|
||||
* @returns {import('../types.js').NormalizedMessage[]}
|
||||
*/
|
||||
export function normalizeMessage(raw, sessionId) {
|
||||
// History format: has message.role
|
||||
if (raw.message?.role) {
|
||||
return normalizeCodexHistoryEntry(raw, sessionId);
|
||||
}
|
||||
|
||||
const ts = raw.timestamp || new Date().toISOString();
|
||||
const baseId = raw.uuid || generateMessageId('codex');
|
||||
|
||||
// SDK event format (output of transformCodexEvent)
|
||||
if (raw.type === 'item') {
|
||||
switch (raw.itemType) {
|
||||
case 'agent_message':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'text', role: 'assistant', content: raw.message?.content || '',
|
||||
})];
|
||||
case 'reasoning':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'thinking', content: raw.message?.content || '',
|
||||
})];
|
||||
case 'command_execution':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_use', toolName: 'Bash', toolInput: { command: raw.command },
|
||||
toolId: baseId,
|
||||
output: raw.output, exitCode: raw.exitCode, status: raw.status,
|
||||
})];
|
||||
case 'file_change':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_use', toolName: 'FileChanges', toolInput: raw.changes,
|
||||
toolId: baseId, status: raw.status,
|
||||
})];
|
||||
case 'mcp_tool_call':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_use', toolName: raw.tool || 'MCP', toolInput: raw.arguments,
|
||||
toolId: baseId, server: raw.server, result: raw.result,
|
||||
error: raw.error, status: raw.status,
|
||||
})];
|
||||
case 'web_search':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_use', toolName: 'WebSearch', toolInput: { query: raw.query },
|
||||
toolId: baseId,
|
||||
})];
|
||||
case 'todo_list':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_use', toolName: 'TodoList', toolInput: { items: raw.items },
|
||||
toolId: baseId,
|
||||
})];
|
||||
case 'error':
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'error', content: raw.message?.content || 'Unknown error',
|
||||
})];
|
||||
default:
|
||||
// Unknown item type — pass through as generic tool_use
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_use', toolName: raw.itemType || 'Unknown',
|
||||
toolInput: raw.item || raw, toolId: baseId,
|
||||
})];
|
||||
}
|
||||
}
|
||||
|
||||
if (raw.type === 'turn_complete') {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'complete',
|
||||
})];
|
||||
}
|
||||
if (raw.type === 'turn_failed') {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'error', content: raw.error?.message || 'Turn failed',
|
||||
})];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import('../types.js').ProviderAdapter}
|
||||
*/
|
||||
export const codexAdapter = {
|
||||
normalizeMessage,
|
||||
/**
|
||||
* Fetch session history from Codex JSONL files.
|
||||
*/
|
||||
async fetchHistory(sessionId, opts = {}) {
|
||||
const { limit = null, offset = 0 } = opts;
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await getCodexSessionMessages(sessionId, limit, offset);
|
||||
} catch (error) {
|
||||
console.warn(`[CodexAdapter] Failed to load session ${sessionId}:`, error.message);
|
||||
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
||||
}
|
||||
|
||||
const rawMessages = Array.isArray(result) ? result : (result.messages || []);
|
||||
const total = Array.isArray(result) ? rawMessages.length : (result.total || 0);
|
||||
const hasMore = Array.isArray(result) ? false : Boolean(result.hasMore);
|
||||
const tokenUsage = result.tokenUsage || null;
|
||||
|
||||
const normalized = [];
|
||||
for (const raw of rawMessages) {
|
||||
const entries = normalizeCodexHistoryEntry(raw, sessionId);
|
||||
normalized.push(...entries);
|
||||
}
|
||||
|
||||
// Attach tool results to tool_use messages
|
||||
const toolResultMap = new Map();
|
||||
for (const msg of normalized) {
|
||||
if (msg.kind === 'tool_result' && msg.toolId) {
|
||||
toolResultMap.set(msg.toolId, msg);
|
||||
}
|
||||
}
|
||||
for (const msg of normalized) {
|
||||
if (msg.kind === 'tool_use' && msg.toolId && toolResultMap.has(msg.toolId)) {
|
||||
const tr = toolResultMap.get(msg.toolId);
|
||||
msg.toolResult = { content: tr.content, isError: tr.isError };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
messages: normalized,
|
||||
total,
|
||||
hasMore,
|
||||
offset,
|
||||
limit,
|
||||
tokenUsage,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,78 +0,0 @@
|
||||
/**
|
||||
* Codex Provider Status
|
||||
*
|
||||
* Checks whether the user has valid Codex authentication credentials.
|
||||
* Codex uses an SDK that makes direct API calls (no external binary),
|
||||
* so installation check always returns true if the server is running.
|
||||
*
|
||||
* @module providers/codex/status
|
||||
*/
|
||||
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
/**
|
||||
* Check if Codex is installed.
|
||||
* Codex SDK is bundled with this application — no external binary needed.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function checkInstalled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full status check: installation + authentication.
|
||||
* @returns {Promise<import('../types.js').ProviderStatus>}
|
||||
*/
|
||||
export async function checkStatus() {
|
||||
const installed = checkInstalled();
|
||||
const result = await checkCredentials();
|
||||
|
||||
return {
|
||||
installed,
|
||||
authenticated: result.authenticated,
|
||||
email: result.email || null,
|
||||
error: result.error || null
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
async function checkCredentials() {
|
||||
try {
|
||||
const authPath = path.join(os.homedir(), '.codex', 'auth.json');
|
||||
const content = await fs.readFile(authPath, 'utf8');
|
||||
const auth = JSON.parse(content);
|
||||
|
||||
const tokens = auth.tokens || {};
|
||||
|
||||
if (tokens.id_token || tokens.access_token) {
|
||||
let email = 'Authenticated';
|
||||
if (tokens.id_token) {
|
||||
try {
|
||||
const parts = tokens.id_token.split('.');
|
||||
if (parts.length >= 2) {
|
||||
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
||||
email = payload.email || payload.user || 'Authenticated';
|
||||
}
|
||||
} catch {
|
||||
email = 'Authenticated';
|
||||
}
|
||||
}
|
||||
|
||||
return { authenticated: true, email };
|
||||
}
|
||||
|
||||
if (auth.OPENAI_API_KEY) {
|
||||
return { authenticated: true, email: 'API Key Auth' };
|
||||
}
|
||||
|
||||
return { authenticated: false, email: null, error: 'No valid tokens found' };
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') {
|
||||
return { authenticated: false, email: null, error: 'Codex not configured' };
|
||||
}
|
||||
return { authenticated: false, email: null, error: error.message };
|
||||
}
|
||||
}
|
||||
@@ -1,348 +0,0 @@
|
||||
/**
|
||||
* Cursor provider adapter.
|
||||
*
|
||||
* Normalizes Cursor CLI session history into NormalizedMessage format.
|
||||
* @module adapters/cursor
|
||||
*/
|
||||
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import crypto from 'crypto';
|
||||
import { createNormalizedMessage, generateMessageId } from '../types.js';
|
||||
|
||||
const PROVIDER = 'cursor';
|
||||
|
||||
/**
|
||||
* Load raw blobs from Cursor's SQLite store.db, parse the DAG structure,
|
||||
* and return sorted message blobs in chronological order.
|
||||
* @param {string} sessionId
|
||||
* @param {string} projectPath - Absolute project path (used to compute cwdId hash)
|
||||
* @returns {Promise<Array<{id: string, sequence: number, rowid: number, content: object}>>}
|
||||
*/
|
||||
async function loadCursorBlobs(sessionId, projectPath) {
|
||||
// Lazy-import better-sqlite3 so the module doesn't fail if it's unavailable
|
||||
const { default: Database } = await import('better-sqlite3');
|
||||
|
||||
const cwdId = crypto.createHash('md5').update(projectPath || process.cwd()).digest('hex');
|
||||
const storeDbPath = path.join(os.homedir(), '.cursor', 'chats', cwdId, sessionId, 'store.db');
|
||||
|
||||
const db = new Database(storeDbPath, { readonly: true, fileMustExist: true });
|
||||
|
||||
try {
|
||||
const allBlobs = db.prepare('SELECT rowid, id, data FROM blobs').all();
|
||||
|
||||
const blobMap = new Map();
|
||||
const parentRefs = new Map();
|
||||
const childRefs = new Map();
|
||||
const jsonBlobs = [];
|
||||
|
||||
for (const blob of allBlobs) {
|
||||
blobMap.set(blob.id, blob);
|
||||
|
||||
if (blob.data && blob.data[0] === 0x7B) {
|
||||
try {
|
||||
const parsed = JSON.parse(blob.data.toString('utf8'));
|
||||
jsonBlobs.push({ ...blob, parsed });
|
||||
} catch {
|
||||
// skip unparseable blobs
|
||||
}
|
||||
} else if (blob.data) {
|
||||
const parents = [];
|
||||
let i = 0;
|
||||
while (i < blob.data.length - 33) {
|
||||
if (blob.data[i] === 0x0A && blob.data[i + 1] === 0x20) {
|
||||
const parentHash = blob.data.slice(i + 2, i + 34).toString('hex');
|
||||
if (blobMap.has(parentHash)) {
|
||||
parents.push(parentHash);
|
||||
}
|
||||
i += 34;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (parents.length > 0) {
|
||||
parentRefs.set(blob.id, parents);
|
||||
for (const parentId of parents) {
|
||||
if (!childRefs.has(parentId)) childRefs.set(parentId, []);
|
||||
childRefs.get(parentId).push(blob.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Topological sort (DFS)
|
||||
const visited = new Set();
|
||||
const sorted = [];
|
||||
function visit(nodeId) {
|
||||
if (visited.has(nodeId)) return;
|
||||
visited.add(nodeId);
|
||||
for (const pid of (parentRefs.get(nodeId) || [])) visit(pid);
|
||||
const b = blobMap.get(nodeId);
|
||||
if (b) sorted.push(b);
|
||||
}
|
||||
for (const blob of allBlobs) {
|
||||
if (!parentRefs.has(blob.id)) visit(blob.id);
|
||||
}
|
||||
for (const blob of allBlobs) visit(blob.id);
|
||||
|
||||
// Order JSON blobs by DAG appearance
|
||||
const messageOrder = new Map();
|
||||
let orderIndex = 0;
|
||||
for (const blob of sorted) {
|
||||
if (blob.data && blob.data[0] !== 0x7B) {
|
||||
for (const jb of jsonBlobs) {
|
||||
try {
|
||||
const idBytes = Buffer.from(jb.id, 'hex');
|
||||
if (blob.data.includes(idBytes) && !messageOrder.has(jb.id)) {
|
||||
messageOrder.set(jb.id, orderIndex++);
|
||||
}
|
||||
} catch { /* skip */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sortedJsonBlobs = jsonBlobs.sort((a, b) => {
|
||||
const oa = messageOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
const ob = messageOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
return oa !== ob ? oa - ob : a.rowid - b.rowid;
|
||||
});
|
||||
|
||||
const messages = [];
|
||||
for (let idx = 0; idx < sortedJsonBlobs.length; idx++) {
|
||||
const blob = sortedJsonBlobs[idx];
|
||||
const parsed = blob.parsed;
|
||||
if (!parsed) continue;
|
||||
const role = parsed?.role || parsed?.message?.role;
|
||||
if (role === 'system') continue;
|
||||
messages.push({
|
||||
id: blob.id,
|
||||
sequence: idx + 1,
|
||||
rowid: blob.rowid,
|
||||
content: parsed,
|
||||
});
|
||||
}
|
||||
|
||||
return messages;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a realtime NDJSON event from Cursor CLI into NormalizedMessage(s).
|
||||
* History uses normalizeCursorBlobs (SQLite DAG), this handles streaming NDJSON.
|
||||
* @param {object|string} raw - A parsed NDJSON event or a raw text line
|
||||
* @param {string} sessionId
|
||||
* @returns {import('../types.js').NormalizedMessage[]}
|
||||
*/
|
||||
export function normalizeMessage(raw, sessionId) {
|
||||
// Structured assistant message with content array
|
||||
if (raw && typeof raw === 'object' && raw.type === 'assistant' && raw.message?.content?.[0]?.text) {
|
||||
return [createNormalizedMessage({ kind: 'stream_delta', content: raw.message.content[0].text, sessionId, provider: PROVIDER })];
|
||||
}
|
||||
// Plain string line (non-JSON output)
|
||||
if (typeof raw === 'string' && raw.trim()) {
|
||||
return [createNormalizedMessage({ kind: 'stream_delta', content: raw, sessionId, provider: PROVIDER })];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import('../types.js').ProviderAdapter}
|
||||
*/
|
||||
export const cursorAdapter = {
|
||||
normalizeMessage,
|
||||
/**
|
||||
* Fetch session history for Cursor from SQLite store.db.
|
||||
*/
|
||||
async fetchHistory(sessionId, opts = {}) {
|
||||
const { projectPath = '', limit = null, offset = 0 } = opts;
|
||||
|
||||
try {
|
||||
const blobs = await loadCursorBlobs(sessionId, projectPath);
|
||||
const allNormalized = cursorAdapter.normalizeCursorBlobs(blobs, sessionId);
|
||||
|
||||
// Apply pagination
|
||||
if (limit !== null && limit > 0) {
|
||||
const start = offset;
|
||||
const page = allNormalized.slice(start, start + limit);
|
||||
return {
|
||||
messages: page,
|
||||
total: allNormalized.length,
|
||||
hasMore: start + limit < allNormalized.length,
|
||||
offset,
|
||||
limit,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
messages: allNormalized,
|
||||
total: allNormalized.length,
|
||||
hasMore: false,
|
||||
offset: 0,
|
||||
limit: null,
|
||||
};
|
||||
} catch (error) {
|
||||
// DB doesn't exist or is unreadable — return empty
|
||||
console.warn(`[CursorAdapter] Failed to load session ${sessionId}:`, error.message);
|
||||
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Normalize raw Cursor blob messages into NormalizedMessage[].
|
||||
* @param {any[]} blobs - Raw cursor blobs from store.db ({id, sequence, rowid, content})
|
||||
* @param {string} sessionId
|
||||
* @returns {import('../types.js').NormalizedMessage[]}
|
||||
*/
|
||||
normalizeCursorBlobs(blobs, sessionId) {
|
||||
const messages = [];
|
||||
const toolUseMap = new Map();
|
||||
|
||||
// Use a fixed base timestamp so messages have stable, monotonically-increasing
|
||||
// timestamps based on their sequence number rather than wall-clock time.
|
||||
const baseTime = Date.now();
|
||||
|
||||
for (let i = 0; i < blobs.length; i++) {
|
||||
const blob = blobs[i];
|
||||
const content = blob.content;
|
||||
const ts = new Date(baseTime + (blob.sequence ?? i) * 100).toISOString();
|
||||
const baseId = blob.id || generateMessageId('cursor');
|
||||
|
||||
try {
|
||||
if (!content?.role || !content?.content) {
|
||||
// Try nested message format
|
||||
if (content?.message?.role && content?.message?.content) {
|
||||
if (content.message.role === 'system') continue;
|
||||
const role = content.message.role === 'user' ? 'user' : 'assistant';
|
||||
let text = '';
|
||||
if (Array.isArray(content.message.content)) {
|
||||
text = content.message.content
|
||||
.map(p => typeof p === 'string' ? p : p?.text || '')
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
} else if (typeof content.message.content === 'string') {
|
||||
text = content.message.content;
|
||||
}
|
||||
if (text?.trim()) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role,
|
||||
content: text,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
}));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (content.role === 'system') continue;
|
||||
|
||||
// Tool results
|
||||
if (content.role === 'tool') {
|
||||
const toolItems = Array.isArray(content.content) ? content.content : [];
|
||||
for (const item of toolItems) {
|
||||
if (item?.type !== 'tool-result') continue;
|
||||
const toolCallId = item.toolCallId || content.id;
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_tr`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_result',
|
||||
toolId: toolCallId,
|
||||
content: item.result || '',
|
||||
isError: false,
|
||||
}));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const role = content.role === 'user' ? 'user' : 'assistant';
|
||||
|
||||
if (Array.isArray(content.content)) {
|
||||
for (let partIdx = 0; partIdx < content.content.length; partIdx++) {
|
||||
const part = content.content[partIdx];
|
||||
|
||||
if (part?.type === 'text' && part?.text) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIdx}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role,
|
||||
content: part.text,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
}));
|
||||
} else if (part?.type === 'reasoning' && part?.text) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIdx}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'thinking',
|
||||
content: part.text,
|
||||
}));
|
||||
} else if (part?.type === 'tool-call' || part?.type === 'tool_use') {
|
||||
const toolName = (part.toolName || part.name || 'Unknown Tool') === 'ApplyPatch'
|
||||
? 'Edit' : (part.toolName || part.name || 'Unknown Tool');
|
||||
const toolId = part.toolCallId || part.id || `tool_${i}_${partIdx}`;
|
||||
messages.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIdx}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_use',
|
||||
toolName,
|
||||
toolInput: part.args || part.input,
|
||||
toolId,
|
||||
}));
|
||||
toolUseMap.set(toolId, messages[messages.length - 1]);
|
||||
}
|
||||
}
|
||||
} else if (typeof content.content === 'string' && content.content.trim()) {
|
||||
messages.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role,
|
||||
content: content.content,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Error normalizing cursor blob:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach tool results to tool_use messages
|
||||
for (const msg of messages) {
|
||||
if (msg.kind === 'tool_result' && msg.toolId && toolUseMap.has(msg.toolId)) {
|
||||
const toolUse = toolUseMap.get(msg.toolId);
|
||||
toolUse.toolResult = {
|
||||
content: msg.content,
|
||||
isError: msg.isError,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by sequence/rowid
|
||||
messages.sort((a, b) => {
|
||||
if (a.sequence !== undefined && b.sequence !== undefined) return a.sequence - b.sequence;
|
||||
if (a.rowid !== undefined && b.rowid !== undefined) return a.rowid - b.rowid;
|
||||
return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
|
||||
});
|
||||
|
||||
return messages;
|
||||
},
|
||||
};
|
||||
@@ -1,128 +0,0 @@
|
||||
/**
|
||||
* Cursor Provider Status
|
||||
*
|
||||
* Checks whether cursor-agent CLI is installed and whether the user
|
||||
* is logged in.
|
||||
*
|
||||
* @module providers/cursor/status
|
||||
*/
|
||||
|
||||
import { execFileSync, spawn } from 'child_process';
|
||||
|
||||
/**
|
||||
* Check if cursor-agent CLI is installed.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function checkInstalled() {
|
||||
try {
|
||||
execFileSync('cursor-agent', ['--version'], { stdio: 'ignore', timeout: 5000 });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Full status check: installation + authentication.
|
||||
* @returns {Promise<import('../types.js').ProviderStatus>}
|
||||
*/
|
||||
export async function checkStatus() {
|
||||
const installed = checkInstalled();
|
||||
|
||||
if (!installed) {
|
||||
return {
|
||||
installed,
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Cursor CLI is not installed'
|
||||
};
|
||||
}
|
||||
|
||||
const result = await checkCursorLogin();
|
||||
|
||||
return {
|
||||
installed,
|
||||
authenticated: result.authenticated,
|
||||
email: result.email || null,
|
||||
error: result.error || null
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
function checkCursorLogin() {
|
||||
return new Promise((resolve) => {
|
||||
let processCompleted = false;
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (!processCompleted) {
|
||||
processCompleted = true;
|
||||
if (childProcess) {
|
||||
childProcess.kill();
|
||||
}
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Command timeout'
|
||||
});
|
||||
}
|
||||
}, 5000);
|
||||
|
||||
let childProcess;
|
||||
try {
|
||||
childProcess = spawn('cursor-agent', ['status']);
|
||||
} catch {
|
||||
clearTimeout(timeout);
|
||||
processCompleted = true;
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Cursor CLI not found or not installed'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
childProcess.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
childProcess.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
childProcess.on('close', (code) => {
|
||||
if (processCompleted) return;
|
||||
processCompleted = true;
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (code === 0) {
|
||||
const emailMatch = stdout.match(/Logged in as ([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i);
|
||||
|
||||
if (emailMatch) {
|
||||
resolve({ authenticated: true, email: emailMatch[1] });
|
||||
} else if (stdout.includes('Logged in')) {
|
||||
resolve({ authenticated: true, email: 'Logged in' });
|
||||
} else {
|
||||
resolve({ authenticated: false, email: null, error: 'Not logged in' });
|
||||
}
|
||||
} else {
|
||||
resolve({ authenticated: false, email: null, error: stderr || 'Not logged in' });
|
||||
}
|
||||
});
|
||||
|
||||
childProcess.on('error', () => {
|
||||
if (processCompleted) return;
|
||||
processCompleted = true;
|
||||
clearTimeout(timeout);
|
||||
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Cursor CLI not found or not installed'
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
/**
|
||||
* Gemini provider adapter.
|
||||
*
|
||||
* Normalizes Gemini CLI session history into NormalizedMessage format.
|
||||
* @module adapters/gemini
|
||||
*/
|
||||
|
||||
import sessionManager from '../../sessionManager.js';
|
||||
import { getGeminiCliSessionMessages } from '../../projects.js';
|
||||
import { createNormalizedMessage, generateMessageId } from '../types.js';
|
||||
|
||||
const PROVIDER = 'gemini';
|
||||
|
||||
/**
|
||||
* Normalize a realtime NDJSON event from Gemini CLI into NormalizedMessage(s).
|
||||
* Handles: message (delta/final), tool_use, tool_result, result, error.
|
||||
* @param {object} raw - A parsed NDJSON event
|
||||
* @param {string} sessionId
|
||||
* @returns {import('../types.js').NormalizedMessage[]}
|
||||
*/
|
||||
export function normalizeMessage(raw, sessionId) {
|
||||
const ts = raw.timestamp || new Date().toISOString();
|
||||
const baseId = raw.uuid || generateMessageId('gemini');
|
||||
|
||||
if (raw.type === 'message' && raw.role === 'assistant') {
|
||||
const content = raw.content || '';
|
||||
const msgs = [];
|
||||
if (content) {
|
||||
msgs.push(createNormalizedMessage({ id: baseId, sessionId, timestamp: ts, provider: PROVIDER, kind: 'stream_delta', content }));
|
||||
}
|
||||
// If not a delta, also send stream_end
|
||||
if (raw.delta !== true) {
|
||||
msgs.push(createNormalizedMessage({ sessionId, timestamp: ts, provider: PROVIDER, kind: 'stream_end' }));
|
||||
}
|
||||
return msgs;
|
||||
}
|
||||
|
||||
if (raw.type === 'tool_use') {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_use', toolName: raw.tool_name, toolInput: raw.parameters || {},
|
||||
toolId: raw.tool_id || baseId,
|
||||
})];
|
||||
}
|
||||
|
||||
if (raw.type === 'tool_result') {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'tool_result', toolId: raw.tool_id || '',
|
||||
content: raw.output === undefined ? '' : String(raw.output),
|
||||
isError: raw.status === 'error',
|
||||
})];
|
||||
}
|
||||
|
||||
if (raw.type === 'result') {
|
||||
const msgs = [createNormalizedMessage({ sessionId, timestamp: ts, provider: PROVIDER, kind: 'stream_end' })];
|
||||
if (raw.stats?.total_tokens) {
|
||||
msgs.push(createNormalizedMessage({
|
||||
sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'status', text: 'Complete', tokens: raw.stats.total_tokens, canInterrupt: false,
|
||||
}));
|
||||
}
|
||||
return msgs;
|
||||
}
|
||||
|
||||
if (raw.type === 'error') {
|
||||
return [createNormalizedMessage({
|
||||
id: baseId, sessionId, timestamp: ts, provider: PROVIDER,
|
||||
kind: 'error', content: raw.error || raw.message || 'Unknown Gemini streaming error',
|
||||
})];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import('../types.js').ProviderAdapter}
|
||||
*/
|
||||
export const geminiAdapter = {
|
||||
normalizeMessage,
|
||||
/**
|
||||
* Fetch session history for Gemini.
|
||||
* First tries in-memory session manager, then falls back to CLI sessions on disk.
|
||||
*/
|
||||
async fetchHistory(sessionId, opts = {}) {
|
||||
let rawMessages;
|
||||
try {
|
||||
rawMessages = sessionManager.getSessionMessages(sessionId);
|
||||
|
||||
// Fallback to Gemini CLI sessions on disk
|
||||
if (rawMessages.length === 0) {
|
||||
rawMessages = await getGeminiCliSessionMessages(sessionId);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[GeminiAdapter] Failed to load session ${sessionId}:`, error.message);
|
||||
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
||||
}
|
||||
|
||||
const normalized = [];
|
||||
for (let i = 0; i < rawMessages.length; i++) {
|
||||
const raw = rawMessages[i];
|
||||
const ts = raw.timestamp || new Date().toISOString();
|
||||
const baseId = raw.uuid || generateMessageId('gemini');
|
||||
|
||||
// sessionManager format: { type: 'message', message: { role, content }, timestamp }
|
||||
// CLI format: { role: 'user'|'gemini'|'assistant', content: string|array }
|
||||
const role = raw.message?.role || raw.role;
|
||||
const content = raw.message?.content || raw.content;
|
||||
|
||||
if (!role || !content) continue;
|
||||
|
||||
const normalizedRole = (role === 'user') ? 'user' : 'assistant';
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
for (let partIdx = 0; partIdx < content.length; partIdx++) {
|
||||
const part = content[partIdx];
|
||||
if (part.type === 'text' && part.text) {
|
||||
normalized.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIdx}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: normalizedRole,
|
||||
content: part.text,
|
||||
}));
|
||||
} else if (part.type === 'tool_use') {
|
||||
normalized.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIdx}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_use',
|
||||
toolName: part.name,
|
||||
toolInput: part.input,
|
||||
toolId: part.id || generateMessageId('gemini_tool'),
|
||||
}));
|
||||
} else if (part.type === 'tool_result') {
|
||||
normalized.push(createNormalizedMessage({
|
||||
id: `${baseId}_${partIdx}`,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'tool_result',
|
||||
toolId: part.tool_use_id || '',
|
||||
content: part.content === undefined ? '' : String(part.content),
|
||||
isError: Boolean(part.is_error),
|
||||
}));
|
||||
}
|
||||
}
|
||||
} else if (typeof content === 'string' && content.trim()) {
|
||||
normalized.push(createNormalizedMessage({
|
||||
id: baseId,
|
||||
sessionId,
|
||||
timestamp: ts,
|
||||
provider: PROVIDER,
|
||||
kind: 'text',
|
||||
role: normalizedRole,
|
||||
content,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// Attach tool results to tool_use messages
|
||||
const toolResultMap = new Map();
|
||||
for (const msg of normalized) {
|
||||
if (msg.kind === 'tool_result' && msg.toolId) {
|
||||
toolResultMap.set(msg.toolId, msg);
|
||||
}
|
||||
}
|
||||
for (const msg of normalized) {
|
||||
if (msg.kind === 'tool_use' && msg.toolId && toolResultMap.has(msg.toolId)) {
|
||||
const tr = toolResultMap.get(msg.toolId);
|
||||
msg.toolResult = { content: tr.content, isError: tr.isError };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
messages: normalized,
|
||||
total: normalized.length,
|
||||
hasMore: false,
|
||||
offset: 0,
|
||||
limit: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,111 +0,0 @@
|
||||
/**
|
||||
* Gemini Provider Status
|
||||
*
|
||||
* Checks whether Gemini CLI is installed and whether the user
|
||||
* has valid authentication credentials.
|
||||
*
|
||||
* @module providers/gemini/status
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'child_process';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
/**
|
||||
* Check if Gemini CLI is installed.
|
||||
* Uses GEMINI_PATH env var if set, otherwise looks for 'gemini' in PATH.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function checkInstalled() {
|
||||
const cliPath = process.env.GEMINI_PATH || 'gemini';
|
||||
try {
|
||||
execFileSync(cliPath, ['--version'], { stdio: 'ignore', timeout: 5000 });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Full status check: installation + authentication.
|
||||
* @returns {Promise<import('../types.js').ProviderStatus>}
|
||||
*/
|
||||
export async function checkStatus() {
|
||||
const installed = checkInstalled();
|
||||
|
||||
if (!installed) {
|
||||
return {
|
||||
installed,
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Gemini CLI is not installed'
|
||||
};
|
||||
}
|
||||
|
||||
const result = await checkCredentials();
|
||||
|
||||
return {
|
||||
installed,
|
||||
authenticated: result.authenticated,
|
||||
email: result.email || null,
|
||||
error: result.error || null
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
async function checkCredentials() {
|
||||
if (process.env.GEMINI_API_KEY && process.env.GEMINI_API_KEY.trim()) {
|
||||
return { authenticated: true, email: 'API Key Auth' };
|
||||
}
|
||||
|
||||
try {
|
||||
const credsPath = path.join(os.homedir(), '.gemini', 'oauth_creds.json');
|
||||
const content = await fs.readFile(credsPath, 'utf8');
|
||||
const creds = JSON.parse(content);
|
||||
|
||||
if (creds.access_token) {
|
||||
let email = 'OAuth Session';
|
||||
|
||||
try {
|
||||
const tokenRes = await fetch(`https://oauth2.googleapis.com/tokeninfo?access_token=${creds.access_token}`);
|
||||
if (tokenRes.ok) {
|
||||
const tokenInfo = await tokenRes.json();
|
||||
if (tokenInfo.email) {
|
||||
email = tokenInfo.email;
|
||||
}
|
||||
} else if (!creds.refresh_token) {
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Access token invalid and no refresh token found'
|
||||
};
|
||||
} else {
|
||||
// Token might be expired but we have a refresh token, so CLI will refresh it
|
||||
email = await getActiveAccountEmail() || email;
|
||||
}
|
||||
} catch {
|
||||
// Network error, fallback to checking local accounts file
|
||||
email = await getActiveAccountEmail() || email;
|
||||
}
|
||||
|
||||
return { authenticated: true, email };
|
||||
}
|
||||
|
||||
return { authenticated: false, email: null, error: 'No valid tokens found in oauth_creds' };
|
||||
} catch {
|
||||
return { authenticated: false, email: null, error: 'Gemini CLI not configured' };
|
||||
}
|
||||
}
|
||||
|
||||
async function getActiveAccountEmail() {
|
||||
try {
|
||||
const accPath = path.join(os.homedir(), '.gemini', 'google_accounts.json');
|
||||
const accContent = await fs.readFile(accPath, 'utf8');
|
||||
const accounts = JSON.parse(accContent);
|
||||
return accounts.active || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* Provider Registry
|
||||
*
|
||||
* Centralizes provider adapter and status checker lookup. All code that needs
|
||||
* a provider adapter or status checker should go through this registry instead
|
||||
* of importing individual modules directly.
|
||||
*
|
||||
* @module providers/registry
|
||||
*/
|
||||
|
||||
import { claudeAdapter } from './claude/adapter.js';
|
||||
import { cursorAdapter } from './cursor/adapter.js';
|
||||
import { codexAdapter } from './codex/adapter.js';
|
||||
import { geminiAdapter } from './gemini/adapter.js';
|
||||
|
||||
import * as claudeStatus from './claude/status.js';
|
||||
import * as cursorStatus from './cursor/status.js';
|
||||
import * as codexStatus from './codex/status.js';
|
||||
import * as geminiStatus from './gemini/status.js';
|
||||
|
||||
/**
|
||||
* @typedef {import('./types.js').ProviderAdapter} ProviderAdapter
|
||||
* @typedef {import('./types.js').SessionProvider} SessionProvider
|
||||
*/
|
||||
|
||||
/** @type {Map<string, ProviderAdapter>} */
|
||||
const providers = new Map();
|
||||
|
||||
/** @type {Map<string, { checkInstalled: () => boolean, checkStatus: () => Promise<import('./types.js').ProviderStatus> }>} */
|
||||
const statusCheckers = new Map();
|
||||
|
||||
// Register built-in providers
|
||||
providers.set('claude', claudeAdapter);
|
||||
providers.set('cursor', cursorAdapter);
|
||||
providers.set('codex', codexAdapter);
|
||||
providers.set('gemini', geminiAdapter);
|
||||
|
||||
statusCheckers.set('claude', claudeStatus);
|
||||
statusCheckers.set('cursor', cursorStatus);
|
||||
statusCheckers.set('codex', codexStatus);
|
||||
statusCheckers.set('gemini', geminiStatus);
|
||||
|
||||
/**
|
||||
* Get a provider adapter by name.
|
||||
* @param {string} name - Provider name (e.g., 'claude', 'cursor', 'codex', 'gemini')
|
||||
* @returns {ProviderAdapter | undefined}
|
||||
*/
|
||||
export function getProvider(name) {
|
||||
return providers.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a provider status checker by name.
|
||||
* @param {string} name - Provider name
|
||||
* @returns {{ checkInstalled: () => boolean, checkStatus: () => Promise<import('./types.js').ProviderStatus> } | undefined}
|
||||
*/
|
||||
export function getStatusChecker(name) {
|
||||
return statusCheckers.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered provider names.
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function getAllProviders() {
|
||||
return Array.from(providers.keys());
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
/**
|
||||
* Provider Types & Interface
|
||||
*
|
||||
* Defines the normalized message format and the provider adapter interface.
|
||||
* All providers normalize their native formats into NormalizedMessage
|
||||
* before sending over REST or WebSocket.
|
||||
*
|
||||
* @module providers/types
|
||||
*/
|
||||
|
||||
// ─── Session Provider ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @typedef {'claude' | 'cursor' | 'codex' | 'gemini'} SessionProvider
|
||||
*/
|
||||
|
||||
// ─── Message Kind ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @typedef {'text' | 'tool_use' | 'tool_result' | 'thinking' | 'stream_delta' | 'stream_end'
|
||||
* | 'error' | 'complete' | 'status' | 'permission_request' | 'permission_cancelled'
|
||||
* | 'session_created' | 'interactive_prompt' | 'task_notification'} MessageKind
|
||||
*/
|
||||
|
||||
// ─── NormalizedMessage ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @typedef {Object} NormalizedMessage
|
||||
* @property {string} id - Unique message id (for dedup between server + realtime)
|
||||
* @property {string} sessionId
|
||||
* @property {string} timestamp - ISO 8601
|
||||
* @property {SessionProvider} provider
|
||||
* @property {MessageKind} kind
|
||||
*
|
||||
* Additional fields depending on kind:
|
||||
* - text: role ('user'|'assistant'), content, images?
|
||||
* - tool_use: toolName, toolInput, toolId
|
||||
* - tool_result: toolId, content, isError
|
||||
* - thinking: content
|
||||
* - stream_delta: content
|
||||
* - stream_end: (no extra fields)
|
||||
* - error: content
|
||||
* - complete: (no extra fields)
|
||||
* - status: text, tokens?, canInterrupt?
|
||||
* - permission_request: requestId, toolName, input, context?
|
||||
* - permission_cancelled: requestId
|
||||
* - session_created: newSessionId
|
||||
* - interactive_prompt: content
|
||||
* - task_notification: status, summary
|
||||
*/
|
||||
|
||||
// ─── Fetch History ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @typedef {Object} FetchHistoryOptions
|
||||
* @property {string} [projectName] - Project name (required for Claude)
|
||||
* @property {string} [projectPath] - Absolute project path (required for Cursor cwdId hash)
|
||||
* @property {number|null} [limit] - Page size (null = all messages)
|
||||
* @property {number} [offset] - Pagination offset (default: 0)
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} FetchHistoryResult
|
||||
* @property {NormalizedMessage[]} messages - Normalized messages
|
||||
* @property {number} total - Total number of messages in the session
|
||||
* @property {boolean} hasMore - Whether more messages exist before the current page
|
||||
* @property {number} offset - Current offset
|
||||
* @property {number|null} limit - Page size used
|
||||
* @property {object} [tokenUsage] - Token usage data (provider-specific)
|
||||
*/
|
||||
|
||||
// ─── Provider Status ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Result of a provider status check (installation + authentication).
|
||||
*
|
||||
* @typedef {Object} ProviderStatus
|
||||
* @property {boolean} installed - Whether the provider's CLI/SDK is available
|
||||
* @property {boolean} authenticated - Whether valid credentials exist
|
||||
* @property {string|null} email - User email or auth method identifier
|
||||
* @property {string|null} [method] - Auth method (e.g. 'api_key', 'credentials_file')
|
||||
* @property {string|null} [error] - Error message if not installed or not authenticated
|
||||
*/
|
||||
|
||||
// ─── Provider Adapter Interface ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Every provider adapter MUST implement this interface.
|
||||
*
|
||||
* @typedef {Object} ProviderAdapter
|
||||
*
|
||||
* @property {(sessionId: string, opts?: FetchHistoryOptions) => Promise<FetchHistoryResult>} fetchHistory
|
||||
* Read persisted session messages from disk/database and return them as NormalizedMessage[].
|
||||
* The backend calls this from the unified GET /api/sessions/:id/messages endpoint.
|
||||
*
|
||||
* Provider implementations:
|
||||
* - Claude: reads ~/.claude/projects/{projectName}/*.jsonl
|
||||
* - Cursor: reads from SQLite store.db (via normalizeCursorBlobs helper)
|
||||
* - Codex: reads ~/.codex/sessions/*.jsonl
|
||||
* - Gemini: reads from in-memory sessionManager or ~/.gemini/tmp/ JSON files
|
||||
*
|
||||
* @property {(raw: any, sessionId: string) => NormalizedMessage[]} normalizeMessage
|
||||
* Normalize a provider-specific event (JSONL entry or live SDK event) into NormalizedMessage[].
|
||||
* Used by provider files to convert both history and realtime events.
|
||||
*/
|
||||
|
||||
// ─── Runtime Helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate a unique message ID.
|
||||
* Uses crypto.randomUUID() to avoid collisions across server restarts and workers.
|
||||
* @param {string} [prefix='msg'] - Optional prefix
|
||||
* @returns {string}
|
||||
*/
|
||||
export function generateMessageId(prefix = 'msg') {
|
||||
return `${prefix}_${crypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a NormalizedMessage with common fields pre-filled.
|
||||
* @param {Partial<NormalizedMessage> & {kind: MessageKind, provider: SessionProvider}} fields
|
||||
* @returns {NormalizedMessage}
|
||||
*/
|
||||
export function createNormalizedMessage(fields) {
|
||||
return {
|
||||
...fields,
|
||||
id: fields.id || generateMessageId(fields.kind),
|
||||
sessionId: fields.sessionId || '',
|
||||
timestamp: fields.timestamp || new Date().toISOString(),
|
||||
provider: fields.provider,
|
||||
};
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
/**
|
||||
* Shared provider utilities.
|
||||
*
|
||||
* @module providers/utils
|
||||
*/
|
||||
|
||||
/**
|
||||
* Prefixes that indicate internal/system content which should be hidden from the UI.
|
||||
* @type {readonly string[]}
|
||||
*/
|
||||
export const INTERNAL_CONTENT_PREFIXES = Object.freeze([
|
||||
'<command-name>',
|
||||
'<command-message>',
|
||||
'<command-args>',
|
||||
'<local-command-stdout>',
|
||||
'<system-reminder>',
|
||||
'Caveat:',
|
||||
'This session is being continued from a previous',
|
||||
'[Request interrupted',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Check if user text content is internal/system that should be skipped.
|
||||
* @param {string} content
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isInternalContent(content) {
|
||||
return INTERNAL_CONTENT_PREFIXES.some(prefix => content.startsWith(prefix));
|
||||
}
|
||||
@@ -450,10 +450,9 @@ async function cleanupProject(projectPath, sessionId = null) {
|
||||
* SSE Stream Writer - Adapts SDK/CLI output to Server-Sent Events
|
||||
*/
|
||||
class SSEStreamWriter {
|
||||
constructor(res, userId = null) {
|
||||
constructor(res) {
|
||||
this.res = res;
|
||||
this.sessionId = null;
|
||||
this.userId = userId;
|
||||
this.isSSEStreamWriter = true; // Marker for transport detection
|
||||
}
|
||||
|
||||
@@ -475,7 +474,6 @@ class SSEStreamWriter {
|
||||
|
||||
setSessionId(sessionId) {
|
||||
this.sessionId = sessionId;
|
||||
this.send({ type: 'session-id', sessionId });
|
||||
}
|
||||
|
||||
getSessionId() {
|
||||
@@ -487,10 +485,9 @@ class SSEStreamWriter {
|
||||
* Non-streaming response collector
|
||||
*/
|
||||
class ResponseCollector {
|
||||
constructor(userId = null) {
|
||||
constructor() {
|
||||
this.messages = [];
|
||||
this.sessionId = null;
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
send(data) {
|
||||
@@ -840,7 +837,7 @@ class ResponseCollector {
|
||||
* }
|
||||
*/
|
||||
router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
const { githubUrl, projectPath, message, provider = 'claude', model, githubToken, branchName, sessionId } = req.body;
|
||||
const { githubUrl, projectPath, message, provider = 'claude', model, githubToken, branchName } = req.body;
|
||||
|
||||
// Parse stream and cleanup as booleans (handle string "true"/"false" from curl)
|
||||
const stream = req.body.stream === undefined ? true : (req.body.stream === true || req.body.stream === 'true');
|
||||
@@ -923,7 +920,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.setHeader('X-Accel-Buffering', 'no'); // Disable nginx buffering
|
||||
|
||||
writer = new SSEStreamWriter(res, req.user.id);
|
||||
writer = new SSEStreamWriter(res);
|
||||
|
||||
// Send initial status
|
||||
writer.send({
|
||||
@@ -933,7 +930,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
});
|
||||
} else {
|
||||
// Non-streaming mode: collect messages
|
||||
writer = new ResponseCollector(req.user.id);
|
||||
writer = new ResponseCollector();
|
||||
|
||||
// Collect initial status message
|
||||
writer.send({
|
||||
@@ -950,7 +947,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
await queryClaudeSDK(message.trim(), {
|
||||
projectPath: finalProjectPath,
|
||||
cwd: finalProjectPath,
|
||||
sessionId: sessionId || null,
|
||||
sessionId: null, // New session
|
||||
model: model,
|
||||
permissionMode: 'bypassPermissions' // Bypass all permissions for API calls
|
||||
}, writer);
|
||||
@@ -961,7 +958,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
await spawnCursor(message.trim(), {
|
||||
projectPath: finalProjectPath,
|
||||
cwd: finalProjectPath,
|
||||
sessionId: sessionId || null,
|
||||
sessionId: null, // New session
|
||||
model: model || undefined,
|
||||
skipPermissions: true // Bypass permissions for Cursor
|
||||
}, writer);
|
||||
@@ -971,7 +968,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
await queryCodex(message.trim(), {
|
||||
projectPath: finalProjectPath,
|
||||
cwd: finalProjectPath,
|
||||
sessionId: sessionId || null,
|
||||
sessionId: null,
|
||||
model: model || CODEX_MODELS.DEFAULT,
|
||||
permissionMode: 'bypassPermissions'
|
||||
}, writer);
|
||||
@@ -981,7 +978,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
await spawnGemini(message.trim(), {
|
||||
projectPath: finalProjectPath,
|
||||
cwd: finalProjectPath,
|
||||
sessionId: sessionId || null,
|
||||
sessionId: null,
|
||||
model: model,
|
||||
skipPermissions: true // CLI mode bypasses permissions
|
||||
}, writer);
|
||||
@@ -1125,7 +1122,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
} else {
|
||||
prBody += `Agent task: ${message}`;
|
||||
}
|
||||
prBody += '\n\n---\n*This pull request was automatically created by CloudCLI.ai Agent.*';
|
||||
prBody += '\n\n---\n*This pull request was automatically created by Claude Code UI Agent.*';
|
||||
|
||||
console.log(`📝 PR Title: ${prTitle}`);
|
||||
|
||||
@@ -1222,7 +1219,7 @@ router.post('/', validateExternalApiKey, async (req, res) => {
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.setHeader('X-Accel-Buffering', 'no');
|
||||
writer = new SSEStreamWriter(res, req.user.id);
|
||||
writer = new SSEStreamWriter(res);
|
||||
}
|
||||
|
||||
if (!res.writableEnded) {
|
||||
|
||||
@@ -1,27 +1,377 @@
|
||||
/**
|
||||
* CLI Auth Routes
|
||||
*
|
||||
* Thin router that delegates to per-provider status checkers
|
||||
* registered in the provider registry.
|
||||
*
|
||||
* @module routes/cli-auth
|
||||
*/
|
||||
|
||||
import express from 'express';
|
||||
import { getAllProviders, getStatusChecker } from '../providers/registry.js';
|
||||
import { spawn } from 'child_process';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
for (const provider of getAllProviders()) {
|
||||
router.get(`/${provider}/status`, async (req, res) => {
|
||||
try {
|
||||
const checker = getStatusChecker(provider);
|
||||
res.json(await checker.checkStatus());
|
||||
} catch (error) {
|
||||
console.error(`Error checking ${provider} status:`, error);
|
||||
res.status(500).json({ authenticated: false, error: error.message });
|
||||
router.get('/claude/status', async (req, res) => {
|
||||
try {
|
||||
const credentialsResult = await checkClaudeCredentials();
|
||||
|
||||
if (credentialsResult.authenticated) {
|
||||
return res.json({
|
||||
authenticated: true,
|
||||
email: credentialsResult.email || 'Authenticated',
|
||||
method: 'credentials_file'
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: credentialsResult.error || 'Not authenticated'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error checking Claude auth status:', error);
|
||||
res.status(500).json({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/cursor/status', async (req, res) => {
|
||||
try {
|
||||
const result = await checkCursorStatus();
|
||||
|
||||
res.json({
|
||||
authenticated: result.authenticated,
|
||||
email: result.email,
|
||||
error: result.error
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error checking Cursor auth status:', error);
|
||||
res.status(500).json({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/codex/status', async (req, res) => {
|
||||
try {
|
||||
const result = await checkCodexCredentials();
|
||||
|
||||
res.json({
|
||||
authenticated: result.authenticated,
|
||||
email: result.email,
|
||||
error: result.error
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error checking Codex auth status:', error);
|
||||
res.status(500).json({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/gemini/status', async (req, res) => {
|
||||
try {
|
||||
const result = await checkGeminiCredentials();
|
||||
|
||||
res.json({
|
||||
authenticated: result.authenticated,
|
||||
email: result.email,
|
||||
error: result.error
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error checking Gemini auth status:', error);
|
||||
res.status(500).json({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Checks Claude authentication credentials using two methods with priority order:
|
||||
*
|
||||
* Priority 1: ANTHROPIC_API_KEY environment variable
|
||||
* Priority 2: ~/.claude/.credentials.json OAuth tokens
|
||||
*
|
||||
* The Claude Agent SDK prioritizes environment variables over authenticated subscriptions.
|
||||
* This matching behavior ensures consistency with how the SDK authenticates.
|
||||
*
|
||||
* References:
|
||||
* - https://support.claude.com/en/articles/12304248-managing-api-key-environment-variables-in-claude-code
|
||||
* "Claude Code prioritizes environment variable API keys over authenticated subscriptions"
|
||||
* - https://platform.claude.com/docs/en/agent-sdk/overview
|
||||
* SDK authentication documentation
|
||||
*
|
||||
* @returns {Promise<Object>} Authentication status with { authenticated, email, method }
|
||||
* - authenticated: boolean indicating if valid credentials exist
|
||||
* - email: user email or auth method identifier
|
||||
* - method: 'api_key' for env var, 'credentials_file' for OAuth tokens
|
||||
*/
|
||||
async function checkClaudeCredentials() {
|
||||
try {
|
||||
const credPath = path.join(os.homedir(), '.claude', '.credentials.json');
|
||||
const content = await fs.readFile(credPath, 'utf8');
|
||||
const creds = JSON.parse(content);
|
||||
|
||||
const oauth = creds.claudeAiOauth;
|
||||
if (oauth && oauth.accessToken) {
|
||||
const isExpired = oauth.expiresAt && Date.now() >= oauth.expiresAt;
|
||||
|
||||
if (!isExpired) {
|
||||
return {
|
||||
authenticated: true,
|
||||
email: creds.email || creds.user || null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function checkCursorStatus() {
|
||||
return new Promise((resolve) => {
|
||||
let processCompleted = false;
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (!processCompleted) {
|
||||
processCompleted = true;
|
||||
if (childProcess) {
|
||||
childProcess.kill();
|
||||
}
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Command timeout'
|
||||
});
|
||||
}
|
||||
}, 5000);
|
||||
|
||||
let childProcess;
|
||||
try {
|
||||
childProcess = spawn('cursor-agent', ['status']);
|
||||
} catch (err) {
|
||||
clearTimeout(timeout);
|
||||
processCompleted = true;
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Cursor CLI not found or not installed'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
childProcess.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
childProcess.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
childProcess.on('close', (code) => {
|
||||
if (processCompleted) return;
|
||||
processCompleted = true;
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (code === 0) {
|
||||
const emailMatch = stdout.match(/Logged in as ([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i);
|
||||
|
||||
if (emailMatch) {
|
||||
resolve({
|
||||
authenticated: true,
|
||||
email: emailMatch[1],
|
||||
output: stdout
|
||||
});
|
||||
} else if (stdout.includes('Logged in')) {
|
||||
resolve({
|
||||
authenticated: true,
|
||||
email: 'Logged in',
|
||||
output: stdout
|
||||
});
|
||||
} else {
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Not logged in'
|
||||
});
|
||||
}
|
||||
} else {
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: stderr || 'Not logged in'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
childProcess.on('error', (err) => {
|
||||
if (processCompleted) return;
|
||||
processCompleted = true;
|
||||
clearTimeout(timeout);
|
||||
|
||||
resolve({
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Cursor CLI not found or not installed'
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function checkCodexCredentials() {
|
||||
try {
|
||||
const authPath = path.join(os.homedir(), '.codex', 'auth.json');
|
||||
const content = await fs.readFile(authPath, 'utf8');
|
||||
const auth = JSON.parse(content);
|
||||
|
||||
// Tokens are nested under 'tokens' key
|
||||
const tokens = auth.tokens || {};
|
||||
|
||||
// Check for valid tokens (id_token or access_token)
|
||||
if (tokens.id_token || tokens.access_token) {
|
||||
// Try to extract email from id_token JWT payload
|
||||
let email = 'Authenticated';
|
||||
if (tokens.id_token) {
|
||||
try {
|
||||
// JWT is base64url encoded: header.payload.signature
|
||||
const parts = tokens.id_token.split('.');
|
||||
if (parts.length >= 2) {
|
||||
// Decode the payload (second part)
|
||||
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
||||
email = payload.email || payload.user || 'Authenticated';
|
||||
}
|
||||
} catch {
|
||||
// If JWT decoding fails, use fallback
|
||||
email = 'Authenticated';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: true,
|
||||
email
|
||||
};
|
||||
}
|
||||
|
||||
// Also check for OPENAI_API_KEY as fallback auth method
|
||||
if (auth.OPENAI_API_KEY) {
|
||||
return {
|
||||
authenticated: true,
|
||||
email: 'API Key Auth'
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'No valid tokens found'
|
||||
};
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') {
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Codex not configured'
|
||||
};
|
||||
}
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: error.message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkGeminiCredentials() {
|
||||
if (process.env.GEMINI_API_KEY && process.env.GEMINI_API_KEY.trim()) {
|
||||
return {
|
||||
authenticated: true,
|
||||
email: 'API Key Auth'
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const credsPath = path.join(os.homedir(), '.gemini', 'oauth_creds.json');
|
||||
const content = await fs.readFile(credsPath, 'utf8');
|
||||
const creds = JSON.parse(content);
|
||||
|
||||
if (creds.access_token) {
|
||||
let email = 'OAuth Session';
|
||||
|
||||
try {
|
||||
// Validate token against Google API
|
||||
const tokenRes = await fetch(`https://oauth2.googleapis.com/tokeninfo?access_token=${creds.access_token}`);
|
||||
if (tokenRes.ok) {
|
||||
const tokenInfo = await tokenRes.json();
|
||||
if (tokenInfo.email) {
|
||||
email = tokenInfo.email;
|
||||
}
|
||||
} else if (!creds.refresh_token) {
|
||||
// Token invalid and no refresh token available
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Access token invalid and no refresh token found'
|
||||
};
|
||||
} else {
|
||||
// Token might be expired but we have a refresh token, so CLI will refresh it
|
||||
try {
|
||||
const accPath = path.join(os.homedir(), '.gemini', 'google_accounts.json');
|
||||
const accContent = await fs.readFile(accPath, 'utf8');
|
||||
const accounts = JSON.parse(accContent);
|
||||
if (accounts.active) {
|
||||
email = accounts.active;
|
||||
}
|
||||
} catch (e) { }
|
||||
}
|
||||
} catch (e) {
|
||||
// Network error, fallback to checking local accounts file
|
||||
try {
|
||||
const accPath = path.join(os.homedir(), '.gemini', 'google_accounts.json');
|
||||
const accContent = await fs.readFile(accPath, 'utf8');
|
||||
const accounts = JSON.parse(accContent);
|
||||
if (accounts.active) {
|
||||
email = accounts.active;
|
||||
}
|
||||
} catch (err) { }
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: true,
|
||||
email: email
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'No valid tokens found in oauth_creds'
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
authenticated: false,
|
||||
email: null,
|
||||
error: 'Gemini CLI not configured'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -4,8 +4,7 @@ import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import TOML from '@iarna/toml';
|
||||
import { getCodexSessions, deleteCodexSession } from '../projects.js';
|
||||
import { applyCustomSessionNames, sessionNamesDb } from '../database/db.js';
|
||||
import { getCodexSessions, getCodexSessionMessages, deleteCodexSession } from '../projects.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -60,7 +59,6 @@ router.get('/sessions', async (req, res) => {
|
||||
}
|
||||
|
||||
const sessions = await getCodexSessions(projectPath);
|
||||
applyCustomSessionNames(sessions, 'codex');
|
||||
res.json({ success: true, sessions });
|
||||
} catch (error) {
|
||||
console.error('Error fetching Codex sessions:', error);
|
||||
@@ -68,11 +66,28 @@ router.get('/sessions', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/sessions/:sessionId/messages', async (req, res) => {
|
||||
try {
|
||||
const { sessionId } = req.params;
|
||||
const { limit, offset } = req.query;
|
||||
|
||||
const result = await getCodexSessionMessages(
|
||||
sessionId,
|
||||
limit ? parseInt(limit, 10) : null,
|
||||
offset ? parseInt(offset, 10) : 0
|
||||
);
|
||||
|
||||
res.json({ success: true, ...result });
|
||||
} catch (error) {
|
||||
console.error('Error fetching Codex session messages:', error);
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/sessions/:sessionId', async (req, res) => {
|
||||
try {
|
||||
const { sessionId } = req.params;
|
||||
await deleteCodexSession(sessionId);
|
||||
sessionNamesDb.deleteName(sessionId, 'codex');
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error(`Error deleting Codex session ${req.params.sessionId}:`, error);
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import express from 'express';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import os from 'os';
|
||||
import matter from 'gray-matter';
|
||||
import { CLAUDE_MODELS, CURSOR_MODELS, CODEX_MODELS } from '../../shared/modelConstants.js';
|
||||
import { parseFrontmatter } from '../utils/frontmatter.js';
|
||||
import { findAppRoot, getModuleDir } from '../utils/runtime-paths.js';
|
||||
|
||||
const __dirname = getModuleDir(import.meta.url);
|
||||
// This route reads the top-level package.json for the status command, so it needs the real
|
||||
// app root even after compilation moves the route file under dist-server/server/routes.
|
||||
const APP_ROOT = findAppRoot(__dirname);
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -40,7 +38,7 @@ async function scanCommandsDirectory(dir, baseDir, namespace) {
|
||||
// Parse markdown file for metadata
|
||||
try {
|
||||
const content = await fs.readFile(fullPath, 'utf8');
|
||||
const { data: frontmatter, content: commandContent } = parseFrontmatter(content);
|
||||
const { data: frontmatter, content: commandContent } = matter(content);
|
||||
|
||||
// Calculate relative path from baseDir for command name
|
||||
const relativePath = path.relative(baseDir, fullPath);
|
||||
@@ -293,7 +291,7 @@ Custom commands can be created in:
|
||||
|
||||
'/status': async (args, context) => {
|
||||
// Read version from package.json
|
||||
const packageJsonPath = path.join(APP_ROOT, 'package.json');
|
||||
const packageJsonPath = path.join(path.dirname(__dirname), '..', 'package.json');
|
||||
let version = 'unknown';
|
||||
let packageName = 'claude-code-ui';
|
||||
|
||||
@@ -477,7 +475,7 @@ router.post('/load', async (req, res) => {
|
||||
|
||||
// Read and parse the command file
|
||||
const content = await fs.readFile(commandPath, 'utf8');
|
||||
const { data: metadata, content: commandContent } = parseFrontmatter(content);
|
||||
const { data: metadata, content: commandContent } = matter(content);
|
||||
|
||||
res.json({
|
||||
path: commandPath,
|
||||
@@ -562,7 +560,7 @@ router.post('/execute', async (req, res) => {
|
||||
}
|
||||
}
|
||||
const content = await fs.readFile(commandPath, 'utf8');
|
||||
const { data: metadata, content: commandContent } = parseFrontmatter(content);
|
||||
const { data: metadata, content: commandContent } = matter(content);
|
||||
// Basic argument replacement (will be enhanced in command parser utility)
|
||||
let processedContent = commandContent;
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@ import express from 'express';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import Database from 'better-sqlite3';
|
||||
import { spawn } from 'child_process';
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { open } from 'sqlite';
|
||||
import crypto from 'crypto';
|
||||
import { CURSOR_MODELS } from '../../shared/modelConstants.js';
|
||||
import { applyCustomSessionNames } from '../database/db.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -385,10 +386,16 @@ router.get('/sessions', async (req, res) => {
|
||||
} catch (_) {}
|
||||
|
||||
// Open SQLite database
|
||||
const db = new Database(storeDbPath, { readonly: true, fileMustExist: true });
|
||||
const db = await open({
|
||||
filename: storeDbPath,
|
||||
driver: sqlite3.Database,
|
||||
mode: sqlite3.OPEN_READONLY
|
||||
});
|
||||
|
||||
// Get metadata from meta table
|
||||
const metaRows = db.prepare('SELECT key, value FROM meta').all();
|
||||
const metaRows = await db.all(`
|
||||
SELECT key, value FROM meta
|
||||
`);
|
||||
|
||||
let sessionData = {
|
||||
id: sessionId,
|
||||
@@ -450,11 +457,20 @@ router.get('/sessions', async (req, res) => {
|
||||
|
||||
// Get message count from JSON blobs only (actual messages, not DAG structure)
|
||||
try {
|
||||
const blobCount = db.prepare(`SELECT COUNT(*) as count FROM blobs WHERE substr(data, 1, 1) = X'7B'`).get();
|
||||
const blobCount = await db.get(`
|
||||
SELECT COUNT(*) as count
|
||||
FROM blobs
|
||||
WHERE substr(data, 1, 1) = X'7B'
|
||||
`);
|
||||
sessionData.messageCount = blobCount.count;
|
||||
|
||||
// Get the most recent JSON blob for preview (actual message, not DAG structure)
|
||||
const lastBlob = db.prepare(`SELECT data FROM blobs WHERE substr(data, 1, 1) = X'7B' ORDER BY rowid DESC LIMIT 1`).get();
|
||||
const lastBlob = await db.get(`
|
||||
SELECT data FROM blobs
|
||||
WHERE substr(data, 1, 1) = X'7B'
|
||||
ORDER BY rowid DESC
|
||||
LIMIT 1
|
||||
`);
|
||||
|
||||
if (lastBlob && lastBlob.data) {
|
||||
try {
|
||||
@@ -509,7 +525,7 @@ router.get('/sessions', async (req, res) => {
|
||||
console.log('Could not read blobs:', e.message);
|
||||
}
|
||||
|
||||
db.close();
|
||||
await db.close();
|
||||
|
||||
// Finalize createdAt: use parsed meta value when valid, else fall back to store.db mtime
|
||||
if (!sessionData.createdAt) {
|
||||
@@ -544,10 +560,8 @@ router.get('/sessions', async (req, res) => {
|
||||
return new Date(b.createdAt) - new Date(a.createdAt);
|
||||
});
|
||||
|
||||
applyCustomSessionNames(sessions, 'cursor');
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
res.json({
|
||||
success: true,
|
||||
sessions: sessions,
|
||||
cwdId: cwdId,
|
||||
path: cursorChatsPath
|
||||
@@ -561,4 +575,221 @@ router.get('/sessions', async (req, res) => {
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/cursor/sessions/:sessionId - Get specific Cursor session from SQLite
|
||||
router.get('/sessions/:sessionId', async (req, res) => {
|
||||
try {
|
||||
const { sessionId } = req.params;
|
||||
const { projectPath } = req.query;
|
||||
|
||||
// Calculate cwdID hash for the project path
|
||||
const cwdId = crypto.createHash('md5').update(projectPath || process.cwd()).digest('hex');
|
||||
const storeDbPath = path.join(os.homedir(), '.cursor', 'chats', cwdId, sessionId, 'store.db');
|
||||
|
||||
|
||||
// Open SQLite database
|
||||
const db = await open({
|
||||
filename: storeDbPath,
|
||||
driver: sqlite3.Database,
|
||||
mode: sqlite3.OPEN_READONLY
|
||||
});
|
||||
|
||||
// Get all blobs to build the DAG structure
|
||||
const allBlobs = await db.all(`
|
||||
SELECT rowid, id, data FROM blobs
|
||||
`);
|
||||
|
||||
// Build the DAG structure from parent-child relationships
|
||||
const blobMap = new Map(); // id -> blob data
|
||||
const parentRefs = new Map(); // blob id -> [parent blob ids]
|
||||
const childRefs = new Map(); // blob id -> [child blob ids]
|
||||
const jsonBlobs = []; // Clean JSON messages
|
||||
|
||||
for (const blob of allBlobs) {
|
||||
blobMap.set(blob.id, blob);
|
||||
|
||||
// Check if this is a JSON blob (actual message) or protobuf (DAG structure)
|
||||
if (blob.data && blob.data[0] === 0x7B) { // Starts with '{' - JSON blob
|
||||
try {
|
||||
const parsed = JSON.parse(blob.data.toString('utf8'));
|
||||
jsonBlobs.push({ ...blob, parsed });
|
||||
} catch (e) {
|
||||
console.log('Failed to parse JSON blob:', blob.rowid);
|
||||
}
|
||||
} else if (blob.data) { // Protobuf blob - extract parent references
|
||||
const parents = [];
|
||||
let i = 0;
|
||||
|
||||
// Scan for parent references (0x0A 0x20 followed by 32-byte hash)
|
||||
while (i < blob.data.length - 33) {
|
||||
if (blob.data[i] === 0x0A && blob.data[i+1] === 0x20) {
|
||||
const parentHash = blob.data.slice(i+2, i+34).toString('hex');
|
||||
if (blobMap.has(parentHash)) {
|
||||
parents.push(parentHash);
|
||||
}
|
||||
i += 34;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
if (parents.length > 0) {
|
||||
parentRefs.set(blob.id, parents);
|
||||
// Update child references
|
||||
for (const parentId of parents) {
|
||||
if (!childRefs.has(parentId)) {
|
||||
childRefs.set(parentId, []);
|
||||
}
|
||||
childRefs.get(parentId).push(blob.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Perform topological sort to get chronological order
|
||||
const visited = new Set();
|
||||
const sorted = [];
|
||||
|
||||
// DFS-based topological sort
|
||||
function visit(nodeId) {
|
||||
if (visited.has(nodeId)) return;
|
||||
visited.add(nodeId);
|
||||
|
||||
// Visit all parents first (dependencies)
|
||||
const parents = parentRefs.get(nodeId) || [];
|
||||
for (const parentId of parents) {
|
||||
visit(parentId);
|
||||
}
|
||||
|
||||
// Add this node after all its parents
|
||||
const blob = blobMap.get(nodeId);
|
||||
if (blob) {
|
||||
sorted.push(blob);
|
||||
}
|
||||
}
|
||||
|
||||
// Start with nodes that have no parents (roots)
|
||||
for (const blob of allBlobs) {
|
||||
if (!parentRefs.has(blob.id)) {
|
||||
visit(blob.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Visit any remaining nodes (disconnected components)
|
||||
for (const blob of allBlobs) {
|
||||
visit(blob.id);
|
||||
}
|
||||
|
||||
// Now extract JSON messages in the order they appear in the sorted DAG
|
||||
const messageOrder = new Map(); // JSON blob id -> order index
|
||||
let orderIndex = 0;
|
||||
|
||||
for (const blob of sorted) {
|
||||
// Check if this blob references any JSON messages
|
||||
if (blob.data && blob.data[0] !== 0x7B) { // Protobuf blob
|
||||
// Look for JSON blob references
|
||||
for (const jsonBlob of jsonBlobs) {
|
||||
try {
|
||||
const jsonIdBytes = Buffer.from(jsonBlob.id, 'hex');
|
||||
if (blob.data.includes(jsonIdBytes)) {
|
||||
if (!messageOrder.has(jsonBlob.id)) {
|
||||
messageOrder.set(jsonBlob.id, orderIndex++);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Skip if can't convert ID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort JSON blobs by their appearance order in the DAG
|
||||
const sortedJsonBlobs = jsonBlobs.sort((a, b) => {
|
||||
const orderA = messageOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
const orderB = messageOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
if (orderA !== orderB) return orderA - orderB;
|
||||
// Fallback to rowid if not in order map
|
||||
return a.rowid - b.rowid;
|
||||
});
|
||||
|
||||
// Use sorted JSON blobs
|
||||
const blobs = sortedJsonBlobs.map((blob, idx) => ({
|
||||
...blob,
|
||||
sequence_num: idx + 1,
|
||||
original_rowid: blob.rowid
|
||||
}));
|
||||
|
||||
// Get metadata from meta table
|
||||
const metaRows = await db.all(`
|
||||
SELECT key, value FROM meta
|
||||
`);
|
||||
|
||||
// Parse metadata
|
||||
let metadata = {};
|
||||
for (const row of metaRows) {
|
||||
if (row.value) {
|
||||
try {
|
||||
// Try to decode as hex-encoded JSON
|
||||
const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
|
||||
if (hexMatch) {
|
||||
const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
|
||||
metadata[row.key] = JSON.parse(jsonStr);
|
||||
} else {
|
||||
metadata[row.key] = row.value.toString();
|
||||
}
|
||||
} catch (e) {
|
||||
metadata[row.key] = row.value.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract messages from sorted JSON blobs
|
||||
const messages = [];
|
||||
for (const blob of blobs) {
|
||||
try {
|
||||
// We already parsed JSON blobs earlier
|
||||
const parsed = blob.parsed;
|
||||
|
||||
if (parsed) {
|
||||
// Filter out ONLY system messages at the server level
|
||||
// Check both direct role and nested message.role
|
||||
const role = parsed?.role || parsed?.message?.role;
|
||||
if (role === 'system') {
|
||||
continue; // Skip only system messages
|
||||
}
|
||||
messages.push({
|
||||
id: blob.id,
|
||||
sequence: blob.sequence_num,
|
||||
rowid: blob.original_rowid,
|
||||
content: parsed
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// Skip blobs that cause errors
|
||||
console.log(`Skipping blob ${blob.id}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
await db.close();
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
session: {
|
||||
id: sessionId,
|
||||
projectPath: projectPath,
|
||||
messages: messages,
|
||||
metadata: metadata,
|
||||
cwdId: cwdId
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error reading Cursor session:', error);
|
||||
res.status(500).json({
|
||||
error: 'Failed to read Cursor session',
|
||||
details: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,9 +1,32 @@
|
||||
import express from 'express';
|
||||
import sessionManager from '../sessionManager.js';
|
||||
import { sessionNamesDb } from '../database/db.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/sessions/:sessionId/messages', async (req, res) => {
|
||||
try {
|
||||
const { sessionId } = req.params;
|
||||
|
||||
if (!sessionId || typeof sessionId !== 'string' || !/^[a-zA-Z0-9_.-]{1,100}$/.test(sessionId)) {
|
||||
return res.status(400).json({ success: false, error: 'Invalid session ID format' });
|
||||
}
|
||||
|
||||
const messages = sessionManager.getSessionMessages(sessionId);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
messages: messages,
|
||||
total: messages.length,
|
||||
hasMore: false,
|
||||
offset: 0,
|
||||
limit: messages.length
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching Gemini session messages:', error);
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/sessions/:sessionId', async (req, res) => {
|
||||
try {
|
||||
const { sessionId } = req.params;
|
||||
@@ -13,7 +36,6 @@ router.delete('/sessions/:sessionId', async (req, res) => {
|
||||
}
|
||||
|
||||
await sessionManager.deleteSession(sessionId);
|
||||
sessionNamesDb.deleteName(sessionId, 'gemini');
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error(`Error deleting Gemini session ${req.params.sessionId}:`, error);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import express from 'express';
|
||||
import { spawn } from 'child_process';
|
||||
import { exec, spawn } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import { extractProjectDirectory } from '../projects.js';
|
||||
@@ -7,7 +8,7 @@ import { queryClaudeSDK } from '../claude-sdk.js';
|
||||
import { spawnCursor } from '../cursor-cli.js';
|
||||
|
||||
const router = express.Router();
|
||||
const COMMIT_DIFF_CHARACTER_LIMIT = 500_000;
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
function spawnAsync(command, args, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -46,71 +47,15 @@ function spawnAsync(command, args, options = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
// Input validation helpers (defense-in-depth)
|
||||
function validateCommitRef(commit) {
|
||||
// Allow hex hashes, HEAD, HEAD~N, HEAD^N, tag names, branch names
|
||||
if (!/^[a-zA-Z0-9._~^{}@\/-]+$/.test(commit)) {
|
||||
throw new Error('Invalid commit reference');
|
||||
}
|
||||
return commit;
|
||||
}
|
||||
|
||||
function validateBranchName(branch) {
|
||||
if (!/^[a-zA-Z0-9._\/-]+$/.test(branch)) {
|
||||
throw new Error('Invalid branch name');
|
||||
}
|
||||
return branch;
|
||||
}
|
||||
|
||||
function validateFilePath(file, projectPath) {
|
||||
if (!file || file.includes('\0')) {
|
||||
throw new Error('Invalid file path');
|
||||
}
|
||||
// Prevent path traversal: resolve the file relative to the project root
|
||||
// and ensure the result stays within the project directory
|
||||
if (projectPath) {
|
||||
const resolved = path.resolve(projectPath, file);
|
||||
const normalizedRoot = path.resolve(projectPath) + path.sep;
|
||||
if (!resolved.startsWith(normalizedRoot) && resolved !== path.resolve(projectPath)) {
|
||||
throw new Error('Invalid file path: path traversal detected');
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
function validateRemoteName(remote) {
|
||||
if (!/^[a-zA-Z0-9._-]+$/.test(remote)) {
|
||||
throw new Error('Invalid remote name');
|
||||
}
|
||||
return remote;
|
||||
}
|
||||
|
||||
function validateProjectPath(projectPath) {
|
||||
if (!projectPath || projectPath.includes('\0')) {
|
||||
throw new Error('Invalid project path');
|
||||
}
|
||||
const resolved = path.resolve(projectPath);
|
||||
// Must be an absolute path after resolution
|
||||
if (!path.isAbsolute(resolved)) {
|
||||
throw new Error('Invalid project path: must be absolute');
|
||||
}
|
||||
// Block obviously dangerous paths
|
||||
if (resolved === '/' || resolved === path.sep) {
|
||||
throw new Error('Invalid project path: root directory not allowed');
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
// Helper function to get the actual project path from the encoded project name
|
||||
async function getActualProjectPath(projectName) {
|
||||
let projectPath;
|
||||
try {
|
||||
projectPath = await extractProjectDirectory(projectName);
|
||||
return await extractProjectDirectory(projectName);
|
||||
} catch (error) {
|
||||
console.error(`Error extracting project directory for ${projectName}:`, error);
|
||||
throw new Error(`Unable to resolve project path for "${projectName}"`);
|
||||
// Fallback to the old method
|
||||
return projectName.replace(/-/g, '/');
|
||||
}
|
||||
return validateProjectPath(projectPath);
|
||||
}
|
||||
|
||||
// Helper function to strip git diff headers
|
||||
@@ -153,140 +98,19 @@ async function validateGitRepository(projectPath) {
|
||||
|
||||
try {
|
||||
// Allow any directory that is inside a work tree (repo root or nested folder).
|
||||
const { stdout: insideWorkTreeOutput } = await spawnAsync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: projectPath });
|
||||
const { stdout: insideWorkTreeOutput } = await execAsync('git rev-parse --is-inside-work-tree', { cwd: projectPath });
|
||||
const isInsideWorkTree = insideWorkTreeOutput.trim() === 'true';
|
||||
if (!isInsideWorkTree) {
|
||||
throw new Error('Not inside a git work tree');
|
||||
}
|
||||
|
||||
// Ensure git can resolve the repository root for this directory.
|
||||
await spawnAsync('git', ['rev-parse', '--show-toplevel'], { cwd: projectPath });
|
||||
await execAsync('git rev-parse --show-toplevel', { cwd: projectPath });
|
||||
} catch {
|
||||
throw new Error('Not a git repository. This directory does not contain a .git folder. Initialize a git repository with "git init" to use source control features.');
|
||||
}
|
||||
}
|
||||
|
||||
function getGitErrorDetails(error) {
|
||||
return `${error?.message || ''} ${error?.stderr || ''} ${error?.stdout || ''}`;
|
||||
}
|
||||
|
||||
function isMissingHeadRevisionError(error) {
|
||||
const errorDetails = getGitErrorDetails(error).toLowerCase();
|
||||
return errorDetails.includes('unknown revision')
|
||||
|| errorDetails.includes('ambiguous argument')
|
||||
|| errorDetails.includes('needed a single revision')
|
||||
|| errorDetails.includes('bad revision');
|
||||
}
|
||||
|
||||
async function getCurrentBranchName(projectPath) {
|
||||
try {
|
||||
// symbolic-ref works even when the repository has no commits.
|
||||
const { stdout } = await spawnAsync('git', ['symbolic-ref', '--short', 'HEAD'], { cwd: projectPath });
|
||||
const branchName = stdout.trim();
|
||||
if (branchName) {
|
||||
return branchName;
|
||||
}
|
||||
} catch (error) {
|
||||
// Fall back to rev-parse for detached HEAD and older git edge cases.
|
||||
}
|
||||
|
||||
const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: projectPath });
|
||||
return stdout.trim();
|
||||
}
|
||||
|
||||
async function repositoryHasCommits(projectPath) {
|
||||
try {
|
||||
await spawnAsync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: projectPath });
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (isMissingHeadRevisionError(error)) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function getRepositoryRootPath(projectPath) {
|
||||
const { stdout } = await spawnAsync('git', ['rev-parse', '--show-toplevel'], { cwd: projectPath });
|
||||
return stdout.trim();
|
||||
}
|
||||
|
||||
function normalizeRepositoryRelativeFilePath(filePath) {
|
||||
return String(filePath)
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/^\.\/+/, '')
|
||||
.replace(/^\/+/, '')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function parseStatusFilePaths(statusOutput) {
|
||||
return statusOutput
|
||||
.split('\n')
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim())
|
||||
.map((line) => {
|
||||
const statusPath = line.substring(3);
|
||||
const renamedFilePath = statusPath.split(' -> ')[1];
|
||||
return normalizeRepositoryRelativeFilePath(renamedFilePath || statusPath);
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function buildFilePathCandidates(projectPath, repositoryRootPath, filePath) {
|
||||
const normalizedFilePath = normalizeRepositoryRelativeFilePath(filePath);
|
||||
const projectRelativePath = normalizeRepositoryRelativeFilePath(path.relative(repositoryRootPath, projectPath));
|
||||
const candidates = [normalizedFilePath];
|
||||
|
||||
if (
|
||||
projectRelativePath
|
||||
&& projectRelativePath !== '.'
|
||||
&& !normalizedFilePath.startsWith(`${projectRelativePath}/`)
|
||||
) {
|
||||
candidates.push(`${projectRelativePath}/${normalizedFilePath}`);
|
||||
}
|
||||
|
||||
return Array.from(new Set(candidates.filter(Boolean)));
|
||||
}
|
||||
|
||||
async function resolveRepositoryFilePath(projectPath, filePath) {
|
||||
validateFilePath(filePath);
|
||||
|
||||
const repositoryRootPath = await getRepositoryRootPath(projectPath);
|
||||
const candidateFilePaths = buildFilePathCandidates(projectPath, repositoryRootPath, filePath);
|
||||
|
||||
for (const candidateFilePath of candidateFilePaths) {
|
||||
const { stdout } = await spawnAsync('git', ['status', '--porcelain', '--', candidateFilePath], { cwd: repositoryRootPath });
|
||||
if (stdout.trim()) {
|
||||
return {
|
||||
repositoryRootPath,
|
||||
repositoryRelativeFilePath: candidateFilePath,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// If the caller sent a bare filename (e.g. "hello.ts"), recover it from changed files.
|
||||
const normalizedFilePath = normalizeRepositoryRelativeFilePath(filePath);
|
||||
if (!normalizedFilePath.includes('/')) {
|
||||
const { stdout: repositoryStatusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: repositoryRootPath });
|
||||
const changedFilePaths = parseStatusFilePaths(repositoryStatusOutput);
|
||||
const suffixMatches = changedFilePaths.filter(
|
||||
(changedFilePath) => changedFilePath === normalizedFilePath || changedFilePath.endsWith(`/${normalizedFilePath}`),
|
||||
);
|
||||
|
||||
if (suffixMatches.length === 1) {
|
||||
return {
|
||||
repositoryRootPath,
|
||||
repositoryRelativeFilePath: suffixMatches[0],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
repositoryRootPath,
|
||||
repositoryRelativeFilePath: candidateFilePaths[0],
|
||||
};
|
||||
}
|
||||
|
||||
// Get git status for a project
|
||||
router.get('/status', async (req, res) => {
|
||||
const { project } = req.query;
|
||||
@@ -301,11 +125,24 @@ router.get('/status', async (req, res) => {
|
||||
// Validate git repository
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
const branch = await getCurrentBranchName(projectPath);
|
||||
const hasCommits = await repositoryHasCommits(projectPath);
|
||||
// Get current branch - handle case where there are no commits yet
|
||||
let branch = 'main';
|
||||
let hasCommits = true;
|
||||
try {
|
||||
const { stdout: branchOutput } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
||||
branch = branchOutput.trim();
|
||||
} catch (error) {
|
||||
// No HEAD exists - repository has no commits yet
|
||||
if (error.message.includes('unknown revision') || error.message.includes('ambiguous argument')) {
|
||||
hasCommits = false;
|
||||
branch = 'main';
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Get git status
|
||||
const { stdout: statusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: projectPath });
|
||||
const { stdout: statusOutput } = await execAsync('git status --porcelain', { cwd: projectPath });
|
||||
|
||||
const modified = [];
|
||||
const added = [];
|
||||
@@ -363,65 +200,44 @@ router.get('/diff', async (req, res) => {
|
||||
|
||||
// Validate git repository
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
const {
|
||||
repositoryRootPath,
|
||||
repositoryRelativeFilePath,
|
||||
} = await resolveRepositoryFilePath(projectPath, file);
|
||||
|
||||
|
||||
// Check if file is untracked or deleted
|
||||
const { stdout: statusOutput } = await spawnAsync(
|
||||
'git',
|
||||
['status', '--porcelain', '--', repositoryRelativeFilePath],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
||||
const isUntracked = statusOutput.startsWith('??');
|
||||
const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
|
||||
|
||||
let diff;
|
||||
if (isUntracked) {
|
||||
// For untracked files, show the entire file content as additions
|
||||
const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
|
||||
const filePath = path.join(projectPath, file);
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
// For directories, show a simple message
|
||||
diff = `Directory: ${repositoryRelativeFilePath}\n(Cannot show diff for directories)`;
|
||||
diff = `Directory: ${file}\n(Cannot show diff for directories)`;
|
||||
} else {
|
||||
const fileContent = await fs.readFile(filePath, 'utf-8');
|
||||
const lines = fileContent.split('\n');
|
||||
diff = `--- /dev/null\n+++ b/${repositoryRelativeFilePath}\n@@ -0,0 +1,${lines.length} @@\n` +
|
||||
diff = `--- /dev/null\n+++ b/${file}\n@@ -0,0 +1,${lines.length} @@\n` +
|
||||
lines.map(line => `+${line}`).join('\n');
|
||||
}
|
||||
} else if (isDeleted) {
|
||||
// For deleted files, show the entire file content from HEAD as deletions
|
||||
const { stdout: fileContent } = await spawnAsync(
|
||||
'git',
|
||||
['show', `HEAD:${repositoryRelativeFilePath}`],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: fileContent } = await execAsync(`git show HEAD:"${file}"`, { cwd: projectPath });
|
||||
const lines = fileContent.split('\n');
|
||||
diff = `--- a/${repositoryRelativeFilePath}\n+++ /dev/null\n@@ -1,${lines.length} +0,0 @@\n` +
|
||||
diff = `--- a/${file}\n+++ /dev/null\n@@ -1,${lines.length} +0,0 @@\n` +
|
||||
lines.map(line => `-${line}`).join('\n');
|
||||
} else {
|
||||
// Get diff for tracked files
|
||||
// First check for unstaged changes (working tree vs index)
|
||||
const { stdout: unstagedDiff } = await spawnAsync(
|
||||
'git',
|
||||
['diff', '--', repositoryRelativeFilePath],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: unstagedDiff } = await execAsync(`git diff -- "${file}"`, { cwd: projectPath });
|
||||
|
||||
if (unstagedDiff) {
|
||||
// Show unstaged changes if they exist
|
||||
diff = stripDiffHeaders(unstagedDiff);
|
||||
} else {
|
||||
// If no unstaged changes, check for staged changes (index vs HEAD)
|
||||
const { stdout: stagedDiff } = await spawnAsync(
|
||||
'git',
|
||||
['diff', '--cached', '--', repositoryRelativeFilePath],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: stagedDiff } = await execAsync(`git diff --cached -- "${file}"`, { cwd: projectPath });
|
||||
diff = stripDiffHeaders(stagedDiff) || '';
|
||||
}
|
||||
}
|
||||
@@ -447,17 +263,8 @@ router.get('/file-with-diff', async (req, res) => {
|
||||
// Validate git repository
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
const {
|
||||
repositoryRootPath,
|
||||
repositoryRelativeFilePath,
|
||||
} = await resolveRepositoryFilePath(projectPath, file);
|
||||
|
||||
// Check file status
|
||||
const { stdout: statusOutput } = await spawnAsync(
|
||||
'git',
|
||||
['status', '--porcelain', '--', repositoryRelativeFilePath],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
||||
const isUntracked = statusOutput.startsWith('??');
|
||||
const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
|
||||
|
||||
@@ -466,16 +273,12 @@ router.get('/file-with-diff', async (req, res) => {
|
||||
|
||||
if (isDeleted) {
|
||||
// For deleted files, get content from HEAD
|
||||
const { stdout: headContent } = await spawnAsync(
|
||||
'git',
|
||||
['show', `HEAD:${repositoryRelativeFilePath}`],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: headContent } = await execAsync(`git show HEAD:"${file}"`, { cwd: projectPath });
|
||||
oldContent = headContent;
|
||||
currentContent = headContent; // Show the deleted content in editor
|
||||
} else {
|
||||
// Get current file content
|
||||
const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
|
||||
const filePath = path.join(projectPath, file);
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
@@ -488,11 +291,7 @@ router.get('/file-with-diff', async (req, res) => {
|
||||
if (!isUntracked) {
|
||||
// Get the old content from HEAD for tracked files
|
||||
try {
|
||||
const { stdout: headContent } = await spawnAsync(
|
||||
'git',
|
||||
['show', `HEAD:${repositoryRelativeFilePath}`],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: headContent } = await execAsync(`git show HEAD:"${file}"`, { cwd: projectPath });
|
||||
oldContent = headContent;
|
||||
} catch (error) {
|
||||
// File might be newly added to git (staged but not committed)
|
||||
@@ -529,17 +328,17 @@ router.post('/initial-commit', async (req, res) => {
|
||||
|
||||
// Check if there are already commits
|
||||
try {
|
||||
await spawnAsync('git', ['rev-parse', 'HEAD'], { cwd: projectPath });
|
||||
await execAsync('git rev-parse HEAD', { cwd: projectPath });
|
||||
return res.status(400).json({ error: 'Repository already has commits. Use regular commit instead.' });
|
||||
} catch (error) {
|
||||
// No HEAD - this is good, we can create initial commit
|
||||
}
|
||||
|
||||
// Add all files
|
||||
await spawnAsync('git', ['add', '.'], { cwd: projectPath });
|
||||
await execAsync('git add .', { cwd: projectPath });
|
||||
|
||||
// Create initial commit
|
||||
const { stdout } = await spawnAsync('git', ['commit', '-m', 'Initial commit'], { cwd: projectPath });
|
||||
const { stdout } = await execAsync('git commit -m "Initial commit"', { cwd: projectPath });
|
||||
|
||||
res.json({ success: true, output: stdout, message: 'Initial commit created successfully' });
|
||||
} catch (error) {
|
||||
@@ -570,16 +369,14 @@ router.post('/commit', async (req, res) => {
|
||||
|
||||
// Validate git repository
|
||||
await validateGitRepository(projectPath);
|
||||
const repositoryRootPath = await getRepositoryRootPath(projectPath);
|
||||
|
||||
// Stage selected files
|
||||
for (const file of files) {
|
||||
const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
|
||||
await spawnAsync('git', ['add', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
|
||||
await execAsync(`git add "${file}"`, { cwd: projectPath });
|
||||
}
|
||||
|
||||
|
||||
// Commit with message
|
||||
const { stdout } = await spawnAsync('git', ['commit', '-m', message], { cwd: repositoryRootPath });
|
||||
const { stdout } = await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd: projectPath });
|
||||
|
||||
res.json({ success: true, output: stdout });
|
||||
} catch (error) {
|
||||
@@ -588,53 +385,6 @@ router.post('/commit', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Revert latest local commit (keeps changes staged)
|
||||
router.post('/revert-local-commit', async (req, res) => {
|
||||
const { project } = req.body;
|
||||
|
||||
if (!project) {
|
||||
return res.status(400).json({ error: 'Project name is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
try {
|
||||
await spawnAsync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: projectPath });
|
||||
} catch (error) {
|
||||
return res.status(400).json({
|
||||
error: 'No local commit to revert',
|
||||
details: 'This repository has no commit yet.',
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Soft reset rewinds one commit while preserving all file changes in the index.
|
||||
await spawnAsync('git', ['reset', '--soft', 'HEAD~1'], { cwd: projectPath });
|
||||
} catch (error) {
|
||||
const errorDetails = `${error.stderr || ''} ${error.message || ''}`;
|
||||
const isInitialCommit = errorDetails.includes('HEAD~1') &&
|
||||
(errorDetails.includes('unknown revision') || errorDetails.includes('ambiguous argument'));
|
||||
|
||||
if (!isInitialCommit) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Initial commit has no parent; deleting HEAD uncommits it and keeps files staged.
|
||||
await spawnAsync('git', ['update-ref', '-d', 'HEAD'], { cwd: projectPath });
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
output: 'Latest local commit reverted successfully. Changes were kept staged.',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Git revert local commit error:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get list of branches
|
||||
router.get('/branches', async (req, res) => {
|
||||
const { project } = req.query;
|
||||
@@ -650,29 +400,27 @@ router.get('/branches', async (req, res) => {
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
// Get all branches
|
||||
const { stdout } = await spawnAsync('git', ['branch', '-a'], { cwd: projectPath });
|
||||
|
||||
const rawLines = stdout
|
||||
const { stdout } = await execAsync('git branch -a', { cwd: projectPath });
|
||||
|
||||
// Parse branches
|
||||
const branches = stdout
|
||||
.split('\n')
|
||||
.map(b => b.trim())
|
||||
.filter(b => b && !b.includes('->'));
|
||||
|
||||
// Local branches (may start with '* ' for current)
|
||||
const localBranches = rawLines
|
||||
.filter(b => !b.startsWith('remotes/'))
|
||||
.map(b => (b.startsWith('* ') ? b.substring(2) : b));
|
||||
|
||||
// Remote branches — strip 'remotes/<remote>/' prefix
|
||||
const remoteBranches = rawLines
|
||||
.filter(b => b.startsWith('remotes/'))
|
||||
.map(b => b.replace(/^remotes\/[^/]+\//, ''))
|
||||
.filter(name => !localBranches.includes(name)); // skip if already a local branch
|
||||
|
||||
// Backward-compat flat list (local + unique remotes, deduplicated)
|
||||
const branches = [...localBranches, ...remoteBranches]
|
||||
.filter((b, i, arr) => arr.indexOf(b) === i);
|
||||
|
||||
res.json({ branches, localBranches, remoteBranches });
|
||||
.map(branch => branch.trim())
|
||||
.filter(branch => branch && !branch.includes('->')) // Remove empty lines and HEAD pointer
|
||||
.map(branch => {
|
||||
// Remove asterisk from current branch
|
||||
if (branch.startsWith('* ')) {
|
||||
return branch.substring(2);
|
||||
}
|
||||
// Remove remotes/ prefix
|
||||
if (branch.startsWith('remotes/origin/')) {
|
||||
return branch.substring(15);
|
||||
}
|
||||
return branch;
|
||||
})
|
||||
.filter((branch, index, self) => self.indexOf(branch) === index); // Remove duplicates
|
||||
|
||||
res.json({ branches });
|
||||
} catch (error) {
|
||||
console.error('Git branches error:', error);
|
||||
res.json({ error: error.message });
|
||||
@@ -691,8 +439,7 @@ router.post('/checkout', async (req, res) => {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
|
||||
// Checkout the branch
|
||||
validateBranchName(branch);
|
||||
const { stdout } = await spawnAsync('git', ['checkout', branch], { cwd: projectPath });
|
||||
const { stdout } = await execAsync(`git checkout "${branch}"`, { cwd: projectPath });
|
||||
|
||||
res.json({ success: true, output: stdout });
|
||||
} catch (error) {
|
||||
@@ -713,8 +460,7 @@ router.post('/create-branch', async (req, res) => {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
|
||||
// Create and checkout new branch
|
||||
validateBranchName(branch);
|
||||
const { stdout } = await spawnAsync('git', ['checkout', '-b', branch], { cwd: projectPath });
|
||||
const { stdout } = await execAsync(`git checkout -b "${branch}"`, { cwd: projectPath });
|
||||
|
||||
res.json({ success: true, output: stdout });
|
||||
} catch (error) {
|
||||
@@ -723,32 +469,6 @@ router.post('/create-branch', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Delete a local branch
|
||||
router.post('/delete-branch', async (req, res) => {
|
||||
const { project, branch } = req.body;
|
||||
|
||||
if (!project || !branch) {
|
||||
return res.status(400).json({ error: 'Project name and branch name are required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
// Safety: cannot delete the currently checked-out branch
|
||||
const { stdout: currentBranch } = await spawnAsync('git', ['branch', '--show-current'], { cwd: projectPath });
|
||||
if (currentBranch.trim() === branch) {
|
||||
return res.status(400).json({ error: 'Cannot delete the currently checked-out branch' });
|
||||
}
|
||||
|
||||
const { stdout } = await spawnAsync('git', ['branch', '-d', branch], { cwd: projectPath });
|
||||
res.json({ success: true, output: stdout });
|
||||
} catch (error) {
|
||||
console.error('Git delete branch error:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get recent commits
|
||||
router.get('/commits', async (req, res) => {
|
||||
const { project, limit = 10 } = req.query;
|
||||
@@ -768,7 +488,7 @@ router.get('/commits', async (req, res) => {
|
||||
// Get commit log with stats
|
||||
const { stdout } = await spawnAsync(
|
||||
'git',
|
||||
['log', '--pretty=format:%H|%an|%ae|%ad|%s', '--date=iso-strict', '-n', String(safeLimit)],
|
||||
['log', '--pretty=format:%H|%an|%ae|%ad|%s', '--date=relative', '-n', String(safeLimit)],
|
||||
{ cwd: projectPath },
|
||||
);
|
||||
|
||||
@@ -789,8 +509,8 @@ router.get('/commits', async (req, res) => {
|
||||
// Get stats for each commit
|
||||
for (const commit of commits) {
|
||||
try {
|
||||
const { stdout: stats } = await spawnAsync(
|
||||
'git', ['show', '--stat', '--format=', commit.hash],
|
||||
const { stdout: stats } = await execAsync(
|
||||
`git show --stat --format='' ${commit.hash}`,
|
||||
{ cwd: projectPath }
|
||||
);
|
||||
commit.stats = stats.trim().split('\n').pop(); // Get the summary line
|
||||
@@ -816,22 +536,14 @@ router.get('/commit-diff', async (req, res) => {
|
||||
|
||||
try {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
|
||||
// Validate commit reference (defense-in-depth)
|
||||
validateCommitRef(commit);
|
||||
|
||||
|
||||
// Get diff for the commit
|
||||
const { stdout } = await spawnAsync(
|
||||
'git', ['show', commit],
|
||||
const { stdout } = await execAsync(
|
||||
`git show ${commit}`,
|
||||
{ cwd: projectPath }
|
||||
);
|
||||
|
||||
const isTruncated = stdout.length > COMMIT_DIFF_CHARACTER_LIMIT;
|
||||
const diff = isTruncated
|
||||
? `${stdout.slice(0, COMMIT_DIFF_CHARACTER_LIMIT)}\n\n... Diff truncated to keep the UI responsive ...`
|
||||
: stdout;
|
||||
|
||||
res.json({ diff, isTruncated });
|
||||
|
||||
res.json({ diff: stdout });
|
||||
} catch (error) {
|
||||
console.error('Git commit diff error:', error);
|
||||
res.json({ error: error.message });
|
||||
@@ -853,20 +565,17 @@ router.post('/generate-commit-message', async (req, res) => {
|
||||
|
||||
try {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
const repositoryRootPath = await getRepositoryRootPath(projectPath);
|
||||
|
||||
// Get diff for selected files
|
||||
let diffContext = '';
|
||||
for (const file of files) {
|
||||
try {
|
||||
const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
|
||||
const { stdout } = await spawnAsync(
|
||||
'git', ['diff', 'HEAD', '--', repositoryRelativeFilePath],
|
||||
{ cwd: repositoryRootPath }
|
||||
const { stdout } = await execAsync(
|
||||
`git diff HEAD -- "${file}"`,
|
||||
{ cwd: projectPath }
|
||||
);
|
||||
if (stdout) {
|
||||
diffContext += `\n--- ${repositoryRelativeFilePath} ---\n${stdout}`;
|
||||
diffContext += `\n--- ${file} ---\n${stdout}`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error getting diff for ${file}:`, error);
|
||||
@@ -878,15 +587,14 @@ router.post('/generate-commit-message', async (req, res) => {
|
||||
// Try to get content of untracked files
|
||||
for (const file of files) {
|
||||
try {
|
||||
const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
|
||||
const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
|
||||
const filePath = path.join(projectPath, file);
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
if (!stats.isDirectory()) {
|
||||
const content = await fs.readFile(filePath, 'utf-8');
|
||||
diffContext += `\n--- ${repositoryRelativeFilePath} (new file) ---\n${content.substring(0, 1000)}\n`;
|
||||
diffContext += `\n--- ${file} (new file) ---\n${content.substring(0, 1000)}\n`;
|
||||
} else {
|
||||
diffContext += `\n--- ${repositoryRelativeFilePath} (new directory) ---\n`;
|
||||
diffContext += `\n--- ${file} (new directory) ---\n`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error reading file ${file}:`, error);
|
||||
@@ -1055,51 +763,44 @@ router.get('/remote-status', async (req, res) => {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
const branch = await getCurrentBranchName(projectPath);
|
||||
const hasCommits = await repositoryHasCommits(projectPath);
|
||||
|
||||
const { stdout: remoteOutput } = await spawnAsync('git', ['remote'], { cwd: projectPath });
|
||||
const remotes = remoteOutput.trim().split('\n').filter(r => r.trim());
|
||||
const hasRemote = remotes.length > 0;
|
||||
const fallbackRemoteName = hasRemote
|
||||
? (remotes.includes('origin') ? 'origin' : remotes[0])
|
||||
: null;
|
||||
|
||||
// Repositories initialized with `git init` can have a branch but no commits.
|
||||
// Return a non-error state so the UI can show the initial-commit workflow.
|
||||
if (!hasCommits) {
|
||||
return res.json({
|
||||
hasRemote,
|
||||
hasUpstream: false,
|
||||
branch,
|
||||
remoteName: fallbackRemoteName,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
isUpToDate: false,
|
||||
message: 'Repository has no commits yet'
|
||||
});
|
||||
}
|
||||
// Get current branch
|
||||
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
||||
const branch = currentBranch.trim();
|
||||
|
||||
// Check if there's a remote tracking branch (smart detection)
|
||||
let trackingBranch;
|
||||
let remoteName;
|
||||
try {
|
||||
const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
|
||||
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
||||
trackingBranch = stdout.trim();
|
||||
remoteName = trackingBranch.split('/')[0]; // Extract remote name (e.g., "origin/main" -> "origin")
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
// No upstream branch configured - but check if we have remotes
|
||||
let hasRemote = false;
|
||||
let remoteName = null;
|
||||
try {
|
||||
const { stdout } = await execAsync('git remote', { cwd: projectPath });
|
||||
const remotes = stdout.trim().split('\n').filter(r => r.trim());
|
||||
if (remotes.length > 0) {
|
||||
hasRemote = true;
|
||||
remoteName = remotes.includes('origin') ? 'origin' : remotes[0];
|
||||
}
|
||||
} catch (remoteError) {
|
||||
// No remotes configured
|
||||
}
|
||||
|
||||
return res.json({
|
||||
hasRemote,
|
||||
hasUpstream: false,
|
||||
branch,
|
||||
remoteName: fallbackRemoteName,
|
||||
remoteName,
|
||||
message: 'No remote tracking branch configured'
|
||||
});
|
||||
}
|
||||
|
||||
// Get ahead/behind counts
|
||||
const { stdout: countOutput } = await spawnAsync(
|
||||
'git', ['rev-list', '--count', '--left-right', `${trackingBranch}...HEAD`],
|
||||
const { stdout: countOutput } = await execAsync(
|
||||
`git rev-list --count --left-right ${trackingBranch}...HEAD`,
|
||||
{ cwd: projectPath }
|
||||
);
|
||||
|
||||
@@ -1134,20 +835,20 @@ router.post('/fetch', async (req, res) => {
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
// Get current branch and its upstream remote
|
||||
const branch = await getCurrentBranchName(projectPath);
|
||||
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
||||
const branch = currentBranch.trim();
|
||||
|
||||
let remoteName = 'origin'; // fallback
|
||||
try {
|
||||
const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
|
||||
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
||||
remoteName = stdout.trim().split('/')[0]; // Extract remote name
|
||||
} catch (error) {
|
||||
// No upstream, try to fetch from origin anyway
|
||||
console.log('No upstream configured, using origin as fallback');
|
||||
}
|
||||
|
||||
validateRemoteName(remoteName);
|
||||
const { stdout } = await spawnAsync('git', ['fetch', remoteName], { cwd: projectPath });
|
||||
|
||||
const { stdout } = await execAsync(`git fetch ${remoteName}`, { cwd: projectPath });
|
||||
|
||||
res.json({ success: true, output: stdout || 'Fetch completed successfully', remoteName });
|
||||
} catch (error) {
|
||||
console.error('Git fetch error:', error);
|
||||
@@ -1175,12 +876,13 @@ router.post('/pull', async (req, res) => {
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
// Get current branch and its upstream remote
|
||||
const branch = await getCurrentBranchName(projectPath);
|
||||
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
||||
const branch = currentBranch.trim();
|
||||
|
||||
let remoteName = 'origin'; // fallback
|
||||
let remoteBranch = branch; // fallback
|
||||
try {
|
||||
const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
|
||||
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
||||
const tracking = stdout.trim();
|
||||
remoteName = tracking.split('/')[0]; // Extract remote name
|
||||
remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
|
||||
@@ -1189,19 +891,17 @@ router.post('/pull', async (req, res) => {
|
||||
console.log('No upstream configured, using origin/branch as fallback');
|
||||
}
|
||||
|
||||
validateRemoteName(remoteName);
|
||||
validateBranchName(remoteBranch);
|
||||
const { stdout } = await spawnAsync('git', ['pull', remoteName, remoteBranch], { cwd: projectPath });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
output: stdout || 'Pull completed successfully',
|
||||
const { stdout } = await execAsync(`git pull ${remoteName} ${remoteBranch}`, { cwd: projectPath });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
output: stdout || 'Pull completed successfully',
|
||||
remoteName,
|
||||
remoteBranch
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Git pull error:', error);
|
||||
|
||||
|
||||
// Enhanced error handling for common pull scenarios
|
||||
let errorMessage = 'Pull failed';
|
||||
let details = error.message;
|
||||
@@ -1243,12 +943,13 @@ router.post('/push', async (req, res) => {
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
// Get current branch and its upstream remote
|
||||
const branch = await getCurrentBranchName(projectPath);
|
||||
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
||||
const branch = currentBranch.trim();
|
||||
|
||||
let remoteName = 'origin'; // fallback
|
||||
let remoteBranch = branch; // fallback
|
||||
try {
|
||||
const { stdout } = await spawnAsync('git', ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], { cwd: projectPath });
|
||||
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
||||
const tracking = stdout.trim();
|
||||
remoteName = tracking.split('/')[0]; // Extract remote name
|
||||
remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
|
||||
@@ -1257,13 +958,11 @@ router.post('/push', async (req, res) => {
|
||||
console.log('No upstream configured, using origin/branch as fallback');
|
||||
}
|
||||
|
||||
validateRemoteName(remoteName);
|
||||
validateBranchName(remoteBranch);
|
||||
const { stdout } = await spawnAsync('git', ['push', remoteName, remoteBranch], { cwd: projectPath });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
output: stdout || 'Push completed successfully',
|
||||
const { stdout } = await execAsync(`git push ${remoteName} ${remoteBranch}`, { cwd: projectPath });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
output: stdout || 'Push completed successfully',
|
||||
remoteName,
|
||||
remoteBranch
|
||||
});
|
||||
@@ -1313,38 +1012,35 @@ router.post('/publish', async (req, res) => {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
|
||||
// Validate branch name
|
||||
validateBranchName(branch);
|
||||
|
||||
// Get current branch to verify it matches the requested branch
|
||||
const currentBranchName = await getCurrentBranchName(projectPath);
|
||||
|
||||
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
||||
const currentBranchName = currentBranch.trim();
|
||||
|
||||
if (currentBranchName !== branch) {
|
||||
return res.status(400).json({
|
||||
error: `Branch mismatch. Current branch is ${currentBranchName}, but trying to publish ${branch}`
|
||||
return res.status(400).json({
|
||||
error: `Branch mismatch. Current branch is ${currentBranchName}, but trying to publish ${branch}`
|
||||
});
|
||||
}
|
||||
|
||||
// Check if remote exists
|
||||
let remoteName = 'origin';
|
||||
try {
|
||||
const { stdout } = await spawnAsync('git', ['remote'], { cwd: projectPath });
|
||||
const { stdout } = await execAsync('git remote', { cwd: projectPath });
|
||||
const remotes = stdout.trim().split('\n').filter(r => r.trim());
|
||||
if (remotes.length === 0) {
|
||||
return res.status(400).json({
|
||||
error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
|
||||
return res.status(400).json({
|
||||
error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
|
||||
});
|
||||
}
|
||||
remoteName = remotes.includes('origin') ? 'origin' : remotes[0];
|
||||
} catch (error) {
|
||||
return res.status(400).json({
|
||||
error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
|
||||
return res.status(400).json({
|
||||
error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
|
||||
});
|
||||
}
|
||||
|
||||
// Publish the branch (set upstream and push)
|
||||
validateRemoteName(remoteName);
|
||||
const { stdout } = await spawnAsync('git', ['push', '--set-upstream', remoteName, branch], { cwd: projectPath });
|
||||
const { stdout } = await execAsync(`git push --set-upstream ${remoteName} ${branch}`, { cwd: projectPath });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
@@ -1391,18 +1087,10 @@ router.post('/discard', async (req, res) => {
|
||||
try {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
const {
|
||||
repositoryRootPath,
|
||||
repositoryRelativeFilePath,
|
||||
} = await resolveRepositoryFilePath(projectPath, file);
|
||||
|
||||
// Check file status to determine correct discard command
|
||||
const { stdout: statusOutput } = await spawnAsync(
|
||||
'git',
|
||||
['status', '--porcelain', '--', repositoryRelativeFilePath],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
|
||||
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
||||
|
||||
if (!statusOutput.trim()) {
|
||||
return res.status(400).json({ error: 'No changes to discard for this file' });
|
||||
}
|
||||
@@ -1411,7 +1099,7 @@ router.post('/discard', async (req, res) => {
|
||||
|
||||
if (status === '??') {
|
||||
// Untracked file or directory - delete it
|
||||
const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
|
||||
const filePath = path.join(projectPath, file);
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
@@ -1421,13 +1109,13 @@ router.post('/discard', async (req, res) => {
|
||||
}
|
||||
} else if (status.includes('M') || status.includes('D')) {
|
||||
// Modified or deleted file - restore from HEAD
|
||||
await spawnAsync('git', ['restore', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
|
||||
await execAsync(`git restore "${file}"`, { cwd: projectPath });
|
||||
} else if (status.includes('A')) {
|
||||
// Added file - unstage it
|
||||
await spawnAsync('git', ['reset', 'HEAD', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
|
||||
await execAsync(`git reset HEAD "${file}"`, { cwd: projectPath });
|
||||
}
|
||||
|
||||
res.json({ success: true, message: `Changes discarded for ${repositoryRelativeFilePath}` });
|
||||
res.json({ success: true, message: `Changes discarded for ${file}` });
|
||||
} catch (error) {
|
||||
console.error('Git discard error:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
@@ -1445,17 +1133,9 @@ router.post('/delete-untracked', async (req, res) => {
|
||||
try {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
const {
|
||||
repositoryRootPath,
|
||||
repositoryRelativeFilePath,
|
||||
} = await resolveRepositoryFilePath(projectPath, file);
|
||||
|
||||
// Check if file is actually untracked
|
||||
const { stdout: statusOutput } = await spawnAsync(
|
||||
'git',
|
||||
['status', '--porcelain', '--', repositoryRelativeFilePath],
|
||||
{ cwd: repositoryRootPath },
|
||||
);
|
||||
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
||||
|
||||
if (!statusOutput.trim()) {
|
||||
return res.status(400).json({ error: 'File is not untracked or does not exist' });
|
||||
@@ -1468,16 +1148,16 @@ router.post('/delete-untracked', async (req, res) => {
|
||||
}
|
||||
|
||||
// Delete the untracked file or directory
|
||||
const filePath = path.join(repositoryRootPath, repositoryRelativeFilePath);
|
||||
const filePath = path.join(projectPath, file);
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
// Use rm with recursive option for directories
|
||||
await fs.rm(filePath, { recursive: true, force: true });
|
||||
res.json({ success: true, message: `Untracked directory ${repositoryRelativeFilePath} deleted successfully` });
|
||||
res.json({ success: true, message: `Untracked directory ${file} deleted successfully` });
|
||||
} else {
|
||||
await fs.unlink(filePath);
|
||||
res.json({ success: true, message: `Untracked file ${repositoryRelativeFilePath} deleted successfully` });
|
||||
res.json({ success: true, message: `Untracked file ${file} deleted successfully` });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Git delete untracked error:', error);
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
/**
|
||||
* Unified messages endpoint.
|
||||
*
|
||||
* GET /api/sessions/:sessionId/messages?provider=claude&projectName=foo&limit=50&offset=0
|
||||
*
|
||||
* Replaces the four provider-specific session message endpoints with a single route
|
||||
* that delegates to the appropriate adapter via the provider registry.
|
||||
*
|
||||
* @module routes/messages
|
||||
*/
|
||||
|
||||
import express from 'express';
|
||||
import { getProvider, getAllProviders } from '../providers/registry.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* GET /api/sessions/:sessionId/messages
|
||||
*
|
||||
* Auth: authenticateToken applied at mount level in index.js
|
||||
*
|
||||
* Query params:
|
||||
* provider - 'claude' | 'cursor' | 'codex' | 'gemini' (default: 'claude')
|
||||
* projectName - required for claude provider
|
||||
* projectPath - required for cursor provider (absolute path used for cwdId hash)
|
||||
* limit - page size (omit or null for all)
|
||||
* offset - pagination offset (default: 0)
|
||||
*/
|
||||
router.get('/:sessionId/messages', async (req, res) => {
|
||||
try {
|
||||
const { sessionId } = req.params;
|
||||
const provider = req.query.provider || 'claude';
|
||||
const projectName = req.query.projectName || '';
|
||||
const projectPath = req.query.projectPath || '';
|
||||
const limitParam = req.query.limit;
|
||||
const limit = limitParam !== undefined && limitParam !== null && limitParam !== ''
|
||||
? parseInt(limitParam, 10)
|
||||
: null;
|
||||
const offset = parseInt(req.query.offset || '0', 10);
|
||||
|
||||
const adapter = getProvider(provider);
|
||||
if (!adapter) {
|
||||
const available = getAllProviders().join(', ');
|
||||
return res.status(400).json({ error: `Unknown provider: ${provider}. Available: ${available}` });
|
||||
}
|
||||
|
||||
const result = await adapter.fetchHistory(sessionId, {
|
||||
projectName,
|
||||
projectPath,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
|
||||
return res.json(result);
|
||||
} catch (error) {
|
||||
console.error('Error fetching unified messages:', error);
|
||||
return res.status(500).json({ error: 'Failed to fetch messages' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,307 +0,0 @@
|
||||
import express from 'express';
|
||||
import path from 'path';
|
||||
import http from 'http';
|
||||
import mime from 'mime-types';
|
||||
import fs from 'fs';
|
||||
import {
|
||||
scanPlugins,
|
||||
getPluginsConfig,
|
||||
getPluginsDir,
|
||||
savePluginsConfig,
|
||||
getPluginDir,
|
||||
resolvePluginAssetPath,
|
||||
installPluginFromGit,
|
||||
updatePluginFromGit,
|
||||
uninstallPlugin,
|
||||
} from '../utils/plugin-loader.js';
|
||||
import {
|
||||
startPluginServer,
|
||||
stopPluginServer,
|
||||
getPluginPort,
|
||||
isPluginRunning,
|
||||
} from '../utils/plugin-process-manager.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET / — List all installed plugins (includes server running status)
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const plugins = scanPlugins().map(p => ({
|
||||
...p,
|
||||
serverRunning: p.server ? isPluginRunning(p.name) : false,
|
||||
}));
|
||||
res.json({ plugins });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: 'Failed to scan plugins', details: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /:name/manifest — Get single plugin manifest
|
||||
router.get('/:name/manifest', (req, res) => {
|
||||
try {
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(req.params.name)) {
|
||||
return res.status(400).json({ error: 'Invalid plugin name' });
|
||||
}
|
||||
const plugins = scanPlugins();
|
||||
const plugin = plugins.find(p => p.name === req.params.name);
|
||||
if (!plugin) {
|
||||
return res.status(404).json({ error: 'Plugin not found' });
|
||||
}
|
||||
res.json(plugin);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: 'Failed to read plugin manifest', details: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /:name/assets/* — Serve plugin static files
|
||||
router.get('/:name/assets/*', (req, res) => {
|
||||
const pluginName = req.params.name;
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
|
||||
return res.status(400).json({ error: 'Invalid plugin name' });
|
||||
}
|
||||
const assetPath = req.params[0];
|
||||
|
||||
if (!assetPath) {
|
||||
return res.status(400).json({ error: 'No asset path specified' });
|
||||
}
|
||||
|
||||
const resolvedPath = resolvePluginAssetPath(pluginName, assetPath);
|
||||
if (!resolvedPath) {
|
||||
return res.status(404).json({ error: 'Asset not found' });
|
||||
}
|
||||
|
||||
try {
|
||||
const stat = fs.statSync(resolvedPath);
|
||||
if (!stat.isFile()) {
|
||||
return res.status(404).json({ error: 'Asset not found' });
|
||||
}
|
||||
} catch {
|
||||
return res.status(404).json({ error: 'Asset not found' });
|
||||
}
|
||||
|
||||
const contentType = mime.lookup(resolvedPath) || 'application/octet-stream';
|
||||
res.setHeader('Content-Type', contentType);
|
||||
// Prevent CDN/proxy caching of plugin assets so updates take effect immediately
|
||||
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
|
||||
res.setHeader('Pragma', 'no-cache');
|
||||
res.setHeader('Expires', '0');
|
||||
const stream = fs.createReadStream(resolvedPath);
|
||||
stream.on('error', () => {
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ error: 'Failed to read asset' });
|
||||
} else {
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
stream.pipe(res);
|
||||
});
|
||||
|
||||
// PUT /:name/enable — Toggle plugin enabled/disabled (starts/stops server if applicable)
|
||||
router.put('/:name/enable', async (req, res) => {
|
||||
try {
|
||||
const { enabled } = req.body;
|
||||
if (typeof enabled !== 'boolean') {
|
||||
return res.status(400).json({ error: '"enabled" must be a boolean' });
|
||||
}
|
||||
|
||||
const plugins = scanPlugins();
|
||||
const plugin = plugins.find(p => p.name === req.params.name);
|
||||
if (!plugin) {
|
||||
return res.status(404).json({ error: 'Plugin not found' });
|
||||
}
|
||||
|
||||
const config = getPluginsConfig();
|
||||
config[req.params.name] = { ...config[req.params.name], enabled };
|
||||
savePluginsConfig(config);
|
||||
|
||||
// Start or stop the plugin server as needed
|
||||
if (plugin.server) {
|
||||
if (enabled && !isPluginRunning(plugin.name)) {
|
||||
const pluginDir = getPluginDir(plugin.name);
|
||||
if (pluginDir) {
|
||||
try {
|
||||
await startPluginServer(plugin.name, pluginDir, plugin.server);
|
||||
} catch (err) {
|
||||
console.error(`[Plugins] Failed to start server for "${plugin.name}":`, err.message);
|
||||
}
|
||||
}
|
||||
} else if (!enabled && isPluginRunning(plugin.name)) {
|
||||
await stopPluginServer(plugin.name);
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true, name: req.params.name, enabled });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: 'Failed to update plugin', details: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /install — Install plugin from git URL
|
||||
router.post('/install', async (req, res) => {
|
||||
try {
|
||||
const { url } = req.body;
|
||||
if (!url || typeof url !== 'string') {
|
||||
return res.status(400).json({ error: '"url" is required and must be a string' });
|
||||
}
|
||||
|
||||
// Basic URL validation
|
||||
if (!url.startsWith('https://') && !url.startsWith('git@')) {
|
||||
return res.status(400).json({ error: 'URL must start with https:// or git@' });
|
||||
}
|
||||
|
||||
const manifest = await installPluginFromGit(url);
|
||||
|
||||
// Auto-start the server if the plugin has one (enabled by default)
|
||||
if (manifest.server) {
|
||||
const pluginDir = getPluginDir(manifest.name);
|
||||
if (pluginDir) {
|
||||
try {
|
||||
await startPluginServer(manifest.name, pluginDir, manifest.server);
|
||||
} catch (err) {
|
||||
console.error(`[Plugins] Failed to start server for "${manifest.name}":`, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true, plugin: manifest });
|
||||
} catch (err) {
|
||||
res.status(400).json({ error: 'Failed to install plugin', details: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /:name/update — Pull latest from git (restarts server if running)
|
||||
router.post('/:name/update', async (req, res) => {
|
||||
try {
|
||||
const pluginName = req.params.name;
|
||||
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
|
||||
return res.status(400).json({ error: 'Invalid plugin name' });
|
||||
}
|
||||
|
||||
const wasRunning = isPluginRunning(pluginName);
|
||||
if (wasRunning) {
|
||||
await stopPluginServer(pluginName);
|
||||
}
|
||||
|
||||
const manifest = await updatePluginFromGit(pluginName);
|
||||
|
||||
// Restart server if it was running before the update
|
||||
if (wasRunning && manifest.server) {
|
||||
const pluginDir = getPluginDir(pluginName);
|
||||
if (pluginDir) {
|
||||
try {
|
||||
await startPluginServer(pluginName, pluginDir, manifest.server);
|
||||
} catch (err) {
|
||||
console.error(`[Plugins] Failed to restart server for "${pluginName}":`, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true, plugin: manifest });
|
||||
} catch (err) {
|
||||
res.status(400).json({ error: 'Failed to update plugin', details: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ALL /:name/rpc/* — Proxy requests to plugin's server subprocess
|
||||
router.all('/:name/rpc/*', async (req, res) => {
|
||||
const pluginName = req.params.name;
|
||||
const rpcPath = req.params[0] || '';
|
||||
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
|
||||
return res.status(400).json({ error: 'Invalid plugin name' });
|
||||
}
|
||||
|
||||
let port = getPluginPort(pluginName);
|
||||
if (!port) {
|
||||
// Lazily start the plugin server if it exists and is enabled
|
||||
const plugins = scanPlugins();
|
||||
const plugin = plugins.find(p => p.name === pluginName);
|
||||
if (!plugin || !plugin.server) {
|
||||
return res.status(503).json({ error: 'Plugin server is not running' });
|
||||
}
|
||||
if (!plugin.enabled) {
|
||||
return res.status(503).json({ error: 'Plugin is disabled' });
|
||||
}
|
||||
const pluginDir = path.join(getPluginsDir(), plugin.dirName);
|
||||
try {
|
||||
port = await startPluginServer(pluginName, pluginDir, plugin.server);
|
||||
} catch (err) {
|
||||
return res.status(503).json({ error: 'Plugin server failed to start', details: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Inject configured secrets as headers
|
||||
const config = getPluginsConfig();
|
||||
const pluginConfig = config[pluginName] || {};
|
||||
const secrets = pluginConfig.secrets || {};
|
||||
|
||||
const headers = {
|
||||
'content-type': req.headers['content-type'] || 'application/json',
|
||||
};
|
||||
|
||||
// Add per-plugin user-configured secrets as X-Plugin-Secret-* headers
|
||||
for (const [key, value] of Object.entries(secrets)) {
|
||||
headers[`x-plugin-secret-${key.toLowerCase()}`] = String(value);
|
||||
}
|
||||
|
||||
// Reconstruct query string
|
||||
const qs = req.url.includes('?') ? '?' + req.url.split('?').slice(1).join('?') : '';
|
||||
|
||||
const options = {
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
path: `/${rpcPath}${qs}`,
|
||||
method: req.method,
|
||||
headers,
|
||||
};
|
||||
|
||||
const proxyReq = http.request(options, (proxyRes) => {
|
||||
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
||||
proxyRes.pipe(res);
|
||||
});
|
||||
|
||||
proxyReq.on('error', (err) => {
|
||||
if (!res.headersSent) {
|
||||
res.status(502).json({ error: 'Plugin server error', details: err.message });
|
||||
} else {
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
||||
// Forward body (already parsed by express JSON middleware, so re-stringify).
|
||||
// Check content-length to detect whether a body was actually sent, since
|
||||
// req.body can be falsy for valid payloads like 0, false, null, or {}.
|
||||
const hasBody = req.headers['content-length'] && parseInt(req.headers['content-length'], 10) > 0;
|
||||
if (hasBody && req.body !== undefined) {
|
||||
const bodyStr = JSON.stringify(req.body);
|
||||
proxyReq.setHeader('content-length', Buffer.byteLength(bodyStr));
|
||||
proxyReq.write(bodyStr);
|
||||
}
|
||||
|
||||
proxyReq.end();
|
||||
});
|
||||
|
||||
// DELETE /:name — Uninstall plugin (stops server first)
|
||||
router.delete('/:name', async (req, res) => {
|
||||
try {
|
||||
const pluginName = req.params.name;
|
||||
|
||||
// Validate name format to prevent path traversal
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
|
||||
return res.status(400).json({ error: 'Invalid plugin name' });
|
||||
}
|
||||
|
||||
// Stop server and wait for the process to fully exit before deleting files
|
||||
if (isPluginRunning(pluginName)) {
|
||||
await stopPluginServer(pluginName);
|
||||
}
|
||||
|
||||
await uninstallPlugin(pluginName);
|
||||
res.json({ success: true, name: pluginName });
|
||||
} catch (err) {
|
||||
res.status(400).json({ error: 'Failed to uninstall plugin', details: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -311,11 +311,13 @@ router.post('/create-workspace', async (req, res) => {
|
||||
* Helper function to get GitHub token from database
|
||||
*/
|
||||
async function getGithubTokenById(tokenId, userId) {
|
||||
const { db } = await import('../database/db.js');
|
||||
const { getDatabase } = await import('../database/db.js');
|
||||
const db = await getDatabase();
|
||||
|
||||
const credential = db.prepare(
|
||||
'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1'
|
||||
).get(tokenId, userId, 'github_token');
|
||||
const credential = await db.get(
|
||||
'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1',
|
||||
[tokenId, userId, 'github_token']
|
||||
);
|
||||
|
||||
// Return in the expected format (github_token field for compatibility)
|
||||
if (credential) {
|
||||
|
||||
@@ -529,7 +529,7 @@ router.get('/next/:projectName', async (req, res) => {
|
||||
|
||||
// Fallback to loading tasks and finding next one locally
|
||||
// Use localhost to bypass proxy for internal server-to-server calls
|
||||
const tasksResponse = await fetch(`http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}/api/taskmaster/tasks/${encodeURIComponent(projectName)}`, {
|
||||
const tasksResponse = await fetch(`http://localhost:${process.env.PORT || 3001}/api/taskmaster/tasks/${encodeURIComponent(projectName)}`, {
|
||||
headers: {
|
||||
'Authorization': req.headers.authorization
|
||||
}
|
||||
@@ -1960,4 +1960,4 @@ Brief description of what this web application will do and why it's needed.
|
||||
];
|
||||
}
|
||||
|
||||
export default router;
|
||||
export default router;
|
||||
@@ -2,29 +2,12 @@ import express from 'express';
|
||||
import { userDb } from '../database/db.js';
|
||||
import { authenticateToken } from '../middleware/auth.js';
|
||||
import { getSystemGitConfig } from '../utils/gitConfig.js';
|
||||
import { spawn } from 'child_process';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
const router = express.Router();
|
||||
|
||||
function spawnAsync(command, args, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, { ...options, shell: false });
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
child.stdout.on('data', (data) => { stdout += data.toString(); });
|
||||
child.stderr.on('data', (data) => { stderr += data.toString(); });
|
||||
child.on('error', (error) => { reject(error); });
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) { resolve({ stdout, stderr }); return; }
|
||||
const error = new Error(`Command failed: ${command} ${args.join(' ')}`);
|
||||
error.code = code;
|
||||
error.stdout = stdout;
|
||||
error.stderr = stderr;
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
router.get('/git-config', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const userId = req.user.id;
|
||||
@@ -72,8 +55,8 @@ router.post('/git-config', authenticateToken, async (req, res) => {
|
||||
userDb.updateGitConfig(userId, gitName, gitEmail);
|
||||
|
||||
try {
|
||||
await spawnAsync('git', ['config', '--global', 'user.name', gitName]);
|
||||
await spawnAsync('git', ['config', '--global', 'user.email', gitEmail]);
|
||||
await execAsync(`git config --global user.name "${gitName.replace(/"/g, '\\"')}"`);
|
||||
await execAsync(`git config --global user.email "${gitEmail.replace(/"/g, '\\"')}"`);
|
||||
console.log(`Applied git config globally: ${gitName} <${gitEmail}>`);
|
||||
} catch (gitError) {
|
||||
console.error('Error applying git config:', gitError);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import webPush from 'web-push';
|
||||
import { notificationPreferencesDb, pushSubscriptionsDb, sessionNamesDb } from '../database/db.js';
|
||||
import { notificationPreferencesDb, pushSubscriptionsDb } from '../database/db.js';
|
||||
|
||||
const KIND_TO_PREF_KEY = {
|
||||
action_required: 'actionRequired',
|
||||
@@ -7,14 +7,6 @@ const KIND_TO_PREF_KEY = {
|
||||
error: 'error'
|
||||
};
|
||||
|
||||
const PROVIDER_LABELS = {
|
||||
claude: 'Claude',
|
||||
cursor: 'Cursor',
|
||||
codex: 'Codex',
|
||||
gemini: 'Gemini',
|
||||
system: 'System'
|
||||
};
|
||||
|
||||
const recentEventKeys = new Map();
|
||||
const DEDUPE_WINDOW_MS = 20000;
|
||||
|
||||
@@ -68,48 +60,6 @@ function createNotificationEvent({
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeErrorMessage(error) {
|
||||
if (typeof error === 'string') {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (error && typeof error.message === 'string') {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (error == null) {
|
||||
return 'Unknown error';
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeSessionName(sessionName) {
|
||||
if (typeof sessionName !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = sessionName.replace(/\s+/g, ' ').trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized.length > 80 ? `${normalized.slice(0, 77)}...` : normalized;
|
||||
}
|
||||
|
||||
function resolveSessionName(event) {
|
||||
const explicitSessionName = normalizeSessionName(event.meta?.sessionName);
|
||||
if (explicitSessionName) {
|
||||
return explicitSessionName;
|
||||
}
|
||||
|
||||
if (!event.sessionId || !event.provider) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeSessionName(sessionNamesDb.getName(event.sessionId, event.provider));
|
||||
}
|
||||
|
||||
function buildPushBody(event) {
|
||||
const CODE_MAP = {
|
||||
'permission.required': event.meta?.toolName
|
||||
@@ -120,19 +70,13 @@ function buildPushBody(event) {
|
||||
'agent.notification': event.meta?.message ? String(event.meta.message) : 'You have a new notification',
|
||||
'push.enabled': 'Push notifications are now enabled!'
|
||||
};
|
||||
const providerLabel = PROVIDER_LABELS[event.provider] || 'Assistant';
|
||||
const sessionName = resolveSessionName(event);
|
||||
const message = CODE_MAP[event.code] || 'You have a new notification';
|
||||
|
||||
return {
|
||||
title: sessionName || 'CloudCLI',
|
||||
body: `${providerLabel}: ${message}`,
|
||||
title: 'Claude Code UI',
|
||||
body: CODE_MAP[event.code] || 'You have a new notification',
|
||||
data: {
|
||||
sessionId: event.sessionId || null,
|
||||
code: event.code,
|
||||
provider: event.provider || null,
|
||||
sessionName,
|
||||
tag: `${event.provider || 'assistant'}:${event.sessionId || 'none'}:${event.code}`
|
||||
code: event.code
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -187,41 +131,7 @@ function notifyUserIfEnabled({ userId, event }) {
|
||||
});
|
||||
}
|
||||
|
||||
function notifyRunStopped({ userId, provider, sessionId = null, stopReason = 'completed', sessionName = null }) {
|
||||
notifyUserIfEnabled({
|
||||
userId,
|
||||
event: createNotificationEvent({
|
||||
provider,
|
||||
sessionId,
|
||||
kind: 'stop',
|
||||
code: 'run.stopped',
|
||||
meta: { stopReason, sessionName },
|
||||
severity: 'info',
|
||||
dedupeKey: `${provider}:run:stop:${sessionId || 'none'}:${stopReason}`
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
function notifyRunFailed({ userId, provider, sessionId = null, error, sessionName = null }) {
|
||||
const errorMessage = normalizeErrorMessage(error);
|
||||
|
||||
notifyUserIfEnabled({
|
||||
userId,
|
||||
event: createNotificationEvent({
|
||||
provider,
|
||||
sessionId,
|
||||
kind: 'error',
|
||||
code: 'run.failed',
|
||||
meta: { error: errorMessage, sessionName },
|
||||
severity: 'error',
|
||||
dedupeKey: `${provider}:run:error:${sessionId || 'none'}:${errorMessage}`
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
createNotificationEvent,
|
||||
notifyUserIfEnabled,
|
||||
notifyRunStopped,
|
||||
notifyRunFailed
|
||||
notifyUserIfEnabled
|
||||
};
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": ["ES2022"],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
// In the backend config, "@" maps to the /server directory itself.
|
||||
"@/*": ["*"]
|
||||
},
|
||||
// The backend is still mostly JavaScript today, so allowJs lets us add a real
|
||||
// TypeScript build without forcing a large rename before the tooling is usable.
|
||||
"allowJs": true,
|
||||
// Keep the migration incremental: existing JS keeps building, while any new TS files
|
||||
// still go through the normal TypeScript pipeline and strict checks.
|
||||
"checkJs": false,
|
||||
"strict": true,
|
||||
"noEmitOnError": true,
|
||||
// The backend build emits both /server and /shared into dist-server, so rootDir must
|
||||
// stay one level above this file even though the config itself now lives in /server.
|
||||
"rootDir": "..",
|
||||
"outDir": "../dist-server",
|
||||
"sourceMap": true,
|
||||
"resolveJsonModule": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["./**/*.js", "./**/*.ts", "../shared/**/*.js", "../shared/**/*.ts"],
|
||||
"exclude": ["../dist", "../dist-server", "../node_modules", "../src"]
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
// ANSI color codes for terminal output
|
||||
const colors = {
|
||||
reset: '\x1b[0m',
|
||||
bright: '\x1b[1m',
|
||||
cyan: '\x1b[36m',
|
||||
green: '\x1b[32m',
|
||||
yellow: '\x1b[33m',
|
||||
blue: '\x1b[34m',
|
||||
dim: '\x1b[2m',
|
||||
};
|
||||
|
||||
const c = {
|
||||
info: (text) => `${colors.cyan}${text}${colors.reset}`,
|
||||
ok: (text) => `${colors.green}${text}${colors.reset}`,
|
||||
warn: (text) => `${colors.yellow}${text}${colors.reset}`,
|
||||
tip: (text) => `${colors.blue}${text}${colors.reset}`,
|
||||
bright: (text) => `${colors.bright}${text}${colors.reset}`,
|
||||
dim: (text) => `${colors.dim}${text}${colors.reset}`,
|
||||
};
|
||||
|
||||
export { colors, c };
|
||||
@@ -1,9 +1,9 @@
|
||||
import matter from 'gray-matter';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { parse as parseShellCommand } from 'shell-quote';
|
||||
import { parseFrontmatter } from './frontmatter.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
@@ -32,7 +32,7 @@ const BASH_COMMAND_ALLOWLIST = [
|
||||
*/
|
||||
export function parseCommand(content) {
|
||||
try {
|
||||
const parsed = parseFrontmatter(content);
|
||||
const parsed = matter(content);
|
||||
return {
|
||||
data: parsed.data || {},
|
||||
content: parsed.content || '',
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import matter from 'gray-matter';
|
||||
|
||||
const disabledFrontmatterEngine = () => ({});
|
||||
|
||||
const frontmatterOptions = {
|
||||
language: 'yaml',
|
||||
// Disable JS/JSON frontmatter parsing to avoid executable project content.
|
||||
// Mirrors Gatsby's mitigation for gray-matter.
|
||||
engines: {
|
||||
js: disabledFrontmatterEngine,
|
||||
javascript: disabledFrontmatterEngine,
|
||||
json: disabledFrontmatterEngine
|
||||
}
|
||||
};
|
||||
|
||||
export function parseFrontmatter(content) {
|
||||
return matter(content, frontmatterOptions);
|
||||
}
|
||||
@@ -1,17 +1,7 @@
|
||||
import { spawn } from 'child_process';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
function spawnAsync(command, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, { shell: false });
|
||||
let stdout = '';
|
||||
child.stdout.on('data', (data) => { stdout += data.toString(); });
|
||||
child.on('error', (error) => { reject(error); });
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) { resolve({ stdout }); return; }
|
||||
reject(new Error(`Command failed with code ${code}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
/**
|
||||
* Read git configuration from system's global git config
|
||||
@@ -20,8 +10,8 @@ function spawnAsync(command, args) {
|
||||
export async function getSystemGitConfig() {
|
||||
try {
|
||||
const [nameResult, emailResult] = await Promise.all([
|
||||
spawnAsync('git', ['config', '--global', 'user.name']).catch(() => ({ stdout: '' })),
|
||||
spawnAsync('git', ['config', '--global', 'user.email']).catch(() => ({ stdout: '' }))
|
||||
execAsync('git config --global user.name').catch(() => ({ stdout: '' })),
|
||||
execAsync('git config --global user.email').catch(() => ({ stdout: '' }))
|
||||
]);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,457 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { spawn } from 'child_process';
|
||||
|
||||
const PLUGINS_DIR = path.join(os.homedir(), '.claude-code-ui', 'plugins');
|
||||
const PLUGINS_CONFIG_PATH = path.join(os.homedir(), '.claude-code-ui', 'plugins.json');
|
||||
|
||||
const REQUIRED_MANIFEST_FIELDS = ['name', 'displayName', 'entry'];
|
||||
|
||||
/** Strip embedded credentials from a repo URL before exposing it to the client. */
|
||||
function sanitizeRepoUrl(raw) {
|
||||
try {
|
||||
const u = new URL(raw);
|
||||
u.username = '';
|
||||
u.password = '';
|
||||
return u.toString().replace(/\/$/, '');
|
||||
} catch {
|
||||
// Not a parseable URL (e.g. SSH shorthand) — strip user:pass@ segment
|
||||
return raw.replace(/\/\/[^@/]+@/, '//');
|
||||
}
|
||||
}
|
||||
const ALLOWED_TYPES = ['react', 'module'];
|
||||
const ALLOWED_SLOTS = ['tab'];
|
||||
|
||||
export function getPluginsDir() {
|
||||
if (!fs.existsSync(PLUGINS_DIR)) {
|
||||
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
|
||||
}
|
||||
return PLUGINS_DIR;
|
||||
}
|
||||
|
||||
export function getPluginsConfig() {
|
||||
try {
|
||||
if (fs.existsSync(PLUGINS_CONFIG_PATH)) {
|
||||
return JSON.parse(fs.readFileSync(PLUGINS_CONFIG_PATH, 'utf-8'));
|
||||
}
|
||||
} catch {
|
||||
// Corrupted config, start fresh
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
export function savePluginsConfig(config) {
|
||||
const dir = path.dirname(PLUGINS_CONFIG_PATH);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
fs.writeFileSync(PLUGINS_CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
|
||||
}
|
||||
|
||||
export function validateManifest(manifest) {
|
||||
if (!manifest || typeof manifest !== 'object') {
|
||||
return { valid: false, error: 'Manifest must be a JSON object' };
|
||||
}
|
||||
|
||||
for (const field of REQUIRED_MANIFEST_FIELDS) {
|
||||
if (!manifest[field] || typeof manifest[field] !== 'string') {
|
||||
return { valid: false, error: `Missing or invalid required field: ${field}` };
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize name — only allow alphanumeric, hyphens, underscores
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(manifest.name)) {
|
||||
return { valid: false, error: 'Plugin name must only contain letters, numbers, hyphens, and underscores' };
|
||||
}
|
||||
|
||||
if (manifest.type && !ALLOWED_TYPES.includes(manifest.type)) {
|
||||
return { valid: false, error: `Invalid plugin type: ${manifest.type}. Must be one of: ${ALLOWED_TYPES.join(', ')}` };
|
||||
}
|
||||
|
||||
if (manifest.slot && !ALLOWED_SLOTS.includes(manifest.slot)) {
|
||||
return { valid: false, error: `Invalid plugin slot: ${manifest.slot}. Must be one of: ${ALLOWED_SLOTS.join(', ')}` };
|
||||
}
|
||||
|
||||
// Validate entry is a relative path without traversal
|
||||
if (manifest.entry.includes('..') || path.isAbsolute(manifest.entry)) {
|
||||
return { valid: false, error: 'Entry must be a relative path without ".."' };
|
||||
}
|
||||
|
||||
if (manifest.server !== undefined && manifest.server !== null) {
|
||||
if (typeof manifest.server !== 'string' || manifest.server.includes('..') || path.isAbsolute(manifest.server)) {
|
||||
return { valid: false, error: 'Server entry must be a relative path string without ".."' };
|
||||
}
|
||||
}
|
||||
|
||||
if (manifest.permissions !== undefined) {
|
||||
if (!Array.isArray(manifest.permissions) || !manifest.permissions.every(p => typeof p === 'string')) {
|
||||
return { valid: false, error: 'Permissions must be an array of strings' };
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
const BUILD_TIMEOUT_MS = 60_000;
|
||||
|
||||
/** Run `npm run build` if the plugin's package.json declares a build script. */
|
||||
function runBuildIfNeeded(dir, packageJsonPath, onSuccess, onError) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
if (!pkg.scripts?.build) {
|
||||
return onSuccess();
|
||||
}
|
||||
} catch {
|
||||
return onSuccess(); // Unreadable package.json — skip build
|
||||
}
|
||||
|
||||
const buildProcess = spawn('npm', ['run', 'build'], {
|
||||
cwd: dir,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let stderr = '';
|
||||
let settled = false;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
buildProcess.removeAllListeners();
|
||||
buildProcess.kill();
|
||||
onError(new Error('npm run build timed out'));
|
||||
}, BUILD_TIMEOUT_MS);
|
||||
|
||||
buildProcess.stderr.on('data', (data) => { stderr += data.toString(); });
|
||||
|
||||
buildProcess.on('close', (code) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (code !== 0) {
|
||||
return onError(new Error(`npm run build failed (exit code ${code}): ${stderr.trim()}`));
|
||||
}
|
||||
onSuccess();
|
||||
});
|
||||
|
||||
buildProcess.on('error', (err) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
onError(new Error(`Failed to spawn build: ${err.message}`));
|
||||
});
|
||||
}
|
||||
|
||||
export function scanPlugins() {
|
||||
const pluginsDir = getPluginsDir();
|
||||
const config = getPluginsConfig();
|
||||
const plugins = [];
|
||||
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(pluginsDir, { withFileTypes: true });
|
||||
} catch {
|
||||
return plugins;
|
||||
}
|
||||
|
||||
const seenNames = new Set();
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
// Skip transient temp directories from in-progress installs
|
||||
if (entry.name.startsWith('.tmp-')) continue;
|
||||
|
||||
const manifestPath = path.join(pluginsDir, entry.name, 'manifest.json');
|
||||
if (!fs.existsSync(manifestPath)) continue;
|
||||
|
||||
try {
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
|
||||
const validation = validateManifest(manifest);
|
||||
if (!validation.valid) {
|
||||
console.warn(`[Plugins] Skipping ${entry.name}: ${validation.error}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip duplicate manifest names
|
||||
if (seenNames.has(manifest.name)) {
|
||||
console.warn(`[Plugins] Skipping ${entry.name}: duplicate plugin name "${manifest.name}"`);
|
||||
continue;
|
||||
}
|
||||
seenNames.add(manifest.name);
|
||||
|
||||
// Try to read git remote URL
|
||||
let repoUrl = null;
|
||||
try {
|
||||
const gitConfigPath = path.join(pluginsDir, entry.name, '.git', 'config');
|
||||
if (fs.existsSync(gitConfigPath)) {
|
||||
const gitConfig = fs.readFileSync(gitConfigPath, 'utf-8');
|
||||
const match = gitConfig.match(/url\s*=\s*(.+)/);
|
||||
if (match) {
|
||||
repoUrl = match[1].trim().replace(/\.git$/, '');
|
||||
// Convert SSH URLs to HTTPS
|
||||
if (repoUrl.startsWith('git@')) {
|
||||
repoUrl = repoUrl.replace(/^git@([^:]+):/, 'https://$1/');
|
||||
}
|
||||
// Strip embedded credentials (e.g. https://user:pass@host/...)
|
||||
repoUrl = sanitizeRepoUrl(repoUrl);
|
||||
}
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
plugins.push({
|
||||
name: manifest.name,
|
||||
displayName: manifest.displayName,
|
||||
version: manifest.version || '0.0.0',
|
||||
description: manifest.description || '',
|
||||
author: manifest.author || '',
|
||||
icon: manifest.icon || 'Puzzle',
|
||||
type: manifest.type || 'module',
|
||||
slot: manifest.slot || 'tab',
|
||||
entry: manifest.entry,
|
||||
server: manifest.server || null,
|
||||
permissions: manifest.permissions || [],
|
||||
enabled: config[manifest.name]?.enabled !== false, // enabled by default
|
||||
dirName: entry.name,
|
||||
repoUrl,
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(`[Plugins] Failed to read manifest for ${entry.name}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return plugins;
|
||||
}
|
||||
|
||||
export function getPluginDir(name) {
|
||||
const plugins = scanPlugins();
|
||||
const plugin = plugins.find(p => p.name === name);
|
||||
if (!plugin) return null;
|
||||
return path.join(getPluginsDir(), plugin.dirName);
|
||||
}
|
||||
|
||||
export function resolvePluginAssetPath(name, assetPath) {
|
||||
const pluginDir = getPluginDir(name);
|
||||
if (!pluginDir) return null;
|
||||
|
||||
const resolved = path.resolve(pluginDir, assetPath);
|
||||
|
||||
// Prevent path traversal — canonicalize via realpath to defeat symlink bypasses
|
||||
if (!fs.existsSync(resolved)) return null;
|
||||
|
||||
const realResolved = fs.realpathSync(resolved);
|
||||
const realPluginDir = fs.realpathSync(pluginDir);
|
||||
if (!realResolved.startsWith(realPluginDir + path.sep) && realResolved !== realPluginDir) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return realResolved;
|
||||
}
|
||||
|
||||
export function installPluginFromGit(url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof url !== 'string' || !url.trim()) {
|
||||
return reject(new Error('Invalid URL: must be a non-empty string'));
|
||||
}
|
||||
if (url.startsWith('-')) {
|
||||
return reject(new Error('Invalid URL: must not start with "-"'));
|
||||
}
|
||||
|
||||
// Extract repo name from URL for directory name
|
||||
const urlClean = url.replace(/\.git$/, '').replace(/\/$/, '');
|
||||
const repoName = urlClean.split('/').pop();
|
||||
|
||||
if (!repoName || !/^[a-zA-Z0-9_.-]+$/.test(repoName)) {
|
||||
return reject(new Error('Could not determine a valid directory name from the URL'));
|
||||
}
|
||||
|
||||
const pluginsDir = getPluginsDir();
|
||||
const targetDir = path.resolve(pluginsDir, repoName);
|
||||
|
||||
// Ensure the resolved target directory stays within the plugins directory
|
||||
if (!targetDir.startsWith(pluginsDir + path.sep)) {
|
||||
return reject(new Error('Invalid plugin directory path'));
|
||||
}
|
||||
|
||||
if (fs.existsSync(targetDir)) {
|
||||
return reject(new Error(`Plugin directory "${repoName}" already exists`));
|
||||
}
|
||||
|
||||
// Clone into a temp directory so scanPlugins() never sees a partially-installed plugin
|
||||
const tempDir = fs.mkdtempSync(path.join(pluginsDir, `.tmp-${repoName}-`));
|
||||
|
||||
const cleanupTemp = () => {
|
||||
try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
|
||||
};
|
||||
|
||||
const finalize = (manifest) => {
|
||||
try {
|
||||
fs.renameSync(tempDir, targetDir);
|
||||
} catch (err) {
|
||||
cleanupTemp();
|
||||
return reject(new Error(`Failed to move plugin into place: ${err.message}`));
|
||||
}
|
||||
resolve(manifest);
|
||||
};
|
||||
|
||||
const gitProcess = spawn('git', ['clone', '--depth', '1', '--', url, tempDir], {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let stderr = '';
|
||||
gitProcess.stderr.on('data', (data) => { stderr += data.toString(); });
|
||||
|
||||
gitProcess.on('close', (code) => {
|
||||
if (code !== 0) {
|
||||
cleanupTemp();
|
||||
return reject(new Error(`git clone failed (exit code ${code}): ${stderr.trim()}`));
|
||||
}
|
||||
|
||||
// Validate manifest exists
|
||||
const manifestPath = path.join(tempDir, 'manifest.json');
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
cleanupTemp();
|
||||
return reject(new Error('Cloned repository does not contain a manifest.json'));
|
||||
}
|
||||
|
||||
let manifest;
|
||||
try {
|
||||
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
|
||||
} catch {
|
||||
cleanupTemp();
|
||||
return reject(new Error('manifest.json is not valid JSON'));
|
||||
}
|
||||
|
||||
const validation = validateManifest(manifest);
|
||||
if (!validation.valid) {
|
||||
cleanupTemp();
|
||||
return reject(new Error(`Invalid manifest: ${validation.error}`));
|
||||
}
|
||||
|
||||
// Reject if another installed plugin already uses this name
|
||||
const existing = scanPlugins().find(p => p.name === manifest.name);
|
||||
if (existing) {
|
||||
cleanupTemp();
|
||||
return reject(new Error(`A plugin named "${manifest.name}" is already installed (in "${existing.dirName}")`));
|
||||
}
|
||||
|
||||
// Run npm install if package.json exists.
|
||||
// --ignore-scripts prevents postinstall hooks from executing arbitrary code.
|
||||
const packageJsonPath = path.join(tempDir, 'package.json');
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
const npmProcess = spawn('npm', ['install', '--ignore-scripts'], {
|
||||
cwd: tempDir,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
npmProcess.on('close', (npmCode) => {
|
||||
if (npmCode !== 0) {
|
||||
cleanupTemp();
|
||||
return reject(new Error(`npm install for ${repoName} failed (exit code ${npmCode})`));
|
||||
}
|
||||
runBuildIfNeeded(tempDir, packageJsonPath, () => finalize(manifest), (err) => { cleanupTemp(); reject(err); });
|
||||
});
|
||||
|
||||
npmProcess.on('error', (err) => {
|
||||
cleanupTemp();
|
||||
reject(err);
|
||||
});
|
||||
} else {
|
||||
finalize(manifest);
|
||||
}
|
||||
});
|
||||
|
||||
gitProcess.on('error', (err) => {
|
||||
cleanupTemp();
|
||||
reject(new Error(`Failed to spawn git: ${err.message}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function updatePluginFromGit(name) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const pluginDir = getPluginDir(name);
|
||||
if (!pluginDir) {
|
||||
return reject(new Error(`Plugin "${name}" not found`));
|
||||
}
|
||||
|
||||
// Only fast-forward to avoid silent divergence
|
||||
const gitProcess = spawn('git', ['pull', '--ff-only', '--'], {
|
||||
cwd: pluginDir,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let stderr = '';
|
||||
gitProcess.stderr.on('data', (data) => { stderr += data.toString(); });
|
||||
|
||||
gitProcess.on('close', (code) => {
|
||||
if (code !== 0) {
|
||||
return reject(new Error(`git pull failed (exit code ${code}): ${stderr.trim()}`));
|
||||
}
|
||||
|
||||
// Re-validate manifest after update
|
||||
const manifestPath = path.join(pluginDir, 'manifest.json');
|
||||
let manifest;
|
||||
try {
|
||||
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
|
||||
} catch {
|
||||
return reject(new Error('manifest.json is not valid JSON after update'));
|
||||
}
|
||||
|
||||
const validation = validateManifest(manifest);
|
||||
if (!validation.valid) {
|
||||
return reject(new Error(`Invalid manifest after update: ${validation.error}`));
|
||||
}
|
||||
|
||||
// Re-run npm install if package.json exists
|
||||
const packageJsonPath = path.join(pluginDir, 'package.json');
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
const npmProcess = spawn('npm', ['install', '--ignore-scripts'], {
|
||||
cwd: pluginDir,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
npmProcess.on('close', (npmCode) => {
|
||||
if (npmCode !== 0) {
|
||||
return reject(new Error(`npm install for ${name} failed (exit code ${npmCode})`));
|
||||
}
|
||||
runBuildIfNeeded(pluginDir, packageJsonPath, () => resolve(manifest), (err) => reject(err));
|
||||
});
|
||||
npmProcess.on('error', (err) => reject(err));
|
||||
} else {
|
||||
resolve(manifest);
|
||||
}
|
||||
});
|
||||
|
||||
gitProcess.on('error', (err) => {
|
||||
reject(new Error(`Failed to spawn git: ${err.message}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function uninstallPlugin(name) {
|
||||
const pluginDir = getPluginDir(name);
|
||||
if (!pluginDir) {
|
||||
throw new Error(`Plugin "${name}" not found`);
|
||||
}
|
||||
|
||||
// On Windows, file handles may be released slightly after process exit.
|
||||
// Retry a few times with a short delay before giving up.
|
||||
const MAX_RETRIES = 5;
|
||||
const RETRY_DELAY_MS = 500;
|
||||
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
fs.rmSync(pluginDir, { recursive: true, force: true });
|
||||
break;
|
||||
} catch (err) {
|
||||
if (err.code === 'EBUSY' && attempt < MAX_RETRIES) {
|
||||
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove from config
|
||||
const config = getPluginsConfig();
|
||||
delete config[name];
|
||||
savePluginsConfig(config);
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import { scanPlugins, getPluginsConfig, getPluginDir } from './plugin-loader.js';
|
||||
|
||||
// Map<pluginName, { process, port }>
|
||||
const runningPlugins = new Map();
|
||||
// Map<pluginName, Promise<port>> — in-flight start operations
|
||||
const startingPlugins = new Map();
|
||||
|
||||
/**
|
||||
* Start a plugin's server subprocess.
|
||||
* The plugin's server entry must print a JSON line with { ready: true, port: <number> }
|
||||
* to stdout within 10 seconds.
|
||||
*/
|
||||
export function startPluginServer(name, pluginDir, serverEntry) {
|
||||
if (runningPlugins.has(name)) {
|
||||
return Promise.resolve(runningPlugins.get(name).port);
|
||||
}
|
||||
|
||||
// Coalesce concurrent starts for the same plugin
|
||||
if (startingPlugins.has(name)) {
|
||||
return startingPlugins.get(name);
|
||||
}
|
||||
|
||||
const startPromise = new Promise((resolve, reject) => {
|
||||
|
||||
const serverPath = path.join(pluginDir, serverEntry);
|
||||
|
||||
// Restricted env — only essentials, no host secrets
|
||||
const pluginProcess = spawn('node', [serverPath], {
|
||||
cwd: pluginDir,
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
HOME: process.env.HOME,
|
||||
NODE_ENV: process.env.NODE_ENV || 'production',
|
||||
PLUGIN_NAME: name,
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let resolved = false;
|
||||
let stdout = '';
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
pluginProcess.kill();
|
||||
reject(new Error('Plugin server did not report ready within 10 seconds'));
|
||||
}
|
||||
}, 10000);
|
||||
|
||||
pluginProcess.stdout.on('data', (data) => {
|
||||
if (resolved) return;
|
||||
stdout += data.toString();
|
||||
|
||||
// Look for the JSON ready line
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const msg = JSON.parse(line.trim());
|
||||
if (msg.ready && typeof msg.port === 'number') {
|
||||
clearTimeout(timeout);
|
||||
resolved = true;
|
||||
runningPlugins.set(name, { process: pluginProcess, port: msg.port });
|
||||
|
||||
pluginProcess.on('exit', () => {
|
||||
runningPlugins.delete(name);
|
||||
});
|
||||
|
||||
console.log(`[Plugins] Server started for "${name}" on port ${msg.port}`);
|
||||
resolve(msg.port);
|
||||
}
|
||||
} catch {
|
||||
// Not JSON yet, keep buffering
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
pluginProcess.stderr.on('data', (data) => {
|
||||
console.warn(`[Plugin:${name}] ${data.toString().trim()}`);
|
||||
});
|
||||
|
||||
pluginProcess.on('error', (err) => {
|
||||
clearTimeout(timeout);
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
reject(new Error(`Failed to start plugin server: ${err.message}`));
|
||||
}
|
||||
});
|
||||
|
||||
pluginProcess.on('exit', (code) => {
|
||||
clearTimeout(timeout);
|
||||
runningPlugins.delete(name);
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
reject(new Error(`Plugin server exited with code ${code} before reporting ready`));
|
||||
}
|
||||
});
|
||||
}).finally(() => {
|
||||
startingPlugins.delete(name);
|
||||
});
|
||||
|
||||
startingPlugins.set(name, startPromise);
|
||||
return startPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop a plugin's server subprocess.
|
||||
* Returns a Promise that resolves when the process has fully exited.
|
||||
*/
|
||||
export function stopPluginServer(name) {
|
||||
const entry = runningPlugins.get(name);
|
||||
if (!entry) return Promise.resolve();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const cleanup = () => {
|
||||
clearTimeout(forceKillTimer);
|
||||
runningPlugins.delete(name);
|
||||
resolve();
|
||||
};
|
||||
|
||||
entry.process.once('exit', cleanup);
|
||||
|
||||
entry.process.kill('SIGTERM');
|
||||
|
||||
// Force kill after 5 seconds if still running
|
||||
const forceKillTimer = setTimeout(() => {
|
||||
if (runningPlugins.has(name)) {
|
||||
entry.process.kill('SIGKILL');
|
||||
cleanup();
|
||||
}
|
||||
}, 5000);
|
||||
|
||||
console.log(`[Plugins] Server stopped for "${name}"`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the port a running plugin server is listening on.
|
||||
*/
|
||||
export function getPluginPort(name) {
|
||||
return runningPlugins.get(name)?.port ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a plugin's server is running.
|
||||
*/
|
||||
export function isPluginRunning(name) {
|
||||
return runningPlugins.has(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop all running plugin servers (called on host shutdown).
|
||||
*/
|
||||
export function stopAllPlugins() {
|
||||
const stops = [];
|
||||
for (const [name] of runningPlugins) {
|
||||
stops.push(stopPluginServer(name));
|
||||
}
|
||||
return Promise.all(stops);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start servers for all enabled plugins that have a server entry.
|
||||
* Called once on host server boot.
|
||||
*/
|
||||
export async function startEnabledPluginServers() {
|
||||
const plugins = scanPlugins();
|
||||
const config = getPluginsConfig();
|
||||
|
||||
for (const plugin of plugins) {
|
||||
if (!plugin.server) continue;
|
||||
if (config[plugin.name]?.enabled === false) continue;
|
||||
|
||||
const pluginDir = getPluginDir(plugin.name);
|
||||
if (!pluginDir) continue;
|
||||
|
||||
try {
|
||||
await startPluginServer(plugin.name, pluginDir, plugin.server);
|
||||
} catch (err) {
|
||||
console.error(`[Plugins] Failed to start server for "${plugin.name}":`, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export function getModuleDir(importMetaUrl) {
|
||||
return path.dirname(fileURLToPath(importMetaUrl));
|
||||
}
|
||||
|
||||
export function findServerRoot(startDir) {
|
||||
// Source files live under /server, while compiled files live under /dist-server/server.
|
||||
// Walking up to the nearest "server" folder gives every backend module one stable anchor
|
||||
// that works in both layouts instead of relying on fragile "../.." assumptions.
|
||||
let currentDir = startDir;
|
||||
|
||||
while (path.basename(currentDir) !== 'server') {
|
||||
const parentDir = path.dirname(currentDir);
|
||||
|
||||
if (parentDir === currentDir) {
|
||||
throw new Error(`Could not resolve the backend server root from "${startDir}".`);
|
||||
}
|
||||
|
||||
currentDir = parentDir;
|
||||
}
|
||||
|
||||
return currentDir;
|
||||
}
|
||||
|
||||
export function findAppRoot(startDir) {
|
||||
const serverRoot = findServerRoot(startDir);
|
||||
const parentOfServerRoot = path.dirname(serverRoot);
|
||||
|
||||
// Source files live at <app>/server, while compiled files live at <app>/dist-server/server.
|
||||
// When the nearest server folder sits inside dist-server we need to hop one extra level up
|
||||
// so repo-level files still resolve from the real app root instead of the build directory.
|
||||
return path.basename(parentOfServerRoot) === 'dist-server'
|
||||
? path.dirname(parentOfServerRoot)
|
||||
: parentOfServerRoot;
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
const ANSI_ESCAPE_SEQUENCE_REGEX = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
|
||||
const TRAILING_URL_PUNCTUATION_REGEX = /[)\]}>.,;:!?]+$/;
|
||||
|
||||
function stripAnsiSequences(value = '') {
|
||||
return value.replace(ANSI_ESCAPE_SEQUENCE_REGEX, '');
|
||||
}
|
||||
|
||||
function normalizeDetectedUrl(url) {
|
||||
if (!url || typeof url !== 'string') return null;
|
||||
|
||||
const cleaned = url.trim().replace(TRAILING_URL_PUNCTUATION_REGEX, '');
|
||||
if (!cleaned) return null;
|
||||
|
||||
try {
|
||||
const parsed = new URL(cleaned);
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
return null;
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function extractUrlsFromText(value = '') {
|
||||
const directMatches = value.match(/https?:\/\/[^\s<>"'`\\\x1b\x07]+/gi) || [];
|
||||
|
||||
// Handle wrapped terminal URLs split across lines by terminal width.
|
||||
const wrappedMatches = [];
|
||||
const continuationRegex = /^[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+$/;
|
||||
const lines = value.split(/\r?\n/);
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
const startMatch = line.match(/https?:\/\/[^\s<>"'`\\\x1b\x07]+/i);
|
||||
if (!startMatch) continue;
|
||||
|
||||
let combined = startMatch[0];
|
||||
let j = i + 1;
|
||||
while (j < lines.length) {
|
||||
const continuation = lines[j].trim();
|
||||
if (!continuation) break;
|
||||
if (!continuationRegex.test(continuation)) break;
|
||||
combined += continuation;
|
||||
j++;
|
||||
}
|
||||
|
||||
wrappedMatches.push(combined.replace(/\r?\n\s*/g, ''));
|
||||
}
|
||||
|
||||
return Array.from(new Set([...directMatches, ...wrappedMatches]));
|
||||
}
|
||||
|
||||
function shouldAutoOpenUrlFromOutput(value = '') {
|
||||
const normalized = value.toLowerCase();
|
||||
return (
|
||||
normalized.includes('browser didn\'t open') ||
|
||||
normalized.includes('open this url') ||
|
||||
normalized.includes('continue in your browser') ||
|
||||
normalized.includes('press enter to open') ||
|
||||
normalized.includes('open_url:')
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
ANSI_ESCAPE_SEQUENCE_REGEX,
|
||||
TRAILING_URL_PUNCTUATION_REGEX,
|
||||
stripAnsiSequences,
|
||||
normalizeDetectedUrl,
|
||||
extractUrlsFromText,
|
||||
shouldAutoOpenUrlFromOutput
|
||||
};
|
||||
@@ -13,15 +13,14 @@
|
||||
export const CLAUDE_MODELS = {
|
||||
// Models in SDK format (what the actual SDK accepts)
|
||||
OPTIONS: [
|
||||
{ value: "sonnet", label: "Sonnet" },
|
||||
{ value: "opus", label: "Opus" },
|
||||
{ value: "haiku", label: "Haiku" },
|
||||
{ value: "opusplan", label: "Opus Plan" },
|
||||
{ value: "sonnet[1m]", label: "Sonnet [1M]" },
|
||||
{ value: "opus[1m]", label: "Opus [1M]" },
|
||||
{ value: 'sonnet', label: 'Sonnet' },
|
||||
{ value: 'opus', label: 'Opus' },
|
||||
{ value: 'haiku', label: 'Haiku' },
|
||||
{ value: 'opusplan', label: 'Opus Plan' },
|
||||
{ value: 'sonnet[1m]', label: 'Sonnet [1M]' }
|
||||
],
|
||||
|
||||
DEFAULT: "opus",
|
||||
DEFAULT: 'sonnet'
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -29,28 +28,26 @@ export const CLAUDE_MODELS = {
|
||||
*/
|
||||
export const CURSOR_MODELS = {
|
||||
OPTIONS: [
|
||||
{ value: "opus-4.6-thinking", label: "Claude 4.6 Opus (Thinking)" },
|
||||
{ value: "gpt-5.3-codex", label: "GPT-5.3" },
|
||||
{ value: "gpt-5.2-high", label: "GPT-5.2 High" },
|
||||
{ value: "gemini-3-pro", label: "Gemini 3 Pro" },
|
||||
{ value: "opus-4.5-thinking", label: "Claude 4.5 Opus (Thinking)" },
|
||||
{ value: "gpt-5.2", label: "GPT-5.2" },
|
||||
{ value: "gpt-5.1", label: "GPT-5.1" },
|
||||
{ value: "gpt-5.1-high", label: "GPT-5.1 High" },
|
||||
{ value: "composer-1", label: "Composer 1" },
|
||||
{ value: "auto", label: "Auto" },
|
||||
{ value: "sonnet-4.5", label: "Claude 4.5 Sonnet" },
|
||||
{ value: "sonnet-4.5-thinking", label: "Claude 4.5 Sonnet (Thinking)" },
|
||||
{ value: "opus-4.5", label: "Claude 4.5 Opus" },
|
||||
{ value: "gpt-5.1-codex", label: "GPT-5.1 Codex" },
|
||||
{ value: "gpt-5.1-codex-high", label: "GPT-5.1 Codex High" },
|
||||
{ value: "gpt-5.1-codex-max", label: "GPT-5.1 Codex Max" },
|
||||
{ value: "gpt-5.1-codex-max-high", label: "GPT-5.1 Codex Max High" },
|
||||
{ value: "opus-4.1", label: "Claude 4.1 Opus" },
|
||||
{ value: "grok", label: "Grok" },
|
||||
{ value: 'gpt-5.2-high', label: 'GPT-5.2 High' },
|
||||
{ value: 'gemini-3-pro', label: 'Gemini 3 Pro' },
|
||||
{ value: 'opus-4.5-thinking', label: 'Claude 4.5 Opus (Thinking)' },
|
||||
{ value: 'gpt-5.2', label: 'GPT-5.2' },
|
||||
{ value: 'gpt-5.1', label: 'GPT-5.1' },
|
||||
{ value: 'gpt-5.1-high', label: 'GPT-5.1 High' },
|
||||
{ value: 'composer-1', label: 'Composer 1' },
|
||||
{ value: 'auto', label: 'Auto' },
|
||||
{ value: 'sonnet-4.5', label: 'Claude 4.5 Sonnet' },
|
||||
{ value: 'sonnet-4.5-thinking', label: 'Claude 4.5 Sonnet (Thinking)' },
|
||||
{ value: 'opus-4.5', label: 'Claude 4.5 Opus' },
|
||||
{ value: 'gpt-5.1-codex', label: 'GPT-5.1 Codex' },
|
||||
{ value: 'gpt-5.1-codex-high', label: 'GPT-5.1 Codex High' },
|
||||
{ value: 'gpt-5.1-codex-max', label: 'GPT-5.1 Codex Max' },
|
||||
{ value: 'gpt-5.1-codex-max-high', label: 'GPT-5.1 Codex Max High' },
|
||||
{ value: 'opus-4.1', label: 'Claude 4.1 Opus' },
|
||||
{ value: 'grok', label: 'Grok' }
|
||||
],
|
||||
|
||||
DEFAULT: "gpt-5-3-codex",
|
||||
DEFAULT: 'gpt-5'
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -58,17 +55,15 @@ export const CURSOR_MODELS = {
|
||||
*/
|
||||
export const CODEX_MODELS = {
|
||||
OPTIONS: [
|
||||
{ value: "gpt-5.4", label: "GPT-5.4" },
|
||||
{ value: "gpt-5.4-mini", label: "GPT-5.4 mini" },
|
||||
{ value: "gpt-5.3-codex", label: "GPT-5.3 Codex" },
|
||||
{ value: "gpt-5.2-codex", label: "GPT-5.2 Codex" },
|
||||
{ value: "gpt-5.2", label: "GPT-5.2" },
|
||||
{ value: "gpt-5.1-codex-max", label: "GPT-5.1 Codex Max" },
|
||||
{ value: "o3", label: "O3" },
|
||||
{ value: "o4-mini", label: "O4-mini" },
|
||||
{ value: 'gpt-5.3-codex', label: 'GPT-5.3 Codex' },
|
||||
{ value: 'gpt-5.2-codex', label: 'GPT-5.2 Codex' },
|
||||
{ value: 'gpt-5.2', label: 'GPT-5.2' },
|
||||
{ value: 'gpt-5.1-codex-max', label: 'GPT-5.1 Codex Max' },
|
||||
{ value: 'o3', label: 'O3' },
|
||||
{ value: 'o4-mini', label: 'O4-mini' }
|
||||
],
|
||||
|
||||
DEFAULT: "gpt-5.4",
|
||||
DEFAULT: 'gpt-5.3-codex'
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -76,19 +71,16 @@ export const CODEX_MODELS = {
|
||||
*/
|
||||
export const GEMINI_MODELS = {
|
||||
OPTIONS: [
|
||||
{ value: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro Preview" },
|
||||
{ value: "gemini-3-pro-preview", label: "Gemini 3 Pro Preview" },
|
||||
{ value: "gemini-3-flash-preview", label: "Gemini 3 Flash Preview" },
|
||||
{ value: "gemini-2.5-flash", label: "Gemini 2.5 Flash" },
|
||||
{ value: "gemini-2.5-pro", label: "Gemini 2.5 Pro" },
|
||||
{ value: "gemini-2.0-flash-lite", label: "Gemini 2.0 Flash Lite" },
|
||||
{ value: "gemini-2.0-flash", label: "Gemini 2.0 Flash" },
|
||||
{ value: "gemini-2.0-pro-exp", label: "Gemini 2.0 Pro Experimental" },
|
||||
{
|
||||
value: "gemini-2.0-flash-thinking-exp",
|
||||
label: "Gemini 2.0 Flash Thinking",
|
||||
},
|
||||
{ value: 'gemini-3.1-pro-preview', label: 'Gemini 3.1 Pro Preview' },
|
||||
{ value: 'gemini-3-pro-preview', label: 'Gemini 3 Pro Preview' },
|
||||
{ value: 'gemini-3-flash-preview', label: 'Gemini 3 Flash Preview' },
|
||||
{ value: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
|
||||
{ value: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
|
||||
{ value: 'gemini-2.0-flash-lite', label: 'Gemini 2.0 Flash Lite' },
|
||||
{ value: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash' },
|
||||
{ value: 'gemini-2.0-pro-exp', label: 'Gemini 2.0 Pro Experimental' },
|
||||
{ value: 'gemini-2.0-flash-thinking-exp', label: 'Gemini 2.0 Flash Thinking' }
|
||||
],
|
||||
|
||||
DEFAULT: "gemini-3.1-pro-preview",
|
||||
DEFAULT: 'gemini-2.5-flash'
|
||||
};
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
export function isWildcardHost(host) {
|
||||
return host === '0.0.0.0' || host === '::';
|
||||
}
|
||||
|
||||
export function isLoopbackHost(host) {
|
||||
return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
|
||||
}
|
||||
|
||||
export function normalizeLoopbackHost(host) {
|
||||
if (!host) {
|
||||
return host;
|
||||
}
|
||||
return isLoopbackHost(host) ? 'localhost' : host;
|
||||
}
|
||||
|
||||
// Use localhost for connectable loopback and wildcard addresses in browser-facing URLs.
|
||||
export function getConnectableHost(host) {
|
||||
if (!host) {
|
||||
return 'localhost';
|
||||
}
|
||||
return isWildcardHost(host) || isLoopbackHost(host) ? 'localhost' : host;
|
||||
}
|
||||
14
src/App.tsx
14
src/App.tsx
@@ -1,11 +1,11 @@
|
||||
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { ThemeProvider } from './contexts/ThemeContext';
|
||||
import { AuthProvider, ProtectedRoute } from './components/auth';
|
||||
import { AuthProvider } from './contexts/AuthContext';
|
||||
import { TaskMasterProvider } from './contexts/TaskMasterContext';
|
||||
import { TasksSettingsProvider } from './contexts/TasksSettingsContext';
|
||||
import { WebSocketProvider } from './contexts/WebSocketContext';
|
||||
import { PluginsProvider } from './contexts/PluginsContext';
|
||||
import ProtectedRoute from './components/ProtectedRoute';
|
||||
import AppContent from './components/app/AppContent';
|
||||
import i18n from './i18n/config.js';
|
||||
|
||||
@@ -15,9 +15,8 @@ export default function App() {
|
||||
<ThemeProvider>
|
||||
<AuthProvider>
|
||||
<WebSocketProvider>
|
||||
<PluginsProvider>
|
||||
<TasksSettingsProvider>
|
||||
<TaskMasterProvider>
|
||||
<TasksSettingsProvider>
|
||||
<TaskMasterProvider>
|
||||
<ProtectedRoute>
|
||||
<Router basename={window.__ROUTER_BASENAME__ || ''}>
|
||||
<Routes>
|
||||
@@ -26,9 +25,8 @@ export default function App() {
|
||||
</Routes>
|
||||
</Router>
|
||||
</ProtectedRoute>
|
||||
</TaskMasterProvider>
|
||||
</TasksSettingsProvider>
|
||||
</PluginsProvider>
|
||||
</TaskMasterProvider>
|
||||
</TasksSettingsProvider>
|
||||
</WebSocketProvider>
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
|
||||
88
src/components/CreateTaskModal.jsx
Normal file
88
src/components/CreateTaskModal.jsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import React from 'react';
|
||||
import { X, Sparkles } from 'lucide-react';
|
||||
|
||||
const CreateTaskModal = ({ currentProject, onClose, onTaskCreated }) => {
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md border border-gray-200 dark:border-gray-700">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/50 rounded-lg flex items-center justify-center">
|
||||
<Sparkles className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">Create AI-Generated Task</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-6 space-y-6">
|
||||
{/* AI-First Approach */}
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/50 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5">
|
||||
<Sparkles className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h4 className="font-semibold text-blue-900 dark:text-blue-100 mb-2">
|
||||
💡 Pro Tip: Ask Claude Code Directly!
|
||||
</h4>
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200 mb-3">
|
||||
You can simply ask Claude Code in the chat to create tasks for you.
|
||||
The AI assistant will automatically generate detailed tasks with research-backed insights.
|
||||
</p>
|
||||
|
||||
<div className="bg-white dark:bg-gray-800 rounded border border-blue-200 dark:border-blue-700 p-3 mb-3">
|
||||
<p className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Example:</p>
|
||||
<p className="text-sm text-gray-900 dark:text-white font-mono">
|
||||
"Please add a new task to implement user profile image uploads using Cloudinary, research the best approach."
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-blue-700 dark:text-blue-300">
|
||||
<strong>This runs:</strong> <code className="bg-blue-100 dark:bg-blue-900/50 px-1 rounded text-xs">
|
||||
task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research
|
||||
</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Learn More Link */}
|
||||
<div className="text-center pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
|
||||
For more examples and advanced usage patterns:
|
||||
</p>
|
||||
<a
|
||||
href="https://github.com/eyaltoledano/claude-task-master/blob/main/docs/examples.md"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-block text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline font-medium"
|
||||
>
|
||||
View TaskMaster Documentation →
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="pt-4">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="w-full px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
|
||||
>
|
||||
Got it, I'll ask Claude Code directly
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateTaskModal;
|
||||
48
src/components/DarkModeToggle.tsx
Normal file
48
src/components/DarkModeToggle.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Moon, Sun } from 'lucide-react';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
|
||||
type DarkModeToggleProps = {
|
||||
checked?: boolean;
|
||||
onToggle?: (nextValue: boolean) => void;
|
||||
ariaLabel?: string;
|
||||
};
|
||||
|
||||
function DarkModeToggle({ checked, onToggle, ariaLabel = 'Toggle dark mode' }: DarkModeToggleProps) {
|
||||
const { isDarkMode, toggleDarkMode } = useTheme();
|
||||
const isControlled = typeof checked === 'boolean' && typeof onToggle === 'function';
|
||||
const isEnabled = isControlled ? checked : isDarkMode;
|
||||
|
||||
const handleToggle = () => {
|
||||
if (isControlled) {
|
||||
onToggle(!isEnabled);
|
||||
return;
|
||||
}
|
||||
|
||||
toggleDarkMode();
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleToggle}
|
||||
className="relative inline-flex h-8 w-14 items-center rounded-full bg-gray-200 dark:bg-gray-700 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900"
|
||||
role="switch"
|
||||
aria-checked={isEnabled}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<span className="sr-only">{ariaLabel}</span>
|
||||
<span
|
||||
className={`${
|
||||
isEnabled ? 'translate-x-7' : 'translate-x-1'
|
||||
} h-6 w-6 transform rounded-full bg-white shadow-lg transition-transform duration-200 flex items-center justify-center`}
|
||||
>
|
||||
{isEnabled ? (
|
||||
<Moon className="h-3.5 w-3.5 text-gray-700" />
|
||||
) : (
|
||||
<Sun className="h-3.5 w-3.5 text-yellow-500" />
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default DarkModeToggle;
|
||||
41
src/components/DiffViewer.jsx
Normal file
41
src/components/DiffViewer.jsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
|
||||
function DiffViewer({ diff, fileName, isMobile, wrapText }) {
|
||||
if (!diff) {
|
||||
return (
|
||||
<div className="p-4 text-center text-muted-foreground text-sm">
|
||||
No diff available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const renderDiffLine = (line, index) => {
|
||||
const isAddition = line.startsWith('+') && !line.startsWith('+++');
|
||||
const isDeletion = line.startsWith('-') && !line.startsWith('---');
|
||||
const isHeader = line.startsWith('@@');
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={`font-mono text-xs px-3 py-0.5 ${
|
||||
isMobile && wrapText ? 'whitespace-pre-wrap break-all' : 'whitespace-pre overflow-x-auto'
|
||||
} ${
|
||||
isAddition ? 'bg-green-50 dark:bg-green-950/50 text-green-700 dark:text-green-300' :
|
||||
isDeletion ? 'bg-red-50 dark:bg-red-950/50 text-red-700 dark:text-red-300' :
|
||||
isHeader ? 'bg-primary/5 text-primary' :
|
||||
'text-muted-foreground/70'
|
||||
}`}
|
||||
>
|
||||
{line}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="diff-viewer">
|
||||
{diff.split('\n').map((line, index) => renderDiffLine(line, index))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default DiffViewer;
|
||||
77
src/components/ErrorBoundary.jsx
Normal file
77
src/components/ErrorBoundary.jsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import { ErrorBoundary as ReactErrorBoundary } from 'react-error-boundary';
|
||||
|
||||
function ErrorFallback({ error, resetErrorBoundary, showDetails, componentStack }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 text-center">
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-6 max-w-md">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="flex-shrink-0">
|
||||
<svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="ml-3 text-sm font-medium text-red-800">
|
||||
Something went wrong
|
||||
</h3>
|
||||
</div>
|
||||
<div className="text-sm text-red-700">
|
||||
<p className="mb-2">An error occurred while loading the chat interface.</p>
|
||||
{showDetails && error && (
|
||||
<details className="mt-4">
|
||||
<summary className="cursor-pointer text-xs font-mono">Error Details</summary>
|
||||
<pre className="mt-2 text-xs bg-red-100 p-2 rounded overflow-auto max-h-40">
|
||||
{error.toString()}
|
||||
{componentStack}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<button
|
||||
onClick={resetErrorBoundary}
|
||||
className="bg-red-600 text-white px-4 py-2 rounded text-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorBoundary({ children, showDetails = false, onRetry = undefined, resetKeys = undefined }) {
|
||||
const [componentStack, setComponentStack] = useState(null);
|
||||
|
||||
const handleError = useCallback((error, errorInfo) => {
|
||||
console.error('ErrorBoundary caught an error:', error, errorInfo);
|
||||
setComponentStack(errorInfo?.componentStack || null);
|
||||
}, []);
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
setComponentStack(null);
|
||||
onRetry?.();
|
||||
}, [onRetry]);
|
||||
|
||||
const renderFallback = useCallback(({ error, resetErrorBoundary }) => (
|
||||
<ErrorFallback
|
||||
error={error}
|
||||
resetErrorBoundary={resetErrorBoundary}
|
||||
showDetails={showDetails}
|
||||
componentStack={componentStack}
|
||||
/>
|
||||
), [showDetails, componentStack]);
|
||||
|
||||
return (
|
||||
<ReactErrorBoundary
|
||||
fallbackRender={renderFallback}
|
||||
onError={handleError}
|
||||
onReset={handleReset}
|
||||
resetKeys={resetKeys}
|
||||
>
|
||||
{children}
|
||||
</ReactErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
export default ErrorBoundary;
|
||||
312
src/components/FileContextMenu.jsx
Normal file
312
src/components/FileContextMenu.jsx
Normal file
@@ -0,0 +1,312 @@
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
FileText,
|
||||
FolderPlus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Copy,
|
||||
Download,
|
||||
RefreshCw
|
||||
} from 'lucide-react';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
/**
|
||||
* FileContextMenu Component
|
||||
* Right-click context menu for file/directory operations
|
||||
*/
|
||||
const FileContextMenu = ({
|
||||
children,
|
||||
item,
|
||||
onRename,
|
||||
onDelete,
|
||||
onNewFile,
|
||||
onNewFolder,
|
||||
onRefresh,
|
||||
onCopyPath,
|
||||
onDownload,
|
||||
isLoading = false,
|
||||
className = ''
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||||
const menuRef = useRef(null);
|
||||
const triggerRef = useRef(null);
|
||||
|
||||
const isDirectory = item?.type === 'directory';
|
||||
const isFile = item?.type === 'file';
|
||||
const isBackground = !item; // Clicked on empty space
|
||||
|
||||
// Handle right-click
|
||||
const handleContextMenu = useCallback((e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
const x = e.clientX;
|
||||
const y = e.clientY;
|
||||
|
||||
// Adjust position if menu would go off screen
|
||||
const menuWidth = 200;
|
||||
const menuHeight = 300;
|
||||
|
||||
let adjustedX = x;
|
||||
let adjustedY = y;
|
||||
|
||||
if (x + menuWidth > window.innerWidth) {
|
||||
adjustedX = window.innerWidth - menuWidth - 10;
|
||||
}
|
||||
if (y + menuHeight > window.innerHeight) {
|
||||
adjustedY = window.innerHeight - menuHeight - 10;
|
||||
}
|
||||
|
||||
setPosition({ x: adjustedX, y: adjustedY });
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
// Close menu
|
||||
const closeMenu = useCallback(() => {
|
||||
setIsOpen(false);
|
||||
}, []);
|
||||
|
||||
// Close on click outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e) => {
|
||||
if (menuRef.current && !menuRef.current.contains(e.target)) {
|
||||
closeMenu();
|
||||
}
|
||||
};
|
||||
|
||||
const handleEscape = (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
closeMenu();
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
document.addEventListener('keydown', handleEscape);
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
document.removeEventListener('keydown', handleEscape);
|
||||
};
|
||||
}, [isOpen, closeMenu]);
|
||||
|
||||
// Handle keyboard navigation
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleKeyDown = (e) => {
|
||||
const menuItems = menuRef.current?.querySelectorAll('[role="menuitem"]');
|
||||
if (!menuItems || menuItems.length === 0) return;
|
||||
|
||||
const currentIndex = Array.from(menuItems).findIndex(
|
||||
(item) => item === document.activeElement
|
||||
);
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
const nextIndex = currentIndex < menuItems.length - 1 ? currentIndex + 1 : 0;
|
||||
menuItems[nextIndex]?.focus();
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
const prevIndex = currentIndex > 0 ? currentIndex - 1 : menuItems.length - 1;
|
||||
menuItems[prevIndex]?.focus();
|
||||
break;
|
||||
case 'Enter':
|
||||
case ' ':
|
||||
if (document.activeElement?.hasAttribute('role', 'menuitem')) {
|
||||
e.preventDefault();
|
||||
document.activeElement.click();
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [isOpen]);
|
||||
|
||||
// Handle action click
|
||||
const handleAction = (action, ...args) => {
|
||||
closeMenu();
|
||||
action?.(...args);
|
||||
};
|
||||
|
||||
// Menu item component
|
||||
const MenuItem = ({ icon: Icon, label, onClick, danger = false, disabled = false, shortcut }) => (
|
||||
<button
|
||||
role="menuitem"
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
disabled={disabled || isLoading}
|
||||
onClick={() => handleAction(onClick)}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-3 py-2 text-sm text-left rounded-md transition-colors',
|
||||
'focus:outline-none focus:bg-accent',
|
||||
disabled
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: danger
|
||||
? 'text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950'
|
||||
: 'hover:bg-accent',
|
||||
isLoading && 'pointer-events-none'
|
||||
)}
|
||||
>
|
||||
{Icon && <Icon className="w-4 h-4 flex-shrink-0" />}
|
||||
<span className="flex-1">{label}</span>
|
||||
{shortcut && (
|
||||
<span className="text-xs text-muted-foreground font-mono">{shortcut}</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
|
||||
// Menu divider
|
||||
const MenuDivider = () => (
|
||||
<div className="h-px bg-border my-1 mx-2" />
|
||||
);
|
||||
|
||||
// Build menu items based on context
|
||||
const renderMenuItems = () => {
|
||||
if (isFile) {
|
||||
return (
|
||||
<>
|
||||
<MenuItem
|
||||
icon={Pencil}
|
||||
label={t('fileTree.context.rename', 'Rename')}
|
||||
onClick={() => onRename?.(item)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={Trash2}
|
||||
label={t('fileTree.context.delete', 'Delete')}
|
||||
onClick={() => onDelete?.(item)}
|
||||
danger
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={Copy}
|
||||
label={t('fileTree.context.copyPath', 'Copy Path')}
|
||||
onClick={() => onCopyPath?.(item)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={Download}
|
||||
label={t('fileTree.context.download', 'Download')}
|
||||
onClick={() => onDownload?.(item)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (isDirectory) {
|
||||
return (
|
||||
<>
|
||||
<MenuItem
|
||||
icon={FileText}
|
||||
label={t('fileTree.context.newFile', 'New File')}
|
||||
onClick={() => onNewFile?.(item.path)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={FolderPlus}
|
||||
label={t('fileTree.context.newFolder', 'New Folder')}
|
||||
onClick={() => onNewFolder?.(item.path)}
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={Pencil}
|
||||
label={t('fileTree.context.rename', 'Rename')}
|
||||
onClick={() => onRename?.(item)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={Trash2}
|
||||
label={t('fileTree.context.delete', 'Delete')}
|
||||
onClick={() => onDelete?.(item)}
|
||||
danger
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={Copy}
|
||||
label={t('fileTree.context.copyPath', 'Copy Path')}
|
||||
onClick={() => onCopyPath?.(item)}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={Download}
|
||||
label={t('fileTree.context.download', 'Download')}
|
||||
onClick={() => onDownload?.(item)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Background context (empty space)
|
||||
return (
|
||||
<>
|
||||
<MenuItem
|
||||
icon={FileText}
|
||||
label={t('fileTree.context.newFile', 'New File')}
|
||||
onClick={() => onNewFile?.('')}
|
||||
/>
|
||||
<MenuItem
|
||||
icon={FolderPlus}
|
||||
label={t('fileTree.context.newFolder', 'New Folder')}
|
||||
onClick={() => onNewFolder?.('')}
|
||||
/>
|
||||
<MenuDivider />
|
||||
<MenuItem
|
||||
icon={RefreshCw}
|
||||
label={t('fileTree.context.refresh', 'Refresh')}
|
||||
onClick={onRefresh}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Trigger element */}
|
||||
<div
|
||||
ref={triggerRef}
|
||||
onContextMenu={handleContextMenu}
|
||||
className={cn('contents', className)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{/* Context menu portal */}
|
||||
{isOpen && (
|
||||
<div
|
||||
ref={menuRef}
|
||||
role="menu"
|
||||
aria-label={t('fileTree.context.menuLabel', 'File context menu')}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: position.x,
|
||||
top: position.y,
|
||||
zIndex: 9999
|
||||
}}
|
||||
className={cn(
|
||||
'min-w-[180px] py-1 px-1',
|
||||
'bg-popover border border-border rounded-lg shadow-lg',
|
||||
'animate-in fade-in-0 zoom-in-95',
|
||||
'data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95'
|
||||
)}
|
||||
>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<RefreshCw className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">
|
||||
{t('fileTree.context.loading', 'Loading...')}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
renderMenuItems()
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default FileContextMenu;
|
||||
@@ -1,3 +1,5 @@
|
||||
import React from 'react';
|
||||
|
||||
const GeminiLogo = ({className = 'w-5 h-5'}) => {
|
||||
return (
|
||||
<img src="/icons/gemini-ai-icon.svg" alt="Gemini" className={className} />
|
||||
90
src/components/GeminiStatus.jsx
Normal file
90
src/components/GeminiStatus.jsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
function GeminiStatus({ status, onAbort, isLoading }) {
|
||||
const [elapsedTime, setElapsedTime] = useState(0);
|
||||
const [animationPhase, setAnimationPhase] = useState(0);
|
||||
|
||||
// Update elapsed time every second
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
setElapsedTime(0);
|
||||
return;
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
const timer = setInterval(() => {
|
||||
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
||||
setElapsedTime(elapsed);
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [isLoading]);
|
||||
|
||||
// Animate the status indicator
|
||||
useEffect(() => {
|
||||
if (!isLoading) return;
|
||||
|
||||
const timer = setInterval(() => {
|
||||
setAnimationPhase(prev => (prev + 1) % 4);
|
||||
}, 500);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [isLoading]);
|
||||
|
||||
if (!isLoading) return null;
|
||||
|
||||
// Clever action words that cycle
|
||||
const actionWords = ['Thinking', 'Processing', 'Analyzing', 'Working', 'Computing', 'Reasoning'];
|
||||
const actionIndex = Math.floor(elapsedTime / 3) % actionWords.length;
|
||||
|
||||
// Parse status data
|
||||
const statusText = status?.text || actionWords[actionIndex];
|
||||
const canInterrupt = status?.can_interrupt !== false;
|
||||
|
||||
// Animation characters
|
||||
const spinners = ['✻', '✹', '✸', '✶'];
|
||||
const currentSpinner = spinners[animationPhase];
|
||||
|
||||
return (
|
||||
<div className="w-full mb-6 animate-in slide-in-from-bottom duration-300">
|
||||
<div className="flex items-center justify-between max-w-4xl mx-auto bg-gradient-to-r from-cyan-900 to-blue-900 dark:from-cyan-950 dark:to-blue-950 text-white rounded-lg shadow-lg px-4 py-3">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Animated spinner */}
|
||||
<span className={cn(
|
||||
"text-xl transition-all duration-500",
|
||||
animationPhase % 2 === 0 ? "text-cyan-400 scale-110" : "text-cyan-300"
|
||||
)}>
|
||||
{currentSpinner}
|
||||
</span>
|
||||
|
||||
{/* Status text - first line */}
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-sm">{statusText}...</span>
|
||||
<span className="text-gray-400 text-sm">({elapsedTime}s)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Interrupt button */}
|
||||
{canInterrupt && onAbort && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAbort}
|
||||
className="ml-3 text-xs bg-red-600 hover:bg-red-700 text-white px-2.5 py-1 sm:px-3 sm:py-1.5 rounded-md transition-colors flex items-center gap-1.5 flex-shrink-0"
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
<span className="hidden sm:inline">Stop</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default GeminiStatus;
|
||||
74
src/components/LanguageSelector.jsx
Normal file
74
src/components/LanguageSelector.jsx
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Language Selector Component
|
||||
*
|
||||
* A dropdown component for selecting the application language.
|
||||
* Automatically updates the i18n language and persists to localStorage.
|
||||
*
|
||||
* Props:
|
||||
* @param {boolean} compact - If true, uses compact style (default: false)
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Languages } from 'lucide-react';
|
||||
import { languages } from '../i18n/languages';
|
||||
|
||||
function LanguageSelector({ compact = false }) {
|
||||
const { i18n, t } = useTranslation('settings');
|
||||
|
||||
const handleLanguageChange = (event) => {
|
||||
const newLanguage = event.target.value;
|
||||
i18n.changeLanguage(newLanguage);
|
||||
};
|
||||
|
||||
// Compact style for QuickSettingsPanel
|
||||
if (compact) {
|
||||
return (
|
||||
<div className="flex items-center justify-between p-3 rounded-lg bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors border border-transparent hover:border-gray-300 dark:hover:border-gray-600">
|
||||
<span className="flex items-center gap-2 text-sm text-gray-900 dark:text-white">
|
||||
<Languages className="h-4 w-4 text-gray-600 dark:text-gray-400" />
|
||||
{t('account.language')}
|
||||
</span>
|
||||
<select
|
||||
value={i18n.language}
|
||||
onChange={handleLanguageChange}
|
||||
className="w-[100px] text-sm bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 rounded-lg focus:ring-blue-500 focus:border-blue-500 p-2 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
|
||||
>
|
||||
{languages.map((lang) => (
|
||||
<option key={lang.value} value={lang.value}>
|
||||
{lang.nativeName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Full style for Settings page
|
||||
return (
|
||||
<div className="bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100 mb-1">
|
||||
{t('account.languageLabel')}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{t('account.languageDescription')}
|
||||
</div>
|
||||
</div>
|
||||
<select
|
||||
value={i18n.language}
|
||||
onChange={handleLanguageChange}
|
||||
className="text-sm bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 rounded-lg focus:ring-blue-500 focus:border-blue-500 p-2 w-36"
|
||||
>
|
||||
{languages.map((lang) => (
|
||||
<option key={lang.value} value={lang.value}>
|
||||
{lang.nativeName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LanguageSelector;
|
||||
112
src/components/LoginForm.jsx
Normal file
112
src/components/LoginForm.jsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { MessageSquare } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const LoginForm = () => {
|
||||
const { t } = useTranslation('auth');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const { login } = useAuth();
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
if (!username || !password) {
|
||||
setError(t('errors.requiredFields'));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
const result = await login(username, password);
|
||||
|
||||
if (!result.success) {
|
||||
setError(result.error);
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-md">
|
||||
<div className="bg-card rounded-lg shadow-lg border border-border p-8 space-y-6">
|
||||
{/* Logo and Title */}
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="w-16 h-16 bg-primary rounded-lg flex items-center justify-center shadow-sm">
|
||||
<MessageSquare className="w-8 h-8 text-primary-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-foreground">{t('login.title')}</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
{t('login.description')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Login Form */}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="username" className="block text-sm font-medium text-foreground mb-1">
|
||||
{t('login.username')}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder={t('login.placeholders.username')}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-foreground mb-1">
|
||||
{t('login.password')}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder={t('login.placeholders.password')}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-800 rounded-md">
|
||||
<p className="text-sm text-red-700 dark:text-red-400">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-medium py-2 px-4 rounded-md transition-colors duration-200"
|
||||
>
|
||||
{isLoading ? t('login.loading') : t('login.submit')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Enter your credentials to access Claude Code UI
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginForm;
|
||||
153
src/components/LoginModal.jsx
Normal file
153
src/components/LoginModal.jsx
Normal file
@@ -0,0 +1,153 @@
|
||||
import { X, ExternalLink, KeyRound } from 'lucide-react';
|
||||
import StandaloneShell from './standalone-shell/view/StandaloneShell';
|
||||
import { IS_PLATFORM } from '../constants/config';
|
||||
|
||||
/**
|
||||
* Reusable login modal component for Claude, Cursor, Codex, and Gemini CLI authentication
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {boolean} props.isOpen - Whether the modal is visible
|
||||
* @param {Function} props.onClose - Callback when modal is closed
|
||||
* @param {'claude'|'cursor'|'codex'|'gemini'} props.provider - Which CLI provider to authenticate with
|
||||
* @param {Object} props.project - Project object containing name and path information
|
||||
* @param {Function} props.onComplete - Callback when login process completes (receives exitCode)
|
||||
* @param {string} props.customCommand - Optional custom command to override defaults
|
||||
* @param {boolean} props.isAuthenticated - Whether user is already authenticated (for re-auth flow)
|
||||
*/
|
||||
function LoginModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
provider = 'claude',
|
||||
project,
|
||||
onComplete,
|
||||
customCommand,
|
||||
isAuthenticated = false,
|
||||
isOnboarding = false
|
||||
}) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
const getCommand = () => {
|
||||
if (customCommand) return customCommand;
|
||||
|
||||
switch (provider) {
|
||||
case 'claude':
|
||||
return isAuthenticated ? 'claude setup-token --dangerously-skip-permissions' : isOnboarding ? 'claude /exit --dangerously-skip-permissions' : 'claude /login --dangerously-skip-permissions';
|
||||
case 'cursor':
|
||||
return 'cursor-agent login';
|
||||
case 'codex':
|
||||
return IS_PLATFORM ? 'codex login --device-auth' : 'codex login';
|
||||
case 'gemini':
|
||||
// No explicit interactive login command for gemini CLI exists yet similar to Claude, so we'll just check status or instruct the user to configure `.gemini.json`
|
||||
return 'gemini status';
|
||||
default:
|
||||
return isAuthenticated ? 'claude setup-token --dangerously-skip-permissions' : isOnboarding ? 'claude /exit --dangerously-skip-permissions' : 'claude /login --dangerously-skip-permissions';
|
||||
}
|
||||
};
|
||||
|
||||
const getTitle = () => {
|
||||
switch (provider) {
|
||||
case 'claude':
|
||||
return 'Claude CLI Login';
|
||||
case 'cursor':
|
||||
return 'Cursor CLI Login';
|
||||
case 'codex':
|
||||
return 'Codex CLI Login';
|
||||
case 'gemini':
|
||||
return 'Gemini CLI Configuration';
|
||||
default:
|
||||
return 'CLI Login';
|
||||
}
|
||||
};
|
||||
|
||||
const handleComplete = (exitCode) => {
|
||||
if (onComplete) {
|
||||
onComplete(exitCode);
|
||||
}
|
||||
// Keep modal open so users can read login output and close explicitly.
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] max-md:items-stretch max-md:justify-stretch">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-4xl h-3/4 flex flex-col md:max-w-4xl md:h-3/4 md:rounded-lg md:m-4 max-md:max-w-none max-md:h-full max-md:rounded-none max-md:m-0">
|
||||
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{getTitle()}
|
||||
</h3>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||
aria-label="Close login modal"
|
||||
>
|
||||
<X className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{provider === 'gemini' ? (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center bg-gray-50 dark:bg-gray-900/50">
|
||||
<div className="w-16 h-16 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center mb-6">
|
||||
<KeyRound className="w-8 h-8 text-blue-600 dark:text-blue-400" />
|
||||
</div>
|
||||
|
||||
<h4 className="text-xl font-medium text-gray-900 dark:text-white mb-3">
|
||||
Setup Gemini API Access
|
||||
</h4>
|
||||
|
||||
<p className="text-gray-600 dark:text-gray-400 max-w-md mb-8">
|
||||
The Gemini CLI requires an API key to function. Unlike Claude, you'll need to configure this directly in your terminal first.
|
||||
</p>
|
||||
|
||||
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6 max-w-lg w-full text-left shadow-sm">
|
||||
<ol className="space-y-4">
|
||||
<li className="flex gap-4">
|
||||
<div className="flex-shrink-0 w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400 flex items-center justify-center text-sm font-medium">
|
||||
1
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white mb-1">Get your API Key</p>
|
||||
<a
|
||||
href="https://aistudio.google.com/app/apikey"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1 inline-flex"
|
||||
>
|
||||
Google AI Studio <ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
<li className="flex gap-4">
|
||||
<div className="flex-shrink-0 w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400 flex items-center justify-center text-sm font-medium">
|
||||
2
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white mb-1">Run configuration</p>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-2">Open your terminal and run:</p>
|
||||
<code className="block bg-gray-100 dark:bg-gray-900 px-3 py-2 rounded text-sm text-pink-600 dark:text-pink-400 font-mono">
|
||||
gemini config set api_key YOUR_KEY
|
||||
</code>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="mt-8 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
|
||||
>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<StandaloneShell
|
||||
project={project}
|
||||
command={getCommand()}
|
||||
onComplete={handleComplete}
|
||||
minimal={true}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LoginModal;
|
||||
90
src/components/MobileNav.jsx
Normal file
90
src/components/MobileNav.jsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import React from 'react';
|
||||
import { MessageSquare, Folder, Terminal, GitBranch, ClipboardCheck } from 'lucide-react';
|
||||
import { useTasksSettings } from '../contexts/TasksSettingsContext';
|
||||
import { useTaskMaster } from '../contexts/TaskMasterContext';
|
||||
|
||||
function MobileNav({ activeTab, setActiveTab, isInputFocused }) {
|
||||
const { tasksEnabled, isTaskMasterInstalled } = useTasksSettings();
|
||||
const shouldShowTasksTab = Boolean(tasksEnabled && isTaskMasterInstalled);
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
id: 'chat',
|
||||
icon: MessageSquare,
|
||||
label: 'Chat',
|
||||
onClick: () => setActiveTab('chat')
|
||||
},
|
||||
{
|
||||
id: 'shell',
|
||||
icon: Terminal,
|
||||
label: 'Shell',
|
||||
onClick: () => setActiveTab('shell')
|
||||
},
|
||||
{
|
||||
id: 'files',
|
||||
icon: Folder,
|
||||
label: 'Files',
|
||||
onClick: () => setActiveTab('files')
|
||||
},
|
||||
{
|
||||
id: 'git',
|
||||
icon: GitBranch,
|
||||
label: 'Git',
|
||||
onClick: () => setActiveTab('git')
|
||||
},
|
||||
...(shouldShowTasksTab ? [{
|
||||
id: 'tasks',
|
||||
icon: ClipboardCheck,
|
||||
label: 'Tasks',
|
||||
onClick: () => setActiveTab('tasks')
|
||||
}] : [])
|
||||
];
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`fixed bottom-0 left-0 right-0 z-50 px-3 pb-[max(8px,env(safe-area-inset-bottom))] transform transition-transform duration-300 ease-in-out ${
|
||||
isInputFocused ? 'translate-y-full' : 'translate-y-0'
|
||||
}`}
|
||||
>
|
||||
<div className="nav-glass mobile-nav-float rounded-2xl border border-border/30">
|
||||
<div className="flex items-center justify-around px-1 py-1.5 gap-0.5">
|
||||
{navItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = activeTab === item.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={item.onClick}
|
||||
onTouchStart={(e) => {
|
||||
e.preventDefault();
|
||||
item.onClick();
|
||||
}}
|
||||
className={`flex flex-col items-center justify-center gap-0.5 px-3 py-2 rounded-xl flex-1 relative touch-manipulation transition-all duration-200 active:scale-95 ${
|
||||
isActive
|
||||
? 'text-primary'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
aria-label={item.label}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
>
|
||||
{isActive && (
|
||||
<div className="absolute inset-0 bg-primary/8 dark:bg-primary/12 rounded-xl" />
|
||||
)}
|
||||
<Icon
|
||||
className={`relative z-10 transition-all duration-200 ${isActive ? 'w-5 h-5' : 'w-[18px] h-[18px]'}`}
|
||||
strokeWidth={isActive ? 2.4 : 1.8}
|
||||
/>
|
||||
<span className={`relative z-10 text-[10px] font-medium transition-all duration-200 ${isActive ? 'opacity-100' : 'opacity-60'}`}>
|
||||
{item.label}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default MobileNav;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user